@sunerpy/kiro-provider 0.5.0-rc.4 → 0.5.0
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 +18 -3
- package/dist/cli.js +78 -74
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var
|
|
4
|
-
GFS4: `),console.error(n)};if(!Sn[Cn]){if(io=global[Cn]||[],xu(Sn,io),Sn.close=function(n){function t(i,r){return n.call(Sn,i,function(s){if(!s)Vu();if(typeof r==="function")r.apply(this,arguments)})}return Object.defineProperty(t,O_,{value:n}),t}(Sn.close),Sn.closeSync=function(n){function t(i){n.apply(Sn,arguments),Vu()}return Object.defineProperty(t,O_,{value:n}),t}(Sn.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){fr(Sn[Cn]),dn("assert").equal(Sn[Cn].length,0)})}var io;if(!global[Cn])xu(global,Sn[Cn]);fo.exports=ro(U8(Sn));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!Sn.__patched)fo.exports=ro(Sn),Sn.__patched=!0;function ro(n){l8(n),n.gracefulify=ro,n.createReadStream=N,n.createWriteStream=l;var t=n.readFile;n.readFile=i;function i(b,H,g){if(typeof H==="function")g=H,H=null;return I(b,H,g);function I(P,m,a,j){return t(P,m,function(G){if(G&&(G.code==="EMFILE"||G.code==="ENFILE"))ns([I,[P,m,a],G,j||Date.now(),Date.now()]);else if(typeof a==="function")a.apply(this,arguments)})}}var r=n.writeFile;n.writeFile=s;function s(b,H,g,I){if(typeof g==="function")I=g,g=null;return P(b,H,g,I);function P(m,a,j,G,U){return r(m,a,j,function(F){if(F&&(F.code==="EMFILE"||F.code==="ENFILE"))ns([P,[m,a,j,G],F,U||Date.now(),Date.now()]);else if(typeof G==="function")G.apply(this,arguments)})}}var f=n.appendFile;if(f)n.appendFile=h;function h(b,H,g,I){if(typeof g==="function")I=g,g=null;return P(b,H,g,I);function P(m,a,j,G,U){return f(m,a,j,function(F){if(F&&(F.code==="EMFILE"||F.code==="ENFILE"))ns([P,[m,a,j,G],F,U||Date.now(),Date.now()]);else if(typeof G==="function")G.apply(this,arguments)})}}var _=n.copyFile;if(_)n.copyFile=o;function o(b,H,g,I){if(typeof g==="function")I=g,g=0;return P(b,H,g,I);function P(m,a,j,G,U){return _(m,a,j,function(F){if(F&&(F.code==="EMFILE"||F.code==="ENFILE"))ns([P,[m,a,j,G],F,U||Date.now(),Date.now()]);else if(typeof G==="function")G.apply(this,arguments)})}}var w=n.readdir;n.readdir=d;var c=/^v[0-5]\./;function d(b,H,g){if(typeof H==="function")g=H,H=null;var I=c.test(process.version)?function(a,j,G,U){return w(a,P(a,j,G,U))}:function(a,j,G,U){return w(a,j,P(a,j,G,U))};return I(b,H,g);function P(m,a,j,G){return function(U,F){if(U&&(U.code==="EMFILE"||U.code==="ENFILE"))ns([I,[m,a,j],U,G||Date.now(),Date.now()]);else{if(F&&F.sort)F.sort();if(typeof j==="function")j.call(this,U,F)}}}}if(process.version.substr(0,4)==="v0.8"){var u=$8(n);T=u.ReadStream,e=u.WriteStream}var y=n.ReadStream;if(y)T.prototype=Object.create(y.prototype),T.prototype.open=O;var R=n.WriteStream;if(R)e.prototype=Object.create(R.prototype),e.prototype.open=L;Object.defineProperty(n,"ReadStream",{get:function(){return T},set:function(b){T=b},enumerable:!0,configurable:!0}),Object.defineProperty(n,"WriteStream",{get:function(){return e},set:function(b){e=b},enumerable:!0,configurable:!0});var M=T;Object.defineProperty(n,"FileReadStream",{get:function(){return M},set:function(b){M=b},enumerable:!0,configurable:!0});var E=e;Object.defineProperty(n,"FileWriteStream",{get:function(){return E},set:function(b){E=b},enumerable:!0,configurable:!0});function T(b,H){if(this instanceof T)return y.apply(this,arguments),this;else return T.apply(Object.create(T.prototype),arguments)}function O(){var b=this;V(b.path,b.flags,b.mode,function(H,g){if(H){if(b.autoClose)b.destroy();b.emit("error",H)}else b.fd=g,b.emit("open",g),b.read()})}function e(b,H){if(this instanceof e)return R.apply(this,arguments),this;else return e.apply(Object.create(e.prototype),arguments)}function L(){var b=this;V(b.path,b.flags,b.mode,function(H,g){if(H)b.destroy(),b.emit("error",H);else b.fd=g,b.emit("open",g)})}function N(b,H){return new n.ReadStream(b,H)}function l(b,H){return new n.WriteStream(b,H)}var Y=n.open;n.open=V;function V(b,H,g,I){if(typeof g==="function")I=g,g=null;return P(b,H,g,I);function P(m,a,j,G,U){return Y(m,a,j,function(F,gn){if(F&&(F.code==="EMFILE"||F.code==="ENFILE"))ns([P,[m,a,j,G],F,U||Date.now(),Date.now()]);else if(typeof G==="function")G.apply(this,arguments)})}}return n}function ns(n){fr("ENQUEUE",n[0].name,n[1]),Sn[Cn].push(n),so()}var e_;function Vu(){var n=Date.now();for(var t=0;t<Sn[Cn].length;++t)if(Sn[Cn][t].length>2)Sn[Cn][t][3]=n,Sn[Cn][t][4]=n;so()}function so(){if(clearTimeout(e_),e_=void 0,Sn[Cn].length===0)return;var n=Sn[Cn].shift(),t=n[0],i=n[1],r=n[2],s=n[3],f=n[4];if(s===void 0)fr("RETRY",t.name,i),t.apply(null,i);else if(Date.now()-s>=60000){fr("TIMEOUT",t.name,i);var h=i.pop();if(typeof h==="function")h.call(null,r)}else{var _=Date.now()-f,o=Math.max(f-s,1),w=Math.min(o*1.2,100);if(_>=w)fr("RETRY",t.name,i),t.apply(null,i.concat([s]));else Sn[Cn].push(n)}if(e_===void 0)e_=setTimeout(so,0)}});var qu=rn((Mj,ju)=>{function At(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)}ju.exports=At;At.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};At.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};At.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};At.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)};At.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};At.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};At.prototype.start=At.prototype.try;At.prototype.errors=function(){return this._errors};At.prototype.attempts=function(){return this._attempts};At.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 au=rn((G8)=>{var B8=qu();G8.operation=function(n){var t=G8.timeouts(n);return new B8(t,{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};G8.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};G8.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};G8.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(o){var w=G8.operation(t),c=Array.prototype.slice.call(arguments,1),d=c.pop();c.push(function(u){if(w.retry(u))return;if(u)arguments[0]=w.mainError();d.apply(this,arguments)}),w.attempt(function(){o.apply(n,c)})}.bind(n,h),n[f].options=t}}});var Zu=rn((Tj,L_)=>{L_.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")L_.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")L_.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var vu=rn((ej,is)=>{var Ln=global.process,_r=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(!_r(Ln))is.exports=function(){return function(){}};else{if(ho=dn("assert"),hr=Zu(),oo=/^win/i.test(Ln.platform),ts=dn("events"),typeof ts!=="function")ts=ts.EventEmitter;if(Ln.__signal_exit_emitter__)Wn=Ln.__signal_exit_emitter__;else Wn=Ln.__signal_exit_emitter__=new ts,Wn.count=0,Wn.emitted={};if(!Wn.infinite)Wn.setMaxListeners(1/0),Wn.infinite=!0;is.exports=function(n,t){if(!_r(global.process))return function(){};if(ho.equal(typeof n,"function","a callback must be provided for exit handler"),or===!1)I_();var i="exit";if(t&&t.alwaysLast)i="afterexit";var r=function(){if(Wn.removeListener(i,n),Wn.listeners("exit").length===0&&Wn.listeners("afterexit").length===0)sf()};return Wn.on(i,n),r},sf=function(){if(!or||!_r(global.process))return;or=!1,hr.forEach(function(t){try{Ln.removeListener(t,ff[t])}catch(i){}}),Ln.emit=_f,Ln.reallyExit=g_,Wn.count-=1},is.exports.unload=sf,Di=function(t,i,r){if(Wn.emitted[t])return;Wn.emitted[t]=!0,Wn.emit(t,i,r)},ff={},hr.forEach(function(n){ff[n]=function(){if(!_r(global.process))return;var i=Ln.listeners(n);if(i.length===Wn.count){if(sf(),Di("exit",null,n),Di("afterexit",null,n),oo&&n==="SIGHUP")n="SIGINT";Ln.kill(Ln.pid,n)}}}),is.exports.signals=function(){return hr},or=!1,I_=function(){if(or||!_r(global.process))return;or=!0,Wn.count+=1,hr=hr.filter(function(t){try{return Ln.on(t,ff[t]),!0}catch(i){return!1}}),Ln.emit=co,Ln.reallyExit=wo},is.exports.load=I_,g_=Ln.reallyExit,wo=function(t){if(!_r(global.process))return;Ln.exitCode=t||0,Di("exit",Ln.exitCode,null),Di("afterexit",Ln.exitCode,null),g_.call(Ln,Ln.exitCode)},_f=Ln.emit,co=function(t,i){if(t==="exit"&&_r(global.process)){if(i!==void 0)Ln.exitCode=i;var r=_f.apply(this,arguments);return Di("exit",Ln.exitCode,null),Di("afterexit",Ln.exitCode,null),r}else return _f.apply(this,arguments)}}var ho,hr,oo,ts,Wn,sf,Di,ff,or,I_,g_,wo,_f,co});var ny=rn((X8,uo)=>{var pu=Symbol();function Y8(n,t,i){let r=t[pu];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 o=_.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(t,pu,{value:o}),i(null,_.mtime,o)})})}function P8(n){let t=Date.now();if(n==="s")t=Math.ceil(t/1000)*1000;return new Date(t)}X8.probe=Y8;X8.getMtime=P8});var fy=rn((j8,of)=>{var Q8=dn("path"),Ro=_o(),m8=au(),z8=vu(),ty=ny(),_i={};function hf(n,t){return t.lockfilePath||`${n}.lock`}function Mo(n,t,i){if(!t.realpath)return i(null,Q8.resolve(n));t.fs.realpath(n,i)}function Ao(n,t,i){let r=hf(n,t);t.fs.mkdir(r,(s)=>{if(!s)return ty.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 Ao(n,{...t,stale:0},i);return i(f)}if(!iy(h,t))return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));ry(n,t,(_)=>{if(_)return i(_);Ao(n,{...t,stale:0},i)})})})}function iy(n,t){return n.mtime.getTime()<Date.now()-t.stale}function ry(n,t,i){t.fs.rmdir(hf(n,t),(r)=>{if(r&&r.code!=="ENOENT")return i(r);i()})}function N_(n,t){let i=_i[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 yo(n,i,Object.assign(r,{code:"ECOMPROMISED"}));return i.updateDelay=1000,N_(n,t)}if(i.mtime.getTime()!==s.mtime.getTime())return yo(n,i,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let _=ty.getMtime(i.mtimePrecision);t.fs.utimes(i.lockfilePath,_,_,(o)=>{let w=i.lastUpdate+t.stale<Date.now();if(i.released)return;if(o){if(o.code==="ENOENT"||w)return yo(n,i,Object.assign(o,{code:"ECOMPROMISED"}));return i.updateDelay=1000,N_(n,t)}i.mtime=_,i.lastUpdate=Date.now(),i.updateDelay=null,N_(n,t)})})},i.updateDelay),i.updateTimeout.unref)i.updateTimeout.unref()}function yo(n,t,i){if(t.released=!0,t.updateTimeout)clearTimeout(t.updateTimeout);if(_i[n]===t)delete _i[n];t.options.onCompromised(i)}function K8(n,t,i){t={stale:1e4,update:null,realpath:!0,retries:0,fs:Ro,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),Mo(n,t,(r,s)=>{if(r)return i(r);let f=m8.operation(t.retries);f.attempt(()=>{Ao(s,t,(h,_,o)=>{if(f.retry(h))return;if(h)return i(f.mainError());let w=_i[s]={lockfilePath:hf(s,t),mtime:_,mtimePrecision:o,options:t,lastUpdate:Date.now()};N_(s,t),i(null,(c)=>{if(w.released)return c&&c(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));sy(s,{...t,realpath:!1},c)})})})})}function sy(n,t,i){t={fs:Ro,realpath:!0,...t},Mo(n,t,(r,s)=>{if(r)return i(r);let f=_i[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 _i[s],ry(s,t,i)})}function V8(n,t,i){t={stale:1e4,realpath:!0,fs:Ro,...t},t.stale=Math.max(t.stale||0,2000),Mo(n,t,(r,s)=>{if(r)return i(r);t.fs.stat(hf(s,t),(f,h)=>{if(f)return f.code==="ENOENT"?i(null,!1):i(f);return i(null,!iy(h,t))})})}function x8(){return _i}z8(()=>{for(let n in _i){let t=_i[n].options;try{t.fs.rmdirSync(hf(n,t))}catch(i){}}});j8.lock=K8;j8.unlock=sy;j8.check=V8;j8.getLocks=x8});var hy=rn((Oj,_y)=>{var v8=_o();function p8(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 n6(n){return(...t)=>new Promise((i,r)=>{t.push((s,f)=>{if(s)r(s);else i(f)}),n(...t)})}function t6(n){return(...t)=>{let i,r;if(t.push((s,f)=>{i=s,r=f}),n(...t),i)throw i;return r}}function i6(n){if(n={...n},n.fs=p8(n.fs||v8),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}_y.exports={toPromise:n6,toSync:t6,toSyncOptions:i6}});var To=rn((Lj,Bi)=>{var rs=fy(),{toPromise:b_,toSync:S_,toSyncOptions:Eo}=hy();async function oy(n,t){let i=await b_(rs.lock)(n,t);return b_(i)}function r6(n,t){let i=S_(rs.lock)(n,Eo(t));return S_(i)}function s6(n,t){return b_(rs.unlock)(n,t)}function f6(n,t){return S_(rs.unlock)(n,Eo(t))}function _6(n,t){return b_(rs.check)(n,t)}function h6(n,t){return S_(rs.check)(n,Eo(t))}Bi.exports=oy;Bi.exports.lock=oy;Bi.exports.unlock=s6;Bi.exports.lockSync=r6;Bi.exports.unlockSync=f6;Bi.exports.check=_6;Bi.exports.checkSync=h6});var yy=rn((bj,uy)=>{var ss=1000,fs=ss*60,_s=fs*60,wr=_s*24,T6=wr*7,e6=wr*365.25;uy.exports=function(n,t){t=t||{};var i=typeof n;if(i==="string"&&n.length>0)return O6(n);else if(i==="number"&&isFinite(n))return t.long?I6(n):L6(n);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function O6(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*e6;case"weeks":case"week":case"w":return i*T6;case"days":case"day":case"d":return i*wr;case"hours":case"hour":case"hrs":case"hr":case"h":return i*_s;case"minutes":case"minute":case"mins":case"min":case"m":return i*fs;case"seconds":case"second":case"secs":case"sec":case"s":return i*ss;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}function L6(n){var t=Math.abs(n);if(t>=wr)return Math.round(n/wr)+"d";if(t>=_s)return Math.round(n/_s)+"h";if(t>=fs)return Math.round(n/fs)+"m";if(t>=ss)return Math.round(n/ss)+"s";return n+"ms"}function I6(n){var t=Math.abs(n);if(t>=wr)return l_(n,t,wr,"day");if(t>=_s)return l_(n,t,_s,"hour");if(t>=fs)return l_(n,t,fs,"minute");if(t>=ss)return l_(n,t,ss,"second");return n+" ms"}function l_(n,t,i,r){var s=t>=i*1.5;return Math.round(n/i)+" "+r+(s?"s":"")}});var Oo=rn((Sj,Ay)=>{function g6(n){i.debug=i,i.default=i,i.coerce=o,i.disable=h,i.enable=s,i.enabled=_,i.humanize=yy(),i.destroy=w,Object.keys(n).forEach((c)=>{i[c]=n[c]}),i.names=[],i.skips=[],i.formatters={};function t(c){let d=0;for(let u=0;u<c.length;u++)d=(d<<5)-d+c.charCodeAt(u),d|=0;return i.colors[Math.abs(d)%i.colors.length]}i.selectColor=t;function i(c){let d,u=null,y,R;function M(...E){if(!M.enabled)return;let T=M,O=Number(new Date),e=O-(d||O);if(T.diff=e,T.prev=d,T.curr=O,d=O,E[0]=i.coerce(E[0]),typeof E[0]!=="string")E.unshift("%O");let L=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(l,Y)=>{if(l==="%%")return"%";L++;let V=i.formatters[Y];if(typeof V==="function"){let b=E[L];l=V.call(T,b),E.splice(L,1),L--}return l}),i.formatArgs.call(T,E),(T.log||i.log).apply(T,E)}if(M.namespace=c,M.useColors=i.useColors(),M.color=i.selectColor(c),M.extend=r,M.destroy=i.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(u!==null)return u;if(y!==i.namespaces)y=i.namespaces,R=i.enabled(c);return R},set:(E)=>{u=E}}),typeof i.init==="function")i.init(M);return M}function r(c,d){let u=i(this.namespace+(typeof d>"u"?":":d)+c);return u.log=this.log,u}function s(c){i.save(c),i.namespaces=c,i.names=[],i.skips=[];let d=(typeof c==="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let u of d)if(u[0]==="-")i.skips.push(u.slice(1));else i.names.push(u)}function f(c,d){let u=0,y=0,R=-1,M=0;while(u<c.length)if(y<d.length&&(d[y]===c[u]||d[y]==="*"))if(d[y]==="*")R=y,M=u,y++;else u++,y++;else if(R!==-1)y=R+1,M++,u=M;else return!1;while(y<d.length&&d[y]==="*")y++;return y===d.length}function h(){let c=[...i.names,...i.skips.map((d)=>"-"+d)].join(",");return i.enable(""),c}function _(c){for(let d of i.skips)if(f(c,d))return!1;for(let d of i.names)if(f(c,d))return!0;return!1}function o(c){if(c instanceof Error)return c.stack||c.message;return c}function w(){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}Ay.exports=g6});var My=rn((Ry,$_)=>{Ry.formatArgs=b6;Ry.save=S6;Ry.load=l6;Ry.useColors=N6;Ry.storage=$6();Ry.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`.")}})();Ry.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 N6(){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 b6(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+$_.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)}Ry.log=console.debug||console.log||(()=>{});function S6(n){try{if(n)Ry.storage.setItem("debug",n);else Ry.storage.removeItem("debug")}catch(t){}}function l6(){let n;try{n=Ry.storage.getItem("debug")||Ry.storage.getItem("DEBUG")}catch(t){}if(!n&&typeof process<"u"&&"env"in process)n=process.env.DEBUG;return n}function $6(){try{return localStorage}catch(n){}}$_.exports=Oo()(Ry);var{formatters:U6}=$_.exports;U6.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Oy=rn((Ty,D_)=>{var P6=dn("tty"),U_=dn("util");Ty.init=K6;Ty.log=Q6;Ty.formatArgs=C6;Ty.save=m6;Ty.load=z6;Ty.useColors=X6;Ty.destroy=U_.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ty.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)Ty.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){}Ty.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 X6(){return"colors"in Ty.inspectOpts?Boolean(Ty.inspectOpts.colors):P6.isatty(process.stderr.fd)}function C6(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(`
|
|
3
|
+
var eO=Object.create;var{getPrototypeOf:cO,defineProperty:o0,getOwnPropertyNames:dO}=Object;var uO=Object.prototype.hasOwnProperty;function wO(n){return this[n]}var yO,AO,k=(n,t,i)=>{var r=n!=null&&typeof n==="object";if(r){var s=t?yO??=new WeakMap:AO??=new WeakMap,f=s.get(n);if(f)return f}i=n!=null?eO(cO(n)):{};let _=t||!n||!n.__esModule?o0(i,"default",{value:n,enumerable:!0}):i;for(let o of dO(n))if(!uO.call(_,o))o0(_,o,{get:wO.bind(n,o),enumerable:!0});if(r)s.set(n,_);return _};var sn=(n,t)=>()=>(t||n((t={exports:{}}).exports,t),t.exports);var RO=(n)=>n;function MO(n,t){this[n]=RO.bind(null,t)}var EO=(n,t)=>{for(var i in t)o0(n,i,{get:t[i],enumerable:!0,configurable:!0,set:MO.bind(t,i)})};var un=import.meta.require;var iw=sn((kV,tw)=>{var Wi=un("constants"),v4=process.cwd,$o=null,p4=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!$o)$o=v4.call(process);return $o};try{process.cwd()}catch(n){}if(typeof process.chdir==="function"){if(Do=process.chdir,process.chdir=function(n){$o=null,Do.call(process,n)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,Do)}var Do;tw.exports=nL;function nL(n){if(Wi.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=_(n.chownSync),n.fchownSync=_(n.fchownSync),n.lchownSync=_(n.lchownSync),n.chmodSync=s(n.chmodSync),n.fchmodSync=s(n.fchmodSync),n.lchmodSync=s(n.lchmodSync),n.stat=o(n.stat),n.fstat=o(n.fstat),n.lstat=o(n.lstat),n.statSync=h(n.statSync),n.fstatSync=h(n.fstatSync),n.lstatSync=h(n.lstatSync),n.chmod&&!n.lchmod)n.lchmod=function(c,d,u){if(u)process.nextTick(u)},n.lchmodSync=function(){};if(n.chown&&!n.lchown)n.lchown=function(c,d,u,w){if(w)process.nextTick(w)},n.lchownSync=function(){};if(p4==="win32")n.rename=typeof n.rename!=="function"?n.rename:function(c){function d(u,w,A){var R=Date.now(),M=0;c(u,w,function E(T){if(T&&(T.code==="EACCES"||T.code==="EPERM"||T.code==="EBUSY")&&Date.now()-R<60000){if(setTimeout(function(){n.stat(w,function(l,g){if(l&&l.code==="ENOENT")c(u,w,E);else A(T)})},M),M<100)M+=10;return}if(A)A(T)})}if(Object.setPrototypeOf)Object.setPrototypeOf(d,c);return d}(n.rename);n.read=typeof n.read!=="function"?n.read:function(c){function d(u,w,A,R,M,E){var T;if(E&&typeof E==="function"){var l=0;T=function(g,O,N){if(g&&g.code==="EAGAIN"&&l<10)return l++,c.call(n,u,w,A,R,M,T);E.apply(this,arguments)}}return c.call(n,u,w,A,R,M,T)}if(Object.setPrototypeOf)Object.setPrototypeOf(d,c);return d}(n.read),n.readSync=typeof n.readSync!=="function"?n.readSync:function(c){return function(d,u,w,A,R){var M=0;while(!0)try{return c.call(n,d,u,w,A,R)}catch(E){if(E.code==="EAGAIN"&&M<10){M++;continue}throw E}}}(n.readSync);function t(c){c.lchmod=function(d,u,w){c.open(d,Wi.O_WRONLY|Wi.O_SYMLINK,u,function(A,R){if(A){if(w)w(A);return}c.fchmod(R,u,function(M){c.close(R,function(E){if(w)w(M||E)})})})},c.lchmodSync=function(d,u){var w=c.openSync(d,Wi.O_WRONLY|Wi.O_SYMLINK,u),A=!0,R;try{R=c.fchmodSync(w,u),A=!1}finally{if(A)try{c.closeSync(w)}catch(M){}else c.closeSync(w)}return R}}function i(c){if(Wi.hasOwnProperty("O_SYMLINK")&&c.futimes)c.lutimes=function(d,u,w,A){c.open(d,Wi.O_SYMLINK,function(R,M){if(R){if(A)A(R);return}c.futimes(M,u,w,function(E){c.close(M,function(T){if(A)A(E||T)})})})},c.lutimesSync=function(d,u,w){var A=c.openSync(d,Wi.O_SYMLINK),R,M=!0;try{R=c.futimesSync(A,u,w),M=!1}finally{if(M)try{c.closeSync(A)}catch(E){}else c.closeSync(A)}return R};else if(c.futimes)c.lutimes=function(d,u,w,A){if(A)process.nextTick(A)},c.lutimesSync=function(){}}function r(c){if(!c)return c;return function(d,u,w){return c.call(n,d,u,function(A){if(e(A))A=null;if(w)w.apply(this,arguments)})}}function s(c){if(!c)return c;return function(d,u){try{return c.call(n,d,u)}catch(w){if(!e(w))throw w}}}function f(c){if(!c)return c;return function(d,u,w,A){return c.call(n,d,u,w,function(R){if(e(R))R=null;if(A)A.apply(this,arguments)})}}function _(c){if(!c)return c;return function(d,u,w){try{return c.call(n,d,u,w)}catch(A){if(!e(A))throw A}}}function o(c){if(!c)return c;return function(d,u,w){if(typeof u==="function")w=u,u=null;function A(R,M){if(M){if(M.uid<0)M.uid+=4294967296;if(M.gid<0)M.gid+=4294967296}if(w)w.apply(this,arguments)}return u?c.call(n,d,u,A):c.call(n,d,A)}}function h(c){if(!c)return c;return function(d,u){var w=u?c.call(n,d,u):c.call(n,d);if(w){if(w.uid<0)w.uid+=4294967296;if(w.gid<0)w.gid+=4294967296}return w}}function e(c){if(!c)return!0;if(c.code==="ENOSYS")return!0;var d=!process.getuid||process.getuid()!==0;if(d){if(c.code==="EINVAL"||c.code==="EPERM")return!0}return!1}}});var fw=sn((ZV,sw)=>{var rw=un("stream").Stream;sw.exports=tL;function tL(n){return{ReadStream:t,WriteStream:i};function t(r,s){if(!(this instanceof t))return new t(r,s);rw.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 _=Object.keys(s);for(var o=0,h=_.length;o<h;o++){var e=_[o];this[e]=s[e]}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(c,d){if(c){f.emit("error",c),f.readable=!1;return}f.fd=d,f.emit("open",d),f._read()})}function i(r,s){if(!(this instanceof i))return new i(r,s);rw.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 _=0,o=f.length;_<o;_++){var h=f[_];this[h]=s[h]}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 _w=sn((vV,ow)=>{ow.exports=rL;var iL=Object.getPrototypeOf||function(n){return n.__proto__};function rL(n){if(n===null||typeof n!=="object")return n;if(n instanceof Object)var t={__proto__:iL(n)};else var t=Object.create(null);return Object.getOwnPropertyNames(n).forEach(function(i){Object.defineProperty(t,i,Object.getOwnPropertyDescriptor(n,i))}),t}});var T0=sn((pV,l0)=>{var Sn=un("fs"),sL=iw(),fL=fw(),oL=_w(),Bo=un("util"),Yn,mo;if(typeof Symbol==="function"&&typeof Symbol.for==="function")Yn=Symbol.for("graceful-fs.queue"),mo=Symbol.for("graceful-fs.previous");else Yn="___graceful-fs.queue",mo="___graceful-fs.previous";function _L(){}function ew(n,t){Object.defineProperty(n,Yn,{get:function(){return t}})}var er=_L;if(Bo.debuglog)er=Bo.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))er=function(){var n=Bo.format.apply(Bo,arguments);n="GFS4: "+n.split(/\n/).join(`
|
|
4
|
+
GFS4: `),console.error(n)};if(!Sn[Yn]){if(R0=global[Yn]||[],ew(Sn,R0),Sn.close=function(n){function t(i,r){return n.call(Sn,i,function(s){if(!s)hw();if(typeof r==="function")r.apply(this,arguments)})}return Object.defineProperty(t,mo,{value:n}),t}(Sn.close),Sn.closeSync=function(n){function t(i){n.apply(Sn,arguments),hw()}return Object.defineProperty(t,mo,{value:n}),t}(Sn.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){er(Sn[Yn]),un("assert").equal(Sn[Yn].length,0)})}var R0;if(!global[Yn])ew(global,Sn[Yn]);l0.exports=M0(oL(Sn));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!Sn.__patched)l0.exports=M0(Sn),Sn.__patched=!0;function M0(n){sL(n),n.gracefulify=M0,n.createReadStream=O,n.createWriteStream=N;var t=n.readFile;n.readFile=i;function i(S,W,C){if(typeof W==="function")C=W,W=null;return I(S,W,C);function I(L,m,q,Q){return t(L,m,function(Z){if(Z&&(Z.code==="EMFILE"||Z.code==="ENFILE"))hs([I,[L,m,q],Z,Q||Date.now(),Date.now()]);else if(typeof q==="function")q.apply(this,arguments)})}}var r=n.writeFile;n.writeFile=s;function s(S,W,C,I){if(typeof C==="function")I=C,C=null;return L(S,W,C,I);function L(m,q,Q,Z,b){return r(m,q,Q,function(D){if(D&&(D.code==="EMFILE"||D.code==="ENFILE"))hs([L,[m,q,Q,Z],D,b||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}var f=n.appendFile;if(f)n.appendFile=_;function _(S,W,C,I){if(typeof C==="function")I=C,C=null;return L(S,W,C,I);function L(m,q,Q,Z,b){return f(m,q,Q,function(D){if(D&&(D.code==="EMFILE"||D.code==="ENFILE"))hs([L,[m,q,Q,Z],D,b||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}var o=n.copyFile;if(o)n.copyFile=h;function h(S,W,C,I){if(typeof C==="function")I=C,C=0;return L(S,W,C,I);function L(m,q,Q,Z,b){return o(m,q,Q,function(D){if(D&&(D.code==="EMFILE"||D.code==="ENFILE"))hs([L,[m,q,Q,Z],D,b||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}var e=n.readdir;n.readdir=d;var c=/^v[0-5]\./;function d(S,W,C){if(typeof W==="function")C=W,W=null;var I=c.test(process.version)?function(q,Q,Z,b){return e(q,L(q,Q,Z,b))}:function(q,Q,Z,b){return e(q,Q,L(q,Q,Z,b))};return I(S,W,C);function L(m,q,Q,Z){return function(b,D){if(b&&(b.code==="EMFILE"||b.code==="ENFILE"))hs([I,[m,q,Q],b,Z||Date.now(),Date.now()]);else{if(D&&D.sort)D.sort();if(typeof Q==="function")Q.call(this,b,D)}}}}if(process.version.substr(0,4)==="v0.8"){var u=fL(n);E=u.ReadStream,l=u.WriteStream}var w=n.ReadStream;if(w)E.prototype=Object.create(w.prototype),E.prototype.open=T;var A=n.WriteStream;if(A)l.prototype=Object.create(A.prototype),l.prototype.open=g;Object.defineProperty(n,"ReadStream",{get:function(){return E},set:function(S){E=S},enumerable:!0,configurable:!0}),Object.defineProperty(n,"WriteStream",{get:function(){return l},set:function(S){l=S},enumerable:!0,configurable:!0});var R=E;Object.defineProperty(n,"FileReadStream",{get:function(){return R},set:function(S){R=S},enumerable:!0,configurable:!0});var M=l;Object.defineProperty(n,"FileWriteStream",{get:function(){return M},set:function(S){M=S},enumerable:!0,configurable:!0});function E(S,W){if(this instanceof E)return w.apply(this,arguments),this;else return E.apply(Object.create(E.prototype),arguments)}function T(){var S=this;K(S.path,S.flags,S.mode,function(W,C){if(W){if(S.autoClose)S.destroy();S.emit("error",W)}else S.fd=C,S.emit("open",C),S.read()})}function l(S,W){if(this instanceof l)return A.apply(this,arguments),this;else return l.apply(Object.create(l.prototype),arguments)}function g(){var S=this;K(S.path,S.flags,S.mode,function(W,C){if(W)S.destroy(),S.emit("error",W);else S.fd=C,S.emit("open",C)})}function O(S,W){return new n.ReadStream(S,W)}function N(S,W){return new n.WriteStream(S,W)}var F=n.open;n.open=K;function K(S,W,C,I){if(typeof C==="function")I=C,C=null;return L(S,W,C,I);function L(m,q,Q,Z,b){return F(m,q,Q,function(D,Dn){if(D&&(D.code==="EMFILE"||D.code==="ENFILE"))hs([L,[m,q,Q,Z],D,b||Date.now(),Date.now()]);else if(typeof Z==="function")Z.apply(this,arguments)})}}return n}function hs(n){er("ENQUEUE",n[0].name,n[1]),Sn[Yn].push(n),E0()}var Go;function hw(){var n=Date.now();for(var t=0;t<Sn[Yn].length;++t)if(Sn[Yn][t].length>2)Sn[Yn][t][3]=n,Sn[Yn][t][4]=n;E0()}function E0(){if(clearTimeout(Go),Go=void 0,Sn[Yn].length===0)return;var n=Sn[Yn].shift(),t=n[0],i=n[1],r=n[2],s=n[3],f=n[4];if(s===void 0)er("RETRY",t.name,i),t.apply(null,i);else if(Date.now()-s>=60000){er("TIMEOUT",t.name,i);var _=i.pop();if(typeof _==="function")_.call(null,r)}else{var o=Date.now()-f,h=Math.max(f-s,1),e=Math.min(h*1.2,100);if(o>=e)er("RETRY",t.name,i),t.apply(null,i.concat([s]));else Sn[Yn].push(n)}if(Go===void 0)Go=setTimeout(E0,0)}});var dw=sn((nj,cw)=>{function Mt(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)}cw.exports=Mt;Mt.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};Mt.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};Mt.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};Mt.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)};Mt.prototype.try=function(n){console.log("Using RetryOperation.try() is deprecated"),this.attempt(n)};Mt.prototype.start=function(n){console.log("Using RetryOperation.start() is deprecated"),this.attempt(n)};Mt.prototype.start=Mt.prototype.try;Mt.prototype.errors=function(){return this._errors};Mt.prototype.attempts=function(){return this._attempts};Mt.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,_=(n[f]||0)+1;if(n[f]=_,_>=i)t=s,i=_}return t}});var ww=sn((eL)=>{var hL=dw();eL.operation=function(n){var t=eL.timeouts(n);return new hL(t,{forever:n&&n.forever,unref:n&&n.unref,maxRetryTime:n&&n.maxRetryTime})};eL.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,_){return f-_}),r};eL.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};eL.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],_=n[f];n[f]=function(h){var e=eL.operation(t),c=Array.prototype.slice.call(arguments,1),d=c.pop();c.push(function(u){if(e.retry(u))return;if(u)arguments[0]=e.mainError();d.apply(this,arguments)}),e.attempt(function(){h.apply(n,c)})}.bind(n,_),n[f].options=t}}});var yw=sn((ij,Ho)=>{Ho.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")Ho.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")Ho.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var Aw=sn((rj,cs)=>{var gn=global.process,cr=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(!cr(gn))cs.exports=function(){return function(){}};else{if(g0=un("assert"),dr=yw(),O0=/^win/i.test(gn.platform),es=un("events"),typeof es!=="function")es=es.EventEmitter;if(gn.__signal_exit_emitter__)Hn=gn.__signal_exit_emitter__;else Hn=gn.__signal_exit_emitter__=new es,Hn.count=0,Hn.emitted={};if(!Hn.infinite)Hn.setMaxListeners(1/0),Hn.infinite=!0;cs.exports=function(n,t){if(!cr(global.process))return function(){};if(g0.equal(typeof n,"function","a callback must be provided for exit handler"),ur===!1)Wo();var i="exit";if(t&&t.alwaysLast)i="afterexit";var r=function(){if(Hn.removeListener(i,n),Hn.listeners("exit").length===0&&Hn.listeners("afterexit").length===0)wf()};return Hn.on(i,n),r},wf=function(){if(!ur||!cr(global.process))return;ur=!1,dr.forEach(function(t){try{gn.removeListener(t,yf[t])}catch(i){}}),gn.emit=Af,gn.reallyExit=Fo,Hn.count-=1},cs.exports.unload=wf,Fi=function(t,i,r){if(Hn.emitted[t])return;Hn.emitted[t]=!0,Hn.emit(t,i,r)},yf={},dr.forEach(function(n){yf[n]=function(){if(!cr(global.process))return;var i=gn.listeners(n);if(i.length===Hn.count){if(wf(),Fi("exit",null,n),Fi("afterexit",null,n),O0&&n==="SIGHUP")n="SIGINT";gn.kill(gn.pid,n)}}}),cs.exports.signals=function(){return dr},ur=!1,Wo=function(){if(ur||!cr(global.process))return;ur=!0,Hn.count+=1,dr=dr.filter(function(t){try{return gn.on(t,yf[t]),!0}catch(i){return!1}}),gn.emit=I0,gn.reallyExit=L0},cs.exports.load=Wo,Fo=gn.reallyExit,L0=function(t){if(!cr(global.process))return;gn.exitCode=t||0,Fi("exit",gn.exitCode,null),Fi("afterexit",gn.exitCode,null),Fo.call(gn,gn.exitCode)},Af=gn.emit,I0=function(t,i){if(t==="exit"&&cr(global.process)){if(i!==void 0)gn.exitCode=i;var r=Af.apply(this,arguments);return Fi("exit",gn.exitCode,null),Fi("afterexit",gn.exitCode,null),r}else return Af.apply(this,arguments)}}var g0,dr,O0,es,Hn,wf,Fi,yf,ur,Wo,Fo,L0,Af,I0});var Mw=sn((AL,S0)=>{var Rw=Symbol();function wL(n,t,i){let r=t[Rw];if(r)return t.stat(n,(f,_)=>{if(f)return i(f);i(null,_.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,(_,o)=>{if(_)return i(_);let h=o.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(t,Rw,{value:h}),i(null,o.mtime,h)})})}function yL(n){let t=Date.now();if(n==="s")t=Math.ceil(t/1000)*1000;return new Date(t)}AL.probe=wL;AL.getMtime=yL});var Ow=sn((IL,Mf)=>{var EL=un("path"),U0=T0(),lL=ww(),TL=Aw(),Ew=Mw(),ci={};function Rf(n,t){return t.lockfilePath||`${n}.lock`}function $0(n,t,i){if(!t.realpath)return i(null,EL.resolve(n));t.fs.realpath(n,i)}function N0(n,t,i){let r=Rf(n,t);t.fs.mkdir(r,(s)=>{if(!s)return Ew.probe(r,t.fs,(f,_,o)=>{if(f)return t.fs.rmdir(r,()=>{}),i(f);i(null,_,o)});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,_)=>{if(f){if(f.code==="ENOENT")return N0(n,{...t,stale:0},i);return i(f)}if(!lw(_,t))return i(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:n}));Tw(n,t,(o)=>{if(o)return i(o);N0(n,{...t,stale:0},i)})})})}function lw(n,t){return n.mtime.getTime()<Date.now()-t.stale}function Tw(n,t,i){t.fs.rmdir(Rf(n,t),(r)=>{if(r&&r.code!=="ENOENT")return i(r);i()})}function Co(n,t){let i=ci[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,Co(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 o=Ew.getMtime(i.mtimePrecision);t.fs.utimes(i.lockfilePath,o,o,(h)=>{let e=i.lastUpdate+t.stale<Date.now();if(i.released)return;if(h){if(h.code==="ENOENT"||e)return b0(n,i,Object.assign(h,{code:"ECOMPROMISED"}));return i.updateDelay=1000,Co(n,t)}i.mtime=o,i.lastUpdate=Date.now(),i.updateDelay=null,Co(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(ci[n]===t)delete ci[n];t.options.onCompromised(i)}function gL(n,t,i){t={stale:1e4,update:null,realpath:!0,retries:0,fs:U0,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),$0(n,t,(r,s)=>{if(r)return i(r);let f=lL.operation(t.retries);f.attempt(()=>{N0(s,t,(_,o,h)=>{if(f.retry(_))return;if(_)return i(f.mainError());let e=ci[s]={lockfilePath:Rf(s,t),mtime:o,mtimePrecision:h,options:t,lastUpdate:Date.now()};Co(s,t),i(null,(c)=>{if(e.released)return c&&c(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));gw(s,{...t,realpath:!1},c)})})})})}function gw(n,t,i){t={fs:U0,realpath:!0,...t},$0(n,t,(r,s)=>{if(r)return i(r);let f=ci[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 ci[s],Tw(s,t,i)})}function OL(n,t,i){t={stale:1e4,realpath:!0,fs:U0,...t},t.stale=Math.max(t.stale||0,2000),$0(n,t,(r,s)=>{if(r)return i(r);t.fs.stat(Rf(s,t),(f,_)=>{if(f)return f.code==="ENOENT"?i(null,!1):i(f);return i(null,!lw(_,t))})})}function LL(){return ci}TL(()=>{for(let n in ci){let t=ci[n].options;try{t.fs.rmdirSync(Rf(n,t))}catch(i){}}});IL.lock=gL;IL.unlock=gw;IL.check=OL;IL.getLocks=LL});var Iw=sn((sj,Lw)=>{var $L=T0();function DL(n){let t=["mkdir","realpath","stat","rmdir","utimes"],i={...n};return t.forEach((r)=>{i[r]=(...s)=>{let f=s.pop(),_;try{_=n[`${r}Sync`](...s)}catch(o){return f(o)}f(null,_)}}),i}function BL(n){return(...t)=>new Promise((i,r)=>{t.push((s,f)=>{if(s)r(s);else i(f)}),n(...t)})}function GL(n){return(...t)=>{let i,r;if(t.push((s,f)=>{i=s,r=f}),n(...t),i)throw i;return r}}function mL(n){if(n={...n},n.fs=DL(n.fs||$L),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}Lw.exports={toPromise:BL,toSync:GL,toSyncOptions:mL}});var B0=sn((fj,Ci)=>{var ds=Ow(),{toPromise:Po,toSync:Yo,toSyncOptions:D0}=Iw();async function Sw(n,t){let i=await Po(ds.lock)(n,t);return Po(i)}function HL(n,t){let i=Yo(ds.lock)(n,D0(t));return Yo(i)}function WL(n,t){return Po(ds.unlock)(n,t)}function FL(n,t){return Yo(ds.unlock)(n,D0(t))}function CL(n,t){return Po(ds.check)(n,t)}function PL(n,t){return Yo(ds.check)(n,D0(t))}Ci.exports=Sw;Ci.exports.lock=Sw;Ci.exports.unlock=WL;Ci.exports.lockSync=HL;Ci.exports.unlockSync=FL;Ci.exports.check=CL;Ci.exports.checkSync=PL});var Dw=sn((ej,$w)=>{var us=1000,ws=us*60,ys=ws*60,wr=ys*24,qL=wr*7,kL=wr*365.25;$w.exports=function(n,t){t=t||{};var i=typeof n;if(i==="string"&&n.length>0)return ZL(n);else if(i==="number"&&isFinite(n))return t.long?pL(n):vL(n);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function ZL(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*kL;case"weeks":case"week":case"w":return i*qL;case"days":case"day":case"d":return i*wr;case"hours":case"hour":case"hrs":case"hr":case"h":return i*ys;case"minutes":case"minute":case"mins":case"min":case"m":return i*ws;case"seconds":case"second":case"secs":case"sec":case"s":return i*us;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return i;default:return}}function vL(n){var t=Math.abs(n);if(t>=wr)return Math.round(n/wr)+"d";if(t>=ys)return Math.round(n/ys)+"h";if(t>=ws)return Math.round(n/ws)+"m";if(t>=us)return Math.round(n/us)+"s";return n+"ms"}function pL(n){var t=Math.abs(n);if(t>=wr)return Xo(n,t,wr,"day");if(t>=ys)return Xo(n,t,ys,"hour");if(t>=ws)return Xo(n,t,ws,"minute");if(t>=us)return Xo(n,t,us,"second");return n+" ms"}function Xo(n,t,i,r){var s=t>=i*1.5;return Math.round(n/i)+" "+r+(s?"s":"")}});var m0=sn((cj,Bw)=>{function nI(n){i.debug=i,i.default=i,i.coerce=h,i.disable=_,i.enable=s,i.enabled=o,i.humanize=Dw(),i.destroy=e,Object.keys(n).forEach((c)=>{i[c]=n[c]}),i.names=[],i.skips=[],i.formatters={};function t(c){let d=0;for(let u=0;u<c.length;u++)d=(d<<5)-d+c.charCodeAt(u),d|=0;return i.colors[Math.abs(d)%i.colors.length]}i.selectColor=t;function i(c){let d,u=null,w,A;function R(...M){if(!R.enabled)return;let E=R,T=Number(new Date),l=T-(d||T);if(E.diff=l,E.prev=d,E.curr=T,d=T,M[0]=i.coerce(M[0]),typeof M[0]!=="string")M.unshift("%O");let g=0;M[0]=M[0].replace(/%([a-zA-Z%])/g,(N,F)=>{if(N==="%%")return"%";g++;let K=i.formatters[F];if(typeof K==="function"){let S=M[g];N=K.call(E,S),M.splice(g,1),g--}return N}),i.formatArgs.call(E,M),(E.log||i.log).apply(E,M)}if(R.namespace=c,R.useColors=i.useColors(),R.color=i.selectColor(c),R.extend=r,R.destroy=i.destroy,Object.defineProperty(R,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(u!==null)return u;if(w!==i.namespaces)w=i.namespaces,A=i.enabled(c);return A},set:(M)=>{u=M}}),typeof i.init==="function")i.init(R);return R}function r(c,d){let u=i(this.namespace+(typeof d>"u"?":":d)+c);return u.log=this.log,u}function s(c){i.save(c),i.namespaces=c,i.names=[],i.skips=[];let d=(typeof c==="string"?c:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let u of d)if(u[0]==="-")i.skips.push(u.slice(1));else i.names.push(u)}function f(c,d){let u=0,w=0,A=-1,R=0;while(u<c.length)if(w<d.length&&(d[w]===c[u]||d[w]==="*"))if(d[w]==="*")A=w,R=u,w++;else u++,w++;else if(A!==-1)w=A+1,R++,u=R;else return!1;while(w<d.length&&d[w]==="*")w++;return w===d.length}function _(){let c=[...i.names,...i.skips.map((d)=>"-"+d)].join(",");return i.enable(""),c}function o(c){for(let d of i.skips)if(f(c,d))return!1;for(let d of i.names)if(f(c,d))return!0;return!1}function h(c){if(c instanceof Error)return c.stack||c.message;return c}function e(){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}Bw.exports=nI});var mw=sn((Gw,Jo)=>{Gw.formatArgs=iI;Gw.save=rI;Gw.load=sI;Gw.useColors=tI;Gw.storage=fI();Gw.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`.")}})();Gw.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 tI(){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 iI(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Jo.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)}Gw.log=console.debug||console.log||(()=>{});function rI(n){try{if(n)Gw.storage.setItem("debug",n);else Gw.storage.removeItem("debug")}catch(t){}}function sI(){let n;try{n=Gw.storage.getItem("debug")||Gw.storage.getItem("DEBUG")}catch(t){}if(!n&&typeof process<"u"&&"env"in process)n=process.env.DEBUG;return n}function fI(){try{return localStorage}catch(n){}}Jo.exports=m0()(Gw);var{formatters:oI}=Jo.exports;oI.j=function(n){try{return JSON.stringify(n)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}});var Cw=sn((Ww,ao)=>{var yI=un("tty"),Qo=un("util");Ww.init=gI;Ww.log=EI;Ww.formatArgs=RI;Ww.save=lI;Ww.load=TI;Ww.useColors=AI;Ww.destroy=Qo.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");Ww.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)Ww.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){}Ww.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 AI(){return"colors"in Ww.inspectOpts?Boolean(Ww.inspectOpts.colors):yI.isatty(process.stderr.fd)}function RI(n){let{namespace:t,useColors:i}=this;if(i){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),f=` ${s};1m${t} \x1B[0m`;n[0]=f+n[0].split(`
|
|
5
5
|
`).join(`
|
|
6
|
-
`+f),n.push(s+"m+"+
|
|
7
|
-
`)}function
|
|
8
|
-
`).map((t)=>t.trim()).join(" ")};
|
|
9
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(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 d.$responseBodyText<"u"){if(d.$response)d.$response.body=d.$responseBodyText}try{if($g.isInstance(s)){let{headers:y={},statusCode:R}=s,M=Object.entries(y);d.$metadata={httpStatusCode:R,requestId:po(/^x-[\w-]+-request-?id$/,M),extendedRequestId:po(/^x-[\w-]+-id-2$/,M),cfId:po(/^x-[\w-]+-cf-id$/,M)}}}catch(y){}}throw d}},po=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},Bg=(n)=>(t,i)=>async(r)=>{let{operationSchema:s}=TA(i),[,f,h,_,o,w]=s??[],c=i.endpointV2?async()=>Ug(i.endpointV2):n.endpoint,d=await n.protocol.serializeRequest(tw(f,h,_,o,w),r.input,{...n,...i,endpoint:c});return t({...r,request:d})},eA={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},OA={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Gg(n){return{applyToStack:(t)=>{t.add(Bg(n),OA),t.add(Dg(n),eA),n.protocol.setSerdeContext(n)}}}class Zn{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 x_ extends Zn{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=x_.symbol}var Hg=(n,t,i,r)=>Zn.assign(new x_,{name:t,namespace:n,traits:i,valueSchema:r});class j_ extends Zn{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=j_.symbol}var Wg=(n,t,i,r,s)=>Zn.assign(new j_,{name:t,namespace:n,traits:i,keySchema:r,valueSchema:s});class q_ extends Zn{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=q_.symbol}var Fg=(n,t,i,r,s)=>Zn.assign(new q_,{name:t,namespace:n,traits:i,input:r,output:s});class Lf extends Zn{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Lf.symbol}var Yg=(n,t,i,r,s)=>Zn.assign(new Lf,{name:t,namespace:n,traits:i,memberNames:r,memberList:s});class k_ extends Lf{static symbol=Symbol.for("@smithy/err");ctor;symbol=k_.symbol}var Pg=(n,t,i,r,s,f)=>Zn.assign(new k_,{name:t,namespace:n,traits:i,memberNames:r,memberList:s,ctor:null}),z_=[];function Of(n){if(typeof n==="object")return n;if(n=n|0,z_[n])return z_[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 z_[n]=t}var Tf={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},K_=[],V_={};class ui{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=ui.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(nw(r))i.push(r[1]),r=r[0],s=m_(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,Of(h))}}else this.memberTraits=0;if(s instanceof ui){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=m_(s),LA(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(K_[n])return K_[n]}else if(typeof n==="string"){if(V_[n])return V_[n]}else if(t){if(n[Tf.ns])return n[Tf.ns]}let i=m_(n);if(i instanceof ui)return i;if(nw(i)){let[s,f]=i;if(s instanceof ui)return Object.assign(s.getMergedTraits(),Of(f)),s;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(n,null,2)}.`)}let r=new ui(i);if(t)return n[Tf.ns]=r;if(typeof i==="string")return V_[i]=r;if(typeof i==="number")return K_[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 Of(this.memberTraits)}getOwnTraits(){return Of(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 ef([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 ef([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 ef(nw(r)?r:[r,0],n)}if(this.isDocumentSchema())return ef([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[Tf.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=ef([n[5][r],0],s);yield i[r]=[s,f]}n[Tf.it]=i}}function ef(n,t){if(n instanceof ui)return Object.assign(n,{memberName:t,_isMemberSchema:!0});return new ui(n,t)}var nw=(n)=>Array.isArray(n)&&n.length===2,LA=(n)=>Array.isArray(n)&&n.length>=5;class If extends Zn{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=If.symbol}var Xg=(n,t,i,r)=>Zn.assign(new If,{name:t,namespace:n,traits:r,schemaRef:i}),Cg=(n,t,i,r)=>Zn.assign(new If,{name:t,namespace:n,traits:i,schemaRef:r}),Jg={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 di{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(!di.registries.has(n))di.registries.set(n,new di(n));return di.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,di.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,di.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 di.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}}Qg.ErrorSchema=k_;Qg.ListSchema=x_;Qg.MapSchema=j_;Qg.NormalizedSchema=ui;Qg.OperationSchema=q_;Qg.SCHEMA=Jg;Qg.Schema=Zn;Qg.SimpleSchema=If;Qg.StructureSchema=Lf;Qg.TypeRegistry=di;Qg.deref=m_;Qg.deserializerMiddlewareOption=eA;Qg.error=Pg;Qg.getSchemaSerdePlugin=Gg;Qg.isStaticSchema=LA;Qg.list=Hg;Qg.map=Wg;Qg.op=Fg;Qg.operation=tw;Qg.serializerMiddlewareOption=OA;Qg.sim=Xg;Qg.simAdapter=Cg;Qg.simpleSchemaCacheN=K_;Qg.simpleSchemaCacheS=V_;Qg.struct=Yg;Qg.traitsCache=z_;Qg.translateTraits=Of});var yi=rn((q5)=>{var{getSmithyContext:R5,normalizeProvider:M5}=Vt();q5.getSmithyContext=R5;q5.normalizeProvider=M5;var{SMITHY_CONTEXT_KEY:E5,AlgorithmId:Z_}=yr();q5.AlgorithmId=Z_;var{NormalizedSchema:T5}=Yi(),Ar=(n,t)=>{let i=[];if(n)i.push(n);if(t)for(let r of t)i.push(r);return i},Pi=(n,t)=>{return`${n||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`},gf=()=>{let n=[],t=[],i=!1,r=new Set,s=(d)=>d.sort((u,y)=>IA[y.step]-IA[u.step]||gA[y.priority||"normal"]-gA[u.priority||"normal"]),f=(d)=>{let u=!1,y=(R)=>{let M=Ar(R.name,R.aliases);if(M.includes(d)){u=!0;for(let E of M)r.delete(E);return!1}return!0};return n=n.filter(y),t=t.filter(y),u},h=(d)=>{let u=!1,y=(R)=>{if(R.middleware===d){u=!0;for(let M of Ar(R.name,R.aliases))r.delete(M);return!1}return!0};return n=n.filter(y),t=t.filter(y),u},_=(d)=>{return n.forEach((u)=>{d.add(u.middleware,{...u})}),t.forEach((u)=>{d.addRelativeTo(u.middleware,{...u})}),d.identifyOnResolve?.(c.identifyOnResolve()),d},o=(d)=>{let u=[];return d.before.forEach((y)=>{if(y.before.length===0&&y.after.length===0)u.push(y);else u.push(...o(y))}),u.push(d),d.after.reverse().forEach((y)=>{if(y.before.length===0&&y.after.length===0)u.push(y);else u.push(...o(y))}),u},w=(d=!1)=>{let u=[],y=[],R={};return n.forEach((E)=>{let T={...E,before:[],after:[]};for(let O of Ar(T.name,T.aliases))R[O]=T;u.push(T)}),t.forEach((E)=>{let T={...E,before:[],after:[]};for(let O of Ar(T.name,T.aliases))R[O]=T;y.push(T)}),y.forEach((E)=>{if(E.toMiddleware){let T=R[E.toMiddleware];if(T===void 0){if(d)return;throw Error(`${E.toMiddleware} is not found when adding ${Pi(E.name,E.aliases)} middleware ${E.relation} ${E.toMiddleware}`)}if(E.relation==="after")T.after.push(E);if(E.relation==="before")T.before.push(E)}}),s(u).map(o).reduce((E,T)=>{return E.push(...T),E},[])},c={add:(d,u={})=>{let{name:y,override:R,aliases:M}=u,E={step:"initialize",priority:"normal",middleware:d,...u},T=Ar(y,M);if(T.length>0){if(T.some((O)=>r.has(O))){if(!R)throw Error(`Duplicate middleware name '${Pi(y,M)}'`);for(let O of T){let e=n.findIndex((N)=>N.name===O||N.aliases?.some((l)=>l===O));if(e===-1)continue;let L=n[e];if(L.step!==E.step||E.priority!==L.priority)throw Error(`"${Pi(L.name,L.aliases)}" middleware with ${L.priority} priority in ${L.step} step cannot be overridden by "${Pi(y,M)}" middleware with ${E.priority} priority in ${E.step} step.`);n.splice(e,1)}}for(let O of T)r.add(O)}n.push(E)},addRelativeTo:(d,u)=>{let{name:y,override:R,aliases:M}=u,E={middleware:d,...u},T=Ar(y,M);if(T.length>0){if(T.some((O)=>r.has(O))){if(!R)throw Error(`Duplicate middleware name '${Pi(y,M)}'`);for(let O of T){let e=t.findIndex((N)=>N.name===O||N.aliases?.some((l)=>l===O));if(e===-1)continue;let L=t[e];if(L.toMiddleware!==E.toMiddleware||L.relation!==E.relation)throw Error(`"${Pi(L.name,L.aliases)}" middleware ${L.relation} "${L.toMiddleware}" middleware cannot be overridden by "${Pi(y,M)}" middleware ${E.relation} "${E.toMiddleware}" middleware.`);t.splice(e,1)}}for(let O of T)r.add(O)}t.push(E)},clone:()=>_(gf()),use:(d)=>{d.applyToStack(c)},remove:(d)=>{if(typeof d==="string")return f(d);else return h(d)},removeByTag:(d)=>{let u=!1,y=(R)=>{let{tags:M,name:E,aliases:T}=R;if(M&&M.includes(d)){let O=Ar(E,T);for(let e of O)r.delete(e);return u=!0,!1}return!0};return n=n.filter(y),t=t.filter(y),u},concat:(d)=>{let u=_(gf());return u.use(d),u.identifyOnResolve(i||u.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),u},applyToStack:_,identify:()=>{return w(!0).map((d)=>{let u=d.step??d.relation+" "+d.toMiddleware;return Pi(d.name,d.aliases)+" - "+u})},identifyOnResolve(d){if(typeof d==="boolean")i=d;return i},resolve:(d,u)=>{for(let y of w().map((R)=>R.middleware).reverse())d=y(d,u);if(i)console.log(c.identify());return d}};return c},IA={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gA={high:3,normal:2,low:1},e5=(n)=>()=>{throw Error(n)},O5=(n)=>()=>Promise.reject(n),a_=()=>{let n=new WeakSet;return(t,i)=>{if(typeof i==="object"&&i!==null){if(n.has(i))return"[Circular]";n.add(i)}return i}},L5=(n)=>{return new Promise((t)=>setTimeout(t,n*1000))},SA={minDelay:2,maxDelay:120},xt;(function(n){n.ABORTED="ABORTED",n.FAILURE="FAILURE",n.SUCCESS="SUCCESS",n.RETRY="RETRY",n.TIMEOUT="TIMEOUT"})(xt||(xt={}));var I5=(n)=>{if(n.state===xt.ABORTED){let t=Error(`${JSON.stringify({...n,reason:"Request was aborted"},a_())}`);throw t.name="AbortError",t}else if(n.state===xt.TIMEOUT){let t=Error(`${JSON.stringify({...n,reason:"Waiter has timed out"},a_())}`);throw t.name="TimeoutError",t}else if(n.state!==xt.SUCCESS)throw Error(`${JSON.stringify(n,a_())}`);return n},g5=async({minDelay:n,maxDelay:t,maxWaitTime:i,abortController:r,client:s,abortSignal:f},h,_)=>{let o={},[w,c]=[n*1000,t*1000],d=0,u=Date.now()+i*1000,y=Date.now()+60000,R=!1;while(!0){if(d>0){let T=S5(w,c,d,u);if(r?.signal?.aborted||f?.aborted)return o["AbortController signal aborted."]|=0,o["AbortController signal aborted."]+=1,{state:xt.ABORTED,observedResponses:o};if(Date.now()+T>u)return{state:xt.TIMEOUT,observedResponses:o};await L5(T/1000)}let{state:M,reason:E}=await _(s,h);if(E){let T=b5(E);o[T]|=0,o[T]+=1}if(M!==xt.RETRY)return{state:M,reason:E,final:E,observedResponses:o};if(d+=1,!R&&Date.now()>=y)N5(o,s),R=!0}},N5=(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.")},b5=(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,a_())??"Unknown")},S5=(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),_=l5(n,h);if(Date.now()+_>r){let o=r-Date.now();return Math.max(0,o-500)}return _},l5=(n,t)=>n+Math.random()*(t-n),$5=(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`)},NA=(n)=>{let t,i=new Promise((r)=>{if(t=()=>r({state:xt.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}},U5=async(n,t,i)=>{let r={...SA,...n};$5(r);let s=[g5(r,t,i)],f=[];if(n.abortSignal){let{aborted:h,clearListener:_}=NA(n.abortSignal);f.push(_),s.push(h)}if(n.abortController?.signal){let{aborted:h,clearListener:_}=NA(n.abortController.signal);f.push(_),s.push(h)}return Promise.race(s).then((h)=>{for(let _ of f)_();return h})};class lA{config;middlewareStack=gf();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 iw="***SensitiveInformation***";function v_(n,t){if(t==null)return t;let i=T5.of(n);if(i.getMergedTraits().sensitive)return iw;if(i.isListSchema()){if(!!i.getValueSchema().getMergedTraits().sensitive)return iw}else if(i.isMapSchema()){if(!!i.getKeySchema().getMergedTraits().sensitive||!!i.getValueSchema().getMergedTraits().sensitive)return iw}else if(i.isStructSchema()&&typeof t==="object"){let r=t,s={};for(let[f,h]of i.structIterator())if(r[f]!=null)s[f]=v_(h,r[f]);return s}return t}class p_{middlewareStack=gf();schema;static classBuilder(){return new $A}resolveMiddlewareWithContext(n,t,i,{middlewareFn:r,clientName:s,commandName:f,inputFilterSensitiveLog:h,outputFilterSensitiveLog:_,smithyContext:o,additionalContext:w,CommandCtor:c}){for(let E of r.bind(this)(c,n,t,i))this.middlewareStack.use(E);let d=n.concat(this.middlewareStack),{logger:u}=t,y={logger:u,clientName:s,commandName:f,inputFilterSensitiveLog:h,outputFilterSensitiveLog:_,[E5]:{commandInstance:this,...o},...w},{requestHandler:R}=t,M=i??{};if(o.eventStream)M={isEventStream:!0,...M};return d.resolve((E)=>R.handle(E.request,M),y)}}class $A{_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 p_{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?v_.bind(null,h):(o)=>o),outputFilterSensitiveLog:n._outputFilterSensitiveLog??(f?v_.bind(null,_):(o)=>o),smithyContext:n._smithyContext,additionalContext:n._additionalContext})}serialize=n._serializer;deserialize=n._deserializer}}}var D5="***SensitiveInformation***",B5=(n,t,i)=>{for(let[f,h]of Object.entries(n)){let _=async function(w,c,d){let u=new h(w);if(typeof c==="function")this.send(u,c);else if(typeof d==="function"){if(typeof c!=="object")throw Error(`Expected http options but got ${typeof c}`);this.send(u,c||{},d)}else return this.send(u,c)},o=(f[0].toLowerCase()+f.slice(1)).replace(/Command$/,"");t.prototype[o]=_}let{paginators:r={},waiters:s={}}=i??{};for(let[f,h]of Object.entries(r))if(t.prototype[f]===void 0)t.prototype[f]=function(_={},o,...w){return h({...o,client:this},_,...w)};for(let[f,h]of Object.entries(s))if(t.prototype[f]===void 0)t.prototype[f]=async function(_={},o,...w){let c=o;if(typeof o==="number")c={maxWaitTime:o};return h({...c,client:this},_,...w)}};class ws 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 ws.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===ws)return ws.isInstance(n);if(ws.isInstance(n)){if(t.name&&this.name)return this.prototype.isPrototypeOf(n)||t.name===this.name;return this.prototype.isPrototypeOf(n)}return!1}}var UA=(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},DA=({output:n,parsedBody:t,exceptionCtor:i,errorCode:r})=>{let s=H5(n),f=s.httpStatusCode?s.httpStatusCode+"":void 0,h=new i({name:t?.code||t?.Code||r||f||"UnknownError",$fault:"client",$metadata:s});throw UA(h,t)},G5=(n)=>{return({output:t,parsedBody:i,errorCode:r})=>{DA({output:t,parsedBody:i,exceptionCtor:n,errorCode:r})}},H5=(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"]}),W5=(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{}}},bA=!1,F5=(n)=>{if(n&&!bA&&parseInt(n.substring(1,n.indexOf(".")))<16)bA=!0},BA=Object.values(Z_),GA=(n)=>{let t=[];for(let i in Z_){let r=Z_[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(BA.includes(r))n.checksumAlgorithms[r.toUpperCase()]=s;else n.checksumAlgorithms[r]=s;t.push(i)},checksumAlgorithms(){return t}}},HA=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{let r=i.algorithmId();if(BA.includes(r))t[r]=i.checksumConstructor()}),t},WA=(n)=>{return{setRetryStrategy(t){n.retryStrategy=t},retryStrategy(){return n.retryStrategy}}},FA=(n)=>{let t={};return t.retryStrategy=n.retryStrategy(),t},YA=(n)=>{return Object.assign(GA(n),WA(n))},Y5=YA,P5=(n)=>{return Object.assign(HA(n),FA(n))},X5=(n)=>Array.isArray(n)?n:[n],PA=(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]=PA(n[i]);return n},C5=(n)=>{return n!=null};class XA{trace(){}debug(){}info(){}warn(){}error(){}}function CA(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,m5(r,s,f);else f=t;for(let h of Object.keys(f)){if(!Array.isArray(f[h])){r[h]=f[h];continue}JA(r,null,f,h)}return r}var J5=(n)=>{let t={};for(let[i,r]of Object.entries(n||{}))t[i]=[,r];return t},Q5=(n,t)=>{let i={};for(let r in t)JA(i,n,t,r);return i},m5=(n,t,i)=>{return CA(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},{}))},JA=(n,t,i,r)=>{if(t!==null){let h=i[r];if(typeof h==="function")h=[,h];let[_=z5,o=K5,w=r]=h;if(typeof _==="function"&&_(t[w])||typeof _!=="function"&&!!_)n[r]=o(t[w]);return}let[s,f]=i[r];if(typeof f==="function"){let h,_=s===void 0&&(h=f())!=null,o=typeof s==="function"&&!!s(void 0)||typeof s!=="function"&&!!s;if(_)n[r]=h;else if(o)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}},z5=(n)=>n!=null,K5=(n)=>n,V5=(n)=>{if(n!==n)return"NaN";switch(n){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return n}},x5=(n)=>n.toISOString().replace(".000Z","Z"),rw=(n)=>{if(n==null)return{};if(Array.isArray(n))return n.filter((t)=>t!=null).map(rw);if(typeof n==="object"){let t={};for(let i of Object.keys(n)){if(n[i]==null)continue;t[i]=rw(n[i])}return t}return n};function j5(n,t,i,r){return function(f,h,_,o,w={}){let c=Object.assign({},n,f);return p_.classBuilder().ep(c).m(function(d,u,y,R){let M=h.call(this,d,u,y,R);return M.unshift(r(y,d.getEndpointParameterInstructions())),M}).s(t,_,w).n(i,_.charAt(0).toUpperCase()+_.slice(1)+"Command").sc(o).build()}}q5.Client=lA;q5.Command=p_;q5.NoOpLogger=XA;q5.SENSITIVE_STRING=D5;q5.ServiceException=ws;q5.WaiterState=xt;q5._json=rw;q5.checkExceptions=I5;q5.constructStack=gf;q5.convertMap=J5;q5.createAggregatedClient=B5;q5.createWaiter=U5;q5.decorateServiceException=UA;q5.emitWarningIfUnsupportedVersion=F5;q5.getArrayIfSingleItem=X5;q5.getChecksumConfiguration=GA;q5.getDefaultClientConfiguration=Y5;q5.getDefaultExtensionConfiguration=YA;q5.getRetryConfiguration=WA;q5.getValueFromTextNode=PA;q5.invalidFunction=e5;q5.invalidProvider=O5;q5.isSerializableHeaderValue=C5;q5.loadConfigsForDefaultMode=W5;q5.makeBuilder=j5;q5.map=CA;q5.resolveChecksumRuntimeConfig=HA;q5.resolveDefaultRuntimeConfig=P5;q5.resolveRetryRuntimeConfig=FA;q5.schemaLogFilter=v_;q5.serializeDateTime=x5;q5.serializeFloat=V5;q5.take=Q5;q5.throwDefaultError=DA;q5.waiterServiceDefaults=SA;q5.withBaseException=G5});var vn=rn((Wb)=>{var{homedir:WN}=dn("os"),{sep:FN,join:Nf}=dn("path"),{createHash:YN}=dn("crypto"),{readFile:kA}=dn("fs/promises"),{IniSectionType:nh}=yr(),{normalizeProvider:th}=yi(),{isValidHostLabel:PN}=Vt();class cs 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,cs.prototype),i?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class bf extends cs{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,bf.prototype)}}class ow extends cs{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ow.prototype)}}var aA=(...n)=>async()=>{if(n.length===0)throw new cs("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},ZA=(n)=>()=>Promise.resolve(n),ww=(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(o)=>{if(!f||o?.forceRefresh)r=await _();return r};return async(o)=>{if(!f||o?.forceRefresh)r=await _();if(h)return r;if(i&&!i(r))return h=!0,r;if(t(r))return await _(),r;return r}},Ai=(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]}.`)},XN=(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},Ut;(function(n){n.ENV="env",n.CONFIG="shared config entry"})(Ut||(Ut={}));var sw={},CN=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Sf=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:i,HOMEDRIVE:r=`C:${FN}`}=process.env;if(n)return n;if(t)return t;if(i)return`${r}${i}`;let s=CN();if(!sw[s])sw[s]=WN();return sw[s]},vA="AWS_PROFILE",pA="default",nR=(n)=>n.profile||process.env[vA]||pA,tR=(n)=>{let i=YN("sha1").update(n).digest("hex");return Nf(Sf(),".aws","sso","cache",`${i}.json`)},ih={},JN=async(n)=>{if(ih[n])return ih[n];let t=tR(n),i=await kA(t,"utf8");return JSON.parse(i)},Rr=".",QN=(n)=>Object.entries(n).filter(([t])=>{let i=t.indexOf(Rr);if(i===-1)return!1;return Object.values(nh).includes(t.substring(0,i))}).reduce((t,[i,r])=>{let s=i.indexOf(Rr),f=i.substring(0,s)===nh.PROFILE?i.substring(s+1):i;return t[f]=r,t},{...n.default&&{default:n.default}}),mN="AWS_CONFIG_FILE",iR=()=>process.env[mN]||Nf(Sf(),".aws","config"),zN="AWS_SHARED_CREDENTIALS_FILE",KN=()=>process.env[zN]||Nf(Sf(),".aws","credentials"),VN=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,xN=["__proto__","profile __proto__"],_w=(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),o=VN.exec(_);if(o){let[,w,,c]=o;if(Object.values(nh).includes(w))i=[w,c].join(Rr)}else i=_;if(xN.includes(_))throw Error(`Found invalid profile name "${_}"`)}else if(i){let _=f.indexOf("=");if(![0,-1].includes(_)){let[o,w]=[f.substring(0,_).trim(),f.substring(_+1).trim()];if(w==="")r=o;else{if(r&&s.trimStart()===s)r=void 0;t[i]=t[i]||{};let c=r?[r,o].join(Rr):o;t[i][c]=w}}}}return t},fw={},rh={},sh=(n,t)=>{if(rh[n]!==void 0)return rh[n];if(!fw[n]||t?.ignoreCache)fw[n]=kA(n,"utf8");return fw[n]},QA=()=>({}),cw=async(n={})=>{let{filepath:t=KN(),configFilepath:i=iR()}=n,r=Sf(),s="~/",f=t;if(t.startsWith("~/"))f=Nf(r,t.slice(2));let h=i;if(i.startsWith("~/"))h=Nf(r,i.slice(2));let _=await Promise.all([sh(h,{ignoreCache:n.ignoreCache}).then(_w).then(QN).catch(QA),sh(f,{ignoreCache:n.ignoreCache}).then(_w).catch(QA)]);return{configFile:_[0],credentialsFile:_[1]}},jN=(n)=>Object.entries(n).filter(([t])=>t.startsWith(nh.SSO_SESSION+Rr)).reduce((t,[i,r])=>({...t,[i.substring(i.indexOf(Rr)+1)]:r}),{}),qN=()=>({}),kN=async(n={})=>sh(n.configFilepath??iR()).then(_w).then(jN).catch(qN),aN=(...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},ZN=async(n)=>{let t=await cw(n);return aN(t.configFile,t.credentialsFile)},vN={getFileRecord(){return rh},interceptFile(n,t){rh[n]=Promise.resolve(t)},getTokenRecord(){return ih},interceptToken(n,t){ih[n]=t}};function rR(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 pN=(n,t)=>async()=>{try{let i=n(process.env,t);if(i===void 0)throw Error();return i}catch(i){throw new bf(i.message||`Not found in ENV: ${rR(n.toString())}`,{logger:t?.logger})}},nb=(n,{preferredFile:t="config",...i}={})=>async()=>{let r=nR(i),{configFile:s,credentialsFile:f}=await cw(i),h=f[r]||{},_=s[r]||{},o=t==="config"?{...h,..._}:{..._,...h};try{let c=n(o,t==="config"?s:f);if(c===void 0)throw Error();return c}catch(w){throw new bf(w.message||`Not found in config files w/ profile [${r}]: ${rR(n.toString())}`,{logger:i.logger})}},tb=(n)=>typeof n==="function",sR=(n)=>tb(n)?async()=>await n():ZA(n),hw=({environmentVariableSelector:n,configFileSelector:t,default:i},r={})=>{let{signingName:s,logger:f}=r;return ww(aA(pN(n,{signingName:s,logger:f}),nb(t,r),sR(i)))},dw="AWS_USE_DUALSTACK_ENDPOINT",uw="use_dualstack_endpoint",ib=!1,rb={environmentVariableSelector:(n)=>Ai(n,dw,Ut.ENV),configFileSelector:(n)=>Ai(n,uw,Ut.CONFIG),default:!1},sb={environmentVariableSelector:(n)=>Ai(n,dw,Ut.ENV),configFileSelector:(n)=>Ai(n,uw,Ut.CONFIG),default:void 0},yw="AWS_USE_FIPS_ENDPOINT",Aw="use_fips_endpoint",fb=!1,_b={environmentVariableSelector:(n)=>Ai(n,yw,Ut.ENV),configFileSelector:(n)=>Ai(n,Aw,Ut.CONFIG),default:!1},hb={environmentVariableSelector:(n)=>Ai(n,yw,Ut.ENV),configFileSelector:(n)=>Ai(n,Aw,Ut.CONFIG),default:void 0},ob=(n)=>{let{tls:t,endpoint:i,urlParser:r,useDualstackEndpoint:s}=n;return Object.assign(n,{tls:t??!0,endpoint:th(typeof i==="string"?r(i):i),isCustomEndpoint:!0,useDualstackEndpoint:th(s??!1)})},wb=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}`)},cb=(n)=>{let t=th(n.useDualstackEndpoint??!1),{endpoint:i,useFipsEndpoint:r,urlParser:s,tls:f}=n;return Object.assign(n,{tls:f??!0,endpoint:i?th(typeof i==="string"?s(i):i):()=>wb({...n,useDualstackEndpoint:t,useFipsEndpoint:r}),isCustomEndpoint:!!i,useDualstackEndpoint:t})},db="AWS_EXECUTION_ENV",mA="AWS_REGION",zA="AWS_DEFAULT_REGION",ub="AWS_EC2_METADATA_DISABLED",yb=["in-region","cross-region","mobile","standard","legacy"],Ab="/latest/meta-data/placement/region",Rb="/latest/api/token",Mb="x-aws-ec2-metadata-token",Eb="x-aws-ec2-metadata-token-ttl-seconds",KA=1000,Tb=60000,fR=0,_R=async()=>{if(process.env[ub])return;if(Date.now()<fR)return;try{let n=eb(),t=(await xA({...n,path:Rb,method:"PUT",headers:{[Eb]:"21600"}})).toString();return(await xA({...n,path:Ab,method:"GET",headers:{[Mb]:t}})).toString().trim()||VA()}catch{return VA()}},VA=()=>{fR=Date.now()+Tb;return},eb=()=>{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"}},xA=async(n)=>{let{request:t}=dn("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:KA,signal:AbortSignal.timeout(KA)});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",(o)=>_.push(o)),f.on("end",()=>{i(Buffer.concat(_)),s.destroy()})}),s.end()})},hR="AWS_REGION",oR="region",wR={environmentVariableSelector:(n)=>n[hR],configFileSelector:(n)=>n[oR],default:async()=>{let n=await _R();if(n)return n;throw Error("Region is missing")}},Ob={preferredFile:"credentials"},jA=new Set,Lb=(n,t=PN)=>{if(!jA.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 jA.add(n)},cR=(n)=>typeof n==="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),Ib=(n)=>cR(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,gb=(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=Ib(r);return Lb(s),s},useFipsEndpoint:async()=>{let r=typeof t==="string"?t:await t();if(cR(r))return!0;return typeof i!=="function"?Promise.resolve(!!i):i()}})},qA=(n=[],{useFipsEndpoint:t,useDualstackEndpoint:i})=>n.find(({tags:r})=>t===r.includes("fips")&&i===r.includes("dualstack"))?.hostname,Nb=(n,{regionHostname:t,partitionHostname:i})=>t?t:i?i.replace("{region}",n):void 0,bb=(n,{partitionHash:t})=>Object.keys(t||{}).find((i)=>t[i].regions.includes(n))??"aws",Sb=(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)}},lb=(n,{useFipsEndpoint:t=!1,useDualstackEndpoint:i=!1,signingService:r,regionHash:s,partitionHash:f})=>{let h=bb(n,{partitionHash:f}),_=n in s?n:f[h]?.endpoint??n,o={useFipsEndpoint:t,useDualstackEndpoint:i},w=qA(s[_]?.variants,o),c=qA(f[h]?.variants,o),d=Nb(_,{regionHostname:w,partitionHostname:c});if(d===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:_,useFipsEndpoint:t,useDualstackEndpoint:i}}`);let u=Sb(d,{signingRegion:s[_]?.signingRegion,regionRegex:f[h].regionRegex,useFipsEndpoint:t});return{partition:h,signingService:r,hostname:d,...u&&{signingRegion:u},...s[_]?.signingService&&{signingService:s[_].signingService}}},$b="AWS_DEFAULTS_MODE",Ub="defaults_mode",Db={environmentVariableSelector:(n)=>{return n[$b]},configFileSelector:(n)=>{return n[Ub]},default:"legacy"},Bb=({region:n=hw(wR),defaultsMode:t=hw(Db)}={})=>ww(async()=>{let i=typeof t==="function"?await t():t;switch(i?.toLowerCase()){case"auto":return Gb(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 ${yb.join(", ")}, got ${i}`)}}),Gb=async(n)=>{if(n){let t=typeof n==="function"?await n():n,i=await Hb();if(!i)return"standard";if(t===i)return"in-region";else return"cross-region"}return"standard"},Hb=async()=>{if(process.env[db]&&(process.env[mA]||process.env[zA]))return process.env[mA]??process.env[zA];return _R()};Wb.CONFIG_PREFIX_SEPARATOR=Rr;Wb.CONFIG_USE_DUALSTACK_ENDPOINT=uw;Wb.CONFIG_USE_FIPS_ENDPOINT=Aw;Wb.CredentialsProviderError=bf;Wb.DEFAULT_PROFILE=pA;Wb.DEFAULT_USE_DUALSTACK_ENDPOINT=ib;Wb.DEFAULT_USE_FIPS_ENDPOINT=fb;Wb.ENV_PROFILE=vA;Wb.ENV_USE_DUALSTACK_ENDPOINT=dw;Wb.ENV_USE_FIPS_ENDPOINT=yw;Wb.NODE_REGION_CONFIG_FILE_OPTIONS=Ob;Wb.NODE_REGION_CONFIG_OPTIONS=wR;Wb.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=rb;Wb.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=_b;Wb.ProviderError=cs;Wb.REGION_ENV_NAME=hR;Wb.REGION_INI_NAME=oR;Wb.SelectorType=Ut;Wb.TokenProviderError=ow;Wb.booleanSelector=Ai;Wb.chain=aA;Wb.externalDataInterceptor=vN;Wb.fromStatic=sR;Wb.fromValue=ZA;Wb.getHomeDir=Sf;Wb.getProfileName=nR;Wb.getRegionInfo=lb;Wb.getSSOTokenFilepath=tR;Wb.getSSOTokenFromFile=JN;Wb.loadConfig=hw;Wb.loadSharedConfigFiles=cw;Wb.loadSsoSessionData=kN;Wb.memoize=ww;Wb.nodeDualstackConfigSelectors=sb;Wb.nodeFipsConfigSelectors=hb;Wb.numberSelector=XN;Wb.parseKnownFiles=ZN;Wb.readFile=sh;Wb.resolveCustomEndpointsConfig=ob;Wb.resolveDefaultsModeConfig=Bb;Wb.resolveEndpointsConfig=cb;Wb.resolveRegionConfig=gb});var Mr=rn((hl)=>{var{CONFIG_PREFIX_SEPARATOR:dR,loadConfig:gS}=vn(),{toEndpointV1:fh,getSmithyContext:NS,normalizeProvider:Rw,isValidHostLabel:AR}=Vt();hl.isValidHostLabel=AR;hl.middlewareEndpointToEndpointV1=fh;hl.toEndpointV1=fh;var{EndpointURLScheme:Tw}=yr(),uR="AWS_ENDPOINT_URL",yR="endpoint_url",bS=(n)=>({environmentVariableSelector:(t)=>{let i=n.split(" ").map((f)=>f.toUpperCase()),r=t[[uR,...i].join("_")];if(r)return r;let s=t[uR];if(s)return s;return},configFileSelector:(t,i)=>{if(i&&t.services){let s=i[["services",t.services].join(dR)];if(s){let f=n.split(" ").map((_)=>_.toLowerCase()),h=s[[f.join("_"),yR].join(dR)];if(h)return h}}let r=t[yR];if(r)return r;return},default:void 0}),_h=async(n)=>gS(bS(n??""))(),SS=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(BS(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!DS(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},lS=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,$S=/(\d+\.){3}\d+/,US=/\.\./,DS=(n)=>lS.test(n)&&!$S.test(n)&&!US.test(n),BS=(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},GS=(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:o,path:w}=f;return`${h}//${_}${o?":"+o:""}${w}`}}return f};return s};function RR(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(fh(_)),r.isCustomEndpoint=!0}let f=await MR(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[o,w]of Object.entries(_.headers))h.headers[o]=Array.isArray(w)?w:[w]}}return h}}var MR=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 GS(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 SS(r);return r};function HS(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 ER(n){let t=RR(n);return({config:i,instructions:r})=>{return(s,f)=>async(h)=>{if(i.isCustomEndpoint)HS(f,"ENDPOINT_OVERRIDE","N");let _=await t(h.input,{getEndpointParameterInstructions(){return r}},{...i},f);f.endpointV2=_,f.authSchemes=_.properties?.authSchemes;let o=f.authSchemes?.[0];if(o){f.signing_region=o.signingRegion,f.signing_service=o.signingName;let c=NS(f)?.selectedHttpAuthScheme?.httpAuthOption;if(c)c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:o.signingRegion,signingRegion:o.signingRegion,signing_service:o.signingName,signingName:o.signingName,signingRegionSet:o.signingRegionSet},o.properties)}return s({...h})}}}var WS={name:"serializerMiddleware"},TR={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:WS.name};function FS(n){let t=ER(n);return(i,r)=>({applyToStack:(s)=>{s.addRelativeTo(t({config:i,instructions:r}),TR)}})}function YS(n){return(t)=>{let i=t.tls??!0,{endpoint:r,useDualstackEndpoint:s,useFipsEndpoint:f}=t,h=r!=null?async()=>fh(await Rw(r)()):void 0,o=Object.assign(t,{endpoint:h,tls:i,isCustomEndpoint:!!r,useDualstackEndpoint:Rw(s??!1),useFipsEndpoint:Rw(f??!1)}),w=void 0;return o.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!w)w=n(t.serviceId);return w},o}}class ew{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 ew(n,t,i,r)}}class eR{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 Jn extends Error{constructor(n){super(n);this.name="EndpointError"}}var lf="endpoints";function Xi(n){if(typeof n!=="object"||n==null)return n;if("ref"in n)return`$${Xi(n.ref)}`;if("fn"in n)return`${n.fn}(${(n.argv||[]).map(Xi).join(", ")})`;return JSON.stringify(n,null,2)}var OR={},PS=(n,t)=>n===t;function XS(...n){for(let t of n)if(t!=null)return t;return}var CS=(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 Jn(`Path: '${n}' does not end with ']'`);let f=r.slice(s+1,-1);if(Number.isNaN(parseInt(f)))throw new Jn(`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},LR=(n,t)=>CS(t).reduce((i,r)=>{if(typeof i!=="object")throw new Jn(`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),JS=(n)=>n!=null;function QS(n,t,i){return n?t:i}var mS=(n)=>!n,zS=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}$"),IR=(n)=>zS.test(n)||n.startsWith("[")&&n.endsWith("]"),Mw={[Tw.HTTP]:80,[Tw.HTTPS]:443},KS=(n)=>{let t=(()=>{try{if(n instanceof URL)return n;if(typeof n==="object"&&"hostname"in n){let{hostname:u,port:y,protocol:R="",path:M="",query:E={}}=n,T=new URL(`${R}//${u}${y?`:${y}`:""}${M}`);return T.search=Object.entries(E).map(([O,e])=>`${O}=${e}`).join("&"),T}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 o=h.slice(0,-1);if(!Object.values(Tw).includes(o))return null;let w=IR(s),c=i.includes(`${r}:${Mw[o]}`)||typeof n==="string"&&n.includes(`${r}:${Mw[o]}`),d=`${r}${c?`:${Mw[o]}`:""}`;return{scheme:o,authority:d,path:f,normalizedPath:f.endsWith("/")?f:`${f}/`,isIp:w}};function VS(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 xS=(n,t)=>n===t,jS=(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)},qS=(n)=>encodeURIComponent(n).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),kS={booleanEquals:PS,coalesce:XS,getAttr:LR,isSet:JS,isValidHostLabel:AR,ite:QS,not:mS,parseURL:KS,split:VS,stringEquals:xS,substring:jS,uriEncode:qS},gR=(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 o=n.substring(h+1,_);if(o.includes("#")){let[w,c]=o.split("#");i.push(LR(r[w]??s[w],c))}else i.push(r[o]??s[o]);f=_+1}return i.join("")},aS=({ref:n},t)=>{return t.referenceRecord[n]??t.endpointParams[n]},$f=(n,t,i)=>{if(typeof n==="string")return gR(n,i);else if(n.fn)return bR.callFunction(n,i);else if(n.ref)return aS(n,i);throw new Jn(`'${t}': ${String(n)} is not a string, function or reference.`)},NR=({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]=bR.evaluateExpression(_,"arg",i)}let s=n.indexOf(".");if(s!==-1){let _=OR[n.slice(0,s)]?.[n.slice(s+1)];if(typeof _==="function")return _(...r)}let f=kS[n];if(typeof f==="function")return f(...r);throw Error(`function ${n} not loaded in endpointFunctions.`)},bR={evaluateExpression:$f,callFunction:NR},SR=(n,t)=>{let{assign:i}=n;if(i&&i in t.referenceRecord)throw new Jn(`'${i}' is already defined in Reference Record.`);let r=NR(n,t);t.logger?.debug?.(`${lf} evaluateCondition: ${Xi(n)} = ${Xi(r)}`);let s=r===""?!0:!!r;if(i!=null)return{result:s,toAssign:{name:i,value:r}};return{result:s}},lR=(n,t)=>Object.entries(n??{}).reduce((i,[r,s])=>{return i[r]=s.map((f)=>{let h=$f(f,"Header value entry",t);if(typeof h!=="string")throw new Jn(`Header '${r}' value '${h}' is not a string`);return h}),i},{}),Ow=(n,t)=>Object.entries(n).reduce((i,[r,s])=>{return i[r]=UR.getEndpointProperty(s,t),i},{}),$R=(n,t)=>{if(Array.isArray(n))return n.map((i)=>$R(i,t));switch(typeof n){case"string":return gR(n,t);case"object":if(n===null)throw new Jn(`Unexpected endpoint property: ${n}`);return UR.getEndpointProperties(n,t);case"boolean":return n;default:throw new Jn(`Unexpected endpoint property type: ${typeof n}`)}},UR={getEndpointProperty:$R,getEndpointProperties:Ow},DR=(n,t)=>{let i=$f(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 Jn(`Endpoint URL must be a string, got ${typeof i}`)},Ew=1e8,ZS=(n,t)=>{let{nodes:i,root:r,results:s,conditions:f}=n,h=r,_={},o={referenceRecord:_,endpointParams:t.endpointParams,logger:t.logger};while(h!==1&&h!==-1&&h<Ew){let w=3*(Math.abs(h)-1),[c,d,u]=[i[w],i[w+1],i[w+2]],[y,R,M]=f[c],E=SR({fn:y,assign:M,argv:R},o);if(E.toAssign){let{name:T,value:O}=E.toAssign;_[T]=O}h=h>=0===E.result?d:u}if(h>=Ew){let w=s[h-Ew];if(w[0]===-1){let[,y]=w;throw new Jn($f(y,"Error",o))}let[c,d,u]=w;return{url:DR(c,o),properties:Ow(d,o),headers:lR(u??{},o)}}throw new Jn("No matching endpoint.")},Lw=(n=[],t)=>{let i={},r={...t,referenceRecord:{...t.referenceRecord}},s=!1;for(let f of n){let{result:h,toAssign:_}=SR(f,r);if(!h)return{result:h};if(_)s=!0,i[_.name]=_.value,r.referenceRecord[_.name]=_.value,t.logger?.debug?.(`${lf} assign: ${_.name} := ${Xi(_.value)}`)}if(s)return{result:!0,referenceRecord:i};return{result:!0}},vS=(n,t)=>{let{conditions:i,endpoint:r}=n,{result:s,referenceRecord:f}=Lw(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t,{url:_,properties:o,headers:w}=r;t.logger?.debug?.(`${lf} Resolving endpoint from template: ${Xi(r)}`);let c={url:DR(_,h)};if(w!=null)c.headers=lR(w,h);if(o!=null)c.properties=Ow(o,h);return c},pS=(n,t)=>{let{conditions:i,error:r}=n,{result:s,referenceRecord:f}=Lw(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;throw new Jn($f(r,"Error",h))},BR=(n,t)=>{for(let i of n)if(i.type==="endpoint"){let r=vS(i,t);if(r)return r}else if(i.type==="error")pS(i,t);else if(i.type==="tree"){let r=GR.evaluateTreeRule(i,t);if(r)return r}else throw new Jn(`Unknown endpoint rule: ${i}`);throw new Jn("Rules evaluation failed")},nl=(n,t)=>{let{conditions:i,rules:r}=n,{result:s,referenceRecord:f}=Lw(i,t);if(!s)return;let h=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;return GR.evaluateRules(r,h)},GR={evaluateRules:BR,evaluateTreeRule:nl},tl=(n,t)=>{let{endpointParams:i,logger:r}=t,{parameters:s,rules:f}=n;t.logger?.debug?.(`${lf} Initial EndpointParams: ${Xi(i)}`);for(let _ in s){let o=s[_],w=i[_];if(w==null&&o.default!=null){i[_]=o.default;continue}if(o.required&&w==null)throw new Jn(`Missing required parameter: '${_}'`)}let h=BR(f,{endpointParams:i,logger:r,referenceRecord:{}});return t.logger?.debug?.(`${lf} Resolved endpoint: ${Xi(h)}`),h},il=(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},rl=RR(_h),sl=YS(_h),fl=ER(_h),_l=FS(_h);hl.BinaryDecisionDiagram=ew;hl.EndpointCache=eR;hl.EndpointError=Jn;hl.customEndpointFunctions=OR;hl.decideEndpoint=ZS;hl.endpointMiddleware=fl;hl.endpointMiddlewareOptions=TR;hl.getEndpointFromInstructions=rl;hl.getEndpointPlugin=_l;hl.isIpAddress=IR;hl.resolveEndpoint=tl;hl.resolveEndpointConfig=sl;hl.resolveEndpointRequiredConfig=il;hl.resolveParams=MR});var pn=rn((p$)=>{var{createHmac:bl,createHash:Sl,getRandomValues:ll}=dn("crypto"),{ReadStream:$l,lstatSync:Ul,fstatSync:Dl}=dn("fs"),{HttpResponse:Bl}=Vt(),{toEndpointV1:Gl}=Mr(),{Readable:ds,Writable:JR,PassThrough:HR}=dn("stream"),QR=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",ys=(n,t=0,i=n.byteLength-t)=>{if(!QR(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return Buffer.from(n,t,i)},ch=(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)},Hl=/^[A-Za-z0-9+/]*={0,2}$/,mR=(n)=>{if(n.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!Hl.exec(n))throw TypeError("Invalid base64 string.");let t=ch(n,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},dh=(n)=>{let t=ch(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Uw=(n)=>{let t;if(typeof n==="string")t=dh(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 ys(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function Wl(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 zR=(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 ys(n.buffer,n.byteOffset,n.byteLength).toString("utf8")},xn=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function Fl(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,xn[t[0]]+xn[t[1]]+xn[t[2]]+xn[t[3]]+"-"+xn[t[4]]+xn[t[5]]+"-"+xn[t[6]]+xn[t[7]]+"-"+xn[t[8]]+xn[t[9]]+"-"+xn[t[10]]+xn[t[11]]+xn[t[12]]+xn[t[13]]+xn[t[14]]+xn[t[15]]}}var Yl=(n,t,i=(r)=>r)=>n,Pl=(n)=>{switch(n){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${n}"`)}},Xl=(n)=>{if(n===null||n===void 0)return;if(typeof n==="number"){if(n===0||n===1)Gf.warn(oh(`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")Gf.warn(oh(`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}`)},Df=(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))Gf.warn(oh(`Expected number but observed string: ${n}`));return t}}if(typeof n==="number")return n;throw TypeError(`Expected number, got ${typeof n}: ${n}`)},Cl=Math.ceil(340282346638528860000000000000000000000),hh=(n)=>{let t=Df(n);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>Cl)throw TypeError(`Expected 32-bit float, got ${n}`)}return t},Bf=(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}`)},Jl=Bf,bw=(n)=>Dw(n,32),Sw=(n)=>Dw(n,16),lw=(n)=>Dw(n,8),Dw=(n,t)=>{let i=Bf(n);if(i!==void 0&&Ql(i,t)!==i)throw TypeError(`Expected ${t}-bit integer, got ${n}`);return i},Ql=(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]}},ml=(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},KR=(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}`)},zl=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string")return n;if(["boolean","number","bigint"].includes(typeof n))return Gf.warn(oh(`Expected string, got ${typeof n}: ${n}`)),String(n);throw TypeError(`Expected string, got ${typeof n}: ${n}`)},Kl=(n)=>{if(n===null||n===void 0)return;let t=KR(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},Bw=(n)=>{if(typeof n=="string")return Df(Ms(n));return Df(n)},Vl=Bw,VR=(n)=>{if(typeof n=="string")return hh(Ms(n));return hh(n)},xl=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ms=(n)=>{let t=n.match(xl);if(t===null||t[0].length!==n.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(n)},Gw=(n)=>{if(typeof n=="string")return xR(n);return Df(n)},jl=Gw,ql=Gw,kl=(n)=>{if(typeof n=="string")return xR(n);return hh(n)},xR=(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}`)}},jR=(n)=>{if(typeof n==="string")return Bf(Ms(n));return Bf(n)},al=jR,Zl=(n)=>{if(typeof n==="string")return bw(Ms(n));return bw(n)},As=(n)=>{if(typeof n==="string")return Sw(Ms(n));return Sw(n)},qR=(n)=>{if(typeof n==="string")return lw(Ms(n));return lw(n)},oh=(n)=>{return String(TypeError(n).stack||n).split(`
|
|
6
|
+
`+f),n.push(s+"m+"+ao.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=MI()+t+" "+n[0]}function MI(){if(Ww.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function EI(...n){return process.stderr.write(Qo.formatWithOptions(Ww.inspectOpts,...n)+`
|
|
7
|
+
`)}function lI(n){if(n)process.env.DEBUG=n;else delete process.env.DEBUG}function TI(){return process.env.DEBUG}function gI(n){n.inspectOpts={};let t=Object.keys(Ww.inspectOpts);for(let i=0;i<t.length;i++)n.inspectOpts[t[i]]=Ww.inspectOpts[t[i]]}ao.exports=m0()(Ww);var{formatters:Hw}=ao.exports;Hw.o=function(n){return this.inspectOpts.colors=this.useColors,Qo.inspect(n,this.inspectOpts).split(`
|
|
8
|
+
`).map((t)=>t.trim()).join(" ")};Hw.O=function(n){return this.inspectOpts.colors=this.useColors,Qo.inspect(n,this.inspectOpts)}});var W0=sn((wj,H0)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)H0.exports=mw();else H0.exports=Cw()});var Mr=sn((G8)=>{var oe;(function(n){n.HEADER="header",n.QUERY="query"})(oe||(oe={}));var _e;(function(n){n.HEADER="header",n.QUERY="query"})(_e||(_e={}));var he;(function(n){n.HTTP="http",n.HTTPS="https"})(he||(he={}));var Nf;(function(n){n.MD5="md5",n.CRC32="crc32",n.CRC32C="crc32c",n.SHA1="sha1",n.SHA256="sha256"})(Nf||(Nf={}));var N8=(n)=>{let t=[];if(n.sha256!==void 0)t.push({algorithmId:()=>Nf.SHA256,checksumConstructor:()=>n.sha256});if(n.md5!=null)t.push({algorithmId:()=>Nf.MD5,checksumConstructor:()=>n.md5});return{addChecksumAlgorithm(i){t.push(i)},checksumAlgorithms(){return t}}},U8=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{t[i.algorithmId()]=i.checksumConstructor()}),t},$8=(n)=>{return N8(n)},D8=(n)=>{return U8(n)},ee;(function(n){n[n.HEADER=0]="HEADER",n[n.TRAILER=1]="TRAILER"})(ee||(ee={}));var B8="__smithy_context",ce;(function(n){n.PROFILE="profile",n.SSO_SESSION="sso-session",n.SERVICES="services"})(ce||(ce={}));var de;(function(n){n.HTTP_0_9="http/0.9",n.HTTP_1_0="http/1.0",n.TDS_8_0="tds/8.0"})(de||(de={}));G8.AlgorithmId=Nf;G8.EndpointURLScheme=he;G8.FieldPosition=ee;G8.HttpApiKeyAuthLocation=_e;G8.HttpAuthLocation=oe;G8.IniSectionType=ce;G8.RequestHandlerProtocol=de;G8.SMITHY_CONTEXT_KEY=B8;G8.getDefaultClientConfiguration=$8;G8.resolveDefaultRuntimeConfig=D8});var qt=sn((q8)=>{var{SMITHY_CONTEXT_KEY:Dy}=Mr(),a8=(n)=>n[Dy]||(n[Dy]={});class po{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 po({...n,headers:{...n.headers}});if(t.query)t.query=z8(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 po.clone(this)}}function z8(n){return Object.keys(n).reduce((t,i)=>{let r=n[i];return{...t,[i]:Array.isArray(r)?[...r]:r}},{})}class By{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 K8=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Gy=(n,t=!1)=>{if(!t)return K8.test(n);let i=n.split(".");for(let r of i)if(!Gy(r))return!1;return!0};function x8(n){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(n)}var V8=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t};function my(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 n_=(n)=>{if(typeof n==="string")return n_(new URL(n));let{hostname:t,pathname:i,port:r,protocol:s,search:f}=n,_;if(f)_=my(f);return{hostname:t,port:r?parseInt(r):void 0,protocol:s,path:i,query:_}},j8=(n)=>{if(typeof n==="object"){if("url"in n){let t=n_(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 n_(n)};q8.HttpRequest=po;q8.HttpResponse=By;q8.getSmithyContext=a8;q8.isValidHostLabel=Gy;q8.isValidHostname=x8;q8.normalizeProvider=V8;q8.parseQueryString=my;q8.parseUrl=n_;q8.toEndpointV1=j8});var Ji=sn((E6)=>{var{getSmithyContext:Hy,HttpResponse:f6,toEndpointV1:o6}=qt(),t_=(n)=>{if(typeof n==="function")return n();return n},ye=(n,t,i,r,s)=>({name:t,namespace:n,traits:i,input:r,output:s}),_6=(n)=>(t,i)=>async(r)=>{let{response:s}=await t(r),{operationSchema:f}=Hy(i),[,_,o,h,e,c]=f??[];try{let d=await n.protocol.deserializeResponse(ye(_,o,h,e,c),{...n,...i},s);return{response:s,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:s,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in d)){try{d.message+=`
|
|
9
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){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 d.$responseBodyText<"u"){if(d.$response)d.$response.body=d.$responseBodyText}try{if(f6.isInstance(s)){let{headers:w={},statusCode:A}=s,R=Object.entries(w);d.$metadata={httpStatusCode:A,requestId:ue(/^x-[\w-]+-request-?id$/,R),extendedRequestId:ue(/^x-[\w-]+-id-2$/,R),cfId:ue(/^x-[\w-]+-cf-id$/,R)}}}catch(w){}}throw d}},ue=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},h6=(n)=>(t,i)=>async(r)=>{let{operationSchema:s}=Hy(i),[,f,_,o,h,e]=s??[],c=i.endpointV2?async()=>o6(i.endpointV2):n.endpoint,d=await n.protocol.serializeRequest(ye(f,_,o,h,e),r.input,{...n,...i,endpoint:c});return t({...r,request:d})},Wy={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},Fy={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function e6(n){return{applyToStack:(t)=>{t.add(h6(n),Fy),t.add(_6(n),Wy),n.protocol.setSerdeContext(n)}}}class pn{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 f_ extends pn{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=f_.symbol}var c6=(n,t,i,r)=>pn.assign(new f_,{name:t,namespace:n,traits:i,valueSchema:r});class o_ extends pn{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=o_.symbol}var d6=(n,t,i,r,s)=>pn.assign(new o_,{name:t,namespace:n,traits:i,keySchema:r,valueSchema:s});class __ extends pn{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=__.symbol}var u6=(n,t,i,r,s)=>pn.assign(new __,{name:t,namespace:n,traits:i,input:r,output:s});class Bf extends pn{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Bf.symbol}var w6=(n,t,i,r,s)=>pn.assign(new Bf,{name:t,namespace:n,traits:i,memberNames:r,memberList:s});class h_ extends Bf{static symbol=Symbol.for("@smithy/err");ctor;symbol=h_.symbol}var y6=(n,t,i,r,s,f)=>pn.assign(new h_,{name:t,namespace:n,traits:i,memberNames:r,memberList:s,ctor:null}),i_=[];function Df(n){if(typeof n==="object")return n;if(n=n|0,i_[n])return i_[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 i_[n]=t}var Uf={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},r_=[],s_={};class Mi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=Mi.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(we(r))i.push(r[1]),r=r[0],s=t_(r),this._isMemberSchema=!0;if(i.length>0){this.memberTraits={};for(let f=i.length-1;f>=0;--f){let _=i[f];Object.assign(this.memberTraits,Df(_))}}else this.memberTraits=0;if(s instanceof Mi){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=t_(s),Cy(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(r_[n])return r_[n]}else if(typeof n==="string"){if(s_[n])return s_[n]}else if(t){if(n[Uf.ns])return n[Uf.ns]}let i=t_(n);if(i instanceof Mi)return i;if(we(i)){let[s,f]=i;if(s instanceof Mi)return Object.assign(s.getMergedTraits(),Df(f)),s;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(n,null,2)}.`)}let r=new Mi(i);if(t)return n[Uf.ns]=r;if(typeof i==="string")return s_[i]=r;if(typeof i==="number")return r_[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 Df(this.memberTraits)}getOwnTraits(){return Df(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 $f([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 $f([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 $f(we(r)?r:[r,0],n)}if(this.isDocumentSchema())return $f([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[Uf.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=$f([n[5][r],0],s);yield i[r]=[s,f]}n[Uf.it]=i}}function $f(n,t){if(n instanceof Mi)return Object.assign(n,{memberName:t,_isMemberSchema:!0});return new Mi(n,t)}var we=(n)=>Array.isArray(n)&&n.length===2,Cy=(n)=>Array.isArray(n)&&n.length>=5;class Gf extends pn{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Gf.symbol}var A6=(n,t,i,r)=>pn.assign(new Gf,{name:t,namespace:n,traits:r,schemaRef:i}),R6=(n,t,i,r)=>pn.assign(new Gf,{name:t,namespace:n,traits:i,schemaRef:r}),M6={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 Ri{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(!Ri.registries.has(n))Ri.registries.set(n,new Ri(n));return Ri.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,Ri.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,Ri.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 Ri.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}}E6.ErrorSchema=h_;E6.ListSchema=f_;E6.MapSchema=o_;E6.NormalizedSchema=Mi;E6.OperationSchema=__;E6.SCHEMA=M6;E6.Schema=pn;E6.SimpleSchema=Gf;E6.StructureSchema=Bf;E6.TypeRegistry=Ri;E6.deref=t_;E6.deserializerMiddlewareOption=Wy;E6.error=y6;E6.getSchemaSerdePlugin=e6;E6.isStaticSchema=Cy;E6.list=c6;E6.map=d6;E6.op=u6;E6.operation=ye;E6.serializerMiddlewareOption=Fy;E6.sim=A6;E6.simAdapter=R6;E6.simpleSchemaCacheN=r_;E6.simpleSchemaCacheS=s_;E6.struct=w6;E6.traitsCache=i_;E6.translateTraits=Df});var Ei=sn((SS)=>{var{getSmithyContext:x6,normalizeProvider:V6}=qt();SS.getSmithyContext=x6;SS.normalizeProvider=V6;var{SMITHY_CONTEXT_KEY:j6,AlgorithmId:c_}=Mr();SS.AlgorithmId=c_;var{NormalizedSchema:q6}=Ji(),Er=(n,t)=>{let i=[];if(n)i.push(n);if(t)for(let r of t)i.push(r);return i},Qi=(n,t)=>{return`${n||"anonymous"}${t&&t.length>0?` (a.k.a. ${t.join(",")})`:""}`},mf=()=>{let n=[],t=[],i=!1,r=new Set,s=(d)=>d.sort((u,w)=>Py[w.step]-Py[u.step]||Yy[w.priority||"normal"]-Yy[u.priority||"normal"]),f=(d)=>{let u=!1,w=(A)=>{let R=Er(A.name,A.aliases);if(R.includes(d)){u=!0;for(let M of R)r.delete(M);return!1}return!0};return n=n.filter(w),t=t.filter(w),u},_=(d)=>{let u=!1,w=(A)=>{if(A.middleware===d){u=!0;for(let R of Er(A.name,A.aliases))r.delete(R);return!1}return!0};return n=n.filter(w),t=t.filter(w),u},o=(d)=>{return n.forEach((u)=>{d.add(u.middleware,{...u})}),t.forEach((u)=>{d.addRelativeTo(u.middleware,{...u})}),d.identifyOnResolve?.(c.identifyOnResolve()),d},h=(d)=>{let u=[];return d.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)u.push(w);else u.push(...h(w))}),u.push(d),d.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)u.push(w);else u.push(...h(w))}),u},e=(d=!1)=>{let u=[],w=[],A={};return n.forEach((M)=>{let E={...M,before:[],after:[]};for(let T of Er(E.name,E.aliases))A[T]=E;u.push(E)}),t.forEach((M)=>{let E={...M,before:[],after:[]};for(let T of Er(E.name,E.aliases))A[T]=E;w.push(E)}),w.forEach((M)=>{if(M.toMiddleware){let E=A[M.toMiddleware];if(E===void 0){if(d)return;throw Error(`${M.toMiddleware} is not found when adding ${Qi(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(h).reduce((M,E)=>{return M.push(...E),M},[])},c={add:(d,u={})=>{let{name:w,override:A,aliases:R}=u,M={step:"initialize",priority:"normal",middleware:d,...u},E=Er(w,R);if(E.length>0){if(E.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Qi(w,R)}'`);for(let T of E){let l=n.findIndex((O)=>O.name===T||O.aliases?.some((N)=>N===T));if(l===-1)continue;let g=n[l];if(g.step!==M.step||M.priority!==g.priority)throw Error(`"${Qi(g.name,g.aliases)}" middleware with ${g.priority} priority in ${g.step} step cannot be overridden by "${Qi(w,R)}" middleware with ${M.priority} priority in ${M.step} step.`);n.splice(l,1)}}for(let T of E)r.add(T)}n.push(M)},addRelativeTo:(d,u)=>{let{name:w,override:A,aliases:R}=u,M={middleware:d,...u},E=Er(w,R);if(E.length>0){if(E.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Qi(w,R)}'`);for(let T of E){let l=t.findIndex((O)=>O.name===T||O.aliases?.some((N)=>N===T));if(l===-1)continue;let g=t[l];if(g.toMiddleware!==M.toMiddleware||g.relation!==M.relation)throw Error(`"${Qi(g.name,g.aliases)}" middleware ${g.relation} "${g.toMiddleware}" middleware cannot be overridden by "${Qi(w,R)}" middleware ${M.relation} "${M.toMiddleware}" middleware.`);t.splice(l,1)}}for(let T of E)r.add(T)}t.push(M)},clone:()=>o(mf()),use:(d)=>{d.applyToStack(c)},remove:(d)=>{if(typeof d==="string")return f(d);else return _(d)},removeByTag:(d)=>{let u=!1,w=(A)=>{let{tags:R,name:M,aliases:E}=A;if(R&&R.includes(d)){let T=Er(M,E);for(let l of T)r.delete(l);return u=!0,!1}return!0};return n=n.filter(w),t=t.filter(w),u},concat:(d)=>{let u=o(mf());return u.use(d),u.identifyOnResolve(i||u.identifyOnResolve()||(d.identifyOnResolve?.()??!1)),u},applyToStack:o,identify:()=>{return e(!0).map((d)=>{let u=d.step??d.relation+" "+d.toMiddleware;return Qi(d.name,d.aliases)+" - "+u})},identifyOnResolve(d){if(typeof d==="boolean")i=d;return i},resolve:(d,u)=>{for(let w of e().map((A)=>A.middleware).reverse())d=w(d,u);if(i)console.log(c.identify());return d}};return c},Py={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},Yy={high:3,normal:2,low:1},k6=(n)=>()=>{throw Error(n)},Z6=(n)=>()=>Promise.reject(n),e_=()=>{let n=new WeakSet;return(t,i)=>{if(typeof i==="object"&&i!==null){if(n.has(i))return"[Circular]";n.add(i)}return i}},v6=(n)=>{return new Promise((t)=>setTimeout(t,n*1000))},Qy={minDelay:2,maxDelay:120},kt;(function(n){n.ABORTED="ABORTED",n.FAILURE="FAILURE",n.SUCCESS="SUCCESS",n.RETRY="RETRY",n.TIMEOUT="TIMEOUT"})(kt||(kt={}));var p6=(n)=>{if(n.state===kt.ABORTED){let t=Error(`${JSON.stringify({...n,reason:"Request was aborted"},e_())}`);throw t.name="AbortError",t}else if(n.state===kt.TIMEOUT){let t=Error(`${JSON.stringify({...n,reason:"Waiter has timed out"},e_())}`);throw t.name="TimeoutError",t}else if(n.state!==kt.SUCCESS)throw Error(`${JSON.stringify(n,e_())}`);return n},nS=async({minDelay:n,maxDelay:t,maxWaitTime:i,abortController:r,client:s,abortSignal:f},_,o)=>{let h={},[e,c]=[n*1000,t*1000],d=0,u=Date.now()+i*1000,w=Date.now()+60000,A=!1;while(!0){if(d>0){let E=rS(e,c,d,u);if(r?.signal?.aborted||f?.aborted)return h["AbortController signal aborted."]|=0,h["AbortController signal aborted."]+=1,{state:kt.ABORTED,observedResponses:h};if(Date.now()+E>u)return{state:kt.TIMEOUT,observedResponses:h};await v6(E/1000)}let{state:R,reason:M}=await o(s,_);if(M){let E=iS(M);h[E]|=0,h[E]+=1}if(R!==kt.RETRY)return{state:R,reason:M,final:M,observedResponses:h};if(d+=1,!A&&Date.now()>=w)tS(h,s),A=!0}},tS=(n={},t)=>{let i=Object.keys(n),r=0;for(let _ of i){let o=n[_]|0;if(_.startsWith("403:"))r+=o}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.")},iS=(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,e_())??"Unknown")},rS=(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),_=Math.min(f,t),o=sS(n,_);if(Date.now()+o>r){let h=r-Date.now();return Math.max(0,h-500)}return o},sS=(n,t)=>n+Math.random()*(t-n),fS=(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`)},Xy=(n)=>{let t,i=new Promise((r)=>{if(t=()=>r({state:kt.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}},oS=async(n,t,i)=>{let r={...Qy,...n};fS(r);let s=[nS(r,t,i)],f=[];if(n.abortSignal){let{aborted:_,clearListener:o}=Xy(n.abortSignal);f.push(o),s.push(_)}if(n.abortController?.signal){let{aborted:_,clearListener:o}=Xy(n.abortController.signal);f.push(o),s.push(_)}return Promise.race(s).then((_)=>{for(let o of f)o();return _})};class ay{config;middlewareStack=mf();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,_;if(f){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(n.constructor))_=o.get(n.constructor);else _=n.resolveMiddleware(this.middlewareStack,this.config,r),o.set(n.constructor,_)}else delete this.handlers,_=n.resolveMiddleware(this.middlewareStack,this.config,r);if(s)_(n).then((o)=>s(null,o.output),(o)=>s(o)).catch(()=>{});else return _(n).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Ae="***SensitiveInformation***";function d_(n,t){if(t==null)return t;let i=q6.of(n);if(i.getMergedTraits().sensitive)return Ae;if(i.isListSchema()){if(!!i.getValueSchema().getMergedTraits().sensitive)return Ae}else if(i.isMapSchema()){if(!!i.getKeySchema().getMergedTraits().sensitive||!!i.getValueSchema().getMergedTraits().sensitive)return Ae}else if(i.isStructSchema()&&typeof t==="object"){let r=t,s={};for(let[f,_]of i.structIterator())if(r[f]!=null)s[f]=d_(_,r[f]);return s}return t}class u_{middlewareStack=mf();schema;static classBuilder(){return new zy}resolveMiddlewareWithContext(n,t,i,{middlewareFn:r,clientName:s,commandName:f,inputFilterSensitiveLog:_,outputFilterSensitiveLog:o,smithyContext:h,additionalContext:e,CommandCtor:c}){for(let M of r.bind(this)(c,n,t,i))this.middlewareStack.use(M);let d=n.concat(this.middlewareStack),{logger:u}=t,w={logger:u,clientName:s,commandName:f,inputFilterSensitiveLog:_,outputFilterSensitiveLog:o,[j6]:{commandInstance:this,...h},...e},{requestHandler:A}=t,R=i??{};if(h.eventStream)R={isEventStream:!0,...R};return d.resolve((M)=>A.handle(M.request,R),w)}}class zy{_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 u_{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,_=f?.[4]??f?.input,o=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?d_.bind(null,_):(h)=>h),outputFilterSensitiveLog:n._outputFilterSensitiveLog??(f?d_.bind(null,o):(h)=>h),smithyContext:n._smithyContext,additionalContext:n._additionalContext})}serialize=n._serializer;deserialize=n._deserializer}}}var _S="***SensitiveInformation***",hS=(n,t,i)=>{for(let[f,_]of Object.entries(n)){let o=async function(e,c,d){let u=new _(e);if(typeof c==="function")this.send(u,c);else if(typeof d==="function"){if(typeof c!=="object")throw Error(`Expected http options but got ${typeof c}`);this.send(u,c||{},d)}else return this.send(u,c)},h=(f[0].toLowerCase()+f.slice(1)).replace(/Command$/,"");t.prototype[h]=o}let{paginators:r={},waiters:s={}}=i??{};for(let[f,_]of Object.entries(r))if(t.prototype[f]===void 0)t.prototype[f]=function(o={},h,...e){return _({...h,client:this},o,...e)};for(let[f,_]of Object.entries(s))if(t.prototype[f]===void 0)t.prototype[f]=async function(o={},h,...e){let c=h;if(typeof h==="number")c={maxWaitTime:h};return _({...c,client:this},o,...e)}};class Es 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 Es.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===Es)return Es.isInstance(n);if(Es.isInstance(n)){if(t.name&&this.name)return this.prototype.isPrototypeOf(n)||t.name===this.name;return this.prototype.isPrototypeOf(n)}return!1}}var Ky=(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},xy=({output:n,parsedBody:t,exceptionCtor:i,errorCode:r})=>{let s=cS(n),f=s.httpStatusCode?s.httpStatusCode+"":void 0,_=new i({name:t?.code||t?.Code||r||f||"UnknownError",$fault:"client",$metadata:s});throw Ky(_,t)},eS=(n)=>{return({output:t,parsedBody:i,errorCode:r})=>{xy({output:t,parsedBody:i,exceptionCtor:n,errorCode:r})}},cS=(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"]}),dS=(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{}}},Jy=!1,uS=(n)=>{if(n&&!Jy&&parseInt(n.substring(1,n.indexOf(".")))<16)Jy=!0},Vy=Object.values(c_),jy=(n)=>{let t=[];for(let i in c_){let r=c_[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(Vy.includes(r))n.checksumAlgorithms[r.toUpperCase()]=s;else n.checksumAlgorithms[r]=s;t.push(i)},checksumAlgorithms(){return t}}},qy=(n)=>{let t={};return n.checksumAlgorithms().forEach((i)=>{let r=i.algorithmId();if(Vy.includes(r))t[r]=i.checksumConstructor()}),t},ky=(n)=>{return{setRetryStrategy(t){n.retryStrategy=t},retryStrategy(){return n.retryStrategy}}},Zy=(n)=>{let t={};return t.retryStrategy=n.retryStrategy(),t},vy=(n)=>{return Object.assign(jy(n),ky(n))},wS=vy,yS=(n)=>{return Object.assign(qy(n),Zy(n))},AS=(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},RS=(n)=>{return n!=null};class nA{trace(){}debug(){}info(){}warn(){}error(){}}function tA(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,lS(r,s,f);else f=t;for(let _ of Object.keys(f)){if(!Array.isArray(f[_])){r[_]=f[_];continue}iA(r,null,f,_)}return r}var MS=(n)=>{let t={};for(let[i,r]of Object.entries(n||{}))t[i]=[,r];return t},ES=(n,t)=>{let i={};for(let r in t)iA(i,n,t,r);return i},lS=(n,t,i)=>{return tA(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},{}))},iA=(n,t,i,r)=>{if(t!==null){let _=i[r];if(typeof _==="function")_=[,_];let[o=TS,h=gS,e=r]=_;if(typeof o==="function"&&o(t[e])||typeof o!=="function"&&!!o)n[r]=h(t[e]);return}let[s,f]=i[r];if(typeof f==="function"){let _,o=s===void 0&&(_=f())!=null,h=typeof s==="function"&&!!s(void 0)||typeof s!=="function"&&!!s;if(o)n[r]=_;else if(h)n[r]=f()}else{let _=s===void 0&&f!=null,o=typeof s==="function"&&!!s(f)||typeof s!=="function"&&!!s;if(_||o)n[r]=f}},TS=(n)=>n!=null,gS=(n)=>n,OS=(n)=>{if(n!==n)return"NaN";switch(n){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return n}},LS=(n)=>n.toISOString().replace(".000Z","Z"),Re=(n)=>{if(n==null)return{};if(Array.isArray(n))return n.filter((t)=>t!=null).map(Re);if(typeof n==="object"){let t={};for(let i of Object.keys(n)){if(n[i]==null)continue;t[i]=Re(n[i])}return t}return n};function IS(n,t,i,r){return function(f,_,o,h,e={}){let c=Object.assign({},n,f);return u_.classBuilder().ep(c).m(function(d,u,w,A){let R=_.call(this,d,u,w,A);return R.unshift(r(w,d.getEndpointParameterInstructions())),R}).s(t,o,e).n(i,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(h).build()}}SS.Client=ay;SS.Command=u_;SS.NoOpLogger=nA;SS.SENSITIVE_STRING=_S;SS.ServiceException=Es;SS.WaiterState=kt;SS._json=Re;SS.checkExceptions=p6;SS.constructStack=mf;SS.convertMap=MS;SS.createAggregatedClient=hS;SS.createWaiter=oS;SS.decorateServiceException=Ky;SS.emitWarningIfUnsupportedVersion=uS;SS.getArrayIfSingleItem=AS;SS.getChecksumConfiguration=jy;SS.getDefaultClientConfiguration=wS;SS.getDefaultExtensionConfiguration=vy;SS.getRetryConfiguration=ky;SS.getValueFromTextNode=py;SS.invalidFunction=k6;SS.invalidProvider=Z6;SS.isSerializableHeaderValue=RS;SS.loadConfigsForDefaultMode=dS;SS.makeBuilder=IS;SS.map=tA;SS.resolveChecksumRuntimeConfig=qy;SS.resolveDefaultRuntimeConfig=yS;SS.resolveRetryRuntimeConfig=Zy;SS.schemaLogFilter=d_;SS.serializeDateTime=LS;SS.serializeFloat=OS;SS.take=ES;SS.throwDefaultError=xy;SS.waiterServiceDefaults=Qy;SS.withBaseException=eS});var nt=sn((dN)=>{var{homedir:db}=un("os"),{sep:ub,join:Hf}=un("path"),{createHash:wb}=un("crypto"),{readFile:dA}=un("fs/promises"),{IniSectionType:w_}=Mr(),{normalizeProvider:y_}=Ei(),{isValidHostLabel:yb}=qt();class ls 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,ls.prototype),i?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${n}`)}static from(n,t=!0){return Object.assign(new this(n.message,t),n)}}class Wf extends ls{name="CredentialsProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,Wf.prototype)}}class ge extends ls{name="TokenProviderError";constructor(n,t=!0){super(n,t);Object.setPrototypeOf(this,ge.prototype)}}var uA=(...n)=>async()=>{if(n.length===0)throw new ls("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},wA=(n)=>()=>Promise.resolve(n),Oe=(n,t,i)=>{let r,s,f,_=!1,o=async()=>{if(!s)s=n();try{r=await s,f=!0,_=!1}finally{s=void 0}return r};if(t===void 0)return async(h)=>{if(!f||h?.forceRefresh)r=await o();return r};return async(h)=>{if(!f||h?.forceRefresh)r=await o();if(_)return r;if(i&&!i(r))return _=!0,r;if(t(r))return await o(),r;return r}},li=(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]}.`)},Ab=(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},mt;(function(n){n.ENV="env",n.CONFIG="shared config entry"})(mt||(mt={}));var Me={},Rb=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Ff=()=>{let{HOME:n,USERPROFILE:t,HOMEPATH:i,HOMEDRIVE:r=`C:${ub}`}=process.env;if(n)return n;if(t)return t;if(i)return`${r}${i}`;let s=Rb();if(!Me[s])Me[s]=db();return Me[s]},yA="AWS_PROFILE",AA="default",RA=(n)=>n.profile||process.env[yA]||AA,MA=(n)=>{let i=wb("sha1").update(n).digest("hex");return Hf(Ff(),".aws","sso","cache",`${i}.json`)},A_={},Mb=async(n)=>{if(A_[n])return A_[n];let t=MA(n),i=await dA(t,"utf8");return JSON.parse(i)},lr=".",Eb=(n)=>Object.entries(n).filter(([t])=>{let i=t.indexOf(lr);if(i===-1)return!1;return Object.values(w_).includes(t.substring(0,i))}).reduce((t,[i,r])=>{let s=i.indexOf(lr),f=i.substring(0,s)===w_.PROFILE?i.substring(s+1):i;return t[f]=r,t},{...n.default&&{default:n.default}}),lb="AWS_CONFIG_FILE",EA=()=>process.env[lb]||Hf(Ff(),".aws","config"),Tb="AWS_SHARED_CREDENTIALS_FILE",gb=()=>process.env[Tb]||Hf(Ff(),".aws","credentials"),Ob=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,Lb=["__proto__","profile __proto__"],le=(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 o=f.substring(1,f.length-1),h=Ob.exec(o);if(h){let[,e,,c]=h;if(Object.values(w_).includes(e))i=[e,c].join(lr)}else i=o;if(Lb.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(i){let o=f.indexOf("=");if(![0,-1].includes(o)){let[h,e]=[f.substring(0,o).trim(),f.substring(o+1).trim()];if(e==="")r=h;else{if(r&&s.trimStart()===s)r=void 0;t[i]=t[i]||{};let c=r?[r,h].join(lr):h;t[i][c]=e}}}}return t},Ee={},R_={},M_=(n,t)=>{if(R_[n]!==void 0)return R_[n];if(!Ee[n]||t?.ignoreCache)Ee[n]=dA(n,"utf8");return Ee[n]},rA=()=>({}),Le=async(n={})=>{let{filepath:t=gb(),configFilepath:i=EA()}=n,r=Ff(),s="~/",f=t;if(t.startsWith("~/"))f=Hf(r,t.slice(2));let _=i;if(i.startsWith("~/"))_=Hf(r,i.slice(2));let o=await Promise.all([M_(_,{ignoreCache:n.ignoreCache}).then(le).then(Eb).catch(rA),M_(f,{ignoreCache:n.ignoreCache}).then(le).catch(rA)]);return{configFile:o[0],credentialsFile:o[1]}},Ib=(n)=>Object.entries(n).filter(([t])=>t.startsWith(w_.SSO_SESSION+lr)).reduce((t,[i,r])=>({...t,[i.substring(i.indexOf(lr)+1)]:r}),{}),Sb=()=>({}),bb=async(n={})=>M_(n.configFilepath??EA()).then(le).then(Ib).catch(Sb),Nb=(...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},Ub=async(n)=>{let t=await Le(n);return Nb(t.configFile,t.credentialsFile)},$b={getFileRecord(){return R_},interceptFile(n,t){R_[n]=Promise.resolve(t)},getTokenRecord(){return A_},interceptToken(n,t){A_[n]=t}};function lA(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 Db=(n,t)=>async()=>{try{let i=n(process.env,t);if(i===void 0)throw Error();return i}catch(i){throw new Wf(i.message||`Not found in ENV: ${lA(n.toString())}`,{logger:t?.logger})}},Bb=(n,{preferredFile:t="config",...i}={})=>async()=>{let r=RA(i),{configFile:s,credentialsFile:f}=await Le(i),_=f[r]||{},o=s[r]||{},h=t==="config"?{..._,...o}:{...o,..._};try{let c=n(h,t==="config"?s:f);if(c===void 0)throw Error();return c}catch(e){throw new Wf(e.message||`Not found in config files w/ profile [${r}]: ${lA(n.toString())}`,{logger:i.logger})}},Gb=(n)=>typeof n==="function",TA=(n)=>Gb(n)?async()=>await n():wA(n),Te=({environmentVariableSelector:n,configFileSelector:t,default:i},r={})=>{let{signingName:s,logger:f}=r;return Oe(uA(Db(n,{signingName:s,logger:f}),Bb(t,r),TA(i)))},Ie="AWS_USE_DUALSTACK_ENDPOINT",Se="use_dualstack_endpoint",mb=!1,Hb={environmentVariableSelector:(n)=>li(n,Ie,mt.ENV),configFileSelector:(n)=>li(n,Se,mt.CONFIG),default:!1},Wb={environmentVariableSelector:(n)=>li(n,Ie,mt.ENV),configFileSelector:(n)=>li(n,Se,mt.CONFIG),default:void 0},be="AWS_USE_FIPS_ENDPOINT",Ne="use_fips_endpoint",Fb=!1,Cb={environmentVariableSelector:(n)=>li(n,be,mt.ENV),configFileSelector:(n)=>li(n,Ne,mt.CONFIG),default:!1},Pb={environmentVariableSelector:(n)=>li(n,be,mt.ENV),configFileSelector:(n)=>li(n,Ne,mt.CONFIG),default:void 0},Yb=(n)=>{let{tls:t,endpoint:i,urlParser:r,useDualstackEndpoint:s}=n;return Object.assign(n,{tls:t??!0,endpoint:y_(typeof i==="string"?r(i):i),isCustomEndpoint:!0,useDualstackEndpoint:y_(s??!1)})},Xb=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:_}=await n.regionInfoProvider(i,{useDualstackEndpoint:s,useFipsEndpoint:f})??{};if(!_)throw Error("Cannot resolve hostname from client config");return n.urlParser(`${t?"https:":"http:"}//${_}`)},Jb=(n)=>{let t=y_(n.useDualstackEndpoint??!1),{endpoint:i,useFipsEndpoint:r,urlParser:s,tls:f}=n;return Object.assign(n,{tls:f??!0,endpoint:i?y_(typeof i==="string"?s(i):i):()=>Xb({...n,useDualstackEndpoint:t,useFipsEndpoint:r}),isCustomEndpoint:!!i,useDualstackEndpoint:t})},Qb="AWS_EXECUTION_ENV",sA="AWS_REGION",fA="AWS_DEFAULT_REGION",ab="AWS_EC2_METADATA_DISABLED",zb=["in-region","cross-region","mobile","standard","legacy"],Kb="/latest/meta-data/placement/region",xb="/latest/api/token",Vb="x-aws-ec2-metadata-token",jb="x-aws-ec2-metadata-token-ttl-seconds",oA=1000,qb=60000,gA=0,OA=async()=>{if(process.env[ab])return;if(Date.now()<gA)return;try{let n=kb(),t=(await hA({...n,path:xb,method:"PUT",headers:{[jb]:"21600"}})).toString();return(await hA({...n,path:Kb,method:"GET",headers:{[Vb]:t}})).toString().trim()||_A()}catch{return _A()}},_A=()=>{gA=Date.now()+qb;return},kb=()=>{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"}},hA=async(n)=>{let{request:t}=un("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:oA,signal:AbortSignal.timeout(oA)});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:_=400}=f;if(_<200||_>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:_})),s.destroy();return}let o=[];f.on("data",(h)=>o.push(h)),f.on("end",()=>{i(Buffer.concat(o)),s.destroy()})}),s.end()})},LA="AWS_REGION",IA="region",SA={environmentVariableSelector:(n)=>n[LA],configFileSelector:(n)=>n[IA],default:async()=>{let n=await OA();if(n)return n;throw Error("Region is missing")}},Zb={preferredFile:"credentials"},eA=new Set,vb=(n,t=yb)=>{if(!eA.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 eA.add(n)},bA=(n)=>typeof n==="string"&&(n.startsWith("fips-")||n.endsWith("-fips")),pb=(n)=>bA(n)?["fips-aws-global","aws-fips"].includes(n)?"us-east-1":n.replace(/fips-(dkr-|prod-)?|-fips/,""):n,nN=(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=pb(r);return vb(s),s},useFipsEndpoint:async()=>{let r=typeof t==="string"?t:await t();if(bA(r))return!0;return typeof i!=="function"?Promise.resolve(!!i):i()}})},cA=(n=[],{useFipsEndpoint:t,useDualstackEndpoint:i})=>n.find(({tags:r})=>t===r.includes("fips")&&i===r.includes("dualstack"))?.hostname,tN=(n,{regionHostname:t,partitionHostname:i})=>t?t:i?i.replace("{region}",n):void 0,iN=(n,{partitionHash:t})=>Object.keys(t||{}).find((i)=>t[i].regions.includes(n))??"aws",rN=(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)}},sN=(n,{useFipsEndpoint:t=!1,useDualstackEndpoint:i=!1,signingService:r,regionHash:s,partitionHash:f})=>{let _=iN(n,{partitionHash:f}),o=n in s?n:f[_]?.endpoint??n,h={useFipsEndpoint:t,useDualstackEndpoint:i},e=cA(s[o]?.variants,h),c=cA(f[_]?.variants,h),d=tN(o,{regionHostname:e,partitionHostname:c});if(d===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:t,useDualstackEndpoint:i}}`);let u=rN(d,{signingRegion:s[o]?.signingRegion,regionRegex:f[_].regionRegex,useFipsEndpoint:t});return{partition:_,signingService:r,hostname:d,...u&&{signingRegion:u},...s[o]?.signingService&&{signingService:s[o].signingService}}},fN="AWS_DEFAULTS_MODE",oN="defaults_mode",_N={environmentVariableSelector:(n)=>{return n[fN]},configFileSelector:(n)=>{return n[oN]},default:"legacy"},hN=({region:n=Te(SA),defaultsMode:t=Te(_N)}={})=>Oe(async()=>{let i=typeof t==="function"?await t():t;switch(i?.toLowerCase()){case"auto":return eN(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 ${zb.join(", ")}, got ${i}`)}}),eN=async(n)=>{if(n){let t=typeof n==="function"?await n():n,i=await cN();if(!i)return"standard";if(t===i)return"in-region";else return"cross-region"}return"standard"},cN=async()=>{if(process.env[Qb]&&(process.env[sA]||process.env[fA]))return process.env[sA]??process.env[fA];return OA()};dN.CONFIG_PREFIX_SEPARATOR=lr;dN.CONFIG_USE_DUALSTACK_ENDPOINT=Se;dN.CONFIG_USE_FIPS_ENDPOINT=Ne;dN.CredentialsProviderError=Wf;dN.DEFAULT_PROFILE=AA;dN.DEFAULT_USE_DUALSTACK_ENDPOINT=mb;dN.DEFAULT_USE_FIPS_ENDPOINT=Fb;dN.ENV_PROFILE=yA;dN.ENV_USE_DUALSTACK_ENDPOINT=Ie;dN.ENV_USE_FIPS_ENDPOINT=be;dN.NODE_REGION_CONFIG_FILE_OPTIONS=Zb;dN.NODE_REGION_CONFIG_OPTIONS=SA;dN.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=Hb;dN.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=Cb;dN.ProviderError=ls;dN.REGION_ENV_NAME=LA;dN.REGION_INI_NAME=IA;dN.SelectorType=mt;dN.TokenProviderError=ge;dN.booleanSelector=li;dN.chain=uA;dN.externalDataInterceptor=$b;dN.fromStatic=TA;dN.fromValue=wA;dN.getHomeDir=Ff;dN.getProfileName=RA;dN.getRegionInfo=sN;dN.getSSOTokenFilepath=MA;dN.getSSOTokenFromFile=Mb;dN.loadConfig=Te;dN.loadSharedConfigFiles=Le;dN.loadSsoSessionData=bb;dN.memoize=Oe;dN.nodeDualstackConfigSelectors=Wb;dN.nodeFipsConfigSelectors=Pb;dN.numberSelector=Ab;dN.parseKnownFiles=Ub;dN.readFile=M_;dN.resolveCustomEndpointsConfig=Yb;dN.resolveDefaultsModeConfig=hN;dN.resolveEndpointsConfig=Jb;dN.resolveRegionConfig=nN});var Tr=sn((P5)=>{var{CONFIG_PREFIX_SEPARATOR:NA,loadConfig:n5}=nt(),{toEndpointV1:E_,getSmithyContext:t5,normalizeProvider:Ue,isValidHostLabel:DA}=qt();P5.isValidHostLabel=DA;P5.middlewareEndpointToEndpointV1=E_;P5.toEndpointV1=E_;var{EndpointURLScheme:Be}=Mr(),UA="AWS_ENDPOINT_URL",$A="endpoint_url",i5=(n)=>({environmentVariableSelector:(t)=>{let i=n.split(" ").map((f)=>f.toUpperCase()),r=t[[UA,...i].join("_")];if(r)return r;let s=t[UA];if(s)return s;return},configFileSelector:(t,i)=>{if(i&&t.services){let s=i[["services",t.services].join(NA)];if(s){let f=n.split(" ").map((o)=>o.toLowerCase()),_=s[[f.join("_"),$A].join(NA)];if(_)return _}}let r=t[$A];if(r)return r;return},default:void 0}),l_=async(n)=>n5(i5(n??""))(),r5=async(n)=>{let t=n?.Bucket||"";if(typeof n.Bucket==="string")n.Bucket=t.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(h5(t)){if(n.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!_5(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},s5=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,f5=/(\d+\.){3}\d+/,o5=/\.\./,_5=(n)=>s5.test(n)&&!f5.test(n)&&!o5.test(n),h5=(n)=>{let[t,i,r,,,s]=n.split(":"),f=t==="arn"&&n.split(":").length>=6,_=Boolean(f&&i&&r&&s);if(f&&!_)throw Error(`Invalid ARN: ${n} was an invalid ARN.`);return _},e5=(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:_,hostname:o,port:h,path:e}=f;return`${_}//${o}${h?":"+h:""}${e}`}}return f};return s};function BA(n){return async(t,i,r,s)=>{if(!r.isCustomEndpoint){let o;if(r.serviceConfiguredEndpoint)o=await r.serviceConfiguredEndpoint();else o=await n(r.serviceId);if(o)r.endpoint=()=>Promise.resolve(E_(o)),r.isCustomEndpoint=!0}let f=await GA(t,i,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let _=r.endpointProvider(f,s);if(r.isCustomEndpoint&&r.endpoint){let o=await r.endpoint();if(o?.headers){_.headers??={};for(let[h,e]of Object.entries(o.headers))_.headers[h]=Array.isArray(e)?e:[e]}}return _}}var GA=async(n,t,i)=>{let r={},s=t?.getEndpointParameterInstructions?.()||{};for(let[f,_]of Object.entries(s))switch(_.type){case"staticContextParams":r[f]=_.value;break;case"contextParams":r[f]=n[_.name];break;case"clientContextParams":case"builtInParams":r[f]=await e5(_.name,f,i,_.type!=="builtInParams")();break;case"operationContextParams":r[f]=_.get(n);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(_))}if(Object.keys(s).length===0)Object.assign(r,i);if(String(i.serviceId).toLowerCase()==="s3")await r5(r);return r};function c5(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 mA(n){let t=BA(n);return({config:i,instructions:r})=>{return(s,f)=>async(_)=>{if(i.isCustomEndpoint)c5(f,"ENDPOINT_OVERRIDE","N");let o=await t(_.input,{getEndpointParameterInstructions(){return r}},{...i},f);f.endpointV2=o,f.authSchemes=o.properties?.authSchemes;let h=f.authSchemes?.[0];if(h){f.signing_region=h.signingRegion,f.signing_service=h.signingName;let c=t5(f)?.selectedHttpAuthScheme?.httpAuthOption;if(c)c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:h.signingRegion,signingRegion:h.signingRegion,signing_service:h.signingName,signingName:h.signingName,signingRegionSet:h.signingRegionSet},h.properties)}return s({..._})}}}var d5={name:"serializerMiddleware"},HA={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:d5.name};function u5(n){let t=mA(n);return(i,r)=>({applyToStack:(s)=>{s.addRelativeTo(t({config:i,instructions:r}),HA)}})}function w5(n){return(t)=>{let i=t.tls??!0,{endpoint:r,useDualstackEndpoint:s,useFipsEndpoint:f}=t,_=r!=null?async()=>E_(await Ue(r)()):void 0,h=Object.assign(t,{endpoint:_,tls:i,isCustomEndpoint:!!r,useDualstackEndpoint:Ue(s??!1),useFipsEndpoint:Ue(f??!1)}),e=void 0;return h.serviceConfiguredEndpoint=async()=>{if(t.serviceId&&!e)e=n(t.serviceId);return e},h}}class Ge{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 Ge(n,t,i,r)}}class WA{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:_}=r.next();if(this.data.delete(f),_||++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 Xn extends Error{constructor(n){super(n);this.name="EndpointError"}}var Cf="endpoints";function ai(n){if(typeof n!=="object"||n==null)return n;if("ref"in n)return`$${ai(n.ref)}`;if("fn"in n)return`${n.fn}(${(n.argv||[]).map(ai).join(", ")})`;return JSON.stringify(n,null,2)}var FA={},y5=(n,t)=>n===t;function A5(...n){for(let t of n)if(t!=null)return t;return}var R5=(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 Xn(`Path: '${n}' does not end with ']'`);let f=r.slice(s+1,-1);if(Number.isNaN(parseInt(f)))throw new Xn(`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},CA=(n,t)=>R5(t).reduce((i,r)=>{if(typeof i!=="object")throw new Xn(`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),M5=(n)=>n!=null;function E5(n,t,i){return n?t:i}var l5=(n)=>!n,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}$"),PA=(n)=>T5.test(n)||n.startsWith("[")&&n.endsWith("]"),$e={[Be.HTTP]:80,[Be.HTTPS]:443},g5=(n)=>{let t=(()=>{try{if(n instanceof URL)return n;if(typeof n==="object"&&"hostname"in n){let{hostname:u,port:w,protocol:A="",path:R="",query:M={}}=n,E=new URL(`${A}//${u}${w?`:${w}`:""}${R}`);return E.search=Object.entries(M).map(([T,l])=>`${T}=${l}`).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:_,search:o}=t;if(o)return null;let h=_.slice(0,-1);if(!Object.values(Be).includes(h))return null;let e=PA(s),c=i.includes(`${r}:${$e[h]}`)||typeof n==="string"&&n.includes(`${r}:${$e[h]}`),d=`${r}${c?`:${$e[h]}`:""}`;return{scheme:h,authority:d,path:f,normalizedPath:f.endsWith("/")?f:`${f}/`,isIp:e}};function O5(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 L5=(n,t)=>n===t,I5=(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)},S5=(n)=>encodeURIComponent(n).replace(/[!*'()]/g,(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`),b5={booleanEquals:y5,coalesce:A5,getAttr:CA,isSet:M5,isValidHostLabel:DA,ite:E5,not:l5,parseURL:g5,split:O5,stringEquals:L5,substring:I5,uriEncode:S5},YA=(n,t)=>{let i=[],{referenceRecord:r,endpointParams:s}=t,f=0;while(f<n.length){let _=n.indexOf("{",f);if(_===-1){i.push(n.slice(f));break}i.push(n.slice(f,_));let o=n.indexOf("}",_);if(o===-1){i.push(n.slice(_));break}if(n[_+1]==="{"&&n[o+1]==="}")i.push(n.slice(_+1,o)),f=o+2;let h=n.substring(_+1,o);if(h.includes("#")){let[e,c]=h.split("#");i.push(CA(r[e]??s[e],c))}else i.push(r[h]??s[h]);f=o+1}return i.join("")},N5=({ref:n},t)=>{return t.referenceRecord[n]??t.endpointParams[n]},Pf=(n,t,i)=>{if(typeof n==="string")return YA(n,i);else if(n.fn)return JA.callFunction(n,i);else if(n.ref)return N5(n,i);throw new Xn(`'${t}': ${String(n)} is not a string, function or reference.`)},XA=({fn:n,argv:t},i)=>{let r=Array(t.length);for(let _=0;_<r.length;++_){let o=t[_];if(typeof o==="boolean"||typeof o==="number")r[_]=o;else r[_]=JA.evaluateExpression(o,"arg",i)}let s=n.indexOf(".");if(s!==-1){let o=FA[n.slice(0,s)]?.[n.slice(s+1)];if(typeof o==="function")return o(...r)}let f=b5[n];if(typeof f==="function")return f(...r);throw Error(`function ${n} not loaded in endpointFunctions.`)},JA={evaluateExpression:Pf,callFunction:XA},QA=(n,t)=>{let{assign:i}=n;if(i&&i in t.referenceRecord)throw new Xn(`'${i}' is already defined in Reference Record.`);let r=XA(n,t);t.logger?.debug?.(`${Cf} evaluateCondition: ${ai(n)} = ${ai(r)}`);let s=r===""?!0:!!r;if(i!=null)return{result:s,toAssign:{name:i,value:r}};return{result:s}},aA=(n,t)=>Object.entries(n??{}).reduce((i,[r,s])=>{return i[r]=s.map((f)=>{let _=Pf(f,"Header value entry",t);if(typeof _!=="string")throw new Xn(`Header '${r}' value '${_}' is not a string`);return _}),i},{}),me=(n,t)=>Object.entries(n).reduce((i,[r,s])=>{return i[r]=KA.getEndpointProperty(s,t),i},{}),zA=(n,t)=>{if(Array.isArray(n))return n.map((i)=>zA(i,t));switch(typeof n){case"string":return YA(n,t);case"object":if(n===null)throw new Xn(`Unexpected endpoint property: ${n}`);return KA.getEndpointProperties(n,t);case"boolean":return n;default:throw new Xn(`Unexpected endpoint property type: ${typeof n}`)}},KA={getEndpointProperty:zA,getEndpointProperties:me},xA=(n,t)=>{let i=Pf(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 Xn(`Endpoint URL must be a string, got ${typeof i}`)},De=1e8,U5=(n,t)=>{let{nodes:i,root:r,results:s,conditions:f}=n,_=r,o={},h={referenceRecord:o,endpointParams:t.endpointParams,logger:t.logger};while(_!==1&&_!==-1&&_<De){let e=3*(Math.abs(_)-1),[c,d,u]=[i[e],i[e+1],i[e+2]],[w,A,R]=f[c],M=QA({fn:w,assign:R,argv:A},h);if(M.toAssign){let{name:E,value:T}=M.toAssign;o[E]=T}_=_>=0===M.result?d:u}if(_>=De){let e=s[_-De];if(e[0]===-1){let[,w]=e;throw new Xn(Pf(w,"Error",h))}let[c,d,u]=e;return{url:xA(c,h),properties:me(d,h),headers:aA(u??{},h)}}throw new Xn("No matching endpoint.")},He=(n=[],t)=>{let i={},r={...t,referenceRecord:{...t.referenceRecord}},s=!1;for(let f of n){let{result:_,toAssign:o}=QA(f,r);if(!_)return{result:_};if(o)s=!0,i[o.name]=o.value,r.referenceRecord[o.name]=o.value,t.logger?.debug?.(`${Cf} assign: ${o.name} := ${ai(o.value)}`)}if(s)return{result:!0,referenceRecord:i};return{result:!0}},$5=(n,t)=>{let{conditions:i,endpoint:r}=n,{result:s,referenceRecord:f}=He(i,t);if(!s)return;let _=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t,{url:o,properties:h,headers:e}=r;t.logger?.debug?.(`${Cf} Resolving endpoint from template: ${ai(r)}`);let c={url:xA(o,_)};if(e!=null)c.headers=aA(e,_);if(h!=null)c.properties=me(h,_);return c},D5=(n,t)=>{let{conditions:i,error:r}=n,{result:s,referenceRecord:f}=He(i,t);if(!s)return;let _=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;throw new Xn(Pf(r,"Error",_))},VA=(n,t)=>{for(let i of n)if(i.type==="endpoint"){let r=$5(i,t);if(r)return r}else if(i.type==="error")D5(i,t);else if(i.type==="tree"){let r=jA.evaluateTreeRule(i,t);if(r)return r}else throw new Xn(`Unknown endpoint rule: ${i}`);throw new Xn("Rules evaluation failed")},B5=(n,t)=>{let{conditions:i,rules:r}=n,{result:s,referenceRecord:f}=He(i,t);if(!s)return;let _=f?{...t,referenceRecord:{...t.referenceRecord,...f}}:t;return jA.evaluateRules(r,_)},jA={evaluateRules:VA,evaluateTreeRule:B5},G5=(n,t)=>{let{endpointParams:i,logger:r}=t,{parameters:s,rules:f}=n;t.logger?.debug?.(`${Cf} Initial EndpointParams: ${ai(i)}`);for(let o in s){let h=s[o],e=i[o];if(e==null&&h.default!=null){i[o]=h.default;continue}if(h.required&&e==null)throw new Xn(`Missing required parameter: '${o}'`)}let _=VA(f,{endpointParams:i,logger:r,referenceRecord:{}});return t.logger?.debug?.(`${Cf} Resolved endpoint: ${ai(_)}`),_},m5=(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},H5=BA(l_),W5=w5(l_),F5=mA(l_),C5=u5(l_);P5.BinaryDecisionDiagram=Ge;P5.EndpointCache=WA;P5.EndpointError=Xn;P5.customEndpointFunctions=FA;P5.decideEndpoint=U5;P5.endpointMiddleware=F5;P5.endpointMiddlewareOptions=HA;P5.getEndpointFromInstructions=H5;P5.getEndpointPlugin=C5;P5.isIpAddress=PA;P5.resolveEndpoint=G5;P5.resolveEndpointConfig=W5;P5.resolveEndpointRequiredConfig=m5;P5.resolveParams=GA});var tt=sn((D$)=>{var{createHmac:iU,createHash:rU,getRandomValues:sU}=un("crypto"),{ReadStream:fU,lstatSync:oU,fstatSync:_U}=un("fs"),{HttpResponse:hU}=qt(),{toEndpointV1:eU}=Tr(),{Readable:Ts,Writable:iR,PassThrough:qA}=un("stream"),rR=(n)=>typeof ArrayBuffer==="function"&&n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",Os=(n,t=0,i=n.byteLength-t)=>{if(!rR(n))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof n} (${n})`);return Buffer.from(n,t,i)},L_=(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)},cU=/^[A-Za-z0-9+/]*={0,2}$/,sR=(n)=>{if(n.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!cU.exec(n))throw TypeError("Invalid base64 string.");let t=L_(n,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)},I_=(n)=>{let t=L_(n,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)},Qe=(n)=>{let t;if(typeof n==="string")t=I_(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 Os(t.buffer,t.byteOffset,t.byteLength).toString("base64")};function dU(n,t,i,r){return class s extends Uint8Array{static fromString(f,_="utf-8"){if(typeof f==="string"){if(_==="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 fR=(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 Os(n.buffer,n.byteOffset,n.byteLength).toString("utf8")},xn=Array.from({length:256},(n,t)=>t.toString(16).padStart(2,"0"));function uU(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,xn[t[0]]+xn[t[1]]+xn[t[2]]+xn[t[3]]+"-"+xn[t[4]]+xn[t[5]]+"-"+xn[t[6]]+xn[t[7]]+"-"+xn[t[8]]+xn[t[9]]+"-"+xn[t[10]]+xn[t[11]]+xn[t[12]]+xn[t[13]]+xn[t[14]]+xn[t[15]]}}var wU=(n,t,i=(r)=>r)=>n,yU=(n)=>{switch(n){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${n}"`)}},AU=(n)=>{if(n===null||n===void 0)return;if(typeof n==="number"){if(n===0||n===1)Qf.warn(g_(`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")Qf.warn(g_(`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}`)},Xf=(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))Qf.warn(g_(`Expected number but observed string: ${n}`));return t}}if(typeof n==="number")return n;throw TypeError(`Expected number, got ${typeof n}: ${n}`)},RU=Math.ceil(340282346638528860000000000000000000000),T_=(n)=>{let t=Xf(n);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0){if(Math.abs(t)>RU)throw TypeError(`Expected 32-bit float, got ${n}`)}return t},Jf=(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}`)},MU=Jf,Pe=(n)=>ae(n,32),Ye=(n)=>ae(n,16),Xe=(n)=>ae(n,8),ae=(n,t)=>{let i=Jf(n);if(i!==void 0&&EU(i,t)!==i)throw TypeError(`Expected ${t}-bit integer, got ${n}`);return i},EU=(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]}},lU=(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},oR=(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}`)},TU=(n)=>{if(n===null||n===void 0)return;if(typeof n==="string")return n;if(["boolean","number","bigint"].includes(typeof n))return Qf.warn(g_(`Expected string, got ${typeof n}: ${n}`)),String(n);throw TypeError(`Expected string, got ${typeof n}: ${n}`)},gU=(n)=>{if(n===null||n===void 0)return;let t=oR(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},ze=(n)=>{if(typeof n=="string")return Xf(Ss(n));return Xf(n)},OU=ze,_R=(n)=>{if(typeof n=="string")return T_(Ss(n));return T_(n)},LU=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ss=(n)=>{let t=n.match(LU);if(t===null||t[0].length!==n.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(n)},Ke=(n)=>{if(typeof n=="string")return hR(n);return Xf(n)},IU=Ke,SU=Ke,bU=(n)=>{if(typeof n=="string")return hR(n);return T_(n)},hR=(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}`)}},eR=(n)=>{if(typeof n==="string")return Jf(Ss(n));return Jf(n)},NU=eR,UU=(n)=>{if(typeof n==="string")return Pe(Ss(n));return Pe(n)},Ls=(n)=>{if(typeof n==="string")return Ye(Ss(n));return Ye(n)},cR=(n)=>{if(typeof n==="string")return Xe(Ss(n));return Xe(n)},g_=(n)=>{return String(TypeError(n).stack||n).split(`
|
|
10
10
|
`).slice(0,5).filter((t)=>!t.includes("stackTraceWarning")).join(`
|
|
11
|
-
`)},
|
|
12
|
-
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(
|
|
13
|
-
`),
|
|
11
|
+
`)},Qf={warn:console.warn},$U=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],xe=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function DU(n){let t=n.getUTCFullYear(),i=n.getUTCMonth(),r=n.getUTCDay(),s=n.getUTCDate(),f=n.getUTCHours(),_=n.getUTCMinutes(),o=n.getUTCSeconds(),h=s<10?`0${s}`:`${s}`,e=f<10?`0${f}`:`${f}`,c=_<10?`0${_}`:`${_}`,d=o<10?`0${o}`:`${o}`;return`${$U[r]}, ${h} ${xe[i]} ${t} ${e}:${c}:${d} GMT`}var BU=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),GU=(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=BU.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,r,s,f,_,o,h,e]=t,c=Ls(Is(r)),d=Zt(s,"month",1,12),u=Zt(f,"day",1,31);return Yf(c,d,u,{hours:_,minutes:o,seconds:h,fractionalMilliseconds:e})},mU=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),HU=(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=mU.exec(n);if(!t)throw TypeError("Invalid RFC-3339 date-time value");let[i,r,s,f,_,o,h,e,c]=t,d=Ls(Is(r)),u=Zt(s,"month",1,12),w=Zt(f,"day",1,31),A=Yf(d,u,w,{hours:_,minutes:o,seconds:h,fractionalMilliseconds:e});if(c.toUpperCase()!="Z")A.setTime(A.getTime()-VU(c));return A},WU=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$/),FU=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$/),CU=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})$/),PU=(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=WU.exec(n);if(t){let[i,r,s,f,_,o,h,e]=t;return Yf(Ls(Is(f)),We(s),Zt(r,"day",1,31),{hours:_,minutes:o,seconds:h,fractionalMilliseconds:e})}if(t=FU.exec(n),t){let[i,r,s,f,_,o,h,e]=t;return QU(Yf(XU(f),We(s),Zt(r,"day",1,31),{hours:_,minutes:o,seconds:h,fractionalMilliseconds:e}))}if(t=CU.exec(n),t){let[i,r,s,f,_,o,h,e]=t;return Yf(Ls(Is(e)),We(r),Zt(s.trimLeft(),"day",1,31),{hours:f,minutes:_,seconds:o,fractionalMilliseconds:h})}throw TypeError("Invalid RFC-7231 date-time value")},YU=(n)=>{if(n===null||n===void 0)return;let t;if(typeof n==="number")t=n;else if(typeof n==="string")t=ze(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))},Yf=(n,t,i,r)=>{let s=t-1;return zU(n,s,i),new Date(Date.UTC(n,s,i,Zt(r.hours,"hour",0,23),Zt(r.minutes,"minute",0,59),Zt(r.seconds,"seconds",0,60),xU(r.fractionalMilliseconds)))},XU=(n)=>{let t=new Date().getUTCFullYear(),i=Math.floor(t/100)*100+Ls(Is(n));if(i<t)return i+100;return i},JU=1576800000000,QU=(n)=>{if(n.getTime()-new Date().getTime()>JU)return new Date(Date.UTC(n.getUTCFullYear()-100,n.getUTCMonth(),n.getUTCDate(),n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()));return n},We=(n)=>{let t=xe.indexOf(n);if(t<0)throw TypeError(`Invalid month: ${n}`);return t+1},aU=[31,28,31,30,31,30,31,31,30,31,30,31],zU=(n,t,i)=>{let r=aU[t];if(t===1&&KU(n))r=29;if(i>r)throw TypeError(`Invalid day for ${xe[t]} in ${n}: ${i}`)},KU=(n)=>{return n%4===0&&(n%100!==0||n%400===0)},Zt=(n,t,i,r)=>{let s=cR(Is(n));if(s<i||s>r)throw TypeError(`${t} must be between ${i} and ${r}, inclusive`);return s},xU=(n)=>{if(n===null||n===void 0)return 0;return _R("0."+n)*1000},VU=(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},Is=(n)=>{let t=0;while(t<n.length-1&&n.charAt(t)==="0")t++;if(t===0)return n;return n.slice(t)},gr=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};gr.from=(n)=>{if(n&&typeof n==="object"&&(n instanceof gr||("deserializeJSON"in n)))return n;else if(typeof n==="string"||Object.getPrototypeOf(n)===String.prototype)return gr(String(n));return gr(JSON.stringify(n))};gr.fromObject=gr.from;function jU(n){if(n.includes(",")||n.includes('"'))n=`"${n.replace(/"/g,"\\\"")}"`;return n}var Ve="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",je="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",qe="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",dR="(\\d?\\d)",uR="(\\d{4})",qU=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),kU=new RegExp(`^${Ve}, ${dR} ${je} ${uR} ${qe} GMT$`),ZU=new RegExp(`^${Ve}, ${dR}-${je}-(\\d\\d) ${qe} GMT$`),vU=new RegExp(`^${Ve} ${je} ( [1-9]|\\d\\d) ${qe} ${uR}$`),pU=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n$=(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))},t$=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC3339 timestamps must be strings");let t=qU.exec(n);if(!t)throw TypeError(`Invalid RFC3339 timestamp format ${n}`);let[,i,r,s,f,_,o,,h,e]=t;Ti(r,1,12),Ti(s,1,31),Ti(f,0,23),Ti(_,0,59),Ti(o,0,60);let c=new Date(Date.UTC(Number(i),Number(r)-1,Number(s),Number(f),Number(_),Number(o),Number(h)?Math.round(parseFloat(`0.${h}`)*1000):0));if(c.setUTCFullYear(Number(i)),e.toUpperCase()!="Z"){let[,d,u,w]=/([+-])(\d\d):(\d\d)/.exec(e)||[void 0,"+",0,0],A=d==="-"?1:-1;c.setTime(c.getTime()+A*(Number(u)*60*60*1000+Number(w)*60*1000))}return c},i$=(n)=>{if(n==null)return;if(typeof n!=="string")throw TypeError("RFC7231 timestamps must be strings.");let t,i,r,s,f,_,o,h;if(h=kU.exec(n))[,t,i,r,s,f,_,o]=h;else if(h=ZU.exec(n))[,t,i,r,s,f,_,o]=h,r=(Number(r)+1900).toString();else if(h=vU.exec(n))[,i,t,s,f,_,o,r]=h;if(r&&_){let e=Date.UTC(Number(r),pU.indexOf(i),Number(t),Number(s),Number(f),Number(_),o?Math.round(parseFloat(`0.${o}`)*1000):0);Ti(t,1,31),Ti(s,0,23),Ti(f,0,59),Ti(_,0,60);let c=new Date(e);return c.setUTCFullYear(Number(r)),c}throw TypeError(`Invalid RFC7231 date-time value ${n}.`)};function Ti(n,t,i){let r=Number(n);if(r<t||r>i)throw Error(`Value ${r} out of range [${t}, ${i}]`)}function r$(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 _=0;_<r.length;_++){if(f==="")f=r[_];else f+=t+r[_];if((_+1)%i===0)s.push(f),f=""}if(f!=="")s.push(f);return s}var s$=(n)=>{let t=n.length,i=[],r=!1,s=void 0,f=0;for(let _=0;_<t;++_){let o=n[_];switch(o){case'"':if(s!=="\\")r=!r;break;case",":if(!r)i.push(n.slice(f,_)),f=_+1;break}s=o}return i.push(n.slice(f)),i.map((_)=>{_=_.trim();let o=_.length;if(o<2)return _;if(_[0]==='"'&&_[o-1]==='"')_=_.slice(1,o-1);return _.replace(/\\"/g,'"')})},kA=/^-?\d*(\.\d+)?$/;class S_{string;type;constructor(n,t){if(this.string=n,this.type=t,!kA.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 S_.prototype.isPrototypeOf(n)||t.type==="bigDecimal"&&kA.test(t.string)}}function f$(n){return new S_(String(n),"bigDecimal")}var wR={},Je={};for(let n=0;n<256;n++){let t=n.toString(16).toLowerCase();if(t.length===1)t=`0${t}`;wR[n]=t,Je[t]=n}function o$(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 Je)t[i/2]=Je[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return t}function yR(n){let t="";for(let i=0;i<n.byteLength;i++)t+=wR[n[i]];return t}var _$=(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 fU){if(n.path!=null)return oU(n.path).size;else if(typeof n.fd==="number")return _U(n.fd).size}throw Error(`Body Length computation failed for ${n}`)},AR=(n)=>{if(n instanceof Uint8Array)return n;if(typeof n==="string")return I_(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(n)};function b_(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 RR=(n,t)=>(i,r)=>async(s)=>{let{response:f}=await i(s);try{let _=await t(f,n);return{response:f,output:_}}catch(_){if(Object.defineProperty(_,"$response",{value:f,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in _)){try{_.message+=`
|
|
12
|
+
Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(h){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 _.$responseBodyText<"u"){if(_.$response)_.$response.body=_.$responseBodyText}try{if(hU.isInstance(f)){let{headers:h={}}=f,e=Object.entries(h);_.$metadata={httpStatusCode:f.statusCode,requestId:Fe(/^x-[\w-]+-request-?id$/,e),extendedRequestId:Fe(/^x-[\w-]+-id-2$/,e),cfId:Fe(/^x-[\w-]+-cf-id$/,e)}}}catch(h){}}throw _}},Fe=(n,t)=>{return(t.find(([i])=>{return i.match(n)})||[void 0,void 0])[1]},MR=(n,t)=>(i,r)=>async(s)=>{let f=n,_=r.endpointV2?async()=>eU(r.endpointV2):f.endpoint;if(!_)throw Error("No valid endpoint provider available.");let o=await t(s.input,{...n,endpoint:_});return i({...s,request:o})},ER={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},lR={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function h$(n,t,i){return{applyToStack:(r)=>{r.add(RR(n,i),ER),r.add(MR(n,t),lR)}}}class TR{algorithmIdentifier;secret;hash;constructor(n,t){this.algorithmIdentifier=n,this.secret=t,this.reset()}update(n,t){this.hash.update(AR(ZA(n,t)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?iU(this.algorithmIdentifier,ZA(this.secret)):rU(this.algorithmIdentifier)}}function ZA(n,t){if(Buffer.isBuffer(n))return n;if(typeof n==="string")return L_(n,t);if(ArrayBuffer.isView(n))return Os(n.buffer,n.byteOffset,n.byteLength);return Os(n)}var gR=class extends Ts{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??Qe,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)}},vt=(n)=>typeof ReadableStream==="function"&&(n?.constructor?.name===ReadableStream.name||n instanceof ReadableStream),N_=(n)=>{return typeof Blob==="function"&&(n?.constructor?.name===Blob.name||n instanceof Blob)},e$=(n)=>new TextEncoder().encode(n),OR="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(OR).reduce((n,[t,i])=>{return n[i]=Number(t),n},{});var c$=OR.split(""),Ce=6,vA=8,d$=63;function LR(n){let t;if(typeof n==="string")t=e$(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 _=0,o=0;for(let e=f,c=Math.min(f+3,t.length);e<c;e++)_|=t[e]<<(c-e-1)*vA,o+=vA;let h=Math.ceil(o/Ce);_<<=h*Ce-o;for(let e=1;e<=h;e++){let c=(h-e)*Ce;s+=c$[(_&d$<<c)>>c]}s+="==".slice(0,4-h)}return s}var u$=typeof ReadableStream==="function"?ReadableStream:function(){};class IR extends u${}var w$=({expectedChecksum:n,checksum:t,source:i,checksumSourceLocation:r,base64Encoder:s})=>{if(!vt(i))throw Error(`@smithy/util-stream: unsupported source type ${i?.constructor?.name??i} in ChecksumStream.`);let f=s??LR;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let _=new TransformStream({start(){},async transform(h,e){t.update(h),e.enqueue(h)},async flush(h){let e=await t.digest(),c=f(e);if(n!==c){let d=Error(`Checksum mismatch: expected "${n}" but received "${c}" in response header "${r}".`);h.error(d)}else h.terminate()}});i.pipeThrough(_);let o=_.readable;return Object.setPrototypeOf(o,IR.prototype),o};function y$(n){if(typeof ReadableStream==="function"&&vt(n.source))return w$(n);return new gR(n)}class O_{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 A$(n,t,i){let r=n.getReader(),s=!1,f=0,_=["",new O_((e)=>new Uint8Array(e))],o=-1,h=async(e)=>{let{value:c,done:d}=await r.read(),u=c;if(d){if(o!==-1){let w=gs(_,o);if(zi(w)>0)e.enqueue(w)}e.close()}else{let w=bR(u,!1);if(o!==w){if(o>=0)e.enqueue(gs(_,o));o=w}if(o===-1){e.enqueue(u);return}let A=zi(u);f+=A;let R=zi(_[o]);if(A>=t&&R===0)e.enqueue(u);else{let M=SR(_,o,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)e.enqueue(gs(_,o));else await h(e)}}};return new ReadableStream({pull:h})}function SR(n,t,i){switch(t){case 0:return n[0]+=i,zi(n[0]);case 1:case 2:return n[t].push(i),zi(n[t])}}function gs(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 zi(n){return n?.byteLength??n?.length??0}function bR(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 R$(n,t,i){if(vt(n))return A$(n,t,i);let r=new Ts({read(){}}),s=!1,f=0,_=["",new O_((h)=>new Uint8Array(h)),new O_((h)=>Buffer.from(new Uint8Array(h)))],o=-1;return n.on("data",(h)=>{let e=bR(h,!0);if(o!==e){if(o>=0)r.push(gs(_,o));o=e}if(o===-1){r.push(h);return}let c=zi(h);f+=c;let d=zi(_[o]);if(c>=t&&d===0)r.push(h);else{let u=SR(_,o,h);if(!s&&f>t*2)s=!0,i?.warn(`@smithy/util-stream - stream chunk size ${c} is below threshold of ${t}, automatically buffering.`);if(u>=t)r.push(gs(_,o))}}),n.on("end",()=>{if(o!==-1){let h=gs(_,o);if(zi(h)>0)r.push(h)}r.push(null)}),r}var M$=(n,t)=>{let{base64Encoder:i,bodyLengthChecker:r,checksumAlgorithmFn:s,checksumLocationName:f,streamHasher:_}=t,o=i!==void 0&&r!==void 0&&s!==void 0&&f!==void 0&&_!==void 0,h=o?_(s,n):void 0,e=n.getReader();return new ReadableStream({async pull(c){let{value:d,done:u}=await e.read();if(u){if(c.enqueue(`0\r
|
|
13
|
+
`),o){let w=i(await h);c.enqueue(`${f}:${w}\r
|
|
14
14
|
`),c.enqueue(`\r
|
|
15
15
|
`)}c.close()}else c.enqueue(`${(r(d)||0).toString(16)}\r
|
|
16
16
|
${d}\r
|
|
17
|
-
`)}})};function
|
|
17
|
+
`)}})};function E$(n,t){let i=n,r=n;if(vt(r))return M$(r,t);let{base64Encoder:s,bodyLengthChecker:f,checksumAlgorithmFn:_,checksumLocationName:o,streamHasher:h}=t,e=s!==void 0&&_!==void 0&&o!==void 0&&h!==void 0,c=e?h(_,i):void 0,d=new Ts({read:()=>{}});return i.on("data",(u)=>{let w=f(u)||0;if(w===0)return;d.push(`${w.toString(16)}\r
|
|
18
18
|
`),d.push(u),d.push(`\r
|
|
19
19
|
`)}),i.on("end",async()=>{if(d.push(`0\r
|
|
20
|
-
`),
|
|
20
|
+
`),e){let u=s(await c);d.push(`${o}:${u}\r
|
|
21
21
|
`),d.push(`\r
|
|
22
|
-
`)}d.push(null)}),d}async function
|
|
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 hM(f);else if(s==="hex")return vR(f);else if(s===void 0||s==="utf8"||s==="utf-8")return V$(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(PR);if(t=!0,XR(n))return r(n);else if(qt(n))return n;else throw Error(`Cannot transform payload to web stream, got ${n}`)}})},XR=(n)=>typeof Blob==="function"&&n instanceof Blob,yM=(n)=>{if(Ah(n))return dM(n);if(qt(n))return uM(n);return new Promise((t,i)=>{let r=new AM,s=n;s.pipe(r),s.on("error",(f)=>{r.end(),i(f)}),r.on("error",i),r.on("finish",function(){let f=yh(this.bufferedBytes);t(f)})})};class AM extends JR{bufferedBytes=[];_write(n,t,i){this.bufferedBytes.push(n),i()}}var CR="The stream has already been transformed.",q$=(n)=>{if(!(n instanceof ds))try{return j$(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(CR);return t=!0,await yM(n)};return Object.assign(n,{transformToByteArray:i,transformToString:async(r)=>{let s=await i();if(r===void 0||Buffer.isEncoding(r))return ys(s.buffer,s.byteOffset,s.byteLength).toString(r);else return new TextDecoder(r).decode(s)},transformToWebStream:()=>{if(t)throw Error(CR);if(n.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof ds.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,ds.toWeb(n)}})};async function k$(n){if(typeof n.stream==="function")n=n.stream();return n.tee()}async function a$(n){if(qt(n)||Ah(n))return k$(n);let t=new HR,i=new HR;return n.pipe(t),n.pipe(i),[t,i]}class RM extends Wl(zR,dh,Uw,mR){}var Z$=ll,MM=Fl(Z$),v$=MM;p$.ChecksumStream=fM;p$.Hash=sM;p$.LazyJsonString=Er;p$.NumericValue=uh;p$.Uint8ArrayBlobAdapter=RM;p$._parseEpochTimestamp=g$;p$._parseRfc3339DateTimeWithOffset=N$;p$._parseRfc7231DateTime=b$;p$.calculateBodyLength=D$;p$.concatBytes=yh;p$.copyDocumentWithTransform=Yl;p$.createBufferedReadable=C$;p$.createChecksumStream=P$;p$.dateToUtcString=pl;p$.deserializerMiddleware=nM;p$.deserializerMiddlewareOption=iM;p$.expectBoolean=Xl;p$.expectByte=lw;p$.expectFloat32=hh;p$.expectInt=Jl;p$.expectInt32=bw;p$.expectLong=Bf;p$.expectNonNull=ml;p$.expectNumber=Df;p$.expectObject=KR;p$.expectShort=Sw;p$.expectString=zl;p$.expectUnion=Kl;p$.fromArrayBuffer=ys;p$.fromBase64=mR;p$.fromHex=U$;p$.fromString=ch;p$.fromUtf8=dh;p$.generateIdempotencyToken=v$;p$.getAwsChunkedEncodingStream=Q$;p$.getSerdePlugin=B$;p$.handleFloat=jl;p$.headStream=z$;p$.isArrayBuffer=QR;p$.isBlob=Ah;p$.isReadableStream=qt;p$.limitedParseDouble=Gw;p$.limitedParseFloat=ql;p$.limitedParseFloat32=kl;p$.logger=Gf;p$.nv=$$;p$.parseBoolean=Pl;p$.parseEpochTimestamp=o$;p$.parseRfc3339DateTime=t$;p$.parseRfc3339DateTimeWithOffset=r$;p$.parseRfc7231DateTime=h$;p$.quoteHeader=E$;p$.sdkStreamMixin=q$;p$.serializerMiddleware=tM;p$.serializerMiddlewareOption=rM;p$.splitEvery=S$;p$.splitHeader=l$;p$.splitStream=a$;p$.streamCollector=yM;p$.strictParseByte=qR;p$.strictParseDouble=Bw;p$.strictParseFloat=Vl;p$.strictParseFloat32=VR;p$.strictParseInt=al;p$.strictParseInt32=Zl;p$.strictParseLong=jR;p$.strictParseShort=As;p$.toBase64=Uw;p$.toHex=vR;p$.toUint8Array=pR;p$.toUtf8=zR;p$.v4=MM});var mw=rn((JD)=>{var{createReadStream:TD}=dn("fs"),{Writable:eD}=dn("stream"),{toUint8Array:Es,concatBytes:OD}=pn(),{createHash:Hf,createHmac:LD}=dn("crypto"),EM=dn("zlib");async function IM(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 ID=async function(t,i){let r=new t;return await IM(i,(s)=>{r.update(s)}),r.digest()};class Cw extends eD{hash;constructor(n,t){super(t);this.hash=n}_write(n,t,i){try{this.hash.update(Es(n))}catch(r){return i(r)}i()}}var gD=(n,t)=>new Promise((i,r)=>{if(!ND(t)){r(Error("Unable to calculate hash for non-file streams."));return}let s=TD(t.path,{start:t.start,end:t.end}),f=new n,h=new Cw(f);s.pipe(h),s.on("error",(_)=>{h.end(),r(_)}),h.on("error",r),h.on("finish",function(){f.digest().then(i).catch(r)})}),ND=(n)=>typeof n.path==="string",bD=(n,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let i=new n,r=new Cw(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 Jw{digestLength=16;state=Uint32Array.from(TM);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(n){let t=Es(n),i=0,r=t.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[i++]),--r,this.bufferLength===64)Pw(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);Pw(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),Pw(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(TM),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var TM=[1732584193,4023233417,2562383102,271733878],Ji=4294967295,SD=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),lD=Array.from({length:64},(n,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function Pw(n,t){let i=n[0],r=n[1],s=n[2],f=n[3];for(let h=0;h<64;++h){let _,o;if(h<16)_=r&s|~r&f,o=h;else if(h<32)_=f&r|s&~f,o=(5*h+1)%16;else if(h<48)_=r^s^f,o=(3*h+5)%16;else _=s^(r|~f),o=7*h%16;let w=t.getUint32(o*4,!0),c=f;f=s,s=r;let d=SD[(h>>4)*4+(h&3)],u=(i+_&Ji)+(w+lD[h]&Ji)&Ji;r=r+((u<<d|u>>>32-d)>>>0)&Ji,i=c}n[0]=n[0]+i&Ji,n[1]=n[1]+r&Ji,n[2]=n[2]+s&Ji,n[3]=n[3]+f&Ji}var $D=(()=>{try{return Hf("md5"),!0}catch{return!1}})(),gM=$D?UD():Jw;function UD(){return class{digestLength=16;hash=Hf("md5");update(t){this.hash.update(Es(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=Hf("md5")}}}var NM=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;NM[n]=t>>>0}var Xw=4294967295;class Qw{digestLength=4;checksum=Xw;update(n){for(let t=0;t<n.length;++t)this.checksum=this.checksum>>>8^NM[(this.checksum^n[t])&255]}digestSync(){return(this.checksum^Xw)>>>0}async digest(){let n=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n,!1),t}reset(){this.checksum=Xw}}var eM=typeof EM.crc32==="function"?EM.crc32:void 0,bM=eM?DD(eM):Qw;function DD(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 Qn=64,OM=32,BD=9007199254740991;class Mi{digestLength=OM;state=Int32Array.from(LM);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(n){if(n){let t=Mi.normalizeKey(n);this.inner=new Mi,this.outer=new Mi;let{inner:i,outer:r}=this,s=new Uint8Array(Qn*2);for(let f=0;f<Qn;++f)s[f]=54^t[f],s[f+Qn]=92^t[f];i.update(s.subarray(0,Qn)),r.update(s.subarray(Qn))}}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(n);return}let t=Es(n),i=0,{byteLength:r}=t;if(this.bytesHashed+=r,this.bytesHashed*8>BD)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=t[i++],r--,this.bufferLength===Qn)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(LM),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)%Qn>=Qn-8){for(let h=i;h<Qn;++h)s.setUint8(h,0);this.hashBufferWith(n,t),i=0}for(let h=i;h<Qn-8;++h)s.setUint8(h,0);s.setUint32(Qn-8,Math.floor(r/4294967296),!1),s.setUint32(Qn-4,r,!1),this.hashBufferWith(n,t);let f=new Uint8Array(OM);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=Es(n);if(t.byteLength>Qn){let i=new Mi;i.update(t);let r=i.digestSync(),s=new Uint8Array(Qn);return s.set(r),s}if(t.byteLength<Qn){let i=new Uint8Array(Qn);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],o=n[5],w=n[6],c=n[7];for(let d=0;d<Qn;++d){if(d<16)i[d]=(t[d*4]&255)<<24|(t[d*4+1]&255)<<16|(t[d*4+2]&255)<<8|t[d*4+3]&255;else{let R=i[d-2],M=(R>>>17|R<<15)^(R>>>19|R<<13)^R>>>10;R=i[d-15];let E=(R>>>7|R<<25)^(R>>>18|R<<14)^R>>>3;i[d]=(M+i[d-7]|0)+(E+i[d-16]|0)}let u=(((_>>>6|_<<26)^(_>>>11|_<<21)^(_>>>25|_<<7))+(_&o^~_&w)|0)+(c+(GD[d]+i[d]|0)|0)|0,y=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&s^r&f^s&f)|0;c=w,w=o,o=_,_=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]+=o,n[6]+=w,n[7]+=c}}var LM=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),GD=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]),HD=(()=>{try{return Hf("sha256"),!0}catch{return!1}})(),SM=HD?WD():Mi;function WD(){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?LD("sha256",FD(this.secret)):Hf("sha256")}}}function FD(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:YD,sign:PD,importKey:XD}=globalThis?.crypto?.subtle??{},Rh=typeof YD==="function"&&typeof PD==="function"&&typeof XD==="function"?globalThis.crypto.subtle:void 0,CD=8388608;class lM{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(n){if(n)this.secret=Es(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>=CD)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=OD(this.pending);if(Rh){if(this.secret){this.finished=!0;let r=await Rh.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await Rh.sign("HMAC",r,n);return new Uint8Array(s)}let i=await Rh.digest("SHA-256",n);return new Uint8Array(i)}let t=new Mi(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 Mi(this.secret);for(let t of this.pending)n.update(t);this.fallback=n,this.pending=[],this.pendingBytes=0}}JD.Crc32=bM;JD.Crc32Js=Qw;JD.Crc32Node=bM;JD.Md5=gM;JD.Md5Js=Jw;JD.Md5Node=gM;JD.Sha256=SM;JD.Sha256Js=Mi;JD.Sha256Node=SM;JD.Sha256WebCrypto=lM;JD.blobHasher=ID;JD.blobReader=IM;JD.fileStreamHasher=gD;JD.readableStreamHasher=bD});var Mh=rn((gB)=>{var{Crc32:DM}=mw(),{toHex:Ts,fromHex:tB,toUtf8:iB,fromUtf8:rB}=pn(),{Readable:sB}=dn("stream");class es{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)$M(t);return new es(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)$M(n);return parseInt(Ts(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function $M(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 zw{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?Un.boolTrue:Un.boolFalse]);case"byte":return Uint8Array.from([Un.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Un.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Un.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=Un.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,Un.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,Un.string),_.setUint16(1,h.byteLength,!1);let o=new Uint8Array(_.buffer);return o.set(h,3),o;case"timestamp":let w=new Uint8Array(9);return w[0]=Un.timestamp,w.set(es.fromNumber(n.value.valueOf()).bytes,1),w;case"uuid":if(!yB.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Un.uuid,c.set(tB(n.value.replace(/-/g,"")),1),c}}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 Un.boolTrue:t[s]={type:UM,value:!0};break;case Un.boolFalse:t[s]={type:UM,value:!1};break;case Un.byte:t[s]={type:fB,value:n.getInt8(i++)};break;case Un.short:t[s]={type:_B,value:n.getInt16(i,!1)},i+=2;break;case Un.integer:t[s]={type:hB,value:n.getInt32(i,!1)},i+=4;break;case Un.long:t[s]={type:oB,value:new es(new Uint8Array(n.buffer,n.byteOffset+i,8))},i+=8;break;case Un.byteArray:let f=n.getUint16(i,!1);i+=2,t[s]={type:wB,value:new Uint8Array(n.buffer,n.byteOffset+i,f)},i+=f;break;case Un.string:let h=n.getUint16(i,!1);i+=2,t[s]={type:cB,value:this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,h))},i+=h;break;case Un.timestamp:t[s]={type:dB,value:new Date(new es(new Uint8Array(n.buffer,n.byteOffset+i,8)).valueOf())},i+=8;break;case Un.uuid:let _=new Uint8Array(n.buffer,n.byteOffset+i,16);i+=16,t[s]={type:uB,value:`${Ts(_.subarray(0,4))}-${Ts(_.subarray(4,6))}-${Ts(_.subarray(6,8))}-${Ts(_.subarray(8,10))}-${Ts(_.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var Un;(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"})(Un||(Un={}));var UM="boolean",fB="byte",_B="short",hB="integer",oB="long",wB="binary",cB="string",dB="timestamp",uB="uuid",yB=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,BM=4,Qi=BM*2,Tr=4,AB=Qi+Tr*2;function RB({byteLength:n,byteOffset:t,buffer:i}){if(n<AB)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(BM,!1),h=r.getUint32(Qi,!1),_=r.getUint32(n-Tr,!1),o=new DM;if(o.update(new Uint8Array(i,t,Qi)),h!==o.digestSync())throw Error(`The prelude checksum specified in the message (${h}) does not match the calculated CRC32 checksum (${o.digestSync()})`);if(o.update(new Uint8Array(i,t+Qi,n-(Qi+Tr))),_!==o.digestSync())throw Error(`The message checksum (${o.digestSync()}) did not match the expected value of ${_}`);return{headers:new DataView(i,t+Qi+Tr,f),body:new Uint8Array(i,t+Qi+Tr+f,s-f-(Qi+Tr+Tr))}}class Kw{headerMarshaller;messageBuffer;isEndOfStream;constructor(n,t){this.headerMarshaller=new zw(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 DM;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}=RB(n);return{headers:this.headerMarshaller.parse(t),body:i}}formatHeaders(n){return this.headerMarshaller.format(n)}}class Vw{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 xw{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 jw{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 qw{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 GM(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:o,done:w}=await _.next();if(w){if(!t)return;else if(t===i)yield r;else throw Error("Truncated event message received.");return}let c=o.length,d=0;while(d<c){if(!r){let y=c-d;if(!s)s=new Uint8Array(4);let R=Math.min(4-i,y);if(s.set(o.slice(d,d+R),i),i+=R,d+=R,i<4)break;f(new DataView(s.buffer).getUint32(0,!1)),s=null}let u=Math.min(t-i,c-d);if(r.set(o.slice(d,d+u),i),i+=u,d+=u,t&&t===i)yield r,r=null,t=0,i=0}}};return{[Symbol.asyncIterator]:h}}function MB(n,t){let i=kw(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 kw(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 aw=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:i}){this.eventStreamCodec=new Kw(t,i),this.utfEncoder=t}deserialize(t,i){let r=GM(t);return new jw({messageStream:new Vw({inputStream:r,decoder:this.eventStreamCodec}),deserializer:kw(i,this.utfEncoder)})}serialize(t,i){return new xw({messageStream:new qw({inputStream:t,serializer:i}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},EB=(n)=>new aw(n);class Zw{universalMarshaller;constructor({utf8Encoder:n,utf8Decoder:t}){this.universalMarshaller=new aw({utf8Decoder:t,utf8Encoder:n})}deserialize(n,t){let i=typeof n[Symbol.asyncIterator]==="function"?n:eB(n);return this.universalMarshaller.deserialize(i,t)}serialize(n,t){return sB.from(this.universalMarshaller.serialize(n,t))}}var TB=(n)=>new Zw(n);async function*eB(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 OB=(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()}}}),LB=(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)}})},IB=(n)=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});class HM{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,o=Symbol("initialRequestMarker"),w={async*[Symbol.asyncIterator](){if(i){let c={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:_}};h.write(t,i);let d=h.flush();yield{[o]:!0,headers:c,body:d}}for await(let c of n)yield c}};return r.serialize(w,(c)=>{if(c[o])return{headers:c.headers,body:c.body};let d="";for(let T in c)if(T!=="__type"){d=T;break}let{additionalHeaders:u,body:y,eventType:R,explicitPayloadContentType:M}=this.writeEventBody(d,f,c);return{headers:{":event-type":{type:"string",value:R},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??_},...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"),o=r.deserialize(n.body,async(d)=>{let u="";for(let R in d)if(R!=="__type"){u=R;break}let y=d[u].body;if(u==="initial-response"){let R=await this.deserializer.read(t,y);return delete R[s],{[_]:!0,...R}}else if(u in h){let R=h[u];if(R.isStructSchema()){let M={},E=!1;for(let[T,O]of R.structIterator()){let{eventHeader:e,eventPayload:L}=O.getMergedTraits();if(E=E||Boolean(e||L),L){if(O.isBlobSchema())M[T]=y;else if(O.isStringSchema())M[T]=(this.serdeContext?.utf8Encoder??iB)(y);else if(O.isStructSchema())M[T]=await this.deserializer.read(O,y)}else if(e){let N=d[u].headers[T]?.value;if(N!=null)if(O.isNumericSchema())if(N&&typeof N==="object"&&"bytes"in N)M[T]=BigInt(N.toString());else M[T]=Number(N);else M[T]=N}}if(E)return{[u]:M};if(y.byteLength===0)return{[u]:{}}}return{[u]:await this.deserializer.read(R,y)}}else return{$unknown:d}}),w=o[Symbol.asyncIterator](),c=await w.next();if(c.done)return o;if(c.value?.[_]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let d in c.value)i[d]=c.value[d]}return{async*[Symbol.asyncIterator](){if(!c?.value?.[_])yield c.value;while(!0){let{done:d,value:u}=await w.next();if(d)break;yield u}}}}writeEventBody(n,t,i){let r=this.serializer,s=n,f=null,h,_=(()=>{return t.getSchema()[4].includes(n)})(),o={};if(!_){let[d,u]=i[n];s=d,r.write(15,u)}else{let d=t.getMemberSchema(n);if(d.isStructSchema()){for(let[u,y]of d.structIterator()){let{eventHeader:R,eventPayload:M}=y.getMergedTraits();if(M)f=u;else if(R){let E=i[n][u],T="binary";if(y.isNumericSchema())if(-2147483648<=E&&E<=2147483647)T="integer";else T="long";else if(y.isTimestampSchema())T="timestamp";else if(y.isStringSchema())T="string";else if(y.isBooleanSchema())T="boolean";if(E!=null)o[u]={type:T,value:E},delete i[n][u]}}if(f!==null){let u=d.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(d,i[n])}else if(d.isUnitSchema())r.write(d,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let w=r.flush()??new Uint8Array;return{body:typeof w==="string"?(this.serdeContext?.utf8Decoder??rB)(w):w,eventType:s,explicitPayloadContentType:h,additionalHeaders:o}}}gB.EventStreamCodec=Kw;gB.EventStreamMarshaller=Zw;gB.EventStreamSerde=HM;gB.HeaderMarshaller=zw;gB.Int64=es;gB.MessageDecoderStream=Vw;gB.MessageEncoderStream=xw;gB.SmithyMessageDecoderStream=jw;gB.SmithyMessageEncoderStream=qw;gB.UniversalEventStreamMarshaller=aw;gB.eventStreamSerdeProvider=TB;gB.getChunkedStream=GM;gB.getMessageUnmarshaller=kw;gB.getUnmarshalledStream=MB;gB.iterableToReadableStream=LB;gB.readableStreamToIterable=OB;gB.resolveEventStreamSerdeConfig=IB;gB.universalEventStreamSerdeProvider=EB});var nt=rn((wG)=>{var{Uint8ArrayBlobAdapter:vw,sdkStreamMixin:mB,splitEvery:zB,splitHeader:PM,fromBase64:WM,_parseEpochTimestamp:KB,_parseRfc7231DateTime:VB,_parseRfc3339DateTimeWithOffset:xB,LazyJsonString:XM,NumericValue:jB,toUtf8:CM,fromUtf8:qB,generateIdempotencyToken:kB,toBase64:FM,dateToUtcString:aB,quoteHeader:ZB}=pn(),{TypeRegistry:vB,NormalizedSchema:kt,translateTraits:JM}=Yi(),{HttpRequest:Os,HttpResponse:QM,isValidHostname:mM}=Vt(),{parseQueryString:pB,parseUrl:nG}=Vt();wG.HttpRequest=Os;wG.HttpResponse=QM;wG.isValidHostname=mM;wG.parseQueryString=pB;wG.parseUrl=nG;var{FieldPosition:tG}=yr(),er=async(n=new Uint8Array,t)=>{if(n instanceof Uint8Array)return vw.mutate(n);if(!n)return vw.mutate(new Uint8Array);let i=t.streamCollector(n);return vw.mutate(await i)};function Ff(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class Ls{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Eh extends Ls{options;compositeErrorRegistry;constructor(n){super();this.options=n,this.compositeErrorRegistry=vB.for(n.defaultNamespace);for(let t of n.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return Os}getResponseType(){return QM}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=kt.of(t.input),s=JM(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 o=i[h];if(typeof o!=="string")throw Error(`@smithy/core/schema - ${h} in input must be a string as hostLabel.`);f=f.replace(`{${h}}`,o)}if(n.hostname=f+n.hostname,!mM(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}=Mh(),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 zM extends Eh{async serializeRequest(n,t,i){let r=t&&typeof t==="object"?t:{},s=this.serializer,f={},h={},_=await i.endpoint(),o=kt.of(n?.input),w=[],c=[],d=!1,u,y=new Os({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 R=JM(n.traits);if(R.http){y.method=R.http[0];let[M,E]=R.http[1].split("?");if(y.path=="/")y.path=M;else y.path+=M;let T=new URLSearchParams(E??"");for(let[O,e]of T)f[O]=e}}for(let[R,M]of o.structIterator()){let E=M.getMergedTraits()??{},T=r[R];if(T==null&&!M.isIdempotencyToken()){if(E.httpLabel){if(y.path.includes(`{${R}+}`)||y.path.includes(`{${R}}`))throw Error(`No value provided for input HTTP label: ${R}.`)}continue}if(E.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(r[R])u=await this.serializeEventStream({eventStream:r[R],requestSchema:o})}else u=T;else s.write(M,T),u=s.flush();else if(E.httpLabel){s.write(M,T);let O=s.flush();if(y.path.includes(`{${R}+}`))y.path=y.path.replace(`{${R}+}`,O.split("/").map(Ff).join("/"));else if(y.path.includes(`{${R}}`))y.path=y.path.replace(`{${R}}`,Ff(O))}else if(E.httpHeader)s.write(M,T),h[E.httpHeader.toLowerCase()]=String(s.flush());else if(typeof E.httpPrefixHeaders==="string")for(let O in T){let e=T[O],L=E.httpPrefixHeaders+O;s.write([M.getValueSchema(),{httpHeader:L}],e),h[L.toLowerCase()]=s.flush()}else if(E.httpQuery||E.httpQueryParams)this.serializeQuery(M,T,f);else d=!0,w.push(R),c.push(M)}if(d&&r){let[R,M]=(o.getName(!0)??"#Unknown").split("#"),E=o.getSchema()[6],T=[3,R,M,o.getMergedTraits(),w,c,void 0];if(E)T[6]=E;else T.pop();s.write(T,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 o=r.flush();if(f||o!==void 0)h.push(o)}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=kt.of(n.output),f={};if(i.statusCode>=300){let _=await er(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 o=i.headers[_];delete i.headers[_],i.headers[_.toLowerCase()]=o}let h=await this.deserializeHttpMessage(s,t,i,f);if(h.length){let _=await er(i.body,t);if(_.byteLength>0){let o=await r.read(s,_);for(let w of h)if(o[w]!=null)f[w]=o[w]}}else if(h.discardResponseBody)await er(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,o=kt.of(n),w=[];for(let[c,d]of o.structIterator()){let u=d.getMemberTraits();if(u.httpPayload){if(h=!1,d.isStreaming())if(d.isStructSchema())f[c]=await this.deserializeEventStream({response:i,responseSchema:o});else f[c]=mB(i.body);else if(i.body){let R=await er(i.body,t);if(R.byteLength>0)f[c]=await _.read(d,R)}}else if(u.httpHeader){let y=String(u.httpHeader).toLowerCase(),R=i.headers[y];if(R!=null)if(d.isListSchema()){let M=d.getValueSchema();M.getMergedTraits().httpHeader=y;let E;if(M.isTimestampSchema()&&M.getSchema()===4)E=zB(R,",",2);else E=PM(R);let T=[];for(let O of E)T.push(await _.read(M,O.trim()));f[c]=T}else f[c]=await _.read(d,R)}else if(u.httpPrefixHeaders!==void 0){f[c]={};for(let y in i.headers)if(y.startsWith(u.httpPrefixHeaders)){let R=i.headers[y],M=d.getValueSchema();M.getMergedTraits().httpHeader=y,f[c][y.slice(u.httpPrefixHeaders.length)]=await _.read(M,R)}}else if(u.httpResponseCode)f[c]=i.statusCode;else w.push(c)}return w.discardResponseBody=h,w}}class KM extends Eh{async serializeRequest(n,t,i){let r=this.serializer,s={},f={},h=await i.endpoint(),_=kt.of(n?.input),o=_.getSchema(),w,c=t&&typeof t==="object"?t:{},d=new Os({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:s,headers:f,body:void 0});if(h)this.updateServiceEndpoint(d,h),this.setHostPrefix(d,n,c);if(c){let u=_.getEventStreamMember();if(u){if(c[u]){let y={};for(let[R,M]of _.structIterator())if(R!==u&&c[R])r.write(M,c[R]),y[R]=r.flush();w=await this.serializeEventStream({eventStream:c[u],requestSchema:_,initialRequest:y})}}else r.write(o,c),w=r.flush()}return d.headers=Object.assign(d.headers,f),d.query=s,d.body=w,d.method="POST",d}async deserializeResponse(n,t,i){let r=this.deserializer,s=kt.of(n.output),f={};if(i.statusCode>=300){let _=await er(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 o=i.headers[_];delete i.headers[_],i.headers[_.toLowerCase()]=o}let h=s.getEventStreamMember();if(h)f[h]=await this.deserializeEventStream({response:i,responseSchema:s,initialResponseContainer:f});else{let _=await er(i.body,t);if(_.byteLength>0)Object.assign(f,await r.read(s,_))}return f.$metadata=this.deserializeMetadata(i),f}}var VM=(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((_)=>Ff(_)).join("/"):Ff(h))}else throw Error("No value provided for input HTTP label: "+i+".");return n};function iG(n,t){return new pw(n,t)}class pw{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 Os({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=VM(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 nc(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 tc extends Ls{settings;constructor(n){super();this.settings=n}read(n,t){let i=kt.of(n);if(i.isListSchema())return PM(t).map((r)=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??WM)(t);if(i.isTimestampSchema())switch(nc(i,this.settings)){case 5:return xB(t);case 6:return VB(t);case 7:return KB(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=XM.from(s);return s}}if(i.isNumericSchema())return Number(t);if(i.isBigIntegerSchema())return BigInt(t);if(i.isBigDecimalSchema())return new jB(t,"bigDecimal");if(i.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(n){return(this.serdeContext?.utf8Encoder??CM)((this.serdeContext?.base64Decoder??WM)(n))}}class xM extends Ls{codecDeserializer;stringDeserializer;constructor(n,t){super();this.codecDeserializer=n,this.stringDeserializer=new tc(t)}setSerdeContext(n){this.stringDeserializer.setSerdeContext(n),this.codecDeserializer.setSerdeContext(n),this.serdeContext=n}read(n,t){let i=kt.of(n),r=i.getMergedTraits(),s=this.serdeContext?.utf8Encoder??CM;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,s(t));if(r.httpPayload){if(i.isBlobSchema()){let f=this.serdeContext?.utf8Decoder??qB;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 ic extends Ls{settings;stringBuffer="";constructor(n){super();this.settings=n}write(n,t){let i=kt.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(nc(i,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=aB(t);break;case 7:this.stringBuffer=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1000)}return}if(i.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??FM)(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(),o=i.getValueSchema().isTimestampSchema()?_:ZB(_);if(f!=="")f+=", ";f+=o}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=XM.from(s);if(i.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??FM)(s.toString());return}}this.stringBuffer=t;break;default:if(i.isIdempotencyToken())this.stringBuffer=kB();else this.stringBuffer=String(t)}}flush(){let n=this.stringBuffer;return this.stringBuffer="",n}}class jM{codecSerializer;stringSerializer;buffer;constructor(n,t,i=new ic(t)){this.codecSerializer=n,this.stringSerializer=i}setSerdeContext(n){this.codecSerializer.setSerdeContext(n),this.stringSerializer.setSerdeContext(n)}write(n,t){let i=kt.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 qM{name;kind;values;constructor({name:n,kind:t=tG.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 kM{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 rG=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,i){n.httpHandler?.updateHttpClientConfig(t,i)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},sG=(n)=>{return{httpHandler:n.httpHandler()}},YM="content-length";function aM(n){return(t)=>async(i)=>{let r=i.request;if(Os.isInstance(r)){let{body:s,headers:f}=r;if(s&&Object.keys(f).map((h)=>h.toLowerCase()).indexOf(YM)===-1)try{let h=n(s);r.headers={...r.headers,[YM]:String(h)}}catch(h){}}return t({...i,request:r})}}var ZM={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},fG=(n)=>({applyToStack:(t)=>{t.add(aM(n.bodyLengthChecker),ZM)}}),Wf=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,_G),_G=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,hG=(n)=>n.split("/").map(Wf).join("/");function oG(n){let t=[];for(let i of Object.keys(n).sort()){let r=n[i];if(i=Wf(i),Array.isArray(r))for(let s=0,f=r.length;s<f;s++)t.push(`${i}=${Wf(r[s])}`);else{let s=i;if(r||typeof r==="string")s+=`=${Wf(r)}`;t.push(s)}}return t.join("&")}wG.Field=qM;wG.Fields=kM;wG.FromStringShapeDeserializer=tc;wG.HttpBindingProtocol=zM;wG.HttpInterceptingShapeDeserializer=xM;wG.HttpInterceptingShapeSerializer=jM;wG.HttpProtocol=Eh;wG.RequestBuilder=pw;wG.RpcProtocol=KM;wG.SerdeContext=Ls;wG.ToStringShapeSerializer=ic;wG.buildQueryString=oG;wG.collectBody=er;wG.contentLengthMiddleware=aM;wG.contentLengthMiddlewareOptions=ZM;wG.determineTimestampFormat=nc;wG.escapeUri=Wf;wG.escapeUriPath=hG;wG.extendedEncodeURIComponent=Ff;wG.getContentLengthPlugin=fG;wG.getHttpHandlerExtensionConfiguration=rG;wG.requestBuilder=iG;wG.resolveHttpHandlerRuntimeConfig=sG;wG.resolvedPath=VM});var Jf=rn((oH)=>{var{Readable:CG}=dn("stream"),{NoOpLogger:JG,normalizeProvider:vM}=yi(),{HttpResponse:pM,HttpRequest:eh}=nt(),{parseRfc7231DateTime:QG,v4:nE}=pn(),tE=(n)=>n?.body instanceof CG||typeof ReadableStream<"u"&&n?.body instanceof ReadableStream,mG=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],zG=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],KG=["TimeoutError","RequestTimeout","RequestTimeoutException"],VG=[500,502,503,504],xG=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],jG=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],_c=(n)=>n?.$retryable!==void 0,iE=(n)=>mG.includes(n.name),rE=(n)=>n.$metadata?.clockSkewCorrected,sE=(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)},Pf=(n)=>n.$metadata?.httpStatusCode===429||zG.includes(n.name)||n.$retryable?.throttling==!0,Xf=(n,t=0)=>_c(n)||rE(n)||n.name==="InvalidSignatureException"&&n.message?.includes("Signature expired")||KG.includes(n.name)||xG.includes(n?.code||"")||jG.includes(n?.code||"")||VG.includes(n.$metadata?.httpStatusCode||0)||sE(n)||_E(n)||n.cause!==void 0&&t<=10&&Xf(n.cause,t+1),fE=(n)=>{if(n.$metadata?.httpStatusCode!==void 0){let t=n.$metadata.httpStatusCode;if(500<=t&&t<=599&&!Xf(n))return!0;return!1}return!1};function _E(n){return n.code==="ERR_HTTP2_STREAM_ERROR"&&n.message.includes("NGHTTP2_REFUSED_STREAM")}var hE=100,Lh=20000,oE=500,Oh=500,wE=5,cE=10,hc=1,Ih="amz-sdk-invocation-id",gh="amz-sdk-request";function dE(n,t){if(!pM.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=(QG(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 qG(n,t){return dE(n,t)}var uE=(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 yE(n){return(t)=>(i,r)=>async(s)=>{let f=await t.retryStrategy(),h=await t.maxAttempts();if(aG(f)){f=f;let _=await f.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),o=Error(),w=0,c=0,{request:d}=s,u=eh.isInstance(d);if(u)d.headers[Ih]=nE();while(!0)try{if(u)d.headers[gh]=`attempt=${w+1}; max=${h}`;let{response:y,output:R}=await i(s);return f.recordSuccess(_),R.$metadata.attempts=w+1,R.$metadata.totalRetryDelay=c,{response:y,output:R}}catch(y){let R=ZG(y,t.logger);if(o=uE(y),u&&n(d))throw(r.logger instanceof JG?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),o;try{_=await f.refreshRetryTokenForRetry(_,R)}catch(E){if(!o.$metadata)o.$metadata={};throw o.$metadata.attempts=w+1,o.$metadata.totalRetryDelay=c,o}w=_.getRetryCount();let M=_.getRetryDelay();if(c+=(_?.$retryLog?.acquisitionDelay??0)+M,M>0)await kG(M)}}else{if(f=f,f?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",f.mode]];return f.retry(i,s)}}}var kG=(n)=>new Promise((t)=>setTimeout(t,n)),aG=(n)=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",ZG=(n,t)=>{let i={error:n,errorType:vG(n)},r=dE(n.$response,t);if(r)i.retryAfterHint=r;return i},vG=(n)=>{if(Pf(n))return"THROTTLING";if(Xf(n))return"TRANSIENT";if(fE(n))return"SERVER_ERROR";return"CLIENT_ERROR"},AE={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function pG(n){let t=yE(n);return(i)=>({applyToStack:(r)=>{r.add(t(i),AE)}})}class Cf{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"||Pf(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)=>Cf.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 Pn{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Pn.v2026?50:100}static throttlingDelay(){return Pn.v2026?1000:500}static cost(){return Pn.v2026?14:5}static throttlingCost(){return Pn.v2026?5:10}static modifiedCostType(){return Pn.v2026?"THROTTLING":"TRANSIENT"}}class RE{x=Pn.delay();computeNextBackoffDelay(n){let t=Math.random(),i=2,r=t*Math.min(this.x*2**n,Lh);return Math.floor(r)}setDelayBase(n){this.x=n}}class rc{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(Lh,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Ei;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(Ei||(Ei={}));var Or=3,ME=Ei.STANDARD,Th={incompatible:1,attempts:2,capacity:3},Yf=class{mode=Ei.STANDARD;retryBackoffStrategy;capacity=Oh;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()=>Or,this.baseDelay??=Pn.delay(),this.retryBackoffStrategy??=new RE}async acquireInitialRetryToken(t){return new rc(Pn.delay(),0,void 0,Pn.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"?Pn.throttlingDelay():this.baseDelay);let o=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),w=o;if(i.retryAfterHint instanceof Date)w=Math.max(o,Math.min(i.retryAfterHint.getTime()-Date.now(),o+5000));if(!f){let c=Pn.v2026&&s===Th.capacity&&h?w:0;if(c>0)await new Promise((d)=>setTimeout(d,c))}else{let c=this.getCapacityCost(_);this.capacity-=c;let d=new rc(0,t.getRetryCount()+1,c,t.isLongPoll?.()??!1);return await new Promise((u)=>setTimeout(u,w)),d.$retryLog.acquisitionDelay=w,d}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(Oh,this.capacity+(t.getRetryCost()??hc))}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 ${Or}`),Or}}retryCode(t,i,r){let s=t.getRetryCount()+1,f=this.isRetryableError(i.errorType)?0:Th.incompatible,h=s<r?0:Th.attempts,_=this.capacity>=this.getCapacityCost(i.errorType)?0:Th.capacity;return f||h||_}getCapacityCost(t){return t===Pn.modifiedCostType()?Pn.throttlingCost():Pn.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},EE=class{mode=Ei.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,i){let{rateLimiter:r}=i??{};this.rateLimiter=r??new Cf,this.standardRetryStrategy=i?new Yf({maxAttempts:typeof t==="number"?t:3,...i}):new Yf(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 TE extends Yf{computeNextBackoffDelay;constructor(n,t=Pn.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 nH=(n,t)=>{let i=n,r=hc,s=wE,f=cE,h=n,_=(d)=>d.name==="TimeoutError"?f:s,o=(d)=>_(d)<=h;return Object.freeze({hasRetryTokens:o,retrieveRetryTokens:(d)=>{if(!o(d))throw Error("No retry token available");let u=_(d);return h-=u,u},releaseRetryTokens:(d)=>{h+=d??r,h=Math.min(h,i)}})},eE=(n,t)=>Math.floor(Math.min(Lh,Math.random()*2**t*n)),OE=(n)=>{if(!n)return!1;return _c(n)||iE(n)||Pf(n)||Xf(n)};class oc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Ei.STANDARD;constructor(n,t){this.maxAttemptsProvider=n,this.retryDecider=t?.retryDecider??OE,this.delayDecider=t?.delayDecider??eE,this.retryQuota=t?.retryQuota??nH(Oh)}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=Or}return n}async retry(n,t,i){let r,s=0,f=0,h=await this.getMaxAttempts(),{request:_}=t;if(eh.isInstance(_))_.headers[Ih]=nE();while(!0)try{if(eh.isInstance(_))_.headers[gh]=`attempt=${s+1}; max=${h}`;if(i?.beforeRequest)await i.beforeRequest();let{response:o,output:w}=await n(t);if(i?.afterRequest)i.afterRequest(o);return this.retryQuota.releaseRetryTokens(r),w.$metadata.attempts=s+1,w.$metadata.totalRetryDelay=f,{response:o,output:w}}catch(o){let w=uE(o);if(s++,this.shouldRetry(w,s,h)){r=this.retryQuota.retrieveRetryTokens(w);let c=this.delayDecider(Pf(w)?oE:hE,s),d=tH(w.$response),u=Math.max(d||0,c);f+=u,await new Promise((y)=>setTimeout(y,u));continue}if(!w.$metadata)w.$metadata={};throw w.$metadata.attempts=s,w.$metadata.totalRetryDelay=f,w}}}var tH=(n)=>{if(!pM.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 LE extends oc{rateLimiter;constructor(n,t){let{rateLimiter:i,...r}=t??{};super(n,r);this.rateLimiter=i??new Cf,this.mode=Ei.ADAPTIVE}async retry(n,t){return super.retry(n,t,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(i)=>{this.rateLimiter.updateClientSendingRate(i)}})}}var sc="AWS_MAX_ATTEMPTS",fc="max_attempts",iH={environmentVariableSelector:(n)=>{let t=n[sc];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Environment variable ${sc} mast be a number, got "${t}"`);return i},configFileSelector:(n)=>{let t=n[fc];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Shared config file entry ${fc} mast be a number, got "${t}"`);return i},default:Or},rH=(n,t)=>{let{retryStrategy:i,retryMode:r}=n,{defaultMaxAttempts:s=Or,defaultBaseDelay:f=Pn.delay()}=t??{},h=vM(n.maxAttempts??s),_=i?Promise.resolve(i):void 0,o=async()=>{let w=await h();if(await vM(r)()===Ei.ADAPTIVE)return new EE(h,{maxAttempts:w,baseDelay:f});return new Yf({maxAttempts:w,baseDelay:f})};return Object.assign(n,{maxAttempts:h,retryStrategy:()=>_??=o()})},IE="AWS_RETRY_MODE",gE="retry_mode",sH={environmentVariableSelector:(n)=>n[IE],configFileSelector:(n)=>n[gE],default:ME},NE=()=>(n)=>async(t)=>{let{request:i}=t;if(eh.isInstance(i))delete i.headers[Ih],delete i.headers[gh];return n(t)},bE={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},fH=(n)=>({applyToStack:(t)=>{t.addRelativeTo(NE(),bE)}}),_H=yE(tE),hH=pG(tE);oH.AdaptiveRetryStrategy=EE;oH.CONFIG_MAX_ATTEMPTS=fc;oH.CONFIG_RETRY_MODE=gE;oH.ConfiguredRetryStrategy=TE;oH.DEFAULT_MAX_ATTEMPTS=Or;oH.DEFAULT_RETRY_DELAY_BASE=hE;oH.DEFAULT_RETRY_MODE=ME;oH.DefaultRateLimiter=Cf;oH.DeprecatedAdaptiveRetryStrategy=LE;oH.DeprecatedStandardRetryStrategy=oc;oH.ENV_MAX_ATTEMPTS=sc;oH.ENV_RETRY_MODE=IE;oH.INITIAL_RETRY_TOKENS=Oh;oH.INVOCATION_ID_HEADER=Ih;oH.MAXIMUM_RETRY_DELAY=Lh;oH.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=iH;oH.NODE_RETRY_MODE_CONFIG_OPTIONS=sH;oH.NO_RETRY_INCREMENT=hc;oH.REQUEST_HEADER=gh;oH.RETRY_COST=wE;oH.RETRY_MODES=Ei;oH.Retry=Pn;oH.StandardRetryStrategy=Yf;oH.THROTTLING_RETRY_DELAY_BASE=oE;oH.TIMEOUT_RETRY_COST=cE;oH.defaultDelayDecider=eE;oH.defaultRetryDecider=OE;oH.getOmitRetryHeadersPlugin=fH;oH.getRetryAfterHint=qG;oH.getRetryPlugin=hH;oH.isBrowserNetworkError=sE;oH.isClockSkewCorrectedError=rE;oH.isClockSkewError=iE;oH.isNodeJsHttp2TransientError=_E;oH.isRetryableByTrait=_c;oH.isServerError=fE;oH.isThrottlingError=Pf;oH.isTransientError=Xf;oH.omitRetryHeadersMiddleware=NE;oH.omitRetryHeadersMiddlewareOptions=bE;oH.resolveRetryConfig=rH;oH.retryMiddleware=_H;oH.retryMiddlewareOptions=AE});var lE=rn((vH)=>{var mi={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")},wc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!wc)globalThis.awslambda=globalThis.awslambda||{};class Nh{static PROTECTED_KEYS=mi;isProtectedKey(n){return Object.values(mi).includes(n)}getRequestId(){return this.get(mi.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(mi.X_RAY_TRACE_ID)}getTenantId(){return this.get(mi.TENANT_ID)}getTraceparent(){return this.get(mi.TRACEPARENT)}getTracestate(){return this.get(mi.TRACESTATE)}getBaggage(){return this.get(mi.BAGGAGE)}}class SE extends Nh{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 dc extends Nh{als;static async create(){let n=new dc,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)}}vH.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 dc.create():new SE;if(!wc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!wc&&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})(vH.InvokeStore||(vH.InvokeStore={}));vH.InvokeStoreBase=Nh});var zi=rn((R3)=>{var{getSmithyContext:uc}=Vt();R3.getSmithyContext=uc;var{HttpRequest:yc}=nt(),{requestBuilder:n3}=nt();R3.requestBuilder=n3;var{HttpApiKeyAuthLocation:$E}=yr(),t3=(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 i3(n){let t=new Map;for(let i of n)t.set(i.schemeId,i);return t}var Ac=(n,t)=>(i,r)=>async(s)=>{let f=n.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(n,r,s.input)),h=n.authSchemePreference?await n.authSchemePreference():[],_=t3(f,h),o=i3(n.httpAuthSchemes),w=uc(r),c=[];for(let d of _){let u=o.get(d.schemeId);if(!u){c.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}let y=u.identityProvider(await t.identityProviderConfigProvider(n));if(!y){c.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:R={},signingProperties:M={}}=d.propertiesExtractor?.(n,r)||{};d.identityProperties=Object.assign(d.identityProperties||{},R),d.signingProperties=Object.assign(d.signingProperties||{},M),w.selectedHttpAuthScheme={httpAuthOption:d,identity:await y(d.identityProperties),signer:u.signer};break}if(!w.selectedHttpAuthScheme)throw Error(c.join(`
|
|
24
|
-
`));return i(s)},UE={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},r3=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Ac(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),UE)}}),DE={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},s3=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Ac(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),DE)}}),f3=(n)=>(t)=>{throw t},_3=(n,t)=>{},BE=(n)=>(t,i)=>async(r)=>{if(!yc.isInstance(r.request))return t(r);let f=uc(i).selectedHttpAuthScheme;if(!f)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:h={}},identity:_,signer:o}=f,w=await t({...r,request:await o.sign(r.request,_,h)}).catch((o.errorHandler||f3)(h));return(o.successHandler||_3)(w.response,h),w},GE={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},h3=(n)=>({applyToStack:(t)=>{t.addRelativeTo(BE(),GE)}}),o3=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t},w3=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,_,...o){let w=_,c=h.startingToken??w[i],d=!0,u;while(d){if(w[i]=c,s)w[s]=w[s]??h.pageSize;if(h.client instanceof n)u=await w3(t,h.client,_,h.withCommand,...o);else throw Error(`Invalid client, expected instance of ${n.name}`);yield u;let y=c;c=d3(u,r),d=!!(c&&(!h.stopOnSameToken||c!==y))}return}}var d3=(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 u3(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 HE{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 WE{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=yc.clone(n);if(i.in===$E.QUERY)r.query[i.name]=t.apiKey;else if(i.in===$E.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 FE{async sign(n,t,i){let r=yc.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 YE{async sign(n,t,i){return n}}var PE=(n)=>function(i){return CE(i)&&i.expiration.getTime()-Date.now()<n},XE=300000,y3=PE(XE),CE=(n)=>n.expiration!==void 0,A3=(n,t,i)=>{if(n===void 0)return;let r=typeof n!=="function"?async()=>Promise.resolve(n):n,s,f,h,_=!1,o=async(w)=>{if(!f)f=r(w);try{s=await f,h=!0,_=!1}finally{f=void 0}return s};if(t===void 0)return async(w)=>{if(!h||w?.forceRefresh)s=await o(w);return s};return async(w)=>{if(!h||w?.forceRefresh)s=await o(w);if(_)return s;if(!i(s))return _=!0,s;if(t(s))return await o(w),s;return s}};R3.DefaultIdentityProviderConfig=HE;R3.EXPIRATION_MS=XE;R3.HttpApiKeyAuthSigner=WE;R3.HttpBearerAuthSigner=FE;R3.NoAuthSigner=YE;R3.createIsIdentityExpiredFunction=PE;R3.createPaginator=c3;R3.doesIdentityRequireRefresh=CE;R3.getHttpAuthSchemeEndpointRuleSetPlugin=r3;R3.getHttpAuthSchemePlugin=s3;R3.getHttpSigningPlugin=h3;R3.httpAuthSchemeEndpointRuleSetMiddlewareOptions=UE;R3.httpAuthSchemeMiddleware=Ac;R3.httpAuthSchemeMiddlewareOptions=DE;R3.httpSigningMiddleware=BE;R3.httpSigningMiddlewareOptions=GE;R3.isIdentityExpired=y3;R3.memoizeIdentityProvider=A3;R3.normalizeProvider=o3;R3.setFeature=u3});var JE=rn((Qf,Rc)=>{(function(n,t){typeof Qf=="object"&&typeof Rc=="object"?Rc.exports=t():typeof define=="function"&&define.amd?define([],t):typeof Qf=="object"?Qf.bowser=t():n.bowser=t()})(Qf,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 o=_.match(h);return o&&o.length>0&&o[1]||""},f.getSecondMatch=function(h,_){var o=_.match(h);return o&&o.length>1&&o[2]||""},f.matchAndReturnConst=function(h,_,o){if(h.test(_))return o},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(c){return parseInt(c,10)||0});_.push(0);var o=_[0],w=_[1];if(o===10)switch(w){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(o){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(o){return parseInt(o,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,_,o){o===void 0&&(o=!1);var w=f.getVersionPrecision(h),c=f.getVersionPrecision(_),d=Math.max(w,c),u=0,y=f.map([h,_],function(R){var M=d-f.getVersionPrecision(R),E=R+Array(M+1).join(".0");return f.map(E.split("."),function(T){return Array(20-T.length).join("0")+T}).reverse()});for(o&&(u=d-Math.min(w,c)),d-=1;d>=u;){if(y[0][d]>y[1][d])return 1;if(y[0][d]===y[1][d]){if(d===u)return 0;d-=1}else if(y[0][d]<y[1][d])return-1}},f.map=function(h,_){var o,w=[];if(Array.prototype.map)return Array.prototype.map.call(h,_);for(o=0;o<h.length;o+=1)w.push(_(h[o]));return w},f.find=function(h,_){var o,w;if(Array.prototype.find)return Array.prototype.find.call(h,_);for(o=0,w=h.length;o<w;o+=1){var c=h[o];if(_(c,o))return c}},f.assign=function(h){for(var _,o,w=h,c=arguments.length,d=Array(c>1?c-1:0),u=1;u<c;u++)d[u-1]=arguments[u];if(Object.assign)return Object.assign.apply(Object,[h].concat(d));var y=function(){var R=d[_];typeof R=="object"&&R!==null&&Object.keys(R).forEach(function(M){w[M]=R[M]})};for(_=0,o=d.length;_<o;_+=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(o,w){for(var c=0;c<w.length;c++){var d=w[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(o,d.key,d)}}var _=function(){function o(){}var w,c,d;return o.getParser=function(u,y,R){if(y===void 0&&(y=!1),R===void 0&&(R=null),typeof u!="string")throw Error("UserAgent should be a string");return new s.default(u,y,R)},o.parse=function(u,y){return y===void 0&&(y=null),new s.default(u,y).getResult()},w=o,d=[{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}}],(c=null)&&h(w.prototype,c),d&&h(w,d),o}();t.default=_,n.exports=t.default},91:function(n,t,i){t.__esModule=!0,t.default=void 0;var r=o(i(92)),s=o(i(93)),f=o(i(94)),h=o(i(95)),_=o(i(17));function o(c){return c&&c.__esModule?c:{default:c}}var w=function(){function c(u,y,R){if(y===void 0&&(y=!1),R===void 0&&(R=null),u==null||u==="")throw Error("UserAgent parameter can't be empty");this._ua=u;var M=!1;typeof y=="boolean"?(M=y,this._hints=R):this._hints=y!=null&&typeof y=="object"?y:null,this.parsedResult={},M!==!0&&this.parse()}var d=c.prototype;return d.getHints=function(){return this._hints},d.hasBrand=function(u){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var y=u.toLowerCase();return this._hints.brands.some(function(R){return R.brand&&R.brand.toLowerCase()===y})},d.getBrandVersion=function(u){if(this._hints&&Array.isArray(this._hints.brands)){var y=u.toLowerCase(),R=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===y});return R?R.version:void 0}},d.getUA=function(){return this._ua},d.test=function(u){return u.test(this._ua)},d.parseBrowser=function(){var u=this;this.parsedResult.browser={};var y=_.default.find(r.default,function(R){if(typeof R.test=="function")return R.test(u);if(Array.isArray(R.test))return R.test.some(function(M){return u.test(M)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.browser=y.describe(this.getUA(),this)),this.parsedResult.browser},d.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},d.getBrowserName=function(u){return u?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},d.getBrowserVersion=function(){return this.getBrowser().version},d.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},d.parseOS=function(){var u=this;this.parsedResult.os={};var y=_.default.find(s.default,function(R){if(typeof R.test=="function")return R.test(u);if(Array.isArray(R.test))return R.test.some(function(M){return u.test(M)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.os=y.describe(this.getUA())),this.parsedResult.os},d.getOSName=function(u){var y=this.getOS().name;return u?String(y).toLowerCase()||"":y||""},d.getOSVersion=function(){return this.getOS().version},d.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},d.getPlatformType=function(u){u===void 0&&(u=!1);var y=this.getPlatform().type;return u?String(y).toLowerCase()||"":y||""},d.parsePlatform=function(){var u=this;this.parsedResult.platform={};var y=_.default.find(f.default,function(R){if(typeof R.test=="function")return R.test(u);if(Array.isArray(R.test))return R.test.some(function(M){return u.test(M)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.platform=y.describe(this.getUA())),this.parsedResult.platform},d.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},d.getEngineName=function(u){return u?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},d.parseEngine=function(){var u=this;this.parsedResult.engine={};var y=_.default.find(h.default,function(R){if(typeof R.test=="function")return R.test(u);if(Array.isArray(R.test))return R.test.some(function(M){return u.test(M)});throw Error("Browser's test function is not valid")});return y&&(this.parsedResult.engine=y.describe(this.getUA())),this.parsedResult.engine},d.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},d.getResult=function(){return _.default.assign({},this.parsedResult)},d.satisfies=function(u){var y=this,R={},M=0,E={},T=0;if(Object.keys(u).forEach(function(b){var H=u[b];typeof H=="string"?(E[b]=H,T+=1):typeof H=="object"&&(R[b]=H,M+=1)}),M>0){var O=Object.keys(R),e=_.default.find(O,function(b){return y.isOS(b)});if(e){var L=this.satisfies(R[e]);if(L!==void 0)return L}var N=_.default.find(O,function(b){return y.isPlatform(b)});if(N){var l=this.satisfies(R[N]);if(l!==void 0)return l}}if(T>0){var Y=Object.keys(E),V=_.default.find(Y,function(b){return y.isBrowser(b,!0)});if(V!==void 0)return this.compareVersion(E[V])}},d.isBrowser=function(u,y){y===void 0&&(y=!1);var R=this.getBrowserName().toLowerCase(),M=u.toLowerCase(),E=_.default.getBrowserTypeByAlias(M);return y&&E&&(M=E.toLowerCase()),M===R},d.compareVersion=function(u){var y=[0],R=u,M=!1,E=this.getBrowserVersion();if(typeof E=="string")return u[0]===">"||u[0]==="<"?(R=u.substr(1),u[1]==="="?(M=!0,R=u.substr(2)):y=[],u[0]===">"?y.push(1):y.push(-1)):u[0]==="="?R=u.substr(1):u[0]==="~"&&(M=!0,R=u.substr(1)),y.indexOf(_.default.compareVersions(E,R,M))>-1},d.isOS=function(u){return this.getOSName(!0)===String(u).toLowerCase()},d.isPlatform=function(u){return this.getPlatformType(!0)===String(u).toLowerCase()},d.isEngine=function(u){return this.getEngineName(!0)===String(u).toLowerCase()},d.is=function(u,y){return y===void 0&&(y=!1),this.isBrowser(u,y)||this.isOS(u)||this.isPlatform(u)},d.some=function(u){var y=this;return u===void 0&&(u=[]),u.some(function(R){return y.is(R)})},c}();t.default=w,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 o={name:"GPTBot"},w=s.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/chatgpt-user/i],describe:function(_){var o={name:"ChatGPT-User"},w=s.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/oai-searchbot/i],describe:function(_){var o={name:"OAI-SearchBot"},w=s.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(_){var o={name:"ClaudeBot"},w=s.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(_){var o={name:"Omgilibot"},w=s.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/diffbot/i],describe:function(_){var o={name:"Diffbot"},w=s.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/perplexitybot/i],describe:function(_){var o={name:"PerplexityBot"},w=s.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/perplexity-user/i],describe:function(_){var o={name:"Perplexity-User"},w=s.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/youbot/i],describe:function(_){var o={name:"YouBot"},w=s.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/meta-webindexer/i],describe:function(_){var o={name:"Meta-WebIndexer"},w=s.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/meta-externalads/i],describe:function(_){var o={name:"Meta-ExternalAds"},w=s.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/meta-externalagent/i],describe:function(_){var o={name:"Meta-ExternalAgent"},w=s.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/meta-externalfetcher/i],describe:function(_){var o={name:"Meta-ExternalFetcher"},w=s.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/googlebot/i],describe:function(_){var o={name:"Googlebot"},w=s.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/linespider/i],describe:function(_){var o={name:"Linespider"},w=s.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/amazonbot/i],describe:function(_){var o={name:"AmazonBot"},w=s.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/bingbot/i],describe:function(_){var o={name:"BingCrawler"},w=s.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/baiduspider/i],describe:function(_){var o={name:"BaiduSpider"},w=s.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/duckduckbot/i],describe:function(_){var o={name:"DuckDuckBot"},w=s.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/ia_archiver/i],describe:function(_){var o={name:"InternetArchiveCrawler"},w=s.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(_){var o={name:"SlackBot"},w=s.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{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 o={name:"Opera"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/opr\/|opios/i],describe:function(_){var o={name:"Opera"},w=s.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/SamsungBrowser/i],describe:function(_){var o={name:"Samsung Internet for Android"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/Whale/i],describe:function(_){var o={name:"NAVER Whale Browser"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/PaleMoon/i],describe:function(_){var o={name:"Pale Moon"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/MZBrowser/i],describe:function(_){var o={name:"MZ Browser"},w=s.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/focus/i],describe:function(_){var o={name:"Focus"},w=s.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/swing/i],describe:function(_){var o={name:"Swing"},w=s.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/coast/i],describe:function(_){var o={name:"Opera Coast"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(_){var o={name:"Opera Touch"},w=s.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/yabrowser/i],describe:function(_){var o={name:"Yandex Browser"},w=s.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/ucbrowser/i],describe:function(_){var o={name:"UC Browser"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/Maxthon|mxios/i],describe:function(_){var o={name:"Maxthon"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/epiphany/i],describe:function(_){var o={name:"Epiphany"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/puffin/i],describe:function(_){var o={name:"Puffin"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/sleipnir/i],describe:function(_){var o={name:"Sleipnir"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/k-meleon/i],describe:function(_){var o={name:"K-Meleon"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/micromessenger/i],describe:function(_){var o={name:"WeChat"},w=s.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/qqbrowser/i],describe:function(_){var o={name:/qqbrowserlite/i.test(_)?"QQ Browser Lite":"QQ Browser"},w=s.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/msie|trident/i],describe:function(_){var o={name:"Internet Explorer"},w=s.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/\sedg\//i],describe:function(_){var o={name:"Microsoft Edge"},w=s.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/edg([ea]|ios)/i],describe:function(_){var o={name:"Microsoft Edge"},w=s.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/vivaldi/i],describe:function(_){var o={name:"Vivaldi"},w=s.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/seamonkey/i],describe:function(_){var o={name:"SeaMonkey"},w=s.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/sailfish/i],describe:function(_){var o={name:"Sailfish"},w=s.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,_);return w&&(o.version=w),o}},{test:[/silk/i],describe:function(_){var o={name:"Amazon Silk"},w=s.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/phantom/i],describe:function(_){var o={name:"PhantomJS"},w=s.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/slimerjs/i],describe:function(_){var o={name:"SlimerJS"},w=s.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(_){var o={name:"BlackBerry"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/(web|hpw)[o0]s/i],describe:function(_){var o={name:"WebOS Browser"},w=s.default.getFirstMatch(f,_)||s.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/bada/i],describe:function(_){var o={name:"Bada"},w=s.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/tizen/i],describe:function(_){var o={name:"Tizen"},w=s.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/qupzilla/i],describe:function(_){var o={name:"QupZilla"},w=s.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/librewolf/i],describe:function(_){var o={name:"LibreWolf"},w=s.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/firefox|iceweasel|fxios/i],describe:function(_){var o={name:"Firefox"},w=s.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/electron/i],describe:function(_){var o={name:"Electron"},w=s.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(_){var o={name:"Sogou Browser"},w=s.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,_),c=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,_),d=s.default.getFirstMatch(/se ([\d.]+)x/i,_),u=w||c||d;return u&&(o.version=u),o}},{test:[/MiuiBrowser/i],describe:function(_){var o={name:"Miui"},w=s.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:function(_){return!!_.hasBrand("DuckDuckGo")||_.test(/\sDdg\/[\d.]+$/i)},describe:function(_,o){var w={name:"DuckDuckGo"};if(o){var c=o.getBrandVersion("DuckDuckGo");if(c)return w.version=c,w}var d=s.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,_);return d&&(w.version=d),w}},{test:function(_){return _.hasBrand("Brave")},describe:function(_,o){var w={name:"Brave"};if(o){var c=o.getBrandVersion("Brave");if(c)return w.version=c,w}return w}},{test:[/chromium/i],describe:function(_){var o={name:"Chromium"},w=s.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,_)||s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/chrome|crios|crmo/i],describe:function(_){var o={name:"Chrome"},w=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/GSA/i],describe:function(_){var o={name:"Google Search"},w=s.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:function(_){var o=!_.test(/like android/i),w=_.test(/android/i);return o&&w},describe:function(_){var o={name:"Android Browser"},w=s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/playstation 4/i],describe:function(_){var o={name:"PlayStation 4"},w=s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/safari|applewebkit/i],describe:function(_){var o={name:"Safari"},w=s.default.getFirstMatch(f,_);return w&&(o.version=w),o}},{test:[/.*/i],describe:function(_){var o=_.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:s.default.getFirstMatch(o,_),version:s.default.getSecondMatch(o,_)}}}];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 o=s.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,_);return{name:f.OS_MAP.Roku,version:o}}},{test:[/windows phone/i],describe:function(_){var o=s.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.WindowsPhone,version:o}}},{test:[/windows /i],describe:function(_){var o=s.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,_),w=s.default.getWindowsVersionName(o);return{name:f.OS_MAP.Windows,version:o,versionName:w}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(_){var o={name:f.OS_MAP.iOS},w=s.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,_);return w&&(o.version=w),o}},{test:[/macintosh/i],describe:function(_){var o=s.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,_).replace(/[_\s]/g,"."),w=s.default.getMacOSVersionName(o),c={name:f.OS_MAP.MacOS,version:o};return w&&(c.versionName=w),c}},{test:[/(ipod|iphone|ipad)/i],describe:function(_){var o=s.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,_).replace(/[_\s]/g,".");return{name:f.OS_MAP.iOS,version:o}}},{test:[/OpenHarmony/i],describe:function(_){var o=s.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.HarmonyOS,version:o}}},{test:function(_){var o=!_.test(/like android/i),w=_.test(/android/i);return o&&w},describe:function(_){var o=s.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,_),w=s.default.getAndroidVersionName(o),c={name:f.OS_MAP.Android,version:o};return w&&(c.versionName=w),c}},{test:[/(web|hpw)[o0]s/i],describe:function(_){var o=s.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,_),w={name:f.OS_MAP.WebOS};return o&&o.length&&(w.version=o),w}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(_){var o=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:o}}},{test:[/bada/i],describe:function(_){var o=s.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.Bada,version:o}}},{test:[/tizen/i],describe:function(_){var o=s.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.Tizen,version:o}}},{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 o=s.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,_);return{name:f.OS_MAP.PlayStation4,version:o}}}];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 o=s.default.getFirstMatch(/(can-l01)/i,_)&&"Nova",w={type:f.PLATFORMS_MAP.mobile,vendor:"Huawei"};return o&&(w.model=o),w}},{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 o=_.test(/ipod|iphone/i),w=_.test(/like (ipod|iphone)/i);return o&&!w},describe:function(_){var o=s.default.getFirstMatch(/(ipod|iphone)/i,_);return{type:f.PLATFORMS_MAP.mobile,vendor:"Apple",model:o}}},{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 o=s.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,_),w={type:f.PLATFORMS_MAP.mobile,vendor:"Nokia"};return o&&(w.model=o),w}},{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 o=Number(String(_.getOSVersion()).split(".")[0]);return _.getOSName(!0)==="android"&&o>=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 o=s.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,_);return{name:f.ENGINE_MAP.EdgeHTML,version:o}}},{test:[/trident/i],describe:function(_){var o={name:f.ENGINE_MAP.Trident},w=s.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:function(_){return _.test(/presto/i)},describe:function(_){var o={name:f.ENGINE_MAP.Presto},w=s.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:function(_){var o=_.test(/gecko/i),w=_.test(/like gecko/i);return o&&!w},describe:function(_){var o={name:f.ENGINE_MAP.Gecko},w=s.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:f.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(_){var o={name:f.ENGINE_MAP.WebKit},w=s.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,_);return w&&(o.version=w),o}}];t.default=h,n.exports=t.default}})})});var Dt=rn((GW)=>{var{Retry:X3,RETRY_MODES:QE}=Jf(),{HttpRequest:Lc,parseUrl:C3}=nt(),{InvokeStore:mE}=lE(),{normalizeProvider:J3}=zi(),{platform:Q3,release:m3}=dn("os"),{versions:Mc,env:zE}=dn("process"),{isValidHostLabel:z3,isIpAddress:qE,customEndpointFunctions:K3}=Mr(),{EndpointError:V3,resolveEndpoint:x3}=Mr();GW.EndpointError=V3;GW.isIpAddress=qE;GW.resolveEndpoint=x3;var{loadConfig:j3,NODE_REGION_CONFIG_OPTIONS:kE,NODE_REGION_CONFIG_FILE_OPTIONS:aE}=vn(),{REGION_ENV_NAME:q3,REGION_INI_NAME:k3,resolveRegionConfig:a3}=vn();GW.NODE_REGION_CONFIG_FILE_OPTIONS=aE;GW.NODE_REGION_CONFIG_OPTIONS=kE;GW.REGION_ENV_NAME=q3;GW.REGION_INI_NAME=k3;GW.resolveRegionConfig=a3;var Sh={warningEmitted:!1},Z3=(n)=>{if(n&&!Sh.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Sh.warningEmitted=!0;return}let t=parseInt(n.substring(1,n.indexOf("."))),i=22;if(t<i)Sh.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
22
|
+
`)}d.push(null)}),d}async function l$(n,t){let i=0,r=[],s=n.getReader(),f=!1;while(!f){let{done:h,value:e}=await s.read();if(e)r.push(e),i+=e?.byteLength??0;if(i>=t)break;f=h}s.releaseLock();let _=new Uint8Array(Math.min(t,i)),o=0;for(let h of r){if(h.byteLength>_.byteLength-o){_.set(h.subarray(0,_.byteLength-o),o);break}else _.set(h,o);o+=h.length}return _}var T$=(n,t)=>{if(vt(n))return l$(n,t);return new Promise((i,r)=>{let s=new g$;s.limit=t,n.pipe(s),n.on("error",(f)=>{s.end(),r(f)}),s.on("error",r),s.on("finish",function(){let f=b_(this.buffers);i(f)})})},g$=class extends iR{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()}},O$=(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)},L$=async(n)=>{if(N_(n))return NR(n);return UR(n)};async function NR(n){return n.arrayBuffer().then((t)=>new Uint8Array(t))}async function UR(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 b_(t,r)}var pA="The stream has already been transformed.",I$=(n)=>{if(!nR(n)&&!vt(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(pA);return t=!0,await L$(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 LR(f);else if(s==="hex")return yR(f);else if(s===void 0||s==="utf8"||s==="utf-8")return O$(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(pA);if(t=!0,nR(n))return r(n);else if(vt(n))return n;else throw Error(`Cannot transform payload to web stream, got ${n}`)}})},nR=(n)=>typeof Blob==="function"&&n instanceof Blob,$R=(n)=>{if(N_(n))return NR(n);if(vt(n))return UR(n);return new Promise((t,i)=>{let r=new DR,s=n;s.pipe(r),s.on("error",(f)=>{r.end(),i(f)}),r.on("error",i),r.on("finish",function(){let f=b_(this.bufferedBytes);t(f)})})};class DR extends iR{bufferedBytes=[];_write(n,t,i){this.bufferedBytes.push(n),i()}}var tR="The stream has already been transformed.",S$=(n)=>{if(!(n instanceof Ts))try{return I$(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(tR);return t=!0,await $R(n)};return Object.assign(n,{transformToByteArray:i,transformToString:async(r)=>{let s=await i();if(r===void 0||Buffer.isEncoding(r))return Os(s.buffer,s.byteOffset,s.byteLength).toString(r);else return new TextDecoder(r).decode(s)},transformToWebStream:()=>{if(t)throw Error(tR);if(n.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Ts.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return t=!0,Ts.toWeb(n)}})};async function b$(n){if(typeof n.stream==="function")n=n.stream();return n.tee()}async function N$(n){if(vt(n)||N_(n))return b$(n);let t=new qA,i=new qA;return n.pipe(t),n.pipe(i),[t,i]}class BR extends dU(fR,I_,Qe,sR){}var U$=sU,GR=uU(U$),$$=GR;D$.ChecksumStream=gR;D$.Hash=TR;D$.LazyJsonString=gr;D$.NumericValue=S_;D$.Uint8ArrayBlobAdapter=BR;D$._parseEpochTimestamp=n$;D$._parseRfc3339DateTimeWithOffset=t$;D$._parseRfc7231DateTime=i$;D$.calculateBodyLength=_$;D$.concatBytes=b_;D$.copyDocumentWithTransform=wU;D$.createBufferedReadable=R$;D$.createChecksumStream=y$;D$.dateToUtcString=DU;D$.deserializerMiddleware=RR;D$.deserializerMiddlewareOption=ER;D$.expectBoolean=AU;D$.expectByte=Xe;D$.expectFloat32=T_;D$.expectInt=MU;D$.expectInt32=Pe;D$.expectLong=Jf;D$.expectNonNull=lU;D$.expectNumber=Xf;D$.expectObject=oR;D$.expectShort=Ye;D$.expectString=TU;D$.expectUnion=gU;D$.fromArrayBuffer=Os;D$.fromBase64=sR;D$.fromHex=o$;D$.fromString=L_;D$.fromUtf8=I_;D$.generateIdempotencyToken=$$;D$.getAwsChunkedEncodingStream=E$;D$.getSerdePlugin=h$;D$.handleFloat=IU;D$.headStream=T$;D$.isArrayBuffer=rR;D$.isBlob=N_;D$.isReadableStream=vt;D$.limitedParseDouble=Ke;D$.limitedParseFloat=SU;D$.limitedParseFloat32=bU;D$.logger=Qf;D$.nv=f$;D$.parseBoolean=yU;D$.parseEpochTimestamp=YU;D$.parseRfc3339DateTime=GU;D$.parseRfc3339DateTimeWithOffset=HU;D$.parseRfc7231DateTime=PU;D$.quoteHeader=jU;D$.sdkStreamMixin=S$;D$.serializerMiddleware=MR;D$.serializerMiddlewareOption=lR;D$.splitEvery=r$;D$.splitHeader=s$;D$.splitStream=N$;D$.streamCollector=$R;D$.strictParseByte=cR;D$.strictParseDouble=ze;D$.strictParseFloat=OU;D$.strictParseFloat32=_R;D$.strictParseInt=NU;D$.strictParseInt32=UU;D$.strictParseLong=eR;D$.strictParseShort=Ls;D$.toBase64=Qe;D$.toHex=yR;D$.toUint8Array=AR;D$.toUtf8=fR;D$.v4=GR});var tc=sn((MB)=>{var{createReadStream:qD}=un("fs"),{Writable:kD}=un("stream"),{toUint8Array:bs,concatBytes:ZD}=tt(),{createHash:af,createHmac:vD}=un("crypto"),mR=un("zlib");async function PR(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 pD=async function(t,i){let r=new t;return await PR(i,(s)=>{r.update(s)}),r.digest()};class ve extends kD{hash;constructor(n,t){super(t);this.hash=n}_write(n,t,i){try{this.hash.update(bs(n))}catch(r){return i(r)}i()}}var nB=(n,t)=>new Promise((i,r)=>{if(!tB(t)){r(Error("Unable to calculate hash for non-file streams."));return}let s=qD(t.path,{start:t.start,end:t.end}),f=new n,_=new ve(f);s.pipe(_),s.on("error",(o)=>{_.end(),r(o)}),_.on("error",r),_.on("finish",function(){f.digest().then(i).catch(r)})}),tB=(n)=>typeof n.path==="string",iB=(n,t)=>{if(t.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let i=new n,r=new ve(i);return t.pipe(r),new Promise((s,f)=>{t.on("error",(_)=>{r.end(),f(_)}),r.on("error",f),r.on("finish",()=>{i.digest().then(s).catch(f)})})};class pe{digestLength=16;state=Uint32Array.from(HR);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(n){let t=bs(n),i=0,r=t.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,t[i++]),--r,this.bufferLength===64)ke(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 _=i;_<64;++_)t.setUint8(_,0);ke(n,t),i=0}for(let _=i;_<56;++_)t.setUint8(_,0);t.setUint32(56,r>>>0,!0),t.setUint32(60,Math.floor(r/4294967296),!0),ke(n,t);let s=new Uint8Array(16),f=new DataView(s.buffer);for(let _=0;_<4;++_)f.setUint32(_*4,n[_],!0);return s}reset(){this.state.set(HR),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var HR=[1732584193,4023233417,2562383102,271733878],Ki=4294967295,rB=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),sB=Array.from({length:64},(n,t)=>Math.abs(Math.sin(t+1))*4294967296>>>0);function ke(n,t){let i=n[0],r=n[1],s=n[2],f=n[3];for(let _=0;_<64;++_){let o,h;if(_<16)o=r&s|~r&f,h=_;else if(_<32)o=f&r|s&~f,h=(5*_+1)%16;else if(_<48)o=r^s^f,h=(3*_+5)%16;else o=s^(r|~f),h=7*_%16;let e=t.getUint32(h*4,!0),c=f;f=s,s=r;let d=rB[(_>>4)*4+(_&3)],u=(i+o&Ki)+(e+sB[_]&Ki)&Ki;r=r+((u<<d|u>>>32-d)>>>0)&Ki,i=c}n[0]=n[0]+i&Ki,n[1]=n[1]+r&Ki,n[2]=n[2]+s&Ki,n[3]=n[3]+f&Ki}var fB=(()=>{try{return af("md5"),!0}catch{return!1}})(),YR=fB?oB():pe;function oB(){return class{digestLength=16;hash=af("md5");update(t){this.hash.update(bs(t))}async digest(){let t=this.hash.copy().digest();return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}reset(){this.hash=af("md5")}}}var XR=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;XR[n]=t>>>0}var Ze=4294967295;class nc{digestLength=4;checksum=Ze;update(n){for(let t=0;t<n.length;++t)this.checksum=this.checksum>>>8^XR[(this.checksum^n[t])&255]}digestSync(){return(this.checksum^Ze)>>>0}async digest(){let n=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n,!1),t}reset(){this.checksum=Ze}}var WR=typeof mR.crc32==="function"?mR.crc32:void 0,JR=WR?_B(WR):nc;function _B(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 Jn=64,FR=32,hB=9007199254740991;class gi{digestLength=FR;state=Int32Array.from(CR);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(n){if(n){let t=gi.normalizeKey(n);this.inner=new gi,this.outer=new gi;let{inner:i,outer:r}=this,s=new Uint8Array(Jn*2);for(let f=0;f<Jn;++f)s[f]=54^t[f],s[f+Jn]=92^t[f];i.update(s.subarray(0,Jn)),r.update(s.subarray(Jn))}}update(n){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(n);return}let t=bs(n),i=0,{byteLength:r}=t;if(this.bytesHashed+=r,this.bytesHashed*8>hB)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=t[i++],r--,this.bufferLength===Jn)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(CR),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)%Jn>=Jn-8){for(let _=i;_<Jn;++_)s.setUint8(_,0);this.hashBufferWith(n,t),i=0}for(let _=i;_<Jn-8;++_)s.setUint8(_,0);s.setUint32(Jn-8,Math.floor(r/4294967296),!1),s.setUint32(Jn-4,r,!1),this.hashBufferWith(n,t);let f=new Uint8Array(FR);for(let _=0;_<8;++_)f[_*4]=n[_]>>>24&255,f[_*4+1]=n[_]>>>16&255,f[_*4+2]=n[_]>>>8&255,f[_*4+3]=n[_]>>>0&255;return f}static normalizeKey(n){let t=bs(n);if(t.byteLength>Jn){let i=new gi;i.update(t);let r=i.digestSync(),s=new Uint8Array(Jn);return s.set(r),s}if(t.byteLength<Jn){let i=new Uint8Array(Jn);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],_=n[3],o=n[4],h=n[5],e=n[6],c=n[7];for(let d=0;d<Jn;++d){if(d<16)i[d]=(t[d*4]&255)<<24|(t[d*4+1]&255)<<16|(t[d*4+2]&255)<<8|t[d*4+3]&255;else{let A=i[d-2],R=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=i[d-15];let M=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;i[d]=(R+i[d-7]|0)+(M+i[d-16]|0)}let u=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&h^~o&e)|0)+(c+(eB[d]+i[d]|0)|0)|0,w=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&s^r&f^s&f)|0;c=e,e=h,h=o,o=_+u|0,_=f,f=s,s=r,r=u+w|0}n[0]+=r,n[1]+=s,n[2]+=f,n[3]+=_,n[4]+=o,n[5]+=h,n[6]+=e,n[7]+=c}}var CR=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),eB=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]),cB=(()=>{try{return af("sha256"),!0}catch{return!1}})(),QR=cB?dB():gi;function dB(){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?vD("sha256",uB(this.secret)):af("sha256")}}}function uB(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:wB,sign:yB,importKey:AB}=globalThis?.crypto?.subtle??{},U_=typeof wB==="function"&&typeof yB==="function"&&typeof AB==="function"?globalThis.crypto.subtle:void 0,RB=8388608;class aR{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(n){if(n)this.secret=bs(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>=RB)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=ZD(this.pending);if(U_){if(this.secret){this.finished=!0;let r=await U_.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),s=await U_.sign("HMAC",r,n);return new Uint8Array(s)}let i=await U_.digest("SHA-256",n);return new Uint8Array(i)}let t=new gi(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 gi(this.secret);for(let t of this.pending)n.update(t);this.fallback=n,this.pending=[],this.pendingBytes=0}}MB.Crc32=JR;MB.Crc32Js=nc;MB.Crc32Node=JR;MB.Md5=YR;MB.Md5Js=pe;MB.Md5Node=YR;MB.Sha256=QR;MB.Sha256Js=gi;MB.Sha256Node=QR;MB.Sha256WebCrypto=aR;MB.blobHasher=pD;MB.blobReader=PR;MB.fileStreamHasher=nB;MB.readableStreamHasher=iB});var $_=sn((nG)=>{var{Crc32:xR}=tc(),{toHex:Ns,fromHex:GB,toUtf8:mB,fromUtf8:HB}=tt(),{Readable:WB}=un("stream");class Us{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)zR(t);return new Us(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)zR(n);return parseInt(Ns(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function zR(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 ic{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?Un.boolTrue:Un.boolFalse]);case"byte":return Uint8Array.from([Un.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Un.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Un.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=Un.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,Un.byteArray),s.setUint16(1,n.value.byteLength,!1);let f=new Uint8Array(s.buffer);return f.set(n.value,3),f;case"string":let _=this.fromUtf8(n.value),o=new DataView(new ArrayBuffer(3+_.byteLength));o.setUint8(0,Un.string),o.setUint16(1,_.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(_,3),h;case"timestamp":let e=new Uint8Array(9);return e[0]=Un.timestamp,e.set(Us.fromNumber(n.value.valueOf()).bytes,1),e;case"uuid":if(!zB.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Un.uuid,c.set(GB(n.value.replace(/-/g,"")),1),c}}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 Un.boolTrue:t[s]={type:KR,value:!0};break;case Un.boolFalse:t[s]={type:KR,value:!1};break;case Un.byte:t[s]={type:FB,value:n.getInt8(i++)};break;case Un.short:t[s]={type:CB,value:n.getInt16(i,!1)},i+=2;break;case Un.integer:t[s]={type:PB,value:n.getInt32(i,!1)},i+=4;break;case Un.long:t[s]={type:YB,value:new Us(new Uint8Array(n.buffer,n.byteOffset+i,8))},i+=8;break;case Un.byteArray:let f=n.getUint16(i,!1);i+=2,t[s]={type:XB,value:new Uint8Array(n.buffer,n.byteOffset+i,f)},i+=f;break;case Un.string:let _=n.getUint16(i,!1);i+=2,t[s]={type:JB,value:this.toUtf8(new Uint8Array(n.buffer,n.byteOffset+i,_))},i+=_;break;case Un.timestamp:t[s]={type:QB,value:new Date(new Us(new Uint8Array(n.buffer,n.byteOffset+i,8)).valueOf())},i+=8;break;case Un.uuid:let o=new Uint8Array(n.buffer,n.byteOffset+i,16);i+=16,t[s]={type:aB,value:`${Ns(o.subarray(0,4))}-${Ns(o.subarray(4,6))}-${Ns(o.subarray(6,8))}-${Ns(o.subarray(8,10))}-${Ns(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return t}}var Un;(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"})(Un||(Un={}));var KR="boolean",FB="byte",CB="short",PB="integer",YB="long",XB="binary",JB="string",QB="timestamp",aB="uuid",zB=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,VR=4,xi=VR*2,Or=4,KB=xi+Or*2;function xB({byteLength:n,byteOffset:t,buffer:i}){if(n<KB)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(VR,!1),_=r.getUint32(xi,!1),o=r.getUint32(n-Or,!1),h=new xR;if(h.update(new Uint8Array(i,t,xi)),_!==h.digestSync())throw Error(`The prelude checksum specified in the message (${_}) does not match the calculated CRC32 checksum (${h.digestSync()})`);if(h.update(new Uint8Array(i,t+xi,n-(xi+Or))),o!==h.digestSync())throw Error(`The message checksum (${h.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(i,t+xi+Or,f),body:new Uint8Array(i,t+xi+Or+f,s-f-(xi+Or+Or))}}class rc{headerMarshaller;messageBuffer;isEndOfStream;constructor(n,t){this.headerMarshaller=new ic(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),_=new xR;return f.setUint32(0,r,!1),f.setUint32(4,i.byteLength,!1),_.update(s.subarray(0,8)),f.setUint32(8,_.digestSync(),!1),s.set(i,12),s.set(t,i.byteLength+12),_.update(s.subarray(8,r-4)),f.setUint32(r-4,_.digestSync(),!1),s}decode(n){let{headers:t,body:i}=xB(n);return{headers:this.headerMarshaller.parse(t),body:i}}formatHeaders(n){return this.headerMarshaller.format(n)}}class sc{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 fc{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 oc{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 _c{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 jR(n){let t=0,i=0,r=null,s=null,f=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);t=o,i=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},_=async function*(){let o=n[Symbol.asyncIterator]();while(!0){let{value:h,done:e}=await o.next();if(e){if(!t)return;else if(t===i)yield r;else throw Error("Truncated event message received.");return}let c=h.length,d=0;while(d<c){if(!r){let w=c-d;if(!s)s=new Uint8Array(4);let A=Math.min(4-i,w);if(s.set(h.slice(d,d+A),i),i+=A,d+=A,i<4)break;f(new DataView(s.buffer).getUint32(0,!1)),s=null}let u=Math.min(t-i,c-d);if(r.set(h.slice(d,d+u),i),i+=u,d+=u,t&&t===i)yield r,r=null,t=0,i=0}}};return{[Symbol.asyncIterator]:_}}function VB(n,t){let i=hc(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 hc(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},_=await n(f);if(_.$unknown){let o=Error(t(i.body));throw o.name=s,o}throw _[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 ec=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:t,utf8Decoder:i}){this.eventStreamCodec=new rc(t,i),this.utfEncoder=t}deserialize(t,i){let r=jR(t);return new oc({messageStream:new sc({inputStream:r,decoder:this.eventStreamCodec}),deserializer:hc(i,this.utfEncoder)})}serialize(t,i){return new fc({messageStream:new _c({inputStream:t,serializer:i}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},jB=(n)=>new ec(n);class cc{universalMarshaller;constructor({utf8Encoder:n,utf8Decoder:t}){this.universalMarshaller=new ec({utf8Decoder:t,utf8Encoder:n})}deserialize(n,t){let i=typeof n[Symbol.asyncIterator]==="function"?n:kB(n);return this.universalMarshaller.deserialize(i,t)}serialize(n,t){return WB.from(this.universalMarshaller.serialize(n,t))}}var qB=(n)=>new cc(n);async function*kB(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 ZB=(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()}}}),vB=(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)}})},pB=(n)=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});class qR{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),_=this.serializer,o=this.defaultContentType,h=Symbol("initialRequestMarker"),e={async*[Symbol.asyncIterator](){if(i){let c={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};_.write(t,i);let d=_.flush();yield{[h]:!0,headers:c,body:d}}for await(let c of n)yield c}};return r.serialize(e,(c)=>{if(c[h])return{headers:c.headers,body:c.body};let d="";for(let E in c)if(E!=="__type"){d=E;break}let{additionalHeaders:u,body:w,eventType:A,explicitPayloadContentType:R}=this.writeEventBody(d,f,c);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:R??o},...u},body:w}})}async deserializeEventStream({response:n,responseSchema:t,initialResponseContainer:i}){let r=this.marshaller,s=t.getEventStreamMember(),_=t.getMemberSchema(s).getMemberSchemas(),o=Symbol("initialResponseMarker"),h=r.deserialize(n.body,async(d)=>{let u="";for(let A in d)if(A!=="__type"){u=A;break}let w=d[u].body;if(u==="initial-response"){let A=await this.deserializer.read(t,w);return delete A[s],{[o]:!0,...A}}else if(u in _){let A=_[u];if(A.isStructSchema()){let R={},M=!1;for(let[E,T]of A.structIterator()){let{eventHeader:l,eventPayload:g}=T.getMergedTraits();if(M=M||Boolean(l||g),g){if(T.isBlobSchema())R[E]=w;else if(T.isStringSchema())R[E]=(this.serdeContext?.utf8Encoder??mB)(w);else if(T.isStructSchema())R[E]=await this.deserializer.read(T,w)}else if(l){let O=d[u].headers[E]?.value;if(O!=null)if(T.isNumericSchema())if(O&&typeof O==="object"&&"bytes"in O)R[E]=BigInt(O.toString());else R[E]=Number(O);else R[E]=O}}if(M)return{[u]:R};if(w.byteLength===0)return{[u]:{}}}return{[u]:await this.deserializer.read(A,w)}}else return{$unknown:d}}),e=h[Symbol.asyncIterator](),c=await e.next();if(c.done)return h;if(c.value?.[o]){if(!t)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let d in c.value)i[d]=c.value[d]}return{async*[Symbol.asyncIterator](){if(!c?.value?.[o])yield c.value;while(!0){let{done:d,value:u}=await e.next();if(d)break;yield u}}}}writeEventBody(n,t,i){let r=this.serializer,s=n,f=null,_,o=(()=>{return t.getSchema()[4].includes(n)})(),h={};if(!o){let[d,u]=i[n];s=d,r.write(15,u)}else{let d=t.getMemberSchema(n);if(d.isStructSchema()){for(let[u,w]of d.structIterator()){let{eventHeader:A,eventPayload:R}=w.getMergedTraits();if(R)f=u;else if(A){let M=i[n][u],E="binary";if(w.isNumericSchema())if(-2147483648<=M&&M<=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(M!=null)h[u]={type:E,value:M},delete i[n][u]}}if(f!==null){let u=d.getMemberSchema(f);if(u.isBlobSchema())_="application/octet-stream";else if(u.isStringSchema())_="text/plain";r.write(u,i[n][f])}else r.write(d,i[n])}else if(d.isUnitSchema())r.write(d,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let e=r.flush()??new Uint8Array;return{body:typeof e==="string"?(this.serdeContext?.utf8Decoder??HB)(e):e,eventType:s,explicitPayloadContentType:_,additionalHeaders:h}}}nG.EventStreamCodec=rc;nG.EventStreamMarshaller=cc;nG.EventStreamSerde=qR;nG.HeaderMarshaller=ic;nG.Int64=Us;nG.MessageDecoderStream=sc;nG.MessageEncoderStream=fc;nG.SmithyMessageDecoderStream=oc;nG.SmithyMessageEncoderStream=_c;nG.UniversalEventStreamMarshaller=ec;nG.eventStreamSerdeProvider=qB;nG.getChunkedStream=jR;nG.getMessageUnmarshaller=hc;nG.getUnmarshalledStream=VB;nG.iterableToReadableStream=vB;nG.readableStreamToIterable=ZB;nG.resolveEventStreamSerdeConfig=pB;nG.universalEventStreamSerdeProvider=jB});var it=sn((XG)=>{var{Uint8ArrayBlobAdapter:dc,sdkStreamMixin:lG,splitEvery:TG,splitHeader:pR,fromBase64:kR,_parseEpochTimestamp:gG,_parseRfc7231DateTime:OG,_parseRfc3339DateTimeWithOffset:LG,LazyJsonString:nM,NumericValue:IG,toUtf8:tM,fromUtf8:SG,generateIdempotencyToken:bG,toBase64:ZR,dateToUtcString:NG,quoteHeader:UG}=tt(),{TypeRegistry:$G,NormalizedSchema:pt,translateTraits:iM}=Ji(),{HttpRequest:$s,HttpResponse:rM,isValidHostname:sM}=qt(),{parseQueryString:DG,parseUrl:BG}=qt();XG.HttpRequest=$s;XG.HttpResponse=rM;XG.isValidHostname=sM;XG.parseQueryString=DG;XG.parseUrl=BG;var{FieldPosition:GG}=Mr(),Lr=async(n=new Uint8Array,t)=>{if(n instanceof Uint8Array)return dc.mutate(n);if(!n)return dc.mutate(new Uint8Array);let i=t.streamCollector(n);return dc.mutate(await i)};function Kf(n){return encodeURIComponent(n).replace(/[!'()*]/g,function(t){return"%"+t.charCodeAt(0).toString(16).toUpperCase()})}class Ds{serdeContext;setSerdeContext(n){this.serdeContext=n}}class D_ extends Ds{options;compositeErrorRegistry;constructor(n){super();this.options=n,this.compositeErrorRegistry=$G.for(n.defaultNamespace);for(let t of n.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return $s}getResponseType(){return rM}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=pt.of(t.input),s=iM(t.traits??{});if(s.endpoint){let f=s.endpoint?.[0];if(typeof f==="string"){for(let[_,o]of r.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let h=i[_];if(typeof h!=="string")throw Error(`@smithy/core/schema - ${_} in input must be a string as hostLabel.`);f=f.replace(`{${_}}`,h)}if(n.hostname=f+n.hostname,!sM(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}=$_(),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 fM extends D_{async serializeRequest(n,t,i){let r=t&&typeof t==="object"?t:{},s=this.serializer,f={},_={},o=await i.endpoint(),h=pt.of(n?.input),e=[],c=[],d=!1,u,w=new $s({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:f,headers:_,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,n,r);let A=iM(n.traits);if(A.http){w.method=A.http[0];let[R,M]=A.http[1].split("?");if(w.path=="/")w.path=R;else w.path+=R;let E=new URLSearchParams(M??"");for(let[T,l]of E)f[T]=l}}for(let[A,R]of h.structIterator()){let M=R.getMergedTraits()??{},E=r[A];if(E==null&&!R.isIdempotencyToken()){if(M.httpLabel){if(w.path.includes(`{${A}+}`)||w.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:h})}else u=E;else s.write(R,E),u=s.flush();else if(M.httpLabel){s.write(R,E);let T=s.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,T.split("/").map(Kf).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Kf(T))}else if(M.httpHeader)s.write(R,E),_[M.httpHeader.toLowerCase()]=String(s.flush());else if(typeof M.httpPrefixHeaders==="string")for(let T in E){let l=E[T],g=M.httpPrefixHeaders+T;s.write([R.getValueSchema(),{httpHeader:g}],l),_[g.toLowerCase()]=s.flush()}else if(M.httpQuery||M.httpQueryParams)this.serializeQuery(R,E,f);else d=!0,e.push(A),c.push(R)}if(d&&r){let[A,R]=(h.getName(!0)??"#Unknown").split("#"),M=h.getSchema()[6],E=[3,A,R,h.getMergedTraits(),e,c,void 0];if(M)E[6]=M;else E.pop();s.write(E,r),u=s.flush()}return w.headers=_,w.query=f,w.body=u,w}serializeQuery(n,t,i){let r=this.serializer,s=n.getMergedTraits();if(s.httpQueryParams){for(let f in t)if(!(f in i)){let _=t[f],o=n.getValueSchema();Object.assign(o.getMergedTraits(),{...s,httpQuery:f,httpQueryParams:void 0}),this.serializeQuery(o,_,i)}return}if(n.isListSchema()){let f=!!n.getMergedTraits().sparse,_=[];for(let o of t){r.write([n.getValueSchema(),s],o);let h=r.flush();if(f||h!==void 0)_.push(h)}i[s.httpQuery]=_}else r.write([n,s],t),i[s.httpQuery]=r.flush()}async deserializeResponse(n,t,i){let r=this.deserializer,s=pt.of(n.output),f={};if(i.statusCode>=300){let o=await Lr(i.body,t);if(o.byteLength>0)Object.assign(f,await r.read(15,o));throw await this.handleError(n,t,i,f,this.deserializeMetadata(i)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let _=await this.deserializeHttpMessage(s,t,i,f);if(_.length){let o=await Lr(i.body,t);if(o.byteLength>0){let h=await r.read(s,o);for(let e of _)if(h[e]!=null)f[e]=h[e]}}else if(_.discardResponseBody)await Lr(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 _=!0,o=this.deserializer,h=pt.of(n),e=[];for(let[c,d]of h.structIterator()){let u=d.getMemberTraits();if(u.httpPayload){if(_=!1,d.isStreaming())if(d.isStructSchema())f[c]=await this.deserializeEventStream({response:i,responseSchema:h});else f[c]=lG(i.body);else if(i.body){let A=await Lr(i.body,t);if(A.byteLength>0)f[c]=await o.read(d,A)}}else if(u.httpHeader){let w=String(u.httpHeader).toLowerCase(),A=i.headers[w];if(A!=null)if(d.isListSchema()){let R=d.getValueSchema();R.getMergedTraits().httpHeader=w;let M;if(R.isTimestampSchema()&&R.getSchema()===4)M=TG(A,",",2);else M=pR(A);let E=[];for(let T of M)E.push(await o.read(R,T.trim()));f[c]=E}else f[c]=await o.read(d,A)}else if(u.httpPrefixHeaders!==void 0){f[c]={};for(let w in i.headers)if(w.startsWith(u.httpPrefixHeaders)){let A=i.headers[w],R=d.getValueSchema();R.getMergedTraits().httpHeader=w,f[c][w.slice(u.httpPrefixHeaders.length)]=await o.read(R,A)}}else if(u.httpResponseCode)f[c]=i.statusCode;else e.push(c)}return e.discardResponseBody=_,e}}class oM extends D_{async serializeRequest(n,t,i){let r=this.serializer,s={},f={},_=await i.endpoint(),o=pt.of(n?.input),h=o.getSchema(),e,c=t&&typeof t==="object"?t:{},d=new $s({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:s,headers:f,body:void 0});if(_)this.updateServiceEndpoint(d,_),this.setHostPrefix(d,n,c);if(c){let u=o.getEventStreamMember();if(u){if(c[u]){let w={};for(let[A,R]of o.structIterator())if(A!==u&&c[A])r.write(R,c[A]),w[A]=r.flush();e=await this.serializeEventStream({eventStream:c[u],requestSchema:o,initialRequest:w})}}else r.write(h,c),e=r.flush()}return d.headers=Object.assign(d.headers,f),d.query=s,d.body=e,d.method="POST",d}async deserializeResponse(n,t,i){let r=this.deserializer,s=pt.of(n.output),f={};if(i.statusCode>=300){let o=await Lr(i.body,t);if(o.byteLength>0)Object.assign(f,await r.read(15,o));throw await this.handleError(n,t,i,f,this.deserializeMetadata(i)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in i.headers){let h=i.headers[o];delete i.headers[o],i.headers[o.toLowerCase()]=h}let _=s.getEventStreamMember();if(_)f[_]=await this.deserializeEventStream({response:i,responseSchema:s,initialResponseContainer:f});else{let o=await Lr(i.body,t);if(o.byteLength>0)Object.assign(f,await r.read(s,o))}return f.$metadata=this.deserializeMetadata(i),f}}var _M=(n,t,i,r,s,f)=>{if(t!=null&&t[i]!==void 0){let _=r();if(_==null||_.length<=0)throw Error("Empty value provided for input HTTP label: "+i+".");n=n.replace(s,f?_.split("/").map((o)=>Kf(o)).join("/"):Kf(_))}else throw Error("No value provided for input HTTP label: "+i+".");return n};function mG(n,t){return new uc(n,t)}class uc{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 $s({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=_M(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 wc(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 yc extends Ds{settings;constructor(n){super();this.settings=n}read(n,t){let i=pt.of(n);if(i.isListSchema())return pR(t).map((r)=>this.read(i.getValueSchema(),r));if(i.isBlobSchema())return(this.serdeContext?.base64Decoder??kR)(t);if(i.isTimestampSchema())switch(wc(i,this.settings)){case 5:return LG(t);case 6:return OG(t);case 7:return gG(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=nM.from(s);return s}}if(i.isNumericSchema())return Number(t);if(i.isBigIntegerSchema())return BigInt(t);if(i.isBigDecimalSchema())return new IG(t,"bigDecimal");if(i.isBooleanSchema())return String(t).toLowerCase()==="true";return t}base64ToUtf8(n){return(this.serdeContext?.utf8Encoder??tM)((this.serdeContext?.base64Decoder??kR)(n))}}class hM extends Ds{codecDeserializer;stringDeserializer;constructor(n,t){super();this.codecDeserializer=n,this.stringDeserializer=new yc(t)}setSerdeContext(n){this.stringDeserializer.setSerdeContext(n),this.codecDeserializer.setSerdeContext(n),this.serdeContext=n}read(n,t){let i=pt.of(n),r=i.getMergedTraits(),s=this.serdeContext?.utf8Encoder??tM;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(i,s(t));if(r.httpPayload){if(i.isBlobSchema()){let f=this.serdeContext?.utf8Decoder??SG;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 Ac extends Ds{settings;stringBuffer="";constructor(n){super();this.settings=n}write(n,t){let i=pt.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(wc(i,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=NG(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??ZR)(t);return}if(i.isListSchema()&&Array.isArray(t)){let f="";for(let _ of t){this.write([i.getValueSchema(),i.getMergedTraits()],_);let o=this.flush(),h=i.getValueSchema().isTimestampSchema()?o:UG(o);if(f!=="")f+=", ";f+=h}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=nM.from(s);if(i.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??ZR)(s.toString());return}}this.stringBuffer=t;break;default:if(i.isIdempotencyToken())this.stringBuffer=bG();else this.stringBuffer=String(t)}}flush(){let n=this.stringBuffer;return this.stringBuffer="",n}}class eM{codecSerializer;stringSerializer;buffer;constructor(n,t,i=new Ac(t)){this.codecSerializer=n,this.stringSerializer=i}setSerdeContext(n){this.codecSerializer.setSerdeContext(n),this.stringSerializer.setSerdeContext(n)}write(n,t){let i=pt.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 cM{name;kind;values;constructor({name:n,kind:t=GG.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 dM{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 HG=(n)=>{return{setHttpHandler(t){n.httpHandler=t},httpHandler(){return n.httpHandler},updateHttpClientConfig(t,i){n.httpHandler?.updateHttpClientConfig(t,i)},httpHandlerConfigs(){return n.httpHandler.httpHandlerConfigs()}}},WG=(n)=>{return{httpHandler:n.httpHandler()}},vR="content-length";function uM(n){return(t)=>async(i)=>{let r=i.request;if($s.isInstance(r)){let{body:s,headers:f}=r;if(s&&Object.keys(f).map((_)=>_.toLowerCase()).indexOf(vR)===-1)try{let _=n(s);r.headers={...r.headers,[vR]:String(_)}}catch(_){}}return t({...i,request:r})}}var wM={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},FG=(n)=>({applyToStack:(t)=>{t.add(uM(n.bodyLengthChecker),wM)}}),zf=(n)=>encodeURIComponent(n).replace(/[!'()*]/g,CG),CG=(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`,PG=(n)=>n.split("/").map(zf).join("/");function YG(n){let t=[];for(let i of Object.keys(n).sort()){let r=n[i];if(i=zf(i),Array.isArray(r))for(let s=0,f=r.length;s<f;s++)t.push(`${i}=${zf(r[s])}`);else{let s=i;if(r||typeof r==="string")s+=`=${zf(r)}`;t.push(s)}}return t.join("&")}XG.Field=cM;XG.Fields=dM;XG.FromStringShapeDeserializer=yc;XG.HttpBindingProtocol=fM;XG.HttpInterceptingShapeDeserializer=hM;XG.HttpInterceptingShapeSerializer=eM;XG.HttpProtocol=D_;XG.RequestBuilder=uc;XG.RpcProtocol=oM;XG.SerdeContext=Ds;XG.ToStringShapeSerializer=Ac;XG.buildQueryString=YG;XG.collectBody=Lr;XG.contentLengthMiddleware=uM;XG.contentLengthMiddlewareOptions=wM;XG.determineTimestampFormat=wc;XG.escapeUri=zf;XG.escapeUriPath=PG;XG.extendedEncodeURIComponent=Kf;XG.getContentLengthPlugin=FG;XG.getHttpHandlerExtensionConfiguration=HG;XG.requestBuilder=mG;XG.resolveHttpHandlerRuntimeConfig=WG;XG.resolvedPath=_M});var kf=sn((Ym)=>{var{Readable:Rm}=un("stream"),{NoOpLogger:Mm,normalizeProvider:yM}=Ei(),{HttpResponse:AM,HttpRequest:G_}=it(),{parseRfc7231DateTime:Em,v4:RM}=tt(),MM=(n)=>n?.body instanceof Rm||typeof ReadableStream<"u"&&n?.body instanceof ReadableStream,lm=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],Tm=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],gm=["TimeoutError","RequestTimeout","RequestTimeoutException"],Om=[500,502,503,504],Lm=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],Im=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],lc=(n)=>n?.$retryable!==void 0,EM=(n)=>lm.includes(n.name),lM=(n)=>n.$metadata?.clockSkewCorrected,TM=(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)},Vf=(n)=>n.$metadata?.httpStatusCode===429||Tm.includes(n.name)||n.$retryable?.throttling==!0,jf=(n,t=0)=>lc(n)||lM(n)||n.name==="InvalidSignatureException"&&n.message?.includes("Signature expired")||gm.includes(n.name)||Lm.includes(n?.code||"")||Im.includes(n?.code||"")||Om.includes(n.$metadata?.httpStatusCode||0)||TM(n)||OM(n)||n.cause!==void 0&&t<=10&&jf(n.cause,t+1),gM=(n)=>{if(n.$metadata?.httpStatusCode!==void 0){let t=n.$metadata.httpStatusCode;if(500<=t&&t<=599&&!jf(n))return!0;return!1}return!1};function OM(n){return n.code==="ERR_HTTP2_STREAM_ERROR"&&n.message.includes("NGHTTP2_REFUSED_STREAM")}var LM=100,H_=20000,IM=500,m_=500,SM=5,bM=10,Tc=1,W_="amz-sdk-invocation-id",F_="amz-sdk-request";function NM(n,t){if(!AM.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=(Em(s).getTime()-Date.now())/1000}catch(_){t?.trace?.("Failed to parse retry-after header"),t?.trace?.(_)}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 Sm(n,t){return NM(n,t)}var UM=(n)=>{if(n instanceof Error)return n;if(n instanceof Object)return Object.assign(Error(),n);if(typeof n==="string")return Error(n);return Error(`AWS SDK error wrapper for ${n}`)};function $M(n){return(t)=>(i,r)=>async(s)=>{let f=await t.retryStrategy(),_=await t.maxAttempts();if(Nm(f)){f=f;let o=await f.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),h=Error(),e=0,c=0,{request:d}=s,u=G_.isInstance(d);if(u)d.headers[W_]=RM();while(!0)try{if(u)d.headers[F_]=`attempt=${e+1}; max=${_}`;let{response:w,output:A}=await i(s);return f.recordSuccess(o),A.$metadata.attempts=e+1,A.$metadata.totalRetryDelay=c,{response:w,output:A}}catch(w){let A=Um(w,t.logger);if(h=UM(w),u&&n(d))throw(r.logger instanceof Mm?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),h;try{o=await f.refreshRetryTokenForRetry(o,A)}catch(M){if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=e+1,h.$metadata.totalRetryDelay=c,h}e=o.getRetryCount();let R=o.getRetryDelay();if(c+=(o?.$retryLog?.acquisitionDelay??0)+R,R>0)await bm(R)}}else{if(f=f,f?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",f.mode]];return f.retry(i,s)}}}var bm=(n)=>new Promise((t)=>setTimeout(t,n)),Nm=(n)=>typeof n.acquireInitialRetryToken<"u"&&typeof n.refreshRetryTokenForRetry<"u"&&typeof n.recordSuccess<"u",Um=(n,t)=>{let i={error:n,errorType:$m(n)},r=NM(n.$response,t);if(r)i.retryAfterHint=r;return i},$m=(n)=>{if(Vf(n))return"THROTTLING";if(jf(n))return"TRANSIENT";if(gM(n))return"SERVER_ERROR";return"CLIENT_ERROR"},DM={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function Dm(n){let t=$M(n);return(i)=>({applyToStack:(r)=>{r.add(t(i),DM)}})}class qf{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"||Vf(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)=>qf.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 Cn{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Cn.v2026?50:100}static throttlingDelay(){return Cn.v2026?1000:500}static cost(){return Cn.v2026?14:5}static throttlingCost(){return Cn.v2026?5:10}static modifiedCostType(){return Cn.v2026?"THROTTLING":"TRANSIENT"}}class BM{x=Cn.delay();computeNextBackoffDelay(n){let t=Math.random(),i=2,r=t*Math.min(this.x*2**n,H_);return Math.floor(r)}setDelayBase(n){this.x=n}}class Rc{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(H_,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Oi;(function(n){n.STANDARD="standard",n.ADAPTIVE="adaptive"})(Oi||(Oi={}));var Ir=3,GM=Oi.STANDARD,B_={incompatible:1,attempts:2,capacity:3},xf=class{mode=Oi.STANDARD;retryBackoffStrategy;capacity=m_;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??=Cn.delay(),this.retryBackoffStrategy??=new BM}async acquireInitialRetryToken(t){return new Rc(Cn.delay(),0,void 0,Cn.v2026&&t.includes(":longpoll"))}async refreshRetryTokenForRetry(t,i){let r=await this.getMaxAttempts(),s=this.retryCode(t,i,r),f=s===0,_=t.isLongPoll?.();if(f||_){let o=i.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Cn.throttlingDelay():this.baseDelay);let h=this.retryBackoffStrategy.computeNextBackoffDelay(t.getRetryCount()),e=h;if(i.retryAfterHint instanceof Date)e=Math.max(h,Math.min(i.retryAfterHint.getTime()-Date.now(),h+5000));if(!f){let c=Cn.v2026&&s===B_.capacity&&_?e:0;if(c>0)await new Promise((d)=>setTimeout(d,c))}else{let c=this.getCapacityCost(o);this.capacity-=c;let d=new Rc(0,t.getRetryCount()+1,c,t.isLongPoll?.()??!1);return await new Promise((u)=>setTimeout(u,e)),d.$retryLog.acquisitionDelay=e,d}}throw Error("No retry token available")}recordSuccess(t){this.capacity=Math.min(m_,this.capacity+(t.getRetryCost()??Tc))}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:B_.incompatible,_=s<r?0:B_.attempts,o=this.capacity>=this.getCapacityCost(i.errorType)?0:B_.capacity;return f||_||o}getCapacityCost(t){return t===Cn.modifiedCostType()?Cn.throttlingCost():Cn.cost()}isRetryableError(t){return t==="THROTTLING"||t==="TRANSIENT"}},mM=class{mode=Oi.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(t,i){let{rateLimiter:r}=i??{};this.rateLimiter=r??new qf,this.standardRetryStrategy=i?new xf({maxAttempts:typeof t==="number"?t:3,...i}):new xf(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 HM extends xf{computeNextBackoffDelay;constructor(n,t=Cn.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 Bm=(n,t)=>{let i=n,r=Tc,s=SM,f=bM,_=n,o=(d)=>d.name==="TimeoutError"?f:s,h=(d)=>o(d)<=_;return Object.freeze({hasRetryTokens:h,retrieveRetryTokens:(d)=>{if(!h(d))throw Error("No retry token available");let u=o(d);return _-=u,u},releaseRetryTokens:(d)=>{_+=d??r,_=Math.min(_,i)}})},WM=(n,t)=>Math.floor(Math.min(H_,Math.random()*2**t*n)),FM=(n)=>{if(!n)return!1;return lc(n)||EM(n)||Vf(n)||jf(n)};class gc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=Oi.STANDARD;constructor(n,t){this.maxAttemptsProvider=n,this.retryDecider=t?.retryDecider??FM,this.delayDecider=t?.delayDecider??WM,this.retryQuota=t?.retryQuota??Bm(m_)}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,_=await this.getMaxAttempts(),{request:o}=t;if(G_.isInstance(o))o.headers[W_]=RM();while(!0)try{if(G_.isInstance(o))o.headers[F_]=`attempt=${s+1}; max=${_}`;if(i?.beforeRequest)await i.beforeRequest();let{response:h,output:e}=await n(t);if(i?.afterRequest)i.afterRequest(h);return this.retryQuota.releaseRetryTokens(r),e.$metadata.attempts=s+1,e.$metadata.totalRetryDelay=f,{response:h,output:e}}catch(h){let e=UM(h);if(s++,this.shouldRetry(e,s,_)){r=this.retryQuota.retrieveRetryTokens(e);let c=this.delayDecider(Vf(e)?IM:LM,s),d=Gm(e.$response),u=Math.max(d||0,c);f+=u,await new Promise((w)=>setTimeout(w,u));continue}if(!e.$metadata)e.$metadata={};throw e.$metadata.attempts=s,e.$metadata.totalRetryDelay=f,e}}}var Gm=(n)=>{if(!AM.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 CM extends gc{rateLimiter;constructor(n,t){let{rateLimiter:i,...r}=t??{};super(n,r);this.rateLimiter=i??new qf,this.mode=Oi.ADAPTIVE}async retry(n,t){return super.retry(n,t,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(i)=>{this.rateLimiter.updateClientSendingRate(i)}})}}var Mc="AWS_MAX_ATTEMPTS",Ec="max_attempts",mm={environmentVariableSelector:(n)=>{let t=n[Mc];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Environment variable ${Mc} mast be a number, got "${t}"`);return i},configFileSelector:(n)=>{let t=n[Ec];if(!t)return;let i=parseInt(t);if(Number.isNaN(i))throw Error(`Shared config file entry ${Ec} mast be a number, got "${t}"`);return i},default:Ir},Hm=(n,t)=>{let{retryStrategy:i,retryMode:r}=n,{defaultMaxAttempts:s=Ir,defaultBaseDelay:f=Cn.delay()}=t??{},_=yM(n.maxAttempts??s),o=i?Promise.resolve(i):void 0,h=async()=>{let e=await _();if(await yM(r)()===Oi.ADAPTIVE)return new mM(_,{maxAttempts:e,baseDelay:f});return new xf({maxAttempts:e,baseDelay:f})};return Object.assign(n,{maxAttempts:_,retryStrategy:()=>o??=h()})},PM="AWS_RETRY_MODE",YM="retry_mode",Wm={environmentVariableSelector:(n)=>n[PM],configFileSelector:(n)=>n[YM],default:GM},XM=()=>(n)=>async(t)=>{let{request:i}=t;if(G_.isInstance(i))delete i.headers[W_],delete i.headers[F_];return n(t)},JM={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},Fm=(n)=>({applyToStack:(t)=>{t.addRelativeTo(XM(),JM)}}),Cm=$M(MM),Pm=Dm(MM);Ym.AdaptiveRetryStrategy=mM;Ym.CONFIG_MAX_ATTEMPTS=Ec;Ym.CONFIG_RETRY_MODE=YM;Ym.ConfiguredRetryStrategy=HM;Ym.DEFAULT_MAX_ATTEMPTS=Ir;Ym.DEFAULT_RETRY_DELAY_BASE=LM;Ym.DEFAULT_RETRY_MODE=GM;Ym.DefaultRateLimiter=qf;Ym.DeprecatedAdaptiveRetryStrategy=CM;Ym.DeprecatedStandardRetryStrategy=gc;Ym.ENV_MAX_ATTEMPTS=Mc;Ym.ENV_RETRY_MODE=PM;Ym.INITIAL_RETRY_TOKENS=m_;Ym.INVOCATION_ID_HEADER=W_;Ym.MAXIMUM_RETRY_DELAY=H_;Ym.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=mm;Ym.NODE_RETRY_MODE_CONFIG_OPTIONS=Wm;Ym.NO_RETRY_INCREMENT=Tc;Ym.REQUEST_HEADER=F_;Ym.RETRY_COST=SM;Ym.RETRY_MODES=Oi;Ym.Retry=Cn;Ym.StandardRetryStrategy=xf;Ym.THROTTLING_RETRY_DELAY_BASE=IM;Ym.TIMEOUT_RETRY_COST=bM;Ym.defaultDelayDecider=WM;Ym.defaultRetryDecider=FM;Ym.getOmitRetryHeadersPlugin=Fm;Ym.getRetryAfterHint=Sm;Ym.getRetryPlugin=Pm;Ym.isBrowserNetworkError=TM;Ym.isClockSkewCorrectedError=lM;Ym.isClockSkewError=EM;Ym.isNodeJsHttp2TransientError=OM;Ym.isRetryableByTrait=lc;Ym.isServerError=gM;Ym.isThrottlingError=Vf;Ym.isTransientError=jf;Ym.omitRetryHeadersMiddleware=XM;Ym.omitRetryHeadersMiddlewareOptions=JM;Ym.resolveRetryConfig=Hm;Ym.retryMiddleware=Cm;Ym.retryMiddlewareOptions=DM});var aM=sn(($H)=>{var Vi={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")},Oc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Oc)globalThis.awslambda=globalThis.awslambda||{};class C_{static PROTECTED_KEYS=Vi;isProtectedKey(n){return Object.values(Vi).includes(n)}getRequestId(){return this.get(Vi.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Vi.X_RAY_TRACE_ID)}getTenantId(){return this.get(Vi.TENANT_ID)}getTraceparent(){return this.get(Vi.TRACEPARENT)}getTracestate(){return this.get(Vi.TRACESTATE)}getBaggage(){return this.get(Vi.BAGGAGE)}}class QM extends C_{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(n){return this.currentContext?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);this.currentContext=this.currentContext||{},this.currentContext[n]=t}run(n,t){return this.currentContext=n,t()}}class Ic extends C_{als;static async create(){let n=new Ic,t=await import("async_hooks");return n.als=new t.AsyncLocalStorage,n}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(n){return this.als.getStore()?.[n]}set(n,t){if(this.isProtectedKey(n))throw Error(`Cannot modify protected Lambda context field: ${String(n)}`);let i=this.als.getStore();if(!i)throw Error("No context available");i[n]=t}run(n,t){return this.als.run(n,t)}}$H.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 Ic.create():new QM;if(!Oc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Oc&&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})($H.InvokeStore||($H.InvokeStore={}));$H.InvokeStoreBase=C_});var ji=sn((xH)=>{var{getSmithyContext:Sc}=qt();xH.getSmithyContext=Sc;var{HttpRequest:bc}=it(),{requestBuilder:BH}=it();xH.requestBuilder=BH;var{HttpApiKeyAuthLocation:zM}=Mr(),GH=(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 mH(n){let t=new Map;for(let i of n)t.set(i.schemeId,i);return t}var Nc=(n,t)=>(i,r)=>async(s)=>{let f=n.httpAuthSchemeProvider(await t.httpAuthSchemeParametersProvider(n,r,s.input)),_=n.authSchemePreference?await n.authSchemePreference():[],o=GH(f,_),h=mH(n.httpAuthSchemes),e=Sc(r),c=[];for(let d of o){let u=h.get(d.schemeId);if(!u){c.push(`HttpAuthScheme \`${d.schemeId}\` was not enabled for this service.`);continue}let w=u.identityProvider(await t.identityProviderConfigProvider(n));if(!w){c.push(`HttpAuthScheme \`${d.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:R={}}=d.propertiesExtractor?.(n,r)||{};d.identityProperties=Object.assign(d.identityProperties||{},A),d.signingProperties=Object.assign(d.signingProperties||{},R),e.selectedHttpAuthScheme={httpAuthOption:d,identity:await w(d.identityProperties),signer:u.signer};break}if(!e.selectedHttpAuthScheme)throw Error(c.join(`
|
|
24
|
+
`));return i(s)},KM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},HH=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Nc(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),KM)}}),xM={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},WH=(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i})=>({applyToStack:(r)=>{r.addRelativeTo(Nc(n,{httpAuthSchemeParametersProvider:t,identityProviderConfigProvider:i}),xM)}}),FH=(n)=>(t)=>{throw t},CH=(n,t)=>{},VM=(n)=>(t,i)=>async(r)=>{if(!bc.isInstance(r.request))return t(r);let f=Sc(i).selectedHttpAuthScheme;if(!f)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:_={}},identity:o,signer:h}=f,e=await t({...r,request:await h.sign(r.request,o,_)}).catch((h.errorHandler||FH)(_));return(h.successHandler||CH)(e.response,_),e},jM={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},PH=(n)=>({applyToStack:(t)=>{t.addRelativeTo(VM(),jM)}}),YH=(n)=>{if(typeof n==="function")return n;let t=Promise.resolve(n);return()=>t},XH=async(n,t,i,r=(f)=>f,...s)=>{let f=new n(i);return f=r(f)??f,await t.send(f,...s)};function JH(n,t,i,r,s){return async function*(_,o,...h){let e=o,c=_.startingToken??e[i],d=!0,u;while(d){if(e[i]=c,s)e[s]=e[s]??_.pageSize;if(_.client instanceof n)u=await XH(t,_.client,o,_.withCommand,...h);else throw Error(`Invalid client, expected instance of ${n.name}`);yield u;let w=c;c=QH(u,r),d=!!(c&&(!_.stopOnSameToken||c!==w))}return}}var QH=(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 aH(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 qM{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 kM{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=bc.clone(n);if(i.in===zM.QUERY)r.query[i.name]=t.apiKey;else if(i.in===zM.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 ZM{async sign(n,t,i){let r=bc.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 vM{async sign(n,t,i){return n}}var pM=(n)=>function(i){return tE(i)&&i.expiration.getTime()-Date.now()<n},nE=300000,zH=pM(nE),tE=(n)=>n.expiration!==void 0,KH=(n,t,i)=>{if(n===void 0)return;let r=typeof n!=="function"?async()=>Promise.resolve(n):n,s,f,_,o=!1,h=async(e)=>{if(!f)f=r(e);try{s=await f,_=!0,o=!1}finally{f=void 0}return s};if(t===void 0)return async(e)=>{if(!_||e?.forceRefresh)s=await h(e);return s};return async(e)=>{if(!_||e?.forceRefresh)s=await h(e);if(o)return s;if(!i(s))return o=!0,s;if(t(s))return await h(e),s;return s}};xH.DefaultIdentityProviderConfig=qM;xH.EXPIRATION_MS=nE;xH.HttpApiKeyAuthSigner=kM;xH.HttpBearerAuthSigner=ZM;xH.NoAuthSigner=vM;xH.createIsIdentityExpiredFunction=pM;xH.createPaginator=JH;xH.doesIdentityRequireRefresh=tE;xH.getHttpAuthSchemeEndpointRuleSetPlugin=HH;xH.getHttpAuthSchemePlugin=WH;xH.getHttpSigningPlugin=PH;xH.httpAuthSchemeEndpointRuleSetMiddlewareOptions=KM;xH.httpAuthSchemeMiddleware=Nc;xH.httpAuthSchemeMiddlewareOptions=xM;xH.httpSigningMiddleware=VM;xH.httpSigningMiddlewareOptions=jM;xH.isIdentityExpired=zH;xH.memoizeIdentityProvider=KH;xH.normalizeProvider=YH;xH.setFeature=aH});var iE=sn((Zf,Uc)=>{(function(n,t){typeof Zf=="object"&&typeof Uc=="object"?Uc.exports=t():typeof define=="function"&&define.amd?define([],t):typeof Zf=="object"?Zf.bowser=t():n.bowser=t()})(Zf,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 _ in r)i.d(f,_,function(o){return r[o]}.bind(null,_));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(_,o){var h=o.match(_);return h&&h.length>0&&h[1]||""},f.getSecondMatch=function(_,o){var h=o.match(_);return h&&h.length>1&&h[2]||""},f.matchAndReturnConst=function(_,o,h){if(_.test(o))return h},f.getWindowsVersionName=function(_){switch(_){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(_){var o=_.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});o.push(0);var h=o[0],e=o[1];if(h===10)switch(e){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(h){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},f.getAndroidVersionName=function(_){var o=_.split(".").splice(0,2).map(function(h){return parseInt(h,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},f.getVersionPrecision=function(_){return _.split(".").length},f.compareVersions=function(_,o,h){h===void 0&&(h=!1);var e=f.getVersionPrecision(_),c=f.getVersionPrecision(o),d=Math.max(e,c),u=0,w=f.map([_,o],function(A){var R=d-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(h&&(u=d-Math.min(e,c)),d-=1;d>=u;){if(w[0][d]>w[1][d])return 1;if(w[0][d]===w[1][d]){if(d===u)return 0;d-=1}else if(w[0][d]<w[1][d])return-1}},f.map=function(_,o){var h,e=[];if(Array.prototype.map)return Array.prototype.map.call(_,o);for(h=0;h<_.length;h+=1)e.push(o(_[h]));return e},f.find=function(_,o){var h,e;if(Array.prototype.find)return Array.prototype.find.call(_,o);for(h=0,e=_.length;h<e;h+=1){var c=_[h];if(o(c,h))return c}},f.assign=function(_){for(var o,h,e=_,c=arguments.length,d=Array(c>1?c-1:0),u=1;u<c;u++)d[u-1]=arguments[u];if(Object.assign)return Object.assign.apply(Object,[_].concat(d));var w=function(){var A=d[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(R){e[R]=A[R]})};for(o=0,h=d.length;o<h;o+=1)w();return _},f.getBrowserAlias=function(_){return r.BROWSER_ALIASES_MAP[_]},f.getBrowserTypeByAlias=function(_){return r.BROWSER_MAP[_]||""},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,e){for(var c=0;c<e.length;c++){var d=e[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(h,d.key,d)}}var o=function(){function h(){}var e,c,d;return h.getParser=function(u,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof u!="string")throw Error("UserAgent should be a string");return new s.default(u,w,A)},h.parse=function(u,w){return w===void 0&&(w=null),new s.default(u,w).getResult()},e=h,d=[{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}}],(c=null)&&_(e.prototype,c),d&&_(e,d),h}();t.default=o,n.exports=t.default},91:function(n,t,i){t.__esModule=!0,t.default=void 0;var r=h(i(92)),s=h(i(93)),f=h(i(94)),_=h(i(95)),o=h(i(17));function h(c){return c&&c.__esModule?c:{default:c}}var e=function(){function c(u,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),u==null||u==="")throw Error("UserAgent parameter can't be empty");this._ua=u;var R=!1;typeof w=="boolean"?(R=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},R!==!0&&this.parse()}var d=c.prototype;return d.getHints=function(){return this._hints},d.hasBrand=function(u){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=u.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},d.getBrandVersion=function(u){if(this._hints&&Array.isArray(this._hints.brands)){var w=u.toLowerCase(),A=this._hints.brands.find(function(R){return R.brand&&R.brand.toLowerCase()===w});return A?A.version:void 0}},d.getUA=function(){return this._ua},d.test=function(u){return u.test(this._ua)},d.parseBrowser=function(){var u=this;this.parsedResult.browser={};var w=o.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 w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},d.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},d.getBrowserName=function(u){return u?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},d.getBrowserVersion=function(){return this.getBrowser().version},d.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},d.parseOS=function(){var u=this;this.parsedResult.os={};var w=o.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 w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},d.getOSName=function(u){var w=this.getOS().name;return u?String(w).toLowerCase()||"":w||""},d.getOSVersion=function(){return this.getOS().version},d.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},d.getPlatformType=function(u){u===void 0&&(u=!1);var w=this.getPlatform().type;return u?String(w).toLowerCase()||"":w||""},d.parsePlatform=function(){var u=this;this.parsedResult.platform={};var w=o.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 w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},d.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},d.getEngineName=function(u){return u?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},d.parseEngine=function(){var u=this;this.parsedResult.engine={};var w=o.default.find(_.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 w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},d.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},d.getResult=function(){return o.default.assign({},this.parsedResult)},d.satisfies=function(u){var w=this,A={},R=0,M={},E=0;if(Object.keys(u).forEach(function(S){var W=u[S];typeof W=="string"?(M[S]=W,E+=1):typeof W=="object"&&(A[S]=W,R+=1)}),R>0){var T=Object.keys(A),l=o.default.find(T,function(S){return w.isOS(S)});if(l){var g=this.satisfies(A[l]);if(g!==void 0)return g}var O=o.default.find(T,function(S){return w.isPlatform(S)});if(O){var N=this.satisfies(A[O]);if(N!==void 0)return N}}if(E>0){var F=Object.keys(M),K=o.default.find(F,function(S){return w.isBrowser(S,!0)});if(K!==void 0)return this.compareVersion(M[K])}},d.isBrowser=function(u,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),R=u.toLowerCase(),M=o.default.getBrowserTypeByAlias(R);return w&&M&&(R=M.toLowerCase()),R===A},d.compareVersion=function(u){var w=[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)):w=[],u[0]===">"?w.push(1):w.push(-1)):u[0]==="="?A=u.substr(1):u[0]==="~"&&(R=!0,A=u.substr(1)),w.indexOf(o.default.compareVersions(M,A,R))>-1},d.isOS=function(u){return this.getOSName(!0)===String(u).toLowerCase()},d.isPlatform=function(u){return this.getPlatformType(!0)===String(u).toLowerCase()},d.isEngine=function(u){return this.getEngineName(!0)===String(u).toLowerCase()},d.is=function(u,w){return w===void 0&&(w=!1),this.isBrowser(u,w)||this.isOS(u)||this.isPlatform(u)},d.some=function(u){var w=this;return u===void 0&&(u=[]),u.some(function(A){return w.is(A)})},c}();t.default=e,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,_=[{test:[/gptbot/i],describe:function(o){var h={name:"GPTBot"},e=s.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/chatgpt-user/i],describe:function(o){var h={name:"ChatGPT-User"},e=s.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/oai-searchbot/i],describe:function(o){var h={name:"OAI-SearchBot"},e=s.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var h={name:"ClaudeBot"},e=s.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var h={name:"Omgilibot"},e=s.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/diffbot/i],describe:function(o){var h={name:"Diffbot"},e=s.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/perplexitybot/i],describe:function(o){var h={name:"PerplexityBot"},e=s.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/perplexity-user/i],describe:function(o){var h={name:"Perplexity-User"},e=s.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/youbot/i],describe:function(o){var h={name:"YouBot"},e=s.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/meta-webindexer/i],describe:function(o){var h={name:"Meta-WebIndexer"},e=s.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/meta-externalads/i],describe:function(o){var h={name:"Meta-ExternalAds"},e=s.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/meta-externalagent/i],describe:function(o){var h={name:"Meta-ExternalAgent"},e=s.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/meta-externalfetcher/i],describe:function(o){var h={name:"Meta-ExternalFetcher"},e=s.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/googlebot/i],describe:function(o){var h={name:"Googlebot"},e=s.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/linespider/i],describe:function(o){var h={name:"Linespider"},e=s.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/amazonbot/i],describe:function(o){var h={name:"AmazonBot"},e=s.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/bingbot/i],describe:function(o){var h={name:"BingCrawler"},e=s.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/baiduspider/i],describe:function(o){var h={name:"BaiduSpider"},e=s.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/duckduckbot/i],describe:function(o){var h={name:"DuckDuckBot"},e=s.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/ia_archiver/i],describe:function(o){var h={name:"InternetArchiveCrawler"},e=s.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var h={name:"SlackBot"},e=s.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var h={name:"Opera"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/opr\/|opios/i],describe:function(o){var h={name:"Opera"},e=s.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/SamsungBrowser/i],describe:function(o){var h={name:"Samsung Internet for Android"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/Whale/i],describe:function(o){var h={name:"NAVER Whale Browser"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/PaleMoon/i],describe:function(o){var h={name:"Pale Moon"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/MZBrowser/i],describe:function(o){var h={name:"MZ Browser"},e=s.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/focus/i],describe:function(o){var h={name:"Focus"},e=s.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/swing/i],describe:function(o){var h={name:"Swing"},e=s.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/coast/i],describe:function(o){var h={name:"Opera Coast"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var h={name:"Opera Touch"},e=s.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/yabrowser/i],describe:function(o){var h={name:"Yandex Browser"},e=s.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/ucbrowser/i],describe:function(o){var h={name:"UC Browser"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/Maxthon|mxios/i],describe:function(o){var h={name:"Maxthon"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/epiphany/i],describe:function(o){var h={name:"Epiphany"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/puffin/i],describe:function(o){var h={name:"Puffin"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/sleipnir/i],describe:function(o){var h={name:"Sleipnir"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/k-meleon/i],describe:function(o){var h={name:"K-Meleon"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/micromessenger/i],describe:function(o){var h={name:"WeChat"},e=s.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/qqbrowser/i],describe:function(o){var h={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},e=s.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/msie|trident/i],describe:function(o){var h={name:"Internet Explorer"},e=s.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/\sedg\//i],describe:function(o){var h={name:"Microsoft Edge"},e=s.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/edg([ea]|ios)/i],describe:function(o){var h={name:"Microsoft Edge"},e=s.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/vivaldi/i],describe:function(o){var h={name:"Vivaldi"},e=s.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/seamonkey/i],describe:function(o){var h={name:"SeaMonkey"},e=s.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/sailfish/i],describe:function(o){var h={name:"Sailfish"},e=s.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return e&&(h.version=e),h}},{test:[/silk/i],describe:function(o){var h={name:"Amazon Silk"},e=s.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/phantom/i],describe:function(o){var h={name:"PhantomJS"},e=s.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/slimerjs/i],describe:function(o){var h={name:"SlimerJS"},e=s.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h={name:"BlackBerry"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h={name:"WebOS Browser"},e=s.default.getFirstMatch(f,o)||s.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/bada/i],describe:function(o){var h={name:"Bada"},e=s.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/tizen/i],describe:function(o){var h={name:"Tizen"},e=s.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/qupzilla/i],describe:function(o){var h={name:"QupZilla"},e=s.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/librewolf/i],describe:function(o){var h={name:"LibreWolf"},e=s.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var h={name:"Firefox"},e=s.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/electron/i],describe:function(o){var h={name:"Electron"},e=s.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var h={name:"Sogou Browser"},e=s.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),c=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),d=s.default.getFirstMatch(/se ([\d.]+)x/i,o),u=e||c||d;return u&&(h.version=u),h}},{test:[/MiuiBrowser/i],describe:function(o){var h={name:"Miui"},e=s.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,h){var e={name:"DuckDuckGo"};if(h){var c=h.getBrandVersion("DuckDuckGo");if(c)return e.version=c,e}var d=s.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return d&&(e.version=d),e}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,h){var e={name:"Brave"};if(h){var c=h.getBrandVersion("Brave");if(c)return e.version=c,e}return e}},{test:[/chromium/i],describe:function(o){var h={name:"Chromium"},e=s.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/chrome|crios|crmo/i],describe:function(o){var h={name:"Chrome"},e=s.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/GSA/i],describe:function(o){var h={name:"Google Search"},e=s.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:function(o){var h=!o.test(/like android/i),e=o.test(/android/i);return h&&e},describe:function(o){var h={name:"Android Browser"},e=s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/playstation 4/i],describe:function(o){var h={name:"PlayStation 4"},e=s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/safari|applewebkit/i],describe:function(o){var h={name:"Safari"},e=s.default.getFirstMatch(f,o);return e&&(h.version=e),h}},{test:[/.*/i],describe:function(o){var h=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:s.default.getFirstMatch(h,o),version:s.default.getSecondMatch(h,o)}}}];t.default=_,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),_=[{test:[/Roku\/DVP/],describe:function(o){var h=s.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:f.OS_MAP.Roku,version:h}}},{test:[/windows phone/i],describe:function(o){var h=s.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:f.OS_MAP.WindowsPhone,version:h}}},{test:[/windows /i],describe:function(o){var h=s.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),e=s.default.getWindowsVersionName(h);return{name:f.OS_MAP.Windows,version:h,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var h={name:f.OS_MAP.iOS},e=s.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return e&&(h.version=e),h}},{test:[/macintosh/i],describe:function(o){var h=s.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),e=s.default.getMacOSVersionName(h),c={name:f.OS_MAP.MacOS,version:h};return e&&(c.versionName=e),c}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var h=s.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:f.OS_MAP.iOS,version:h}}},{test:[/OpenHarmony/i],describe:function(o){var h=s.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:f.OS_MAP.HarmonyOS,version:h}}},{test:function(o){var h=!o.test(/like android/i),e=o.test(/android/i);return h&&e},describe:function(o){var h=s.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),e=s.default.getAndroidVersionName(h),c={name:f.OS_MAP.Android,version:h};return e&&(c.versionName=e),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var h=s.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),e={name:f.OS_MAP.WebOS};return h&&h.length&&(e.version=h),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var h=s.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||s.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||s.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:f.OS_MAP.BlackBerry,version:h}}},{test:[/bada/i],describe:function(o){var h=s.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:f.OS_MAP.Bada,version:h}}},{test:[/tizen/i],describe:function(o){var h=s.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:f.OS_MAP.Tizen,version:h}}},{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(o){var h=s.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:f.OS_MAP.PlayStation4,version:h}}}];t.default=_,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),_=[{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(o){var h=s.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",e={type:f.PLATFORMS_MAP.mobile,vendor:"Huawei"};return h&&(e.model=h),e}},{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(o){var h=o.test(/ipod|iphone/i),e=o.test(/like (ipod|iphone)/i);return h&&!e},describe:function(o){var h=s.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:f.PLATFORMS_MAP.mobile,vendor:"Apple",model:h}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var h=s.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),e={type:f.PLATFORMS_MAP.mobile,vendor:"Nokia"};return h&&(e.model=h),e}},{test:[/[^-]mobi/i],describe:function(){return{type:f.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:f.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:f.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var h=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&h>=3},describe:function(){return{type:f.PLATFORMS_MAP.tablet}}},{test:function(o){return o.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(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:f.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:f.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:f.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:f.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:f.PLATFORMS_MAP.tv}}}];t.default=_,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),_=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:f.ENGINE_MAP.Blink};var h=s.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:f.ENGINE_MAP.EdgeHTML,version:h}}},{test:[/trident/i],describe:function(o){var h={name:f.ENGINE_MAP.Trident},e=s.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:function(o){return o.test(/presto/i)},describe:function(o){var h={name:f.ENGINE_MAP.Presto},e=s.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:function(o){var h=o.test(/gecko/i),e=o.test(/like gecko/i);return h&&!e},describe:function(o){var h={name:f.ENGINE_MAP.Gecko},e=s.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:f.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var h={name:f.ENGINE_MAP.WebKit},e=s.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return e&&(h.version=e),h}}];t.default=_,n.exports=t.default}})})});var Ht=sn((eW)=>{var{Retry:A3,RETRY_MODES:rE}=kf(),{HttpRequest:Hc,parseUrl:R3}=it(),{InvokeStore:sE}=aM(),{normalizeProvider:M3}=ji(),{platform:E3,release:l3}=un("os"),{versions:$c,env:fE}=un("process"),{isValidHostLabel:T3,isIpAddress:cE,customEndpointFunctions:g3}=Tr(),{EndpointError:O3,resolveEndpoint:L3}=Tr();eW.EndpointError=O3;eW.isIpAddress=cE;eW.resolveEndpoint=L3;var{loadConfig:I3,NODE_REGION_CONFIG_OPTIONS:dE,NODE_REGION_CONFIG_FILE_OPTIONS:uE}=nt(),{REGION_ENV_NAME:S3,REGION_INI_NAME:b3,resolveRegionConfig:N3}=nt();eW.NODE_REGION_CONFIG_FILE_OPTIONS=uE;eW.NODE_REGION_CONFIG_OPTIONS=dE;eW.REGION_ENV_NAME=S3;eW.REGION_INI_NAME=b3;eW.resolveRegionConfig=N3;var Y_={warningEmitted:!1},U3=(n)=>{if(n&&!Y_.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Y_.warningEmitted=!0;return}let t=parseInt(n.substring(1,n.indexOf("."))),i=22;if(t<i)Y_.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
|
|
25
25
|
versions published after the first week of January 2027
|
|
26
26
|
will require node >=${i}. You are running node ${n}.
|
|
27
27
|
|
|
28
28
|
To continue receiving updates to AWS services, bug fixes,
|
|
29
29
|
and security updates please upgrade to node >=${i}.
|
|
30
30
|
|
|
31
|
-
More information can be found at: https://a.co/c895JFp`)}},v3=()=>(n,t)=>async(i)=>{return t.__retryLongPoll=!0,n(i)},p3={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},nW=(n)=>({applyToStack:(t)=>{t.add(v3(),p3)}});function tW(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}X3.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function at(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 iW(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}function rW(n){return n}var ZE=(n)=>(t)=>async(i)=>{if(!Lc.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)},vE={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},sW=(n)=>({applyToStack:(t)=>{t.add(ZE(n),vE)}}),pE=()=>(n,t)=>async(i)=>{try{let r=await n(i),{clientName:s,commandName:f,logger:h,dynamoDbDocumentClientOptions:_={}}=t,{overrideInputFilterSensitiveLog:o,overrideOutputFilterSensitiveLog:w}=_,c=o??t.inputFilterSensitiveLog,d=w??t.outputFilterSensitiveLog,{$metadata:u,...y}=r.output;return h?.info?.({clientName:s,commandName:f,input:c(i.input),output:d(y),metadata:u}),r}catch(r){let{clientName:s,commandName:f,logger:h,dynamoDbDocumentClientOptions:_={}}=t,{overrideInputFilterSensitiveLog:o}=_,w=o??t.inputFilterSensitiveLog;throw h?.error?.({clientName:s,commandName:f,input:w(i.input),error:r,metadata:r.$metadata}),r}},n1={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},fW=(n)=>({applyToStack:(t)=>{t.add(pE(),n1)}}),t1={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},_W="AWS_LAMBDA_FUNCTION_NAME",hW="_X_AMZN_TRACE_ID",Ec="X-Amzn-Trace-Id",Oc="traceparent",i1="tracestate",r1="baggage",s1=()=>(n)=>async(t)=>{let{request:i}=t;if(!Lc.isInstance(i))return n(t);let r;{let s=Object.keys(i.headers??{}).find((f)=>f.toLowerCase()===Ec.toLowerCase())??Ec;if(!i.headers.hasOwnProperty(s)){let f=process.env[_W],h=process.env[hW];r??=await mE.getInstanceAsync();let o=r?.getXRayTraceId()??h,w=(c)=>typeof c==="string"&&c.length>0;if(w(f)&&w(o))i.headers[Ec]=o}}if(oW(i.headers),!i.headers[Oc]){let f=(r??=await mE.getInstanceAsync())?.getTraceparent?.();if(f){i.headers[Oc]=f;let h=r?.getTracestate?.();if(h)i.headers[i1]=h;let _=r?.getBaggage?.();if(_)i.headers[r1]=_}}return n(t)};function oW(n){for(let t of Object.keys(n)){let i=t.toLowerCase();if(t!==i&&(i===Oc||i===i1||i===r1))n[i]=n[t],delete n[t]}}var wW=(n)=>({applyToStack:(t)=>{t.add(s1(),t1)}}),Ic=void 0;function cW(n){if(n===void 0)return!0;return typeof n==="string"&&n.length<=50}function dW(n){let t=J3(n.userAgentAppId??Ic),{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 f1={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"},_1=f1,h1="",o1=(n)=>{let{partitions:t}=_1;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}},w1=(n,t="")=>{_1=n,h1=t},uW=()=>{w1(f1,"")},c1=()=>h1,yW=/\d{12}\.ddb/;async function AW(n,t,i){if(i.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")at(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 QE.ADAPTIVE:at(n,"RETRY_MODE_ADAPTIVE","F");break;case QE.STANDARD:at(n,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let f=n.endpointV2;if(String(f?.url?.hostname).match(yW))at(n,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":at(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":at(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":at(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let s=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(s?.$source){let f=s;if(f.accountId)at(n,"RESOLVED_ACCOUNT_ID","T");for(let[h,_]of Object.entries(f.$source??{}))at(n,h,_)}}var KE="user-agent",Tc="x-amz-user-agent",VE=" ",ec="/",RW=/[^!$%&'*+\-.^_`|~\w]/g,MW=/[^!$%&'*+\-.^_`|~\w#]/g,xE="-",EW=1024;function TW(n){let t="";for(let i in n){let r=n[i];if(t.length+r.length+1<=EW){if(t.length)t+=","+r;else t+=r;continue}break}return t}var d1=(n)=>(t,i)=>async(r)=>{let{request:s}=r;if(!Lc.isInstance(s))return t(r);let{headers:f}=s,h=i?.userAgent?.map(bh)||[],_=(await n.defaultUserAgentProvider()).map(bh);await AW(i,n,r);let o=i;_.push(`m/${TW(Object.assign({},i.__smithy_context?.features,o.__aws_sdk_context?.features))}`);let w=n?.customUserAgent?.map(bh)||[],c=await n.userAgentAppId();if(c)_.push(bh(["app",`${c}`]));let d=c1(),u=(d?[d]:[]).concat([..._,...h,...w]).join(VE),y=[..._.filter((R)=>R.startsWith("aws-sdk-")),...w].join(VE);if(n.runtime!=="browser"){if(y)f[Tc]=f[Tc]?`${f[KE]} ${y}`:y;f[KE]=u}else f[Tc]=u;return t({...r,request:s})},bh=(n)=>{let t=n[0].split(ec).map((h)=>h.replace(RW,xE)).join(ec),i=n[1]?.replace(MW,xE),r=t.indexOf(ec),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,_,o)=>{switch(o){case 0:return _;case 1:return`${h}/${_}`;default:return`${h}#${_}`}},"")},u1={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},eW=(n)=>({applyToStack:(t)=>{t.add(d1(n),u1)}}),OW=()=>{let n=["deno","bun","llrt"];for(let t of n)if(Mc[t])return[`md/${t}`,Mc[t]];return["md/nodejs",Mc.node]},y1={isCrtAvailable:!1},LW=()=>{if(y1.isCrtAvailable)return["md/crt-avail"];return null},A1=({serviceId:n,clientVersion:t})=>{let i=OW();return async(r)=>{let s=[["aws-sdk-js",t],["ua","2.1"],[`os/${Q3()}`,m3()],["lang/js"],i],f=LW();if(f)s.push(f);if(n)s.push([`api/${n}`,t]);if(zE.AWS_EXECUTION_ENV)s.push([`exec-env/${zE.AWS_EXECUTION_ENV}`]);let h=await r?.userAgentAppId?.();return h?[...s,[`app/${h}`]]:[...s]}},IW=A1,R1="AWS_SDK_UA_APP_ID",M1="sdk_ua_app_id",gW="sdk-ua-app-id",NW={environmentVariableSelector:(n)=>n[R1],configFileSelector:(n)=>n[M1]??n[gW],default:Ic},bW=({serviceId:n,clientVersion:t})=>async(i)=>{let r=JE(),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},SW={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}},gc=(n,t=!1)=>{if(t){for(let i of n.split("."))if(!gc(i))return!1;return!0}if(!z3(n))return!1;if(n.length<3||n.length>63)return!1;if(n!==n.toLowerCase())return!1;if(qE(n))return!1;return!0},jE=":",lW="/",E1=(n)=>{let t=n.split(jE);if(t.length<6)return null;let[i,r,s,f,h,..._]=t;if(i!=="arn"||r===""||s===""||_.join(jE)==="")return null;let o=_.map((w)=>w.split(lW)).flat();return{partition:r,service:s,region:f,accountId:h,resourceId:o}},T1={isVirtualHostableS3Bucket:gc,parseArn:E1,partition:o1};K3.aws=T1;var $W=(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 e1(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},e1=(n)=>C3(n.url);function UW(n={}){return j3({...kE,async default(){if(!O1.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"}},{...aE,...n})}var O1={silence:!1},DW=(n)=>{return{setRegion(t){n.region=t},region(){return n.region}}},BW=(n)=>{return{region:n.region()}};GW.DEFAULT_UA_APP_ID=Ic;GW.NODE_APP_ID_CONFIG_OPTIONS=NW;GW.UA_APP_ID_ENV_NAME=R1;GW.UA_APP_ID_INI_NAME=M1;GW.awsEndpointFunctions=T1;GW.createDefaultUserAgentProvider=A1;GW.createUserAgentStringParsingProvider=bW;GW.crtAvailability=y1;GW.defaultUserAgent=IW;GW.emitWarningIfUnsupportedVersion=Z3;GW.fallback=SW;GW.getAwsRegionExtensionConfiguration=DW;GW.getHostHeaderPlugin=sW;GW.getLoggerPlugin=fW;GW.getLongPollPlugin=nW;GW.getRecursionDetectionPlugin=wW;GW.getUserAgentMiddlewareOptions=u1;GW.getUserAgentPlugin=eW;GW.getUserAgentPrefix=c1;GW.hostHeaderMiddleware=ZE;GW.hostHeaderMiddlewareOptions=vE;GW.isVirtualHostableS3Bucket=gc;GW.loggerMiddleware=pE;GW.loggerMiddlewareOptions=n1;GW.parseArn=E1;GW.partition=o1;GW.recursionDetectionMiddleware=s1;GW.recursionDetectionMiddlewareOptions=t1;GW.resolveAwsRegionExtensionConfiguration=BW;GW.resolveDefaultAwsRegionalEndpointsConfig=$W;GW.resolveHostHeaderConfig=rW;GW.resolveUserAgentConfig=dW;GW.setCredentialFeature=tW;GW.setFeature=at;GW.setPartitionInfo=w1;GW.setTokenFeature=iW;GW.state=Sh;GW.stsRegionDefaultResolver=UW;GW.stsRegionWarning=O1;GW.toEndpointV1=e1;GW.useDefaultPartitionInfo=uW;GW.userAgentMiddleware=d1});var p1=rn((m7)=>{var{fromUtf8:l1,fromHex:B7,toHex:Lr,toUint8Array:Vf,isArrayBuffer:G7}=pn(),{normalizeProvider:$1}=yi(),{escapeUri:lh,HttpRequest:B1}=nt();class G1{format(n){let t=[];for(let s of Object.keys(n)){let f=l1(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?Mt.boolTrue:Mt.boolFalse]);case"byte":return Uint8Array.from([Mt.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Mt.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Mt.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=Mt.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,Mt.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=l1(n.value),_=new DataView(new ArrayBuffer(3+h.byteLength));_.setUint8(0,Mt.string),_.setUint16(1,h.byteLength,!1);let o=new Uint8Array(_.buffer);return o.set(h,3),o;case"timestamp":let w=new Uint8Array(9);return w[0]=Mt.timestamp,w.set(lc.fromNumber(n.value.valueOf()).bytes,1),w;case"uuid":if(!H7.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Mt.uuid,c.set(B7(n.value.replace(/-/g,"")),1),c}}}var Mt;(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"})(Mt||(Mt={}));var H7=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class lc{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)U1(t);return new lc(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)U1(n);return parseInt(Lr(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function U1(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",W1="X-Amz-Credential",$c="X-Amz-Date",F1="X-Amz-SignedHeaders",Y1="X-Amz-Expires",Uc="X-Amz-Signature",Dc="X-Amz-Security-Token",W7="X-Amz-Region-Set",Bc="authorization",Gc=$c.toLowerCase(),P1="date",X1=[Bc,Gc,P1],C1=Uc.toLowerCase(),Gh="x-amz-content-sha256",J1=Dc.toLowerCase(),F7="host",Q1={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},m1=/^proxy-/,z1=/^sec-/,Y7=[/^proxy-/i,/^sec-/i],$h="AWS4-HMAC-SHA256",P7="AWS4-ECDSA-P256-SHA256",K1="AWS4-HMAC-SHA256-PAYLOAD",V1="UNSIGNED-PAYLOAD",x1=50,Hc="aws4_request",j1=604800,q1=({query:n={}})=>{let t=[],i={};for(let r of Object.keys(n)){if(r.toLowerCase()===C1)continue;let s=lh(r);t.push(s);let f=n[r];if(typeof f==="string")i[s]=`${s}=${lh(f)}`;else if(Array.isArray(f))i[s]=f.slice(0).reduce((h,_)=>h.concat([`${s}=${lh(_)}`]),[]).sort().join("&")}return t.sort().map((r)=>i[r]).filter((r)=>r).join("&")},X7=(n)=>C7(n).toISOString().replace(/\.\d{3}Z$/,"Z"),C7=(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 Wc{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=$1(i),this.credentialProvider=$1(t)}createCanonicalRequest(n,t,i){let r=Object.keys(t).sort();return`${n.method}
|
|
31
|
+
More information can be found at: https://a.co/c895JFp`)}},$3=()=>(n,t)=>async(i)=>{return t.__retryLongPoll=!0,n(i)},D3={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},B3=(n)=>({applyToStack:(t)=>{t.add($3(),D3)}});function G3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}A3.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function ni(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 m3(n,t,i){if(!n.$source)n.$source={};return n.$source[t]=i,n}function H3(n){return n}var wE=(n)=>(t)=>async(i)=>{if(!Hc.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)},yE={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},W3=(n)=>({applyToStack:(t)=>{t.add(wE(n),yE)}}),AE=()=>(n,t)=>async(i)=>{try{let r=await n(i),{clientName:s,commandName:f,logger:_,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h,overrideOutputFilterSensitiveLog:e}=o,c=h??t.inputFilterSensitiveLog,d=e??t.outputFilterSensitiveLog,{$metadata:u,...w}=r.output;return _?.info?.({clientName:s,commandName:f,input:c(i.input),output:d(w),metadata:u}),r}catch(r){let{clientName:s,commandName:f,logger:_,dynamoDbDocumentClientOptions:o={}}=t,{overrideInputFilterSensitiveLog:h}=o,e=h??t.inputFilterSensitiveLog;throw _?.error?.({clientName:s,commandName:f,input:e(i.input),error:r,metadata:r.$metadata}),r}},RE={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},F3=(n)=>({applyToStack:(t)=>{t.add(AE(),RE)}}),ME={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},C3="AWS_LAMBDA_FUNCTION_NAME",P3="_X_AMZN_TRACE_ID",Dc="X-Amzn-Trace-Id",mc="traceparent",EE="tracestate",lE="baggage",TE=()=>(n)=>async(t)=>{let{request:i}=t;if(!Hc.isInstance(i))return n(t);let r;{let s=Object.keys(i.headers??{}).find((f)=>f.toLowerCase()===Dc.toLowerCase())??Dc;if(!i.headers.hasOwnProperty(s)){let f=process.env[C3],_=process.env[P3];r??=await sE.getInstanceAsync();let h=r?.getXRayTraceId()??_,e=(c)=>typeof c==="string"&&c.length>0;if(e(f)&&e(h))i.headers[Dc]=h}}if(Y3(i.headers),!i.headers[mc]){let f=(r??=await sE.getInstanceAsync())?.getTraceparent?.();if(f){i.headers[mc]=f;let _=r?.getTracestate?.();if(_)i.headers[EE]=_;let o=r?.getBaggage?.();if(o)i.headers[lE]=o}}return n(t)};function Y3(n){for(let t of Object.keys(n)){let i=t.toLowerCase();if(t!==i&&(i===mc||i===EE||i===lE))n[i]=n[t],delete n[t]}}var X3=(n)=>({applyToStack:(t)=>{t.add(TE(),ME)}}),Wc=void 0;function J3(n){if(n===void 0)return!0;return typeof n==="string"&&n.length<=50}function Q3(n){let t=M3(n.userAgentAppId??Wc),{customUserAgent:i}=n;return Object.assign(n,{customUserAgent:typeof i==="string"?[[i]]:i,userAgentAppId:async()=>{let r=await t();if(!J3(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 gE={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"},OE=gE,LE="",IE=(n)=>{let{partitions:t}=OE;for(let r of t){let{regions:s,outputs:f}=r;for(let[_,o]of Object.entries(s))if(_===n)return{...f,...o}}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}},SE=(n,t="")=>{OE=n,LE=t},a3=()=>{SE(gE,"")},bE=()=>LE,z3=/\d{12}\.ddb/;async function K3(n,t,i){if(i.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")ni(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 rE.ADAPTIVE:ni(n,"RETRY_MODE_ADAPTIVE","F");break;case rE.STANDARD:ni(n,"RETRY_MODE_STANDARD","E");break}}if(typeof t.accountIdEndpointMode==="function"){let f=n.endpointV2;if(String(f?.url?.hostname).match(z3))ni(n,"ACCOUNT_ID_ENDPOINT","O");switch(await t.accountIdEndpointMode?.()){case"disabled":ni(n,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":ni(n,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":ni(n,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let s=n.__smithy_context?.selectedHttpAuthScheme?.identity;if(s?.$source){let f=s;if(f.accountId)ni(n,"RESOLVED_ACCOUNT_ID","T");for(let[_,o]of Object.entries(f.$source??{}))ni(n,_,o)}}var oE="user-agent",Bc="x-amz-user-agent",_E=" ",Gc="/",x3=/[^!$%&'*+\-.^_`|~\w]/g,V3=/[^!$%&'*+\-.^_`|~\w#]/g,hE="-",j3=1024;function q3(n){let t="";for(let i in n){let r=n[i];if(t.length+r.length+1<=j3){if(t.length)t+=","+r;else t+=r;continue}break}return t}var NE=(n)=>(t,i)=>async(r)=>{let{request:s}=r;if(!Hc.isInstance(s))return t(r);let{headers:f}=s,_=i?.userAgent?.map(P_)||[],o=(await n.defaultUserAgentProvider()).map(P_);await K3(i,n,r);let h=i;o.push(`m/${q3(Object.assign({},i.__smithy_context?.features,h.__aws_sdk_context?.features))}`);let e=n?.customUserAgent?.map(P_)||[],c=await n.userAgentAppId();if(c)o.push(P_(["app",`${c}`]));let d=bE(),u=(d?[d]:[]).concat([...o,..._,...e]).join(_E),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...e].join(_E);if(n.runtime!=="browser"){if(w)f[Bc]=f[Bc]?`${f[oE]} ${w}`:w;f[oE]=u}else f[Bc]=u;return t({...r,request:s})},P_=(n)=>{let t=n[0].split(Gc).map((_)=>_.replace(x3,hE)).join(Gc),i=n[1]?.replace(V3,hE),r=t.indexOf(Gc),s=t.substring(0,r),f=t.substring(r+1);if(s==="api")f=f.toLowerCase();return[s,f,i].filter((_)=>_&&_.length>0).reduce((_,o,h)=>{switch(h){case 0:return o;case 1:return`${_}/${o}`;default:return`${_}#${o}`}},"")},UE={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},k3=(n)=>({applyToStack:(t)=>{t.add(NE(n),UE)}}),Z3=()=>{let n=["deno","bun","llrt"];for(let t of n)if($c[t])return[`md/${t}`,$c[t]];return["md/nodejs",$c.node]},$E={isCrtAvailable:!1},v3=()=>{if($E.isCrtAvailable)return["md/crt-avail"];return null},DE=({serviceId:n,clientVersion:t})=>{let i=Z3();return async(r)=>{let s=[["aws-sdk-js",t],["ua","2.1"],[`os/${E3()}`,l3()],["lang/js"],i],f=v3();if(f)s.push(f);if(n)s.push([`api/${n}`,t]);if(fE.AWS_EXECUTION_ENV)s.push([`exec-env/${fE.AWS_EXECUTION_ENV}`]);let _=await r?.userAgentAppId?.();return _?[...s,[`app/${_}`]]:[...s]}},p3=DE,BE="AWS_SDK_UA_APP_ID",GE="sdk_ua_app_id",nW="sdk-ua-app-id",tW={environmentVariableSelector:(n)=>n[BE],configFileSelector:(n)=>n[GE]??n[nW],default:Wc},iW=({serviceId:n,clientVersion:t})=>async(i)=>{let r=iE(),s=r.parse??r.default.parse??(()=>""),f=typeof window<"u"&&window?.navigator?.userAgent?s(window.navigator.userAgent):void 0,_=[["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)_.push([`api/${n}`,t]);let o=await i?.userAgentAppId?.();if(o)_.push([`app/${o}`]);return _},rW={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}},Fc=(n,t=!1)=>{if(t){for(let i of n.split("."))if(!Fc(i))return!1;return!0}if(!T3(n))return!1;if(n.length<3||n.length>63)return!1;if(n!==n.toLowerCase())return!1;if(cE(n))return!1;return!0},eE=":",sW="/",mE=(n)=>{let t=n.split(eE);if(t.length<6)return null;let[i,r,s,f,_,...o]=t;if(i!=="arn"||r===""||s===""||o.join(eE)==="")return null;let h=o.map((e)=>e.split(sW)).flat();return{partition:r,service:s,region:f,accountId:_,resourceId:h}},HE={isVirtualHostableS3Bucket:Fc,parseArn:mE,partition:IE};g3.aws=HE;var fW=(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 WE(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},WE=(n)=>R3(n.url);function oW(n={}){return I3({...dE,async default(){if(!FE.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"}},{...uE,...n})}var FE={silence:!1},_W=(n)=>{return{setRegion(t){n.region=t},region(){return n.region}}},hW=(n)=>{return{region:n.region()}};eW.DEFAULT_UA_APP_ID=Wc;eW.NODE_APP_ID_CONFIG_OPTIONS=tW;eW.UA_APP_ID_ENV_NAME=BE;eW.UA_APP_ID_INI_NAME=GE;eW.awsEndpointFunctions=HE;eW.createDefaultUserAgentProvider=DE;eW.createUserAgentStringParsingProvider=iW;eW.crtAvailability=$E;eW.defaultUserAgent=p3;eW.emitWarningIfUnsupportedVersion=U3;eW.fallback=rW;eW.getAwsRegionExtensionConfiguration=_W;eW.getHostHeaderPlugin=W3;eW.getLoggerPlugin=F3;eW.getLongPollPlugin=B3;eW.getRecursionDetectionPlugin=X3;eW.getUserAgentMiddlewareOptions=UE;eW.getUserAgentPlugin=k3;eW.getUserAgentPrefix=bE;eW.hostHeaderMiddleware=wE;eW.hostHeaderMiddlewareOptions=yE;eW.isVirtualHostableS3Bucket=Fc;eW.loggerMiddleware=AE;eW.loggerMiddlewareOptions=RE;eW.parseArn=mE;eW.partition=IE;eW.recursionDetectionMiddleware=TE;eW.recursionDetectionMiddlewareOptions=ME;eW.resolveAwsRegionExtensionConfiguration=hW;eW.resolveDefaultAwsRegionalEndpointsConfig=fW;eW.resolveHostHeaderConfig=H3;eW.resolveUserAgentConfig=Q3;eW.setCredentialFeature=G3;eW.setFeature=ni;eW.setPartitionInfo=SE;eW.setTokenFeature=m3;eW.state=Y_;eW.stsRegionDefaultResolver=oW;eW.stsRegionWarning=FE;eW.toEndpointV1=WE;eW.useDefaultPartitionInfo=a3;eW.userAgentMiddleware=NE});var A1=sn((lF)=>{var{fromUtf8:aE,fromHex:hF,toHex:Sr,toUint8Array:to,isArrayBuffer:eF}=tt(),{normalizeProvider:zE}=Ei(),{escapeUri:X_,HttpRequest:VE}=it();class jE{format(n){let t=[];for(let s of Object.keys(n)){let f=aE(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?Tt.boolTrue:Tt.boolFalse]);case"byte":return Uint8Array.from([Tt.byte,n.value]);case"short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,Tt.short),t.setInt16(1,n.value,!1),new Uint8Array(t.buffer);case"integer":let i=new DataView(new ArrayBuffer(5));return i.setUint8(0,Tt.integer),i.setInt32(1,n.value,!1),new Uint8Array(i.buffer);case"long":let r=new Uint8Array(9);return r[0]=Tt.long,r.set(n.value.bytes,1),r;case"binary":let s=new DataView(new ArrayBuffer(3+n.value.byteLength));s.setUint8(0,Tt.byteArray),s.setUint16(1,n.value.byteLength,!1);let f=new Uint8Array(s.buffer);return f.set(n.value,3),f;case"string":let _=aE(n.value),o=new DataView(new ArrayBuffer(3+_.byteLength));o.setUint8(0,Tt.string),o.setUint16(1,_.byteLength,!1);let h=new Uint8Array(o.buffer);return h.set(_,3),h;case"timestamp":let e=new Uint8Array(9);return e[0]=Tt.timestamp,e.set(Xc.fromNumber(n.value.valueOf()).bytes,1),e;case"uuid":if(!cF.test(n.value))throw Error(`Invalid UUID received: ${n.value}`);let c=new Uint8Array(17);return c[0]=Tt.uuid,c.set(hF(n.value.replace(/-/g,"")),1),c}}}var Tt;(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"})(Tt||(Tt={}));var cF=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Xc{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)KE(t);return new Xc(t)}valueOf(){let n=this.bytes.slice(0),t=n[0]&128;if(t)KE(n);return parseInt(Sr(n),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function KE(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 qE="X-Amz-Algorithm",kE="X-Amz-Credential",Jc="X-Amz-Date",ZE="X-Amz-SignedHeaders",vE="X-Amz-Expires",Qc="X-Amz-Signature",ac="X-Amz-Security-Token",dF="X-Amz-Region-Set",zc="authorization",Kc=Jc.toLowerCase(),pE="date",n1=[zc,Kc,pE],t1=Qc.toLowerCase(),K_="x-amz-content-sha256",i1=ac.toLowerCase(),uF="host",r1={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},s1=/^proxy-/,f1=/^sec-/,wF=[/^proxy-/i,/^sec-/i],J_="AWS4-HMAC-SHA256",yF="AWS4-ECDSA-P256-SHA256",o1="AWS4-HMAC-SHA256-PAYLOAD",_1="UNSIGNED-PAYLOAD",h1=50,xc="aws4_request",e1=604800,c1=({query:n={}})=>{let t=[],i={};for(let r of Object.keys(n)){if(r.toLowerCase()===t1)continue;let s=X_(r);t.push(s);let f=n[r];if(typeof f==="string")i[s]=`${s}=${X_(f)}`;else if(Array.isArray(f))i[s]=f.slice(0).reduce((_,o)=>_.concat([`${s}=${X_(o)}`]),[]).sort().join("&")}return t.sort().map((r)=>i[r]).filter((r)=>r).join("&")},AF=(n)=>RF(n).toISOString().replace(/\.\d{3}Z$/,"Z"),RF=(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 Vc{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=zE(i),this.credentialProvider=zE(t)}createCanonicalRequest(n,t,i){let r=Object.keys(t).sort();return`${n.method}
|
|
32
32
|
${this.getCanonicalPath(n)}
|
|
33
|
-
${
|
|
33
|
+
${c1(n)}
|
|
34
34
|
${r.map((s)=>`${s}:${t[s]}`).join(`
|
|
35
35
|
`)}
|
|
36
36
|
|
|
37
37
|
${r.join(";")}
|
|
38
|
-
${i}`}async createStringToSign(n,t,i,r){let s=new this.sha256;s.update(
|
|
38
|
+
${i}`}async createStringToSign(n,t,i,r){let s=new this.sha256;s.update(to(i));let f=await s.digest();return`${r}
|
|
39
39
|
${n}
|
|
40
40
|
${t}
|
|
41
|
-
${
|
|
42
|
-
`);return this.signString(R,{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),o=new this.sha256(await this.getSigningKey(f,h,_,r));return o.update(Vf(n)),Lr(await o.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(),o=Sc(n),{longDate:w,shortDate:c}=this.formatDate(t),d=Dh(c,_,f??this.service);if(o.headers[Gc]=w,h.sessionToken)o.headers[J1]=h.sessionToken;let u=await Bh(o,this.sha256);if(!a1(Gh,o.headers)&&this.applyChecksum)o.headers[Gh]=u;let y=bc(o,r,i),R=await this.getSignature(w,d,this.getSigningKey(h,_,c,f),this.createCanonicalRequest(o,y,u));return o.headers[Bc]=`${$h} Credential=${h.accessKeyId}/${d}, SignedHeaders=${this.getCanonicalHeaderList(y)}, Signature=${R}`,o}async getSignature(n,t,i,r){let s=await this.createStringToSign(n,t,r,$h),f=new this.sha256(await i);return f.update(Vf(s)),Lr(await f.digest())}getSigningKey(n,t,i,r){return k1(this.sha256,n,i,t,r||this.service)}}var Q7={SignatureV4a:null};m7.ALGORITHM_IDENTIFIER=$h;m7.ALGORITHM_IDENTIFIER_V4A=P7;m7.ALGORITHM_QUERY_PARAM=H1;m7.ALWAYS_UNSIGNABLE_HEADERS=Q1;m7.AMZ_DATE_HEADER=Gc;m7.AMZ_DATE_QUERY_PARAM=$c;m7.AUTH_HEADER=Bc;m7.CREDENTIAL_QUERY_PARAM=W1;m7.DATE_HEADER=P1;m7.EVENT_ALGORITHM_IDENTIFIER=K1;m7.EXPIRES_QUERY_PARAM=Y1;m7.GENERATED_HEADERS=X1;m7.HOST_HEADER=F7;m7.KEY_TYPE_IDENTIFIER=Hc;m7.MAX_CACHE_SIZE=x1;m7.MAX_PRESIGNED_TTL=j1;m7.PROXY_HEADER_PATTERN=m1;m7.REGION_SET_PARAM=W7;m7.SEC_HEADER_PATTERN=z1;m7.SHA256_HEADER=Gh;m7.SIGNATURE_HEADER=C1;m7.SIGNATURE_QUERY_PARAM=Uc;m7.SIGNED_HEADERS_QUERY_PARAM=F1;m7.SignatureV4=v1;m7.SignatureV4Base=Wc;m7.TOKEN_HEADER=J1;m7.TOKEN_QUERY_PARAM=Dc;m7.UNSIGNABLE_PATTERNS=Y7;m7.UNSIGNED_PAYLOAD=V1;m7.clearCredentialCache=J7;m7.createScope=Dh;m7.getCanonicalHeaders=bc;m7.getCanonicalQuery=q1;m7.getPayloadHash=Bh;m7.getSigningKey=k1;m7.hasHeader=a1;m7.moveHeadersToQuery=Z1;m7.prepareRequest=Sc;m7.signatureV4aContainer=Q7});var Pc=rn((QF)=>{var{HttpResponse:$F,HttpRequest:hT}=nt(),{normalizeProvider:xf,memoizeIdentityProvider:UF,isIdentityExpired:DF,doesIdentityRequireRefresh:BF}=zi(),{ProviderError:nT}=vn(),{setCredentialFeature:GF}=Dt(),{SignatureV4:tT}=p1(),iT=(n)=>$F.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,Fc=(n)=>new Date(Date.now()+n),HF=(n,t)=>Math.abs(Fc(t).getTime()-n)>=300000,rT=(n,t)=>{let i=Date.parse(n);if(HF(i,t))return i-Date.now();return t},jf=(n,t)=>{if(!t)throw Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return t},Yc=async(n)=>{let t=jf("context",n.context),i=jf("config",n.config),r=t.endpointV2?.properties?.authSchemes?.[0],f=await jf("signer",i.signer)(r),h=n?.signingRegion,_=n?.signingRegionSet,o=n?.signingName;return{config:i,signer:f,signingRegion:h,signingRegionSet:_,signingName:o}};class Hh{async sign(n,t,i){if(!hT.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await Yc(i),{config:s,signer:f}=r,{signingRegion:h,signingName:_}=r,o=i.context;if(o?.authSchemes?.length??!1){let[c,d]=o.authSchemes;if(c?.name==="sigv4a"&&d?.name==="sigv4")h=d?.signingRegion??h,_=d?.signingName??_}return i._preRequestSystemClockOffset=s.systemClockOffset,await f.sign(n,{signingDate:Fc(s.systemClockOffset),signingRegion:h,signingService:_})}errorHandler(n){return(t)=>{let i=t,r=i.ServerTime??iT(i.$response);if(r){let s=jf("config",n.config),f=n._preRequestSystemClockOffset,h=rT(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=iT(n);if(i){let r=jf("config",t.config);r.systemClockOffset=rT(i,r.systemClockOffset)}}}var WF=Hh;class oT extends Hh{async sign(n,t,i){if(!hT.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 Yc(i),w=(await r.sigv4aSigningRegionSet?.()??h??[f]).join(",");return i._preRequestSystemClockOffset=r.systemClockOffset,await s.sign(n,{signingDate:Fc(r.systemClockOffset),signingRegion:w,signingService:_})}}var sT=(n)=>typeof n==="string"&&n.length>0?n.split(",").map((t)=>t.trim()):[],wT=(n)=>`AWS_BEARER_TOKEN_${n.replace(/[\s-]/g,"_").toUpperCase()}`,fT="AWS_AUTH_SCHEME_PREFERENCE",_T="auth_scheme_preference",FF={environmentVariableSelector:(n,t)=>{if(t?.signingName){if(wT(t.signingName)in n)return["httpBearerAuth"]}if(!(fT in n))return;return sT(n[fT])},configFileSelector:(n)=>{if(!(_T in n))return;return sT(n[_T])},default:[]},YF=(n)=>{return n.sigv4aSigningRegionSet=xf(n.sigv4aSigningRegionSet),n},PF={environmentVariableSelector(n){if(n.AWS_SIGV4A_SIGNING_REGION_SET)return n.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new nT("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 nT("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},cT=(n)=>{let t=n.credentials,i=!!n.credentials,r=void 0;Object.defineProperty(n,"credentials",{set(w){if(w&&w!==t&&w!==r)i=!0;t=w;let c=CF(n,{credentials:t,credentialDefaultProvider:n.credentialDefaultProvider}),d=JF(n,c);if(i&&!d.attributed){let u=typeof t==="object"&&t!==null;r=async(y)=>{let M=await d(y);if(u&&(!M.$source||Object.keys(M.$source).length===0))return GF(M,"CREDENTIALS_CODE","e");return M},r.memoized=d.memoized,r.configBound=d.configBound,r.attributed=!0}else r=d},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)_=xf(n.signer);else if(n.regionInfoProvider)_=()=>xf(n.region)().then(async(w)=>[await n.regionInfoProvider(w,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},w]).then(([w,c])=>{let{signingRegion:d,signingService:u}=w;n.signingRegion=n.signingRegion||d||c,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||tT)(y)});else _=async(w)=>{w=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await xf(n.region)(),properties:{}},w);let{signingRegion:c,signingName:d}=w;n.signingRegion=n.signingRegion||c,n.signingName=n.signingName||d||n.serviceId;let u={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:h,uriEscapePath:s};return new(n.signerConstructor||tT)(u)};return Object.assign(n,{systemClockOffset:f,signingEscapePath:s,signer:_})},XF=cT;function CF(n,{credentials:t,credentialDefaultProvider:i}){let r;if(t)if(!t?.memoized)r=UF(t,DF,BF);else r=t;else if(i)r=xf(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 JF(n,t){if(t.configBound)return t;let i=async(r)=>t({...r,callerClientConfig:n});return i.memoized=t.memoized,i.configBound=!0,i}QF.AWSSDKSigV4Signer=WF;QF.AwsSdkSigV4ASigner=oT;QF.AwsSdkSigV4Signer=Hh;QF.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=FF;QF.NODE_SIGV4A_CONFIG_OPTIONS=PF;QF.getBearerTokenEnvKey=wT;QF.resolveAWSSDKSigV4Config=XF;QF.resolveAwsSdkSigV4AConfig=YF;QF.resolveAwsSdkSigV4Config=cT;QF.validateSigningProperties=Yc});var Ch=rn((wY)=>{var{buildQueryString:ET,HttpResponse:TT}=nt(),Wh=dn("https"),{Readable:vF}=dn("stream"),Xc=dn("http2"),{streamCollector:pF}=pn();wY.streamCollector=pF;function Yh(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 nY=["ECONNRESET","EPIPE","ETIMEDOUT"],eT=(n)=>{let t={};for(let i in n){let r=n[i];t[i]=Array.isArray(r)?r.join(","):r}return t},mn={setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:(n)=>clearTimeout(n)},uT=1000,tY=(n,t,i=0)=>{if(!i)return-1;let r=(s)=>{let f=mn.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",()=>{mn.clearTimeout(f)});else mn.clearTimeout(f)};if(n.socket)h(n.socket);else n.on("socket",h)};if(i<2000)return r(0),0;return mn.setTimeout(r.bind(null,uT),uT)},iY=(n,t,i=0,r,s)=>{if(i)return mn.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},rY=3000,sY=(n,{keepAlive:t,keepAliveMsecs:i},r=rY)=>{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 mn.setTimeout(s,r)},yT=3000,fY=(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 mn.setTimeout(r.bind(null,i===0?0:yT),yT)},AT=6000;async function OT(n,t,i=AT,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((o)=>{h=Number(mn.setTimeout(()=>o(!0),Math.max(AT,i)))}),new Promise((o)=>{n.on("continue",()=>{mn.clearTimeout(h),o(!0)}),n.on("response",()=>{mn.clearTimeout(h),o(!1)}),n.on("error",()=>{mn.clearTimeout(h),o(!1)})})]);if(_)_Y(n,t.body)}function _Y(n,t){if(t instanceof vF){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 hY=0,Fh=void 0,RT=void 0;class Ph{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(n){if(typeof n?.handle==="function")return n;return new Ph(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 o=r[_]?.length??0,w=s[_]?.length??0;if(o>=f&&w>=2*f)return i?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${o} and ${w} additional requests are enqueued.
|
|
41
|
+
${Sr(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 X_(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=AF(n).replace(/[-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(n){return Object.keys(n).sort().join(";")}}var ms={},Q_=[],a_=(n,t,i)=>`${n}/${t}/${i}/${xc}`,d1=async(n,t,i,r,s)=>{let f=await xE(n,t.secretAccessKey,t.accessKeyId),_=`${i}:${r}:${s}:${Sr(f)}:${t.sessionToken}`;if(_ in ms)return ms[_];Q_.push(_);while(Q_.length>h1)delete ms[Q_.shift()];let o=`AWS4${t.secretAccessKey}`;for(let h of[i,r,s,xc])o=await xE(n,o,h);return ms[_]=o},MF=()=>{Q_.length=0,Object.keys(ms).forEach((n)=>{delete ms[n]})},xE=(n,t,i)=>{let r=new n(t);return r.update(to(i)),r.digest()},Pc=({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 r1||t?.has(f)||s1.test(f)||f1.test(f)){if(!i||i&&!i.has(f))continue}r[f]=n[s].trim().replace(/\s+/g," ")}return r},z_=async({headers:n,body:t},i)=>{for(let r of Object.keys(n))if(r.toLowerCase()===K_)return n[r];if(t==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof t==="string"||ArrayBuffer.isView(t)||eF(t)){let r=new i;return r.update(to(t)),Sr(await r.digest())}return _1},u1=(n,t)=>{n=n.toLowerCase();for(let i of Object.keys(t))if(n===i.toLowerCase())return!0;return!1},w1=(n,t={})=>{let{headers:i,query:r={}}=VE.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}},Yc=(n)=>{n=VE.clone(n);for(let t of Object.keys(n.headers))if(n1.indexOf(t.toLowerCase())>-1)delete n.headers[t];return n};class y1 extends Vc{headerFormatter=new jE;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:_,hoistableHeaders:o,signingRegion:h,signingService:e}=t,c=await this.credentialProvider();this.validateResolvedCredentials(c);let d=h??await this.regionProvider(),{longDate:u,shortDate:w}=this.formatDate(i);if(r>e1)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=a_(w,d,e??this.service),R=w1(Yc(n),{unhoistableHeaders:f,hoistableHeaders:o});if(c.sessionToken)R.query[ac]=c.sessionToken;R.query[qE]=J_,R.query[kE]=`${c.accessKeyId}/${A}`,R.query[Jc]=u,R.query[vE]=r.toString(10);let M=Pc(R,s,_);return R.query[ZE]=this.getCanonicalHeaderList(M),R.query[Qc]=await this.getSignature(u,A,this.getSigningKey(c,d,w,e),this.createCanonicalRequest(R,M,await z_(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:_}){let o=s??await this.regionProvider(),{shortDate:h,longDate:e}=this.formatDate(i),c=a_(h,o,f??this.service),d=await z_({headers:{},body:t},this.sha256),u=new this.sha256;u.update(n);let w=Sr(await u.digest()),A=[o1,e,c,r,w,d].join(`
|
|
42
|
+
`);return this.signString(A,{signingDate:i,signingRegion:o,signingService:f,eventStreamCredentials:_})}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((_)=>{return{message:n.message,signature:_}})}async signString(n,{signingDate:t=new Date,signingRegion:i,signingService:r,eventStreamCredentials:s}={}){let f=s??await this.credentialProvider();this.validateResolvedCredentials(f);let _=i??await this.regionProvider(),{shortDate:o}=this.formatDate(t),h=new this.sha256(await this.getSigningKey(f,_,o,r));return h.update(to(n)),Sr(await h.digest())}async signRequest(n,{signingDate:t=new Date,signableHeaders:i,unsignableHeaders:r,signingRegion:s,signingService:f}={}){let _=await this.credentialProvider();this.validateResolvedCredentials(_);let o=s??await this.regionProvider(),h=Yc(n),{longDate:e,shortDate:c}=this.formatDate(t),d=a_(c,o,f??this.service);if(h.headers[Kc]=e,_.sessionToken)h.headers[i1]=_.sessionToken;let u=await z_(h,this.sha256);if(!u1(K_,h.headers)&&this.applyChecksum)h.headers[K_]=u;let w=Pc(h,r,i),A=await this.getSignature(e,d,this.getSigningKey(_,o,c,f),this.createCanonicalRequest(h,w,u));return h.headers[zc]=`${J_} Credential=${_.accessKeyId}/${d}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,h}async getSignature(n,t,i,r){let s=await this.createStringToSign(n,t,r,J_),f=new this.sha256(await i);return f.update(to(s)),Sr(await f.digest())}getSigningKey(n,t,i,r){return d1(this.sha256,n,i,t,r||this.service)}}var EF={SignatureV4a:null};lF.ALGORITHM_IDENTIFIER=J_;lF.ALGORITHM_IDENTIFIER_V4A=yF;lF.ALGORITHM_QUERY_PARAM=qE;lF.ALWAYS_UNSIGNABLE_HEADERS=r1;lF.AMZ_DATE_HEADER=Kc;lF.AMZ_DATE_QUERY_PARAM=Jc;lF.AUTH_HEADER=zc;lF.CREDENTIAL_QUERY_PARAM=kE;lF.DATE_HEADER=pE;lF.EVENT_ALGORITHM_IDENTIFIER=o1;lF.EXPIRES_QUERY_PARAM=vE;lF.GENERATED_HEADERS=n1;lF.HOST_HEADER=uF;lF.KEY_TYPE_IDENTIFIER=xc;lF.MAX_CACHE_SIZE=h1;lF.MAX_PRESIGNED_TTL=e1;lF.PROXY_HEADER_PATTERN=s1;lF.REGION_SET_PARAM=dF;lF.SEC_HEADER_PATTERN=f1;lF.SHA256_HEADER=K_;lF.SIGNATURE_HEADER=t1;lF.SIGNATURE_QUERY_PARAM=Qc;lF.SIGNED_HEADERS_QUERY_PARAM=ZE;lF.SignatureV4=y1;lF.SignatureV4Base=Vc;lF.TOKEN_HEADER=i1;lF.TOKEN_QUERY_PARAM=ac;lF.UNSIGNABLE_PATTERNS=wF;lF.UNSIGNED_PAYLOAD=_1;lF.clearCredentialCache=MF;lF.createScope=a_;lF.getCanonicalHeaders=Pc;lF.getCanonicalQuery=c1;lF.getPayloadHash=z_;lF.getSigningKey=d1;lF.hasHeader=u1;lF.moveHeadersToQuery=w1;lF.prepareRequest=Yc;lF.signatureV4aContainer=EF});var kc=sn((EC)=>{var{HttpResponse:fC,HttpRequest:L1}=it(),{normalizeProvider:io,memoizeIdentityProvider:oC,isIdentityExpired:_C,doesIdentityRequireRefresh:hC}=ji(),{ProviderError:R1}=nt(),{setCredentialFeature:eC}=Ht(),{SignatureV4:M1}=A1(),E1=(n)=>fC.isInstance(n)?n.headers?.date??n.headers?.Date:void 0,jc=(n)=>new Date(Date.now()+n),cC=(n,t)=>Math.abs(jc(t).getTime()-n)>=300000,l1=(n,t)=>{let i=Date.parse(n);if(cC(i,t))return i-Date.now();return t},ro=(n,t)=>{if(!t)throw Error(`Property \`${n}\` is not resolved for AWS SDK SigV4Auth`);return t},qc=async(n)=>{let t=ro("context",n.context),i=ro("config",n.config),r=t.endpointV2?.properties?.authSchemes?.[0],f=await ro("signer",i.signer)(r),_=n?.signingRegion,o=n?.signingRegionSet,h=n?.signingName;return{config:i,signer:f,signingRegion:_,signingRegionSet:o,signingName:h}};class x_{async sign(n,t,i){if(!L1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await qc(i),{config:s,signer:f}=r,{signingRegion:_,signingName:o}=r,h=i.context;if(h?.authSchemes?.length??!1){let[c,d]=h.authSchemes;if(c?.name==="sigv4a"&&d?.name==="sigv4")_=d?.signingRegion??_,o=d?.signingName??o}return i._preRequestSystemClockOffset=s.systemClockOffset,await f.sign(n,{signingDate:jc(s.systemClockOffset),signingRegion:_,signingService:o})}errorHandler(n){return(t)=>{let i=t,r=i.ServerTime??E1(i.$response);if(r){let s=ro("config",n.config),f=n._preRequestSystemClockOffset,_=l1(r,s.systemClockOffset);if((_!==s.systemClockOffset||f!==void 0&&f!==_)&&i.$metadata)s.systemClockOffset=_,i.$metadata.clockSkewCorrected=!0}throw t}}successHandler(n,t){let i=E1(n);if(i){let r=ro("config",t.config);r.systemClockOffset=l1(i,r.systemClockOffset)}}}var dC=x_;class I1 extends x_{async sign(n,t,i){if(!L1.isInstance(n))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:s,signingRegion:f,signingRegionSet:_,signingName:o}=await qc(i),e=(await r.sigv4aSigningRegionSet?.()??_??[f]).join(",");return i._preRequestSystemClockOffset=r.systemClockOffset,await s.sign(n,{signingDate:jc(r.systemClockOffset),signingRegion:e,signingService:o})}}var T1=(n)=>typeof n==="string"&&n.length>0?n.split(",").map((t)=>t.trim()):[],S1=(n)=>`AWS_BEARER_TOKEN_${n.replace(/[\s-]/g,"_").toUpperCase()}`,g1="AWS_AUTH_SCHEME_PREFERENCE",O1="auth_scheme_preference",uC={environmentVariableSelector:(n,t)=>{if(t?.signingName){if(S1(t.signingName)in n)return["httpBearerAuth"]}if(!(g1 in n))return;return T1(n[g1])},configFileSelector:(n)=>{if(!(O1 in n))return;return T1(n[O1])},default:[]},wC=(n)=>{return n.sigv4aSigningRegionSet=io(n.sigv4aSigningRegionSet),n},yC={environmentVariableSelector(n){if(n.AWS_SIGV4A_SIGNING_REGION_SET)return n.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((t)=>t.trim());throw new R1("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 R1("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},b1=(n)=>{let t=n.credentials,i=!!n.credentials,r=void 0;Object.defineProperty(n,"credentials",{set(e){if(e&&e!==t&&e!==r)i=!0;t=e;let c=RC(n,{credentials:t,credentialDefaultProvider:n.credentialDefaultProvider}),d=MC(n,c);if(i&&!d.attributed){let u=typeof t==="object"&&t!==null;r=async(w)=>{let R=await d(w);if(u&&(!R.$source||Object.keys(R.$source).length===0))return eC(R,"CREDENTIALS_CODE","e");return R},r.memoized=d.memoized,r.configBound=d.configBound,r.attributed=!0}else r=d},get(){return r},enumerable:!0,configurable:!0}),n.credentials=t;let{signingEscapePath:s=!0,systemClockOffset:f=n.systemClockOffset||0,sha256:_}=n,o;if(n.signer)o=io(n.signer);else if(n.regionInfoProvider)o=()=>io(n.region)().then(async(e)=>[await n.regionInfoProvider(e,{useFipsEndpoint:await n.useFipsEndpoint(),useDualstackEndpoint:await n.useDualstackEndpoint()})||{},e]).then(([e,c])=>{let{signingRegion:d,signingService:u}=e;n.signingRegion=n.signingRegion||d||c,n.signingName=n.signingName||u||n.serviceId;let w={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:_,uriEscapePath:s};return new(n.signerConstructor||M1)(w)});else o=async(e)=>{e=Object.assign({},{name:"sigv4",signingName:n.signingName||n.defaultSigningName,signingRegion:await io(n.region)(),properties:{}},e);let{signingRegion:c,signingName:d}=e;n.signingRegion=n.signingRegion||c,n.signingName=n.signingName||d||n.serviceId;let u={...n,credentials:n.credentials,region:n.signingRegion,service:n.signingName,sha256:_,uriEscapePath:s};return new(n.signerConstructor||M1)(u)};return Object.assign(n,{systemClockOffset:f,signingEscapePath:s,signer:o})},AC=b1;function RC(n,{credentials:t,credentialDefaultProvider:i}){let r;if(t)if(!t?.memoized)r=oC(t,_C,hC);else r=t;else if(i)r=io(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 MC(n,t){if(t.configBound)return t;let i=async(r)=>t({...r,callerClientConfig:n});return i.memoized=t.memoized,i.configBound=!0,i}EC.AWSSDKSigV4Signer=dC;EC.AwsSdkSigV4ASigner=I1;EC.AwsSdkSigV4Signer=x_;EC.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=uC;EC.NODE_SIGV4A_CONFIG_OPTIONS=yC;EC.getBearerTokenEnvKey=S1;EC.resolveAWSSDKSigV4Config=AC;EC.resolveAwsSdkSigV4AConfig=wC;EC.resolveAwsSdkSigV4Config=b1;EC.validateSigningProperties=qc});var v_=sn((XC)=>{var{buildQueryString:m1,HttpResponse:H1}=it(),V_=un("https"),{Readable:$C}=un("stream"),Zc=un("http2"),{streamCollector:DC}=tt();XC.streamCollector=DC;function q_(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 BC=["ECONNRESET","EPIPE","ETIMEDOUT"],W1=(n)=>{let t={};for(let i in n){let r=n[i];t[i]=Array.isArray(r)?r.join(","):r}return t},Qn={setTimeout:(n,t)=>setTimeout(n,t),clearTimeout:(n)=>clearTimeout(n)},U1=1000,GC=(n,t,i=0)=>{if(!i)return-1;let r=(s)=>{let f=Qn.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),_=(o)=>{if(o?.connecting)o.on("connect",()=>{Qn.clearTimeout(f)});else Qn.clearTimeout(f)};if(n.socket)_(n.socket);else n.on("socket",_)};if(i<2000)return r(0),0;return Qn.setTimeout(r.bind(null,U1),U1)},mC=(n,t,i=0,r,s)=>{if(i)return Qn.setTimeout(()=>{let f=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${i} ms requestTimeout.`;if(r){let _=Object.assign(Error(f),{name:"TimeoutError",code:"ETIMEDOUT"});n.destroy(_),t(_)}else f+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",s?.warn?.(f)},i);return-1},HC=3000,WC=(n,{keepAlive:t,keepAliveMsecs:i},r=HC)=>{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 Qn.setTimeout(s,r)},$1=3000,FC=(n,t,i=0)=>{let r=(s)=>{let f=i-s,_=()=>{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,_),n.on("close",()=>n.socket?.removeListener("timeout",_));else n.setTimeout(f,_)};if(0<i&&i<6000)return r(0),0;return Qn.setTimeout(r.bind(null,i===0?0:$1),$1)},D1=6000;async function F1(n,t,i=D1,r=!1){let s=t.headers,f=s?s.Expect||s.expect:void 0,_=-1,o=!0;if(!r&&f==="100-continue")o=await Promise.race([new Promise((h)=>{_=Number(Qn.setTimeout(()=>h(!0),Math.max(D1,i)))}),new Promise((h)=>{n.on("continue",()=>{Qn.clearTimeout(_),h(!0)}),n.on("response",()=>{Qn.clearTimeout(_),h(!1)}),n.on("error",()=>{Qn.clearTimeout(_),h(!1)})})]);if(o)CC(n,t.body)}function CC(n,t){if(t instanceof $C){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 PC=0,j_=void 0,B1=void 0;class k_{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(n){if(typeof n?.handle==="function")return n;return new k_(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 _=15000;if(Date.now()-_<t)return t;if(r&&s)for(let o in r){let h=r[o]?.length??0,e=s[o]?.length??0;if(h>=f&&e>=2*f)return i?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${h} and ${e} additional requests are enqueued.
|
|
43
43
|
See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
|
|
44
|
-
or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return t}constructor(n){this.configProvider=new Promise((t,i)=>{if(typeof n==="function")n().then((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,o=-1,w=-1,c=-1,d=-1,u=-1,y=()=>{mn.clearTimeout(o),mn.clearTimeout(w),mn.clearTimeout(c),mn.clearTimeout(d),mn.clearTimeout(u)},R=async(I)=>{await _,y(),f(I)},M=async(I)=>{await _,y(),h(I)};if(t?.aborted){let I=Yh(t);M(I);return}let E=n.headers,T=E?(E.Expect??E.expect)==="100-continue":!1,O=s?r.httpsAgent:r.httpAgent;if(T&&!this.externalAgent)O=new(s?Wh.Agent:Fh)({keepAlive:!1,maxSockets:1/0});o=mn.setTimeout(()=>{this.socketWarningTimestamp=Ph.checkSocketUsage(O,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let e=n.query?ET(n.query):"",L=void 0;if(n.username!=null||n.password!=null){let I=n.username??"",P=n.password??"";L=`${I}:${P}`}let N=n.path;if(e)N+=`?${e}`;if(n.fragment)N+=`#${n.fragment}`;let l=n.hostname??"";if(l[0]==="["&&l.endsWith("]"))l=n.hostname.slice(1,-1);else l=n.hostname;let Y={headers:n.headers,host:l,method:n.method,path:N,port:n.port,agent:O,auth:L},b=(s?Wh.request:RT)(Y,(I)=>{let P=new TT({statusCode:I.statusCode||-1,reason:I.statusMessage,headers:eT(I.headers),body:I});R({response:P})});if(b.on("error",(I)=>{if(nY.includes(I.code))M(Object.assign(I,{name:"TimeoutError"}));else M(I)}),t){let I=()=>{b.destroy();let P=Yh(t);M(P)};if(typeof t.addEventListener==="function"){let P=t;P.addEventListener("abort",I,{once:!0}),b.once("close",()=>P.removeEventListener("abort",I))}else t.onabort=I}let H=i??r.requestTimeout;w=tY(b,M,r.connectionTimeout),c=iY(b,M,H,r.throwOnRequestTimeout,r.logger??console),d=fY(b,M,r.socketTimeout);let g=Y.agent;if(typeof g==="object"&&"keepAlive"in g)u=sY(b,{keepAlive:g.keepAlive,keepAliveMsecs:g.keepAliveMsecs});_=OT(b,n,H,this.externalAgent).catch((I)=>{return y(),h(I)})})}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:o}=n||{},w=!0,c=50;return{connectionTimeout:i,requestTimeout:t,socketTimeout:r,socketAcquisitionWarningTimeout:s,throwOnRequestTimeout:_,httpAgentProvider:async()=>{let d=dn("http"),{Agent:u,request:y}=d.default??d;if(RT=y,Fh=u,f instanceof Fh||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Fh({keepAlive:!0,maxSockets:50,...f})},httpsAgent:(()=>{if(h instanceof Wh.Agent||typeof h?.destroy==="function")return this.externalAgent=!0,h;return new Wh.Agent({keepAlive:!0,maxSockets:50,...h})})(),logger:o}}}var oY=new Uint16Array(1);class Xh{id=oY[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 LT{sessions=[];maxConcurrency=0;constructor(n){this.sessions=(n??[]).map((t)=>new Xh(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 IT{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 o=r.poll();if(o)return o.retain(),o}let s=new Xh(this.connect(i)),f=s.deref();if(this.config.maxConcurrency)f.settings({maxConcurrentStreams:this.config.maxConcurrency},(o)=>{if(o)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 Xh(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 LT;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?Xc.connect(n):Xc.connect(n,this.connectOptions)}}var{constants:MT}=Xc;class Cc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new IT({});static create(n){if(typeof n?.handle==="function")return n;return new Cc(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:o,maxConcurrentStreams:w,nodeHttp2ConnectOptions:c}=this.config;if(this.connectionManager.setDisableConcurrentStreams(o??!1),w)this.connectionManager.setMaxConcurrentStreams(w);if(c)this.connectionManager.setNodeHttp2ConnectOptions(c)}let{requestTimeout:s,disableConcurrentStreams:f}=this.config,h=f||r,_=i??s;return new Promise((o,w)=>{let c=!1,d=void 0,u=async(P)=>{await d,o(P)},y=async(P)=>{await d,w(P)};if(t?.aborted){c=!0;let P=Yh(t);y(P);return}let{hostname:R,method:M,port:E,protocol:T,query:O}=n,e="";if(n.username!=null||n.password!=null){let P=n.username??"",m=n.password??"";e=`${P}:${m}@`}let L=`${T}//${e}${R}${E?`:${E}`:""}`,N={destination:new URL(L)},l={requestTimeout:this.config?.sessionTimeout,isEventStream:r},Y=h?this.connectionManager.createIsolatedSession(N,l):this.connectionManager.lease(N,l),V=Y.deref(),b=(P)=>{if(h)Y.destroy();c=!0,y(P)},H=O?ET(O):"",g=n.path;if(H)g+=`?${H}`;if(n.fragment)g+=`#${n.fragment}`;let I=V.request({...n.headers,[MT.HTTP2_HEADER_PATH]:g,[MT.HTTP2_HEADER_METHOD]:M});if(_)I.setTimeout(_,()=>{I.close();let P=Error(`Stream timed out because of no activity for ${_} ms`);P.name="TimeoutError",b(P)});if(t){let P=()=>{I.close();let m=Yh(t);b(m)};if(typeof t.addEventListener==="function"){let m=t;m.addEventListener("abort",P,{once:!0}),I.once("close",()=>m.removeEventListener("abort",P))}else t.onabort=P}I.on("frameError",(P,m,a)=>{b(Error(`Frame type id ${P} in stream id ${a} has failed with code ${m}.`))}),I.on("error",b),I.on("aborted",()=>{b(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${I.rstCode}.`))}),I.on("response",(P)=>{let m=new TT({statusCode:P[":status"]??-1,headers:eT(P),body:I});if(c=!0,u({response:m}),h)V.close()}),I.on("close",()=>{if(h)Y.destroy();else this.connectionManager.release(N,Y);if(!c)b(Error("Unexpected error: http2 request did not get a response"))}),d=OT(I,n,_)})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}}wY.DEFAULT_REQUEST_TIMEOUT=hY;wY.NodeHttp2Handler=Cc;wY.NodeHttpHandler=Ph});var WT=rn((xY)=>{var{nv:AY,NumericValue:lT,calculateBodyLength:RY,_parseEpochTimestamp:gT,fromBase64:$T,generateIdempotencyToken:MY}=pn(),{HttpRequest:EY,collectBody:TY,SerdeContext:Vc,RpcProtocol:eY}=nt(),{NormalizedSchema:xc,deref:OY,TypeRegistry:NT}=Yi(),{getSmithyContext:LY}=Vt();function $s(n){return typeof Buffer<"u"?Buffer.alloc(n):new Uint8Array(n)}var jc=Symbol("@smithy/core/cbor::tagSymbol");function qc(n){return n[jc]=!0,n}var UT=typeof Buffer<"u",kc=new TextDecoder,wn=$s(0),ac=!1,Bt=new DataView(wn.buffer,wn.byteOffset,wn.byteLength),v=0;function IY(n){wn=n,ac=UT&&wn instanceof Buffer,Bt=new DataView(wn.buffer,wn.byteOffset,wn.byteLength)}function Vi(n,t){if(n>=t)throw Error("unexpected end of (decode) payload.");let i=(wn[n]&224)>>5,r=wn[n]&31;if(r===31&&2<=i&&i<=5)return gY(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)Zt(1);s=wn[n+1],f=2;break;case 25:if(t-n<3)Zt(2);s=Bt.getUint16(n+1),f=3;break;case 26:if(t-n<5)Zt(4);s=Bt.getUint32(n+1),f=5;break;case 27:if(t-n<9)Zt(8);{let h=Bt.getUint32(n+1);if(h<2097152)s=h*4294967296+Bt.getUint32(n+5);else s=Bt.getBigUint64(n+1)}f=9;break;default:vc(r)}if(i===0)return v=f,mc(s);else if(i===1){let h;if(typeof s==="bigint")h=BigInt(-1)-s;else h=-1-s;return v=f,mc(h)}else return BY(n,t,r,s,f)}case 3:return af(n,t);case 5:return bY(n,t);case 4:return $Y(n,t);case 2:return Zc(n,t);default:return GY(n,t)}}function gY(n,t){let i=(wn[n]&224)>>5;if((wn[n]&31)===31)switch(i){case 3:return FY(n,t);case 5:return HY(n,t);case 4:return WY(n,t);case 2:return YY(n,t)}}function NY(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 bY(n,t){let i=Zf(n,t);if(i<15)return lY(n,t,i);return SY(n,t,i)}function SY(n,t,i){let r=v;n+=r;let s=n,f=Object.create(null);for(let h=0;h<i;++h){let _=af(n,t);if(n+=v,(wn[n]&224)>>5===3)f[_]=af(n,t);else f[_]=Vi(n,t);n+=v}return v=r+(n-s),Object.setPrototypeOf(f,Object.prototype),f}function lY(n,t,i){let r=v;n+=r;let s=n,f={};for(let h=0;h<i;++h){let _=af(n,t);n+=v,f[_]=Vi(n,t),n+=v}return v=r+(n-s),f}function $Y(n,t){let i=Zf(n,t),r=v;n+=r;let s=n,f=Array(i);for(let h=0;h<i;++h)f[h]=Vi(n,t),n+=v;return v=r+(n-s),f}function af(n,t){let i=Zf(n,t),r=v;if(n+=r,t-n<i)Zt(i);if(v=r+i,i<24)return DY(n,i);if(ac)return wn.toString("utf-8",n,n+i);return kc.decode(wn.subarray(n,n+i))}var bT=Array(2048),Jc=new Uint16Array(2048),qf=0;function UY(){qf=qf+1&65535}function DY(n,t){let i=t;for(let h=0;h<t;++h)i=i*31+wn[n+h]|0;let r=i>>>0&2047,s=bT[r];if(s!==void 0){if(s.length===t){let h=!0;for(let _=0;_<t;++_)if(s.charCodeAt(_)!==wn[n+_]){h=!1;break}if(h)return Jc[r]=qf,s}}let f=ac?wn.toString("utf-8",n,n+t):kc.decode(wn.subarray(n,n+t));if(Jc[r]!==qf)bT[r]=f,Jc[r]=qf;return f}function Zc(n,t){let i=Zf(n,t),r=v;if(n+=r,t-n<i)Zt(i);let s=wn.subarray(n,n+i);return v=r+i,s}function BY(n,t,i,r,s){if(i===2||i===3){let f=Zf(n+s,t),h=BigInt(0),_=n+s+v;for(let o=_;o<_+f;++o)h=h<<BigInt(8)|BigInt(wn[o]);return v=s+v+f,i===3?-h-BigInt(1):h}else if(i===4){let f=Vi(n+s,t),[h,_]=f,o=_<0?-1:1,w="0".repeat(Math.abs(h)+1)+String(BigInt(o)*BigInt(_)),c,d=_<0?"-":"";if(c=h===0?w:w.slice(0,w.length+h)+"."+w.slice(h),c=c.replace(/^0+/g,""),c==="")c="0";if(c[0]===".")c="0"+c;return c=d+c,v=s+v,AY(c)}else{let f=Vi(n+s,t);return v=s+v,qc({tag:mc(r),value:f})}}function GY(n,t){let i=wn[n]&31;switch(i){case 21:case 20:return v=1,i===21;case 22:return v=1,null;case 23:return v=1,null;case 25:if(t-n<3)throw Error("incomplete float16 at end of buf.");return v=3,NY(wn[n+1],wn[n+2]);case 26:if(t-n<5)throw Error("incomplete float32 at end of buf.");return v=5,Bt.getFloat32(n+1);case 27:if(t-n<9)throw Error("incomplete float64 at end of buf.");return v=9,Bt.getFloat64(n+1);default:vc(i)}}function Zf(n,t){let i=wn[n]&31;if(i<24)return v=1,i;switch(i){case 24:if(t-n<2)Zt(1);return v=2,wn[n+1];case 25:if(t-n<3)Zt(2);return v=3,Bt.getUint16(n+1);case 26:if(t-n<5)Zt(4);return v=5,Bt.getUint32(n+1);case 27:if(t-n<9)Zt(8);return v=9,PY(Bt.getBigUint64(n+1));default:vc(i)}}function HY(n,t){n+=1;let i=n,r={};for(;n<t;){if(wn[n]===255)return v=n-i+2,r;let s=af(n,t);n+=v,r[s]=Vi(n,t),n+=v}throw Error("expected break marker.")}function WY(n,t){n+=1;let i=[];for(let r=n;n<t;){if(wn[n]===255)return v=n-r+2,i;i.push(Vi(n,t)),n+=v}throw Error("expected break marker.")}function FY(n,t){n+=1;let i=[];for(let r=n;n<t;){if(wn[n]===255){let o=$s(i.length);if(o.set(i,0),v=n-r+2,UT)return o.toString("utf-8",0,o.length);return kc.decode(o)}let s=(wn[n]&224)>>5,f=wn[n]&31;if(s!==3)DT(s);if(f===31)throw Error("nested indefinite string.");let h=Zc(n,t);n+=v;for(let o=0;o<h.length;++o)i.push(h[o])}throw Error("expected break marker.")}function YY(n,t){n+=1;let i=[];for(let r=n;n<t;){if(wn[n]===255){let o=$s(i.length);return o.set(i,0),v=n-r+2,o}let s=(wn[n]&224)>>5,f=wn[n]&31;if(s!==2)DT(s);if(f===31)throw Error("nested indefinite string.");let h=Zc(n,t);n+=v;for(let o=0;o<h.length;++o)i.push(h[o])}throw Error("expected break marker.")}function mc(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 PY(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 Zt(n){throw Error(`length ${n} greater than remaining buf len.`)}function vc(n){throw Error(`unexpected minor value ${n}.`)}function DT(n){throw Error(`unexpected major type ${n} in indefinite string.`)}var XY=typeof Buffer<"u",Ss=new Map,kf=0,zc=!1,CY=2048,K=$s(CY),Et=new DataView(K.buffer,K.byteOffset,K.byteLength),W=0;function JY(n){let t=[n];while(t.length){let i=t.pop();if(typeof i==="string"){let r=i.length;if(XY)if(ls(r*3+9),r>23)Qc(3,Buffer.byteLength(i)),W+=K.write(i,W);else mY(i);else{let s=r*3;ls(s+9);let f=W,_=new TextEncoder().encodeInto(i,K.subarray(W+9)).written,o;if(_<24)o=1;else if(_<256)o=2;else if(_<65536)o=3;else if(_<4294967296)o=5;else o=9;if(o<9)K.copyWithin(f+o,f+9,f+9+_);W=f,Ir(3,_),W+=_}continue}if(K.byteLength-W<9)ls(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)K[W++]=s<<5|f;else if(f<256)K[W++]=s<<5|24,K[W++]=f;else if(f<65536)K[W++]=s<<5|25,K[W++]=f>>8,K[W++]=f&255;else if(f<4294967296)K[W++]=s<<5|26,Et.setUint32(W,f),W+=4;else{K[W++]=s<<5|27;let h=f/4294967296|0,_=f-h*4294967296|0;Et.setUint32(W,h),Et.setUint32(W+4,_),W+=8}continue}K[W++]=251,Et.setFloat64(W,i),W+=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)Ir(s,h);else K[W++]=s<<5|27,Et.setBigUint64(W,f),W+=8}else{let h=f.toString(2),_=new Uint8Array(Math.ceil(h.length/8)),o=f,w=0;while(_.byteLength-++w>=0)_[_.byteLength-w]=Number(o&BigInt(255)),o>>=BigInt(8);ls(_.byteLength*2+16),K[W++]=r?194:195,Qc(2,_.byteLength),K.set(_,W),W+=_.byteLength}continue}else if(i===null){K[W++]=246;continue}else if(typeof i==="boolean"){K[W++]=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)){Ir(4,i.length),ls(i.length*9+64);for(let r=i.length-1;r>=0;--r)t.push(i[r]);continue}else if(typeof i.byteLength==="number"){ls(i.length*2+9),Ir(2,i.length),K.set(i,W),W+=i.byteLength;continue}else if(typeof i==="object"){if(i instanceof lT){let f=i.string.indexOf("."),h=f===-1?0:f-i.string.length+1,_=BigInt(i.string.replace(".",""));K[W++]=196,Ir(4,2),t.push(_),t.push(h);continue}if(i[jc])if("tag"in i&&"value"in i){t.push(i.value),Qc(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;Ir(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 QY(){kf=kf+1&65535,zc=!1}function ST(){let n=$s(W);return n.set(K.subarray(0,W),0),W=0,n}function Kc(n){let t=K;if(K=$s(n),t)if(t.copy)t.copy(K,0,0,t.byteLength);else K.set(t,0);Et=new DataView(K.buffer,K.byteOffset,K.byteLength)}function mY(n){let t=Ss.get(n);if(t!==void 0){K.set(t.bytes,W),W+=t.bytes.length,t.epoch=kf;return}let i=W,r=Buffer.byteLength(n);Ir(3,r),W+=K.write(n,W);let s=Uint8Array.prototype.slice.call(K,i,W);if(Ss.size>=2048){if(zc)return;let f=0;for(let[h,_]of Ss){if(f>=1024)break;if(_.epoch!==kf)Ss.delete(h),f++}if(f===0){zc=!0;return}}if(Ss.size<2048)Ss.set(n,{epoch:kf,bytes:s})}function ls(n){if(K.byteLength-W<n)if(W<16000000)Kc(Math.max(K.byteLength*4,K.byteLength+n));else Kc(K.byteLength+n+16000000)}function Qc(n,t){if(t<24)K[W++]=n<<5|t;else if(t<256)K[W++]=n<<5|24,K[W++]=t;else if(t<65536)K[W++]=n<<5|25,Et.setUint16(W,t),W+=2;else if(t<4294967296)K[W++]=n<<5|26,Et.setUint32(W,t),W+=4;else K[W++]=n<<5|27,Et.setBigUint64(W,typeof t==="bigint"?t:BigInt(t)),W+=8}function Ir(n,t){if(t<24)K[W++]=n<<5|t;else if(t<256)K[W++]=n<<5|24,K[W++]=t;else if(t<65536)K[W++]=n<<5|25,K[W++]=t>>8,K[W++]=t&255;else if(t<4294967296)K[W++]=n<<5|26,Et.setUint32(W,t),W+=4;else{K[W++]=n<<5|27;let i=t/4294967296|0,r=t-i*4294967296|0;Et.setUint32(W,i),Et.setUint32(W+4,r),W+=8}}var Qh={deserialize(n){return UY(),IY(n),Vi(0,n.length)},serialize(n){QY();try{return JY(n),ST()}catch(t){throw ST(),t}},resizeEncodingBuffer(n){Kc(n)}},BT=(n,t)=>{return TY(n,t).then(async(i)=>{if(i.length)try{return Qh.deserialize(i)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:t.utf8Encoder(i)}),r}return{}})},Jh=(n)=>{return qc({tag:1,value:n.getTime()/1000})},zY=async(n,t)=>{let i=await BT(n,t);return i.message=i.message??i.Message,i},GT=(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])},KY=(n)=>{if(String(n.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+n.statusCode)},VY=async(n,t,i,r,s)=>{let f=await n.endpoint(),{hostname:h,protocol:_="https",port:o,path:w}=f,c={protocol:_,hostname:h,port:o,method:"POST",path:w.endsWith("/")?w.slice(0,-1)+i:w+i,headers:{...t}};if(r!==void 0)c.hostname=r;if(f.headers)for(let d in f.headers)c.headers[d]=f.headers[d];if(s!==void 0){c.body=s;try{c.headers["content-length"]=String(RY(s))}catch(d){}}return new EY(c)};class pc extends Vc{createSerializer(){let n=new nd;return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new td;return n.setSerdeContext(this.serdeContext),n}}class nd extends Vc{value;write(n,t){this.value=this.serialize(n,t)}serialize(n,t){let i=xc.of(n);if(t==null){if(i.isIdempotencyToken())return MY();return t}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??$T)(t);return t}if(i.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return Jh(new Date(Number(t)/1000|0));return Jh(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 o of r){let w=this.serialize(i.getValueSchema(),o);if(w!=null||f)h[_++]=w}return h}if(r instanceof Date)return Jh(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 o=this.serialize(_,r[h]);if(o!=null)s[h]=o}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=Qh.serialize(this.value);return this.value=void 0,n}}class td extends Vc{read(n,t){let i=Qh.deserialize(t);return this.readValue(n,i)}readValue(n,t){let i=xc.of(n);if(i.isTimestampSchema()){if(typeof t==="number")return gT(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return gT(t.value)}}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??$T)(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 lT)return t;return r}else return t}}class HT extends eY{codec=new pc;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()}),OY(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}=LY(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=GT(i,r)??"Unknown",h={$metadata:s,$fault:i.statusCode<=500?"client":"server"},_=this.options.defaultNamespace;if(f.includes("#"))[_]=f.split("#");let o=this.compositeErrorRegistry,w=NT.for(_);o.copyFrom(w);let c;try{c=o.getSchema(f)}catch(E){if(r.Message)r.message=r.Message;let T=NT.for("smithy.ts.sdk.synthetic."+_);o.copyFrom(T);let O=o.getBaseException();if(O){let e=o.getErrorCtor(O);throw Object.assign(new e({name:f}),h,r)}throw Object.assign(Error(f),h,r)}let d=xc.of(c),u=o.getErrorCtor(c),y=r.message??r.Message??"Unknown",R=new u({}),M={};for(let[E,T]of d.structIterator())M[E]=this.deserializer.readValue(T,r[E]);throw Object.assign(R,h,{$fault:d.getMergedTraits().error,message:y},M)}getDefaultContentType(){return"application/cbor"}}xY.CborCodec=pc;xY.CborShapeDeserializer=td;xY.CborShapeSerializer=nd;xY.SmithyRpcV2CborProtocol=HT;xY.buildHttpRpcRequest=VY;xY.cbor=Qh;xY.checkCborResponse=KY;xY.dateToTag=Jh;xY.loadSmithyRpcV2CborErrorCode=GT;xY.parseCborBody=BT;xY.parseCborErrorBody=zY;xY.tag=qc;xY.tagSymbol=jc});var FT=rn((y9)=>{var _9=/[&<>"]/g,h9={"&":"&","<":"<",">":">",'"':"""};function o9(n){return n.replace(_9,(t)=>h9[t])}var w9=/[&"'<>\r\n\u0085\u2028]/g,c9={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function d9(n){return n.replace(w9,(t)=>c9[t])}class id{value;constructor(n){this.value=n}toString(){return d9(""+this.value)}}class vf{name;children;attributes={};static of(n,t,i){let r=new vf(n);if(t!==void 0)r.addChildNode(new id(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=vf.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 vf(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}="${o9(""+s)}"`}return t+=!n?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function u9(n){return new rd(n).parse()}class rd{x;i=0;z;constructor(n){this.x=n,this.x=n.replace(/\r\n?/g,`
|
|
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,_)=>{let o=void 0,h=-1,e=-1,c=-1,d=-1,u=-1,w=()=>{Qn.clearTimeout(h),Qn.clearTimeout(e),Qn.clearTimeout(c),Qn.clearTimeout(d),Qn.clearTimeout(u)},A=async(I)=>{await o,w(),f(I)},R=async(I)=>{await o,w(),_(I)};if(t?.aborted){let I=q_(t);R(I);return}let M=n.headers,E=M?(M.Expect??M.expect)==="100-continue":!1,T=s?r.httpsAgent:r.httpAgent;if(E&&!this.externalAgent)T=new(s?V_.Agent:j_)({keepAlive:!1,maxSockets:1/0});h=Qn.setTimeout(()=>{this.socketWarningTimestamp=k_.checkSocketUsage(T,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let l=n.query?m1(n.query):"",g=void 0;if(n.username!=null||n.password!=null){let I=n.username??"",L=n.password??"";g=`${I}:${L}`}let O=n.path;if(l)O+=`?${l}`;if(n.fragment)O+=`#${n.fragment}`;let N=n.hostname??"";if(N[0]==="["&&N.endsWith("]"))N=n.hostname.slice(1,-1);else N=n.hostname;let F={headers:n.headers,host:N,method:n.method,path:O,port:n.port,agent:T,auth:g},S=(s?V_.request:B1)(F,(I)=>{let L=new H1({statusCode:I.statusCode||-1,reason:I.statusMessage,headers:W1(I.headers),body:I});A({response:L})});if(S.on("error",(I)=>{if(BC.includes(I.code))R(Object.assign(I,{name:"TimeoutError"}));else R(I)}),t){let I=()=>{S.destroy();let L=q_(t);R(L)};if(typeof t.addEventListener==="function"){let L=t;L.addEventListener("abort",I,{once:!0}),S.once("close",()=>L.removeEventListener("abort",I))}else t.onabort=I}let W=i??r.requestTimeout;e=GC(S,R,r.connectionTimeout),c=mC(S,R,W,r.throwOnRequestTimeout,r.logger??console),d=FC(S,R,r.socketTimeout);let C=F.agent;if(typeof C==="object"&&"keepAlive"in C)u=WC(S,{keepAlive:C.keepAlive,keepAliveMsecs:C.keepAliveMsecs});o=F1(S,n,W,this.externalAgent).catch((I)=>{return w(),_(I)})})}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:_,throwOnRequestTimeout:o,logger:h}=n||{},e=!0,c=50;return{connectionTimeout:i,requestTimeout:t,socketTimeout:r,socketAcquisitionWarningTimeout:s,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let d=un("http"),{Agent:u,request:w}=d.default??d;if(B1=w,j_=u,f instanceof j_||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new j_({keepAlive:!0,maxSockets:50,...f})},httpsAgent:(()=>{if(_ instanceof V_.Agent||typeof _?.destroy==="function")return this.externalAgent=!0,_;return new V_.Agent({keepAlive:!0,maxSockets:50,..._})})(),logger:h}}}var YC=new Uint16Array(1);class Z_{id=YC[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 C1{sessions=[];maxConcurrency=0;constructor(n){this.sessions=(n??[]).map((t)=>new Z_(t))}poll(){let n=!1;for(let t of this.sessions){if(t.deref().destroyed){n=!0;continue}if(!this.maxConcurrency||t.useCount()<this.maxConcurrency)return t}if(n){for(let t of this.sessions)if(t.deref().destroyed)this.remove(t)}}offerLast(n){this.sessions.push(n)}remove(n){let t=this.sessions.indexOf(n);if(t>-1)this.sessions.splice(t,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(n){this.maxConcurrency=n}destroy(n){this.remove(n),n.destroy()}}class P1{config;connectOptions;connectionPools=new Map;constructor(n){if(this.config=n,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(n,t){let i=this.getUrlString(n),r=this.getPool(i);if(!this.config.disableConcurrency&&!t.isEventStream){let h=r.poll();if(h)return h.retain(),h}let s=new Z_(this.connect(i)),f=s.deref();if(this.config.maxConcurrency)f.settings({maxConcurrentStreams:this.config.maxConcurrency},(h)=>{if(h)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+n.destination.toString())});let _=()=>{this.removeFromPoolAndClose(i,s)},o=()=>{this.removeFromPoolAndCheckedDestroy(i,s)};if(f.on("goaway",_),f.on("error",o),f.on("frameError",o),f.on("close",o),t.requestTimeout)f.setTimeout(t.requestTimeout,o);return r.offerLast(s),s.retain(),s}release(n,t){t.free()}createIsolatedSession(n,t){let i=this.getUrlString(n),r=new Z_(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 C1;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?Zc.connect(n):Zc.connect(n,this.connectOptions)}}var{constants:G1}=Zc;class vc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new P1({});static create(n){if(typeof n?.handle==="function")return n;return new vc(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:h,maxConcurrentStreams:e,nodeHttp2ConnectOptions:c}=this.config;if(this.connectionManager.setDisableConcurrentStreams(h??!1),e)this.connectionManager.setMaxConcurrentStreams(e);if(c)this.connectionManager.setNodeHttp2ConnectOptions(c)}let{requestTimeout:s,disableConcurrentStreams:f}=this.config,_=f||r,o=i??s;return new Promise((h,e)=>{let c=!1,d=void 0,u=async(L)=>{await d,h(L)},w=async(L)=>{await d,e(L)};if(t?.aborted){c=!0;let L=q_(t);w(L);return}let{hostname:A,method:R,port:M,protocol:E,query:T}=n,l="";if(n.username!=null||n.password!=null){let L=n.username??"",m=n.password??"";l=`${L}:${m}@`}let g=`${E}//${l}${A}${M?`:${M}`:""}`,O={destination:new URL(g)},N={requestTimeout:this.config?.sessionTimeout,isEventStream:r},F=_?this.connectionManager.createIsolatedSession(O,N):this.connectionManager.lease(O,N),K=F.deref(),S=(L)=>{if(_)F.destroy();c=!0,w(L)},W=T?m1(T):"",C=n.path;if(W)C+=`?${W}`;if(n.fragment)C+=`#${n.fragment}`;let I=K.request({...n.headers,[G1.HTTP2_HEADER_PATH]:C,[G1.HTTP2_HEADER_METHOD]:R});if(o)I.setTimeout(o,()=>{I.close();let L=Error(`Stream timed out because of no activity for ${o} ms`);L.name="TimeoutError",S(L)});if(t){let L=()=>{I.close();let m=q_(t);S(m)};if(typeof t.addEventListener==="function"){let m=t;m.addEventListener("abort",L,{once:!0}),I.once("close",()=>m.removeEventListener("abort",L))}else t.onabort=L}I.on("frameError",(L,m,q)=>{S(Error(`Frame type id ${L} in stream id ${q} has failed with code ${m}.`))}),I.on("error",S),I.on("aborted",()=>{S(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${I.rstCode}.`))}),I.on("response",(L)=>{let m=new H1({statusCode:L[":status"]??-1,headers:W1(L),body:I});if(c=!0,u({response:m}),_)K.close()}),I.on("close",()=>{if(_)F.destroy();else this.connectionManager.release(O,F);if(!c)S(Error("Unexpected error: http2 request did not get a response"))}),d=F1(I,n,o)})}updateHttpClientConfig(n,t){this.config=void 0,this.configProvider=this.configProvider.then((i)=>{return{...i,[n]:t}})}httpHandlerConfigs(){return this.config??{}}}XC.DEFAULT_REQUEST_TIMEOUT=PC;XC.NodeHttp2Handler=vc;XC.NodeHttpHandler=k_});var k1=sn((LP)=>{var{nv:KC,NumericValue:a1,calculateBodyLength:xC,_parseEpochTimestamp:Y1,fromBase64:z1,generateIdempotencyToken:VC}=tt(),{HttpRequest:jC,collectBody:qC,SerdeContext:sd,RpcProtocol:kC}=it(),{NormalizedSchema:fd,deref:ZC,TypeRegistry:X1}=Ji(),{getSmithyContext:vC}=qt();function Cs(n){return typeof Buffer<"u"?Buffer.alloc(n):new Uint8Array(n)}var od=Symbol("@smithy/core/cbor::tagSymbol");function _d(n){return n[od]=!0,n}var K1=typeof Buffer<"u",hd=new TextDecoder,en=Cs(0),ed=!1,Wt=new DataView(en.buffer,en.byteOffset,en.byteLength),v=0;function pC(n){en=n,ed=K1&&en instanceof Buffer,Wt=new DataView(en.buffer,en.byteOffset,en.byteLength)}function ki(n,t){if(n>=t)throw Error("unexpected end of (decode) payload.");let i=(en[n]&224)>>5,r=en[n]&31;if(r===31&&2<=i&&i<=5)return nP(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)ti(1);s=en[n+1],f=2;break;case 25:if(t-n<3)ti(2);s=Wt.getUint16(n+1),f=3;break;case 26:if(t-n<5)ti(4);s=Wt.getUint32(n+1),f=5;break;case 27:if(t-n<9)ti(8);{let _=Wt.getUint32(n+1);if(_<2097152)s=_*4294967296+Wt.getUint32(n+5);else s=Wt.getBigUint64(n+1)}f=9;break;default:dd(r)}if(i===0)return v=f,td(s);else if(i===1){let _;if(typeof s==="bigint")_=BigInt(-1)-s;else _=-1-s;return v=f,td(_)}else return hP(n,t,r,s,f)}case 3:return oo(n,t);case 5:return iP(n,t);case 4:return fP(n,t);case 2:return cd(n,t);default:return eP(n,t)}}function nP(n,t){let i=(en[n]&224)>>5;if((en[n]&31)===31)switch(i){case 3:return uP(n,t);case 5:return cP(n,t);case 4:return dP(n,t);case 2:return wP(n,t)}}function tP(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 iP(n,t){let i=_o(n,t);if(i<15)return sP(n,t,i);return rP(n,t,i)}function rP(n,t,i){let r=v;n+=r;let s=n,f=Object.create(null);for(let _=0;_<i;++_){let o=oo(n,t);if(n+=v,(en[n]&224)>>5===3)f[o]=oo(n,t);else f[o]=ki(n,t);n+=v}return v=r+(n-s),Object.setPrototypeOf(f,Object.prototype),f}function sP(n,t,i){let r=v;n+=r;let s=n,f={};for(let _=0;_<i;++_){let o=oo(n,t);n+=v,f[o]=ki(n,t),n+=v}return v=r+(n-s),f}function fP(n,t){let i=_o(n,t),r=v;n+=r;let s=n,f=Array(i);for(let _=0;_<i;++_)f[_]=ki(n,t),n+=v;return v=r+(n-s),f}function oo(n,t){let i=_o(n,t),r=v;if(n+=r,t-n<i)ti(i);if(v=r+i,i<24)return _P(n,i);if(ed)return en.toString("utf-8",n,n+i);return hd.decode(en.subarray(n,n+i))}var J1=Array(2048),pc=new Uint16Array(2048),so=0;function oP(){so=so+1&65535}function _P(n,t){let i=t;for(let _=0;_<t;++_)i=i*31+en[n+_]|0;let r=i>>>0&2047,s=J1[r];if(s!==void 0){if(s.length===t){let _=!0;for(let o=0;o<t;++o)if(s.charCodeAt(o)!==en[n+o]){_=!1;break}if(_)return pc[r]=so,s}}let f=ed?en.toString("utf-8",n,n+t):hd.decode(en.subarray(n,n+t));if(pc[r]!==so)J1[r]=f,pc[r]=so;return f}function cd(n,t){let i=_o(n,t),r=v;if(n+=r,t-n<i)ti(i);let s=en.subarray(n,n+i);return v=r+i,s}function hP(n,t,i,r,s){if(i===2||i===3){let f=_o(n+s,t),_=BigInt(0),o=n+s+v;for(let h=o;h<o+f;++h)_=_<<BigInt(8)|BigInt(en[h]);return v=s+v+f,i===3?-_-BigInt(1):_}else if(i===4){let f=ki(n+s,t),[_,o]=f,h=o<0?-1:1,e="0".repeat(Math.abs(_)+1)+String(BigInt(h)*BigInt(o)),c,d=o<0?"-":"";if(c=_===0?e:e.slice(0,e.length+_)+"."+e.slice(_),c=c.replace(/^0+/g,""),c==="")c="0";if(c[0]===".")c="0"+c;return c=d+c,v=s+v,KC(c)}else{let f=ki(n+s,t);return v=s+v,_d({tag:td(r),value:f})}}function eP(n,t){let i=en[n]&31;switch(i){case 21:case 20:return v=1,i===21;case 22:return v=1,null;case 23:return v=1,null;case 25:if(t-n<3)throw Error("incomplete float16 at end of buf.");return v=3,tP(en[n+1],en[n+2]);case 26:if(t-n<5)throw Error("incomplete float32 at end of buf.");return v=5,Wt.getFloat32(n+1);case 27:if(t-n<9)throw Error("incomplete float64 at end of buf.");return v=9,Wt.getFloat64(n+1);default:dd(i)}}function _o(n,t){let i=en[n]&31;if(i<24)return v=1,i;switch(i){case 24:if(t-n<2)ti(1);return v=2,en[n+1];case 25:if(t-n<3)ti(2);return v=3,Wt.getUint16(n+1);case 26:if(t-n<5)ti(4);return v=5,Wt.getUint32(n+1);case 27:if(t-n<9)ti(8);return v=9,yP(Wt.getBigUint64(n+1));default:dd(i)}}function cP(n,t){n+=1;let i=n,r={};for(;n<t;){if(en[n]===255)return v=n-i+2,r;let s=oo(n,t);n+=v,r[s]=ki(n,t),n+=v}throw Error("expected break marker.")}function dP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(en[n]===255)return v=n-r+2,i;i.push(ki(n,t)),n+=v}throw Error("expected break marker.")}function uP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(en[n]===255){let h=Cs(i.length);if(h.set(i,0),v=n-r+2,K1)return h.toString("utf-8",0,h.length);return hd.decode(h)}let s=(en[n]&224)>>5,f=en[n]&31;if(s!==3)x1(s);if(f===31)throw Error("nested indefinite string.");let _=cd(n,t);n+=v;for(let h=0;h<_.length;++h)i.push(_[h])}throw Error("expected break marker.")}function wP(n,t){n+=1;let i=[];for(let r=n;n<t;){if(en[n]===255){let h=Cs(i.length);return h.set(i,0),v=n-r+2,h}let s=(en[n]&224)>>5,f=en[n]&31;if(s!==2)x1(s);if(f===31)throw Error("nested indefinite string.");let _=cd(n,t);n+=v;for(let h=0;h<_.length;++h)i.push(_[h])}throw Error("expected break marker.")}function td(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 yP(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 ti(n){throw Error(`length ${n} greater than remaining buf len.`)}function dd(n){throw Error(`unexpected minor value ${n}.`)}function x1(n){throw Error(`unexpected major type ${n} in indefinite string.`)}var AP=typeof Buffer<"u",Ws=new Map,fo=0,id=!1,RP=2048,z=Cs(RP),gt=new DataView(z.buffer,z.byteOffset,z.byteLength),H=0;function MP(n){let t=[n];while(t.length){let i=t.pop();if(typeof i==="string"){let r=i.length;if(AP)if(Fs(r*3+9),r>23)nd(3,Buffer.byteLength(i)),H+=z.write(i,H);else lP(i);else{let s=r*3;Fs(s+9);let f=H,o=new TextEncoder().encodeInto(i,z.subarray(H+9)).written,h;if(o<24)h=1;else if(o<256)h=2;else if(o<65536)h=3;else if(o<4294967296)h=5;else h=9;if(h<9)z.copyWithin(f+h,f+9,f+9+o);H=f,br(3,o),H+=o}continue}if(z.byteLength-H<9)Fs(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)z[H++]=s<<5|f;else if(f<256)z[H++]=s<<5|24,z[H++]=f;else if(f<65536)z[H++]=s<<5|25,z[H++]=f>>8,z[H++]=f&255;else if(f<4294967296)z[H++]=s<<5|26,gt.setUint32(H,f),H+=4;else{z[H++]=s<<5|27;let _=f/4294967296|0,o=f-_*4294967296|0;gt.setUint32(H,_),gt.setUint32(H+4,o),H+=8}continue}z[H++]=251,gt.setFloat64(H,i),H+=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 _=Number(f);if(_<4294967296)br(s,_);else z[H++]=s<<5|27,gt.setBigUint64(H,f),H+=8}else{let _=f.toString(2),o=new Uint8Array(Math.ceil(_.length/8)),h=f,e=0;while(o.byteLength-++e>=0)o[o.byteLength-e]=Number(h&BigInt(255)),h>>=BigInt(8);Fs(o.byteLength*2+16),z[H++]=r?194:195,nd(2,o.byteLength),z.set(o,H),H+=o.byteLength}continue}else if(i===null){z[H++]=246;continue}else if(typeof i==="boolean"){z[H++]=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)){br(4,i.length),Fs(i.length*9+64);for(let r=i.length-1;r>=0;--r)t.push(i[r]);continue}else if(typeof i.byteLength==="number"){Fs(i.length*2+9),br(2,i.length),z.set(i,H),H+=i.byteLength;continue}else if(typeof i==="object"){if(i instanceof a1){let f=i.string.indexOf("."),_=f===-1?0:f-i.string.length+1,o=BigInt(i.string.replace(".",""));z[H++]=196,br(4,2),t.push(o),t.push(_);continue}if(i[od])if("tag"in i&&"value"in i){t.push(i.value),nd(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;br(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 EP(){fo=fo+1&65535,id=!1}function Q1(){let n=Cs(H);return n.set(z.subarray(0,H),0),H=0,n}function rd(n){let t=z;if(z=Cs(n),t)if(t.copy)t.copy(z,0,0,t.byteLength);else z.set(t,0);gt=new DataView(z.buffer,z.byteOffset,z.byteLength)}function lP(n){let t=Ws.get(n);if(t!==void 0){z.set(t.bytes,H),H+=t.bytes.length,t.epoch=fo;return}let i=H,r=Buffer.byteLength(n);br(3,r),H+=z.write(n,H);let s=Uint8Array.prototype.slice.call(z,i,H);if(Ws.size>=2048){if(id)return;let f=0;for(let[_,o]of Ws){if(f>=1024)break;if(o.epoch!==fo)Ws.delete(_),f++}if(f===0){id=!0;return}}if(Ws.size<2048)Ws.set(n,{epoch:fo,bytes:s})}function Fs(n){if(z.byteLength-H<n)if(H<16000000)rd(Math.max(z.byteLength*4,z.byteLength+n));else rd(z.byteLength+n+16000000)}function nd(n,t){if(t<24)z[H++]=n<<5|t;else if(t<256)z[H++]=n<<5|24,z[H++]=t;else if(t<65536)z[H++]=n<<5|25,gt.setUint16(H,t),H+=2;else if(t<4294967296)z[H++]=n<<5|26,gt.setUint32(H,t),H+=4;else z[H++]=n<<5|27,gt.setBigUint64(H,typeof t==="bigint"?t:BigInt(t)),H+=8}function br(n,t){if(t<24)z[H++]=n<<5|t;else if(t<256)z[H++]=n<<5|24,z[H++]=t;else if(t<65536)z[H++]=n<<5|25,z[H++]=t>>8,z[H++]=t&255;else if(t<4294967296)z[H++]=n<<5|26,gt.setUint32(H,t),H+=4;else{z[H++]=n<<5|27;let i=t/4294967296|0,r=t-i*4294967296|0;gt.setUint32(H,i),gt.setUint32(H+4,r),H+=8}}var nh={deserialize(n){return oP(),pC(n),ki(0,n.length)},serialize(n){EP();try{return MP(n),Q1()}catch(t){throw Q1(),t}},resizeEncodingBuffer(n){rd(n)}},V1=(n,t)=>{return qC(n,t).then(async(i)=>{if(i.length)try{return nh.deserialize(i)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:t.utf8Encoder(i)}),r}return{}})},p_=(n)=>{return _d({tag:1,value:n.getTime()/1000})},TP=async(n,t)=>{let i=await V1(n,t);return i.message=i.message??i.Message,i},j1=(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])},gP=(n)=>{if(String(n.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+n.statusCode)},OP=async(n,t,i,r,s)=>{let f=await n.endpoint(),{hostname:_,protocol:o="https",port:h,path:e}=f,c={protocol:o,hostname:_,port:h,method:"POST",path:e.endsWith("/")?e.slice(0,-1)+i:e+i,headers:{...t}};if(r!==void 0)c.hostname=r;if(f.headers)for(let d in f.headers)c.headers[d]=f.headers[d];if(s!==void 0){c.body=s;try{c.headers["content-length"]=String(xC(s))}catch(d){}}return new jC(c)};class ud extends sd{createSerializer(){let n=new wd;return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new yd;return n.setSerdeContext(this.serdeContext),n}}class wd extends sd{value;write(n,t){this.value=this.serialize(n,t)}serialize(n,t){let i=fd.of(n);if(t==null){if(i.isIdempotencyToken())return VC();return t}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(i.isTimestampSchema()){if(typeof t==="number"||typeof t==="bigint")return p_(new Date(Number(t)/1000|0));return p_(t)}if(typeof t==="function"||typeof t==="object"){let r=t;if(i.isListSchema()&&Array.isArray(r)){let f=!!i.getMergedTraits().sparse,_=[],o=0;for(let h of r){let e=this.serialize(i.getValueSchema(),h);if(e!=null||f)_[o++]=e}return _}if(r instanceof Date)return p_(r);let s={};if(i.isMapSchema()){let f=!!i.getMergedTraits().sparse;for(let _ in r){let o=this.serialize(i.getValueSchema(),r[_]);if(o!=null||f)s[_]=o}}else if(i.isStructSchema()){for(let[_,o]of i.structIterator()){let h=this.serialize(o,r[_]);if(h!=null)s[_]=h}if(i.isUnionSchema()&&Array.isArray(r.$unknown)){let[_,o]=r.$unknown;s[_]=o}else if(typeof r.__type==="string"){for(let _ in r)if(!(_ in s))s[_]=this.serialize(15,r[_])}}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=nh.serialize(this.value);return this.value=void 0,n}}class yd extends sd{read(n,t){let i=nh.deserialize(t);return this.readValue(n,i)}readValue(n,t){let i=fd.of(n);if(i.isTimestampSchema()){if(typeof t==="number")return Y1(t);if(typeof t==="object"){if(t.tag===1&&"value"in t)return Y1(t.value)}}if(i.isBlobSchema()){if(typeof t==="string")return(this.serdeContext?.base64Decoder??z1)(t);return t}if(typeof t>"u"||typeof t==="boolean"||typeof t==="number"||typeof t==="string"||typeof t==="bigint"||typeof t==="symbol")return t;else if(typeof t==="object"){if(t===null)return null;if("byteLength"in t)return t;if(t instanceof Date)return t;if(i.isDocumentSchema())return t;if(i.isListSchema()){let s=[],f=i.getValueSchema();for(let _ of t){let o=this.readValue(f,_);s.push(o)}return s}let r={};if(i.isMapSchema()){let s=i.getValueSchema();for(let f in t){let _=this.readValue(s,t[f]);r[f]=_}}else if(i.isStructSchema()){let s=i.isUnionSchema(),f;if(s){f=new Set;for(let _ in t)if(_!=="__type")f.add(_)}for(let[_,o]of i.structIterator()){if(s)f.delete(_);if(t[_]!=null)r[_]=this.readValue(o,t[_])}if(s&&f?.size===1){let _=!0;for(let o in r){_=!1;break}if(_){let o=f.values().next().value;r.$unknown=[o,t[o]]}}else if(typeof t.__type==="string"){for(let _ in t)if(!(_ in r))r[_]=t[_]}}else if(t instanceof a1)return t;return r}else return t}}class q1 extends kC{codec=new ud;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()}),ZC(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(o){}}let{service:s,operation:f}=vC(i),_=`/service/${s}/operation/${f}`;if(r.path.endsWith("/"))r.path+=_.slice(1);else r.path+=_;return r}async deserializeResponse(n,t,i){return super.deserializeResponse(n,t,i)}async handleError(n,t,i,r,s){let f=j1(i,r)??"Unknown",_={$metadata:s,$fault:i.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(f.includes("#"))[o]=f.split("#");let h=this.compositeErrorRegistry,e=X1.for(o);h.copyFrom(e);let c;try{c=h.getSchema(f)}catch(M){if(r.Message)r.message=r.Message;let E=X1.for("smithy.ts.sdk.synthetic."+o);h.copyFrom(E);let T=h.getBaseException();if(T){let l=h.getErrorCtor(T);throw Object.assign(new l({name:f}),_,r)}throw Object.assign(Error(f),_,r)}let d=fd.of(c),u=h.getErrorCtor(c),w=r.message??r.Message??"Unknown",A=new u({}),R={};for(let[M,E]of d.structIterator())R[M]=this.deserializer.readValue(E,r[M]);throw Object.assign(A,_,{$fault:d.getMergedTraits().error,message:w},R)}getDefaultContentType(){return"application/cbor"}}LP.CborCodec=ud;LP.CborShapeDeserializer=yd;LP.CborShapeSerializer=wd;LP.SmithyRpcV2CborProtocol=q1;LP.buildHttpRpcRequest=OP;LP.cbor=nh;LP.checkCborResponse=gP;LP.dateToTag=p_;LP.loadSmithyRpcV2CborErrorCode=j1;LP.parseCborBody=V1;LP.parseCborErrorBody=TP;LP.tag=_d;LP.tagSymbol=od});var Z1=sn((zP)=>{var CP=/[&<>"]/g,PP={"&":"&","<":"<",">":">",'"':"""};function YP(n){return n.replace(CP,(t)=>PP[t])}var XP=/[&"'<>\r\n\u0085\u2028]/g,JP={"&":"&",'"':""","'":"'","<":"<",">":">","\r":"
","\n":"
","\x85":"…","\u2028":"
"};function QP(n){return n.replace(XP,(t)=>JP[t])}class Ad{value;constructor(n){this.value=n}toString(){return QP(""+this.value)}}class ho{name;children;attributes={};static of(n,t,i){let r=new ho(n);if(t!==void 0)r.addChildNode(new Ad(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=ho.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 ho(i);s.map((_)=>{f.c(_)}),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}="${YP(""+s)}"`}return t+=!n?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function aP(n){return new Rd(n).parse()}class Rd{x;i=0;z;constructor(n){this.x=n,this.x=n.replace(/\r\n?/g,`
|
|
45
45
|
`),this.z=this.x.length}parse(){let n=this,{z:t}=n;while(n.i<t){if(n.trim(),n.i>=t)break;if(n.isNext("<?"))n.readTo("?>"),n.trim();else if(n.isNext("<!--"))n.readTo("-->"),n.trim();else if(n.isNext("<!DOCTYPE",!1))n.skipDoctype(),n.trim();else if(n.x[n.i]==="<"){let i=n.parseTag();return{[i.tag]:i.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(n,t=!0){let i=this;if(t)return i.x.startsWith(n,i.i);return i.x.toLowerCase().startsWith(n.toLowerCase(),i.i)}readTo(n){let t=this,i=t.x.indexOf(n,t.i);if(i===-1)throw Error(`@aws-sdk XML parse error: expected "${n}" not found.`);let r=t.x.slice(t.i,i);return t.i=i+n.length,r}trim(){let n=this;while(n.i<n.z&&` \r
|
|
46
46
|
`.includes(n.x[n.i]))++n.i}readAttrValue(){let n=this,t=n.x[n.i];++n.i;let i="";while(n.i<n.z&&n.x[n.i]!==t)i+=n.x[n.i++];return++n.i,n.decodeEntities(i)}parseTag(){let n=this;++n.i;let t="";while(n.i<n.z&&!` \r
|
|
47
|
-
>/`.includes(n.x[n.i]))t+=n.x[n.i++];let i=!1,r=Object.create(null);while(n.i<n.z){if(n.trim(),">/".includes(n.x[n.i]))break;let
|
|
48
|
-
>/?`.includes(n.x[n.i]))
|
|
49
|
-
`))return{tag:t,value:""};return{tag:t,value:
|
|
50
|
-
`))continue;o["#text"]="#text"in o?o["#text"]+w:w}for(let w of f)if(w.tag in o)if(Array.isArray(o[w.tag]))o[w.tag].push(w.value);else o[w.tag]=[o[w.tag],w.value];else o[w.tag]=w.value;for(let[w,c]of Object.entries(r))o[w]=c;return Object.setPrototypeOf(o,Object.prototype),{tag:t,value:o}}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 rd.ENTITIES[s]??""})}}y9.XmlNode=vf;y9.XmlText=id;y9.parseXML=u9});var Rd=rn((B9)=>{var{SmithyRpcV2CborProtocol:E9,loadSmithyRpcV2CborErrorCode:T9}=WT(),{TypeRegistry:YT,NormalizedSchema:Bn,deref:mT}=Yi(),{decorateServiceException:PT,getValueFromTextNode:zT}=yi(),{collectBody:fd,determineTimestampFormat:Kh,RpcProtocol:KT,HttpBindingProtocol:VT,HttpInterceptingShapeSerializer:xT,HttpInterceptingShapeDeserializer:jT,FromStringShapeDeserializer:e9,extendedEncodeURIComponent:XT}=nt(),{NumericValue:vt,toUtf8:qT,fromBase64:kT,LazyJsonString:aT,parseEpochTimestamp:O9,parseRfc7231DateTime:L9,parseRfc3339DateTimeWithOffset:I9,toBase64:mh,dateToUtcString:zh,generateIdempotencyToken:_d,expectUnion:g9}=pn(),{parseXML:ZT,XmlNode:Gt,XmlText:CT}=FT();class Us{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:o,httpLabel:w,httpPrefixHeaders:c}=f.getMergedTraits();return!h&&!_&&!o&&!w&&c===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(o){r.message=r.message??r.Message??"UnknownError";let w=this.errorRegistry,c=w.getBaseException();if(c){let y=w.getErrorCtor(c)??Error;throw this.decorateServiceException(Object.assign(new y({name:h}),_),r)}let d=r,u=d?.message??d?.Message??d?.Error?.Message??d?.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=YT.for(r),f=YT.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=PT(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 PT(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 o=f[_];h[o==="message"?"Message":o]=n[o]}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)=>Bn.of(r).getMergedTraits().awsQueryError?.[0]===t)}}}class vT extends E9{awsQueryCompatible;mixin;constructor({defaultNamespace:n,errorTypeRegistries:t,awsQueryCompatible:i}){super({defaultNamespace:n,errorTypeRegistries:t});this.awsQueryCompatible=!!i,this.mixin=new Us(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 T9(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),o=Bn.of(h),w=r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({}),u={};for(let[y,R]of o.structIterator())if(r[y]!=null)u[y]=this.deserializer.readValue(R,r[y]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,u);throw this.mixin.decorateServiceException(Object.assign(d,_,{$fault:o.getMergedTraits().error,message:w},u),r)}}var N9=(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},b9=(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},S9=(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 xi{serdeContext;setSerdeContext(n){this.serdeContext=n}}class hd{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 l9(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 vt(r,"bigDecimal");else return BigInt(r)}}return t}var pT=(n,t)=>fd(n,t).then((i)=>(t?.utf8Encoder??qT)(i)),od=(n,t)=>pT(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{}}),$9=async(n,t)=>{let i=await od(n,t);return i.message=i.message??i.Message,i},JT=(n,t)=>Object.keys(n).find((i)=>i.toLowerCase()===t.toLowerCase()),sd=(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},n2=(n,t)=>{return i2(n,t,["header","code","type"])},t2=(n,t,i=!1)=>{return i2(n,t,i?["code","header","type"]:["type","code","header"])},i2=({headers:n},t,i)=>{while(i.length>0)switch(i.shift()){case"header":let s=JT(n??{},"x-amzn-errortype");if(s!==void 0)return sd(n[s]);break;case"code":let f=JT(t??{},"code");if(f&&t[f]!==void 0)return sd(t[f]);break;case"type":if(t?.__type!==void 0)return sd(t.__type);break}};class wd extends xi{settings;constructor(n){super();this.settings=n}async read(n,t){return this._read(n,typeof t==="string"?JSON.parse(t,l9):await od(t,this.serdeContext))}readObject(n,t){return this._read(n,t)}_read(n,t){let i=t!==null&&typeof t==="object",r=Bn.of(n);if(i){if(r.isStructSchema()){let f=t,h=r.isUnionSchema(),_={},o=void 0,{jsonName:w}=this.settings;if(w)o={};let c;if(h)c=new hd(f,_);for(let[d,u]of r.structIterator()){let y=d;if(w)y=u.getMergedTraits().jsonName??y,o[y]=d;if(h)c.mark(y);if(f[y]!=null)_[d]=this._read(u,f[y])}if(h)c.writeUnknown();else if(typeof f.__type==="string")for(let d in f){let u=f[d],y=w?o[d]??d:d;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 kT(t);let s=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof t==="string"&&s){if(s==="application/json"||s.endsWith("+json"))return aT.from(t);return t}if(r.isTimestampSchema()&&t!=null)switch(Kh(r,this.settings)){case 5:return I9(t);case 6:return L9(t);case 7:return O9(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 vt)return t;let f=t;if(f.type==="bigDecimal"&&"string"in f)return new vt(f.string,f.type);return new vt(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 vt)f[h]=_;else f[h]=this._read(r,_)}return f}else return structuredClone(t);return t}}var QT=String.fromCharCode(925);class r2{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 vt){let i=`${QT+"nv"+this.counter++}_`+t.string;return this.values.set(`"${i}"`,t.string),i}if(typeof t==="bigint"){let i=t.toString(),r=`${QT+"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 cd extends xi{settings;buffer;useReplacer=!1;rootSchema;constructor(n){super();this.settings=n}write(n,t){this.rootSchema=Bn.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 r2;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=Bn.of(n).getName(!0)}_write(n,t,i){let r=t!==null&&typeof t==="object",s=Bn.of(n);if(r){if(s.isStructSchema()){let f=t,h={},{jsonName:_}=this.settings,o=void 0;if(_)o={};let w=0;for(let[c,d]of s.structIterator()){let u=this._write(d,f[c],s);if(u!==void 0){let y=c;if(_)y=d.getMergedTraits().jsonName??c,o[c]=y;h[y]=u,w++}}if(s.isUnionSchema()&&w===0){let{$unknown:c}=f;if(Array.isArray(c)){let[d,u]=c;h[d]=this._write(15,u)}}else if(typeof f.__type==="string")for(let c in f){let d=f[c],u=_?o[c]??c:c;if(!(u in h))h[u]=this._write(15,d)}return h}if(Array.isArray(t)&&s.isListSchema()){let f=s.getValueSchema(),h=[],_=!!s.getMergedTraits().sparse;for(let o of t)if(_||o!=null)h.push(this._write(f,o));return h}if(s.isMapSchema()){let f=s.getValueSchema(),h={},_=!!s.getMergedTraits().sparse;for(let o in t){let w=t[o];if(_||w!=null)h[o]=this._write(f,w)}return h}if(t instanceof Uint8Array&&(s.isBlobSchema()||s.isDocumentSchema())){if(s===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??mh)(t)}if(t instanceof Date&&(s.isTimestampSchema()||s.isDocumentSchema()))switch(Kh(s,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return zh(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof vt)this.useReplacer=!0}if(t===null&&i?.isStructSchema())return;if(s.isStringSchema()){if(typeof t>"u"&&s.isIdempotencyToken())return _d();let f=s.getMergedTraits().mediaType;if(t!=null&&f){if(f==="application/json"||f.endsWith("+json"))return aT.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??mh)(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 vt)this.useReplacer=!0,f[h]=_;else f[h]=this._write(s,_)}return f}else return structuredClone(t);return t}}class Vh extends xi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new cd(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new wd(this.settings);return n.setSerdeContext(this.serdeContext),n}}class xh extends KT{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 Vh({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new Us(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(mT(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=t2(i,r,f)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,h,this.options.defaultNamespace);let{errorSchema:_,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(h,this.options.defaultNamespace,i,r,s,f?this.mixin.findQueryCompatibleError:void 0),w=Bn.of(_),c=r.message??r.Message??"UnknownError",u=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({}),y={},R=this.codec.createDeserializer();for(let[M,E]of w.structIterator())if(r[M]!=null)y[M]=R.readObject(E,r[M]);if(f)this.mixin.queryCompatOutput(r,y);throw this.mixin.decorateServiceException(Object.assign(u,o,{$fault:w.getMergedTraits().error,message:c},y),r)}}class s2 extends xh{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 f2 extends xh{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 _2 extends VT{serializer;deserializer;codec;mixin=new Us;constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t});let i={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new Vh(i),this.serializer=new xT(this.codec.createSerializer(),i),this.deserializer=new jT(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=Bn.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=Bn.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=n2(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),o=Bn.of(h),w=r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({});await this.deserializeHttpMessage(h,t,i,r);let u={},y=this.codec.createDeserializer();for(let[R,M]of o.structIterator()){let E=M.getMergedTraits().jsonName??R;u[R]=y.readObject(M,r[E])}throw this.mixin.decorateServiceException(Object.assign(d,_,{$fault:o.getMergedTraits().error,message:w},u),r)}getDefaultContentType(){return"application/json"}}var U9=(n)=>{if(n==null)return;if(typeof n==="object"&&"__type"in n)delete n.__type;return g9(n)};class jh extends xi{settings;stringDeserializer;constructor(n){super();this.settings=n,this.stringDeserializer=new e9(n)}setSerdeContext(n){this.serdeContext=n,this.stringDeserializer.setSerdeContext(n)}read(n,t,i){let r=Bn.of(n),s=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(s).find((o)=>{return!!o.getMemberTraits().eventPayload})){let o={},w=Object.keys(s)[0];if(s[w].isBlobSchema())o[w]=t;else o[w]=this.read(s[w],t);return o}let h=(this.serdeContext?.utf8Encoder??qT)(t),_=this.parseXml(h);return this.readSchema(n,i?_[i]:_)}readSchema(n,t){let i=Bn.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(),_=[],o=h.getMergedTraits().xmlName??"member",w=s?t:(t[0]??t)[o];if(w==null)return _;let c=Array.isArray(w)?w:[w];for(let d of c)_.push(this.readSchema(h,d));return _}let f={};if(i.isMapSchema()){let h=i.getKeySchema(),_=i.getValueSchema(),o;if(s)o=Array.isArray(t)?t:[t];else o=Array.isArray(t.entry)?t.entry:[t.entry];let w=h.getMergedTraits().xmlName??"key",c=_.getMergedTraits().xmlName??"value";for(let d of o){let u=d[w],y=d[c];f[u]=this.readSchema(_,y)}return f}if(i.isStructSchema()){let h=i.isUnionSchema(),_;if(h)_=new hd(t,f);for(let[o,w]of i.structIterator()){let c=w.getMergedTraits(),d=!c.httpPayload?w.getMemberTraits().xmlName??o:c.xmlName??w.getName();if(h)_.mark(d);if(t[d]!=null)f[o]=this.readSchema(w,t[d])}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=ZT(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 zT(s)}return{}}}class dd extends xi{settings;buffer;constructor(n){super();this.settings=n}write(n,t,i=""){if(this.buffer===void 0)this.buffer="";let r=Bn.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??mh)(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(_d())}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 vt?t.string:String(t))}else if(r.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(i),Kh(r,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(zh(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 o=s.getMergedTraits(),w=this.getKey("member",o.xmlName,o.ec2QueryName),c=f?`${i}${h}`:`${i}${w}.${h}`;this.write(s,_,c),++h}}}else if(r.isMapSchema()){if(t&&typeof t==="object"){let s=r.getKeySchema(),f=r.getValueSchema(),h=r.getMergedTraits().xmlFlattened,_=1;for(let o in t){let w=t[o];if(w==null)continue;let c=s.getMergedTraits(),d=this.getKey("key",c.xmlName,c.ec2QueryName),u=h?`${i}${_}.${d}`:`${i}entry.${_}.${d}`,y=f.getMergedTraits(),R=this.getKey("value",y.xmlName,y.ec2QueryName),M=h?`${i}${_}.${R}`:`${i}entry.${_}.${R}`;this.write(s,o,u),this.write(f,w,M),++_}}}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(),o=this.getKey(f,_.xmlName,_.ec2QueryName,"struct"),w=`${i}${o}`;this.write(h,t[f],w),s=!0}if(!s&&r.isUnionSchema()){let{$unknown:f}=t;if(Array.isArray(f)){let[h,_]=f,o=`${i}${h}`;this.write(15,_,o)}}}}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+=`&${XT(n)}=`}writeValue(n){this.buffer+=XT(n)}}class ud extends KT{options;serializer;deserializer;mixin=new Us;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 dd(t),this.deserializer=new jh(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",mT(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=Bn.of(n.output),f={};if(i.statusCode>=300){let w=await fd(i.body,t);if(w.byteLength>0)Object.assign(f,await r.read(15,w));await this.handleError(n,t,i,f,this.deserializeMetadata(i))}for(let w in i.headers){let c=i.headers[w];delete i.headers[w],i.headers[w.toLowerCase()]=c}let h=n.name.split("#")[1]??n.name,_=s.isStructSchema()&&this.useNestedResult()?h+"Result":void 0,o=await fd(i.body,t);if(o.byteLength>0)Object.assign(f,await r.read(s,o,_));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:o,errorMetadata:w}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,h,s,this.mixin.findQueryCompatibleError),c=Bn.of(o),u=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),y={Type:h.Error.Type,Code:h.Error.Code,Error:h.Error};for(let[R,M]of c.structIterator()){let E=M.getMergedTraits().xmlName??R,T=h[E]??r[E];y[R]=this.deserializer.readSchema(M,T)}throw this.mixin.decorateServiceException(Object.assign(u,w,{$fault:c.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 h2 extends ud{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 o2=(n,t)=>pT(n,t).then((i)=>{if(i.length){let r;try{r=ZT(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 zT(h)}return{}}),D9=async(n,t)=>{let i=await o2(n,t);if(i.Error)i.Error.message=i.Error.message??i.Error.Message;return i},w2=(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 yd extends xi{settings;stringBuffer;byteBuffer;buffer;constructor(n){super();this.settings=n}write(n,t){let i=Bn.of(n);if(i.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(i.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??kT)(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=Gt.of(s),[h,_]=this.getXmlnsAttribute(n,i);for(let[w,c]of n.structIterator()){let d=t[w];if(d!=null||c.isIdempotencyToken()){if(c.getMergedTraits().xmlAttribute){f.addAttribute(c.getMergedTraits().xmlName??w,this.writeSimple(c,d));continue}if(c.isListSchema())this.writeList(c,d,f,_);else if(c.isMapSchema())this.writeMap(c,d,f,_);else if(c.isStructSchema())f.addChildNode(this.writeStruct(c,d,_));else{let u=Gt.of(c.getMergedTraits().xmlName??c.getMemberName());this.writeSimpleInto(c,d,u,_),f.addChildNode(u)}}}let{$unknown:o}=t;if(o&&n.isUnionSchema()&&Array.isArray(o)&&Object.keys(t).length===1){let[w,c]=o,d=Gt.of(w);if(typeof c!=="string")if(t instanceof Gt||t instanceof CT)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,c,d,_),f.addChildNode(d)}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,o=!!s.xmlFlattened,[w,c]=this.getXmlnsAttribute(n,r),d=(u,y)=>{if(f.isListSchema())this.writeList(f,Array.isArray(y)?y:[y],u,c);else if(f.isMapSchema())this.writeMap(f,y,u,c);else if(f.isStructSchema()){let R=this.writeStruct(f,y,c);u.addChildNode(R.withName(o?s.xmlName??n.getMemberName():h.xmlName??"member"))}else{let R=Gt.of(o?s.xmlName??n.getMemberName():h.xmlName??"member");this.writeSimpleInto(f,y,R,c),u.addChildNode(R)}};if(o){for(let u of t)if(_||u!=null)d(i,u)}else{let u=Gt.of(s.xmlName??n.getMemberName());if(c)u.addAttribute(w,c);for(let y of t)if(_||y!=null)d(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(),o=h.getMergedTraits().xmlName??"key",w=n.getValueSchema(),c=w.getMergedTraits(),d=c.xmlName??"value",u=!!c.sparse,y=!!f.xmlFlattened,[R,M]=this.getXmlnsAttribute(n,r),E=(T,O,e)=>{let L=Gt.of(o,O),[N,l]=this.getXmlnsAttribute(h,M);if(l)L.addAttribute(N,l);T.addChildNode(L);let Y=Gt.of(d);if(w.isListSchema())this.writeList(w,e,Y,M);else if(w.isMapSchema())this.writeMap(w,e,Y,M,!0);else if(w.isStructSchema())Y=this.writeStruct(w,e,M);else this.writeSimpleInto(w,e,Y,M);T.addChildNode(Y)};if(y)for(let T in t){let O=t[T];if(u||O!=null){let e=Gt.of(f.xmlName??n.getMemberName());E(e,T,O),i.addChildNode(e)}}else{let T;if(!s){if(T=Gt.of(f.xmlName??n.getMemberName()),M)T.addAttribute(R,M);i.addChildNode(T)}for(let O in t){let e=t[O];if(u||e!=null){let L=Gt.of("entry");E(L,O,e),(s?i:T).addChildNode(L)}}}}writeSimple(n,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let i=Bn.of(n),r=null;if(t&&typeof t==="object")if(i.isBlobSchema())r=(this.serdeContext?.base64Encoder??mh)(t);else if(i.isTimestampSchema()&&t instanceof Date)switch(Kh(i,this.settings)){case 5:r=t.toISOString().replace(".000Z","Z");break;case 6:r=zh(t);break;case 7:r=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),r=zh(t);break}else if(i.isBigDecimalSchema()&&t){if(t instanceof vt)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=_d();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=Bn.of(n),h=new CT(s),[_,o]=this.getXmlnsAttribute(f,r);if(o)i.addAttribute(_,o);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 Ad extends xi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new yd(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new jh(this.settings);return n.setSerdeContext(this.serdeContext),n}}class c2 extends VT{codec;serializer;deserializer;mixin=new Us;constructor(n){super(n);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace};this.codec=new Ad(t),this.serializer=new xT(this.codec.createSerializer(),t),this.deserializer=new jT(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=Bn.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=w2(i,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace),r.Error&&typeof r.Error==="object"){for(let R of Object.keys(r.Error))if(r[R]=r.Error[R],R.toLowerCase()==="message")r.message=r.Error[R]}if(r.RequestId&&!s.requestId)s.requestId=r.RequestId;let{errorSchema:h,errorMetadata:_}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s),o=Bn.of(h),w=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({});await this.deserializeHttpMessage(h,t,i,r);let u={},y=this.codec.createDeserializer();for(let[R,M]of o.structIterator()){let E=M.getMergedTraits().xmlName??R,T=r.Error?.[E]??r[E];u[R]=y.readSchema(M,T)}throw this.mixin.decorateServiceException(Object.assign(d,_,{$fault:o.getMergedTraits().error,message:w},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}}B9.AwsEc2QueryProtocol=h2;B9.AwsJson1_0Protocol=s2;B9.AwsJson1_1Protocol=f2;B9.AwsJsonRpcProtocol=xh;B9.AwsQueryProtocol=ud;B9.AwsRestJsonProtocol=_2;B9.AwsRestXmlProtocol=c2;B9.AwsSmithyRpcV2CborProtocol=vT;B9.JsonCodec=Vh;B9.JsonShapeDeserializer=wd;B9.JsonShapeSerializer=cd;B9.QueryShapeSerializer=dd;B9.XmlCodec=Ad;B9.XmlShapeDeserializer=jh;B9.XmlShapeSerializer=yd;B9._toBool=b9;B9._toNum=S9;B9._toStr=N9;B9.awsExpectUnion=U9;B9.loadJsonRpcErrorCode=t2;B9.loadRestJsonErrorCode=n2;B9.loadRestXmlErrorCode=w2;B9.parseJsonBody=od;B9.parseJsonErrorBody=$9;B9.parseXmlBody=o2;B9.parseXmlErrorBody=D9});var Ld=rn((TC)=>{var{awsEndpointFunctions:sP,emitWarningIfUnsupportedVersion:fP,createDefaultUserAgentProvider:_P,NODE_APP_ID_CONFIG_OPTIONS:hP,getAwsRegionExtensionConfiguration:oP,resolveAwsRegionExtensionConfiguration:wP,resolveUserAgentConfig:cP,resolveHostHeaderConfig:dP,getUserAgentPlugin:uP,getHostHeaderPlugin:yP,getLoggerPlugin:AP,getRecursionDetectionPlugin:RP}=Dt(),{NoAuthSigner:MP,getHttpAuthSchemeEndpointRuleSetPlugin:EP,DefaultIdentityProviderConfig:TP,getHttpSigningPlugin:eP}=zi(),{normalizeProvider:R2,getSmithyContext:OP,ServiceException:LP,NoOpLogger:IP,emitWarningIfUnsupportedVersion:gP,loadConfigsForDefaultMode:NP,getDefaultExtensionConfiguration:bP,resolveDefaultRuntimeConfig:SP,Client:M2,makeBuilder:lP,createAggregatedClient:$P}=yi(),{Command:UP}=yi();TC.$Command=UP;TC.__Client=M2;var{resolveDefaultsModeConfig:DP,loadConfig:gr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:BP,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:GP,NODE_REGION_CONFIG_OPTIONS:HP,NODE_REGION_CONFIG_FILE_OPTIONS:WP,resolveRegionConfig:FP}=vn(),{BinaryDecisionDiagram:YP,EndpointCache:PP,decideEndpoint:XP,customEndpointFunctions:CP,resolveEndpointConfig:JP,getEndpointPlugin:QP}=Mr(),{parseUrl:mP,getHttpHandlerExtensionConfiguration:zP,resolveHttpHandlerRuntimeConfig:KP,getContentLengthPlugin:VP}=nt(),{DEFAULT_RETRY_MODE:xP,NODE_RETRY_MODE_CONFIG_OPTIONS:jP,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:qP,resolveRetryConfig:kP,getRetryPlugin:aP}=Jf(),{TypeRegistry:E2,getSchemaSerdePlugin:ZP}=Yi(),{resolveAwsSdkSigV4Config:vP,AwsSdkSigV4Signer:pP,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:nX}=Pc(),{toUtf8:tX,fromUtf8:iX,toBase64:rX,fromBase64:sX,calculateBodyLength:fX}=pn(),{streamCollector:_X,NodeHttpHandler:hX}=Ch(),{AwsRestJsonProtocol:oX}=Rd(),{Sha256:wX}=mw(),cX=async(n,t,i)=>{return{operation:OP(t).operation,region:await R2(n.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function dX(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:n.region},propertiesExtractor:(t,i)=>({signingProperties:{config:t,context:i}})}}function uX(n){return{schemeId:"smithy.api#noAuth"}}var yX=(n)=>{let t=[];switch(n.operation){case"CreateToken":{t.push(uX());break}default:t.push(dX(n))}return t},AX=(n)=>{let t=vP(n);return Object.assign(t,{authSchemePreference:R2(n.authSchemePreference??[])})},RX=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},MX={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},EX="3.997.32",TX={version:EX},pf="ref",Nr=-1,qh=!0,d2="isSet",T2="PartitionResult",kh="booleanEquals",Md="getAttr",u2={[pf]:"Endpoint"},Ed={[pf]:T2},Ds={},y2=[{[pf]:"Region"}],A2={conditions:[[d2,[u2]],[d2,y2],["aws.partition",y2,T2],[kh,[{[pf]:"UseFIPS"},qh]],[kh,[{[pf]:"UseDualStack"},qh]],[kh,[{fn:Md,argv:[Ed,"supportsDualStack"]},qh]],[kh,[{fn:Md,argv:[Ed,"supportsFIPS"]},qh]],["stringEquals",[{fn:Md,argv:[Ed,"name"]},"aws-us-gov"]]],results:[[Nr],[Nr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Nr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[u2,Ds],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ds],[Nr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",Ds],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",Ds],[Nr,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",Ds],[Nr,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",Ds],[Nr,"Invalid Configuration: Missing Region"]]},eX=2,tt=1e8,OX=new Int32Array([-1,1,-1,0,13,3,1,4,tt+12,2,5,tt+12,3,8,6,4,7,tt+11,5,tt+9,tt+10,4,11,9,6,10,tt+8,7,tt+6,tt+7,5,12,tt+5,6,tt+4,tt+5,3,tt+1,14,4,tt+2,tt+3]),LX=YP.from(OX,eX,A2.conditions,A2.results),IX=new PP({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),gX=(n,t={})=>{return IX.get(n,()=>XP(LX,{endpointParams:n,logger:t.logger}))};CP.aws=sP;class qn extends LP{constructor(n){super(n);Object.setPrototypeOf(this,qn.prototype)}}class ah extends qn{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,ah.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Zh extends qn{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(n){super({name:"AuthorizationPendingException",$fault:"client",...n});Object.setPrototypeOf(this,Zh.prototype),this.error=n.error,this.error_description=n.error_description}}class vh extends qn{name="ExpiredTokenException";$fault="client";error;error_description;constructor(n){super({name:"ExpiredTokenException",$fault:"client",...n});Object.setPrototypeOf(this,vh.prototype),this.error=n.error,this.error_description=n.error_description}}class ph extends qn{name="InternalServerException";$fault="server";error;error_description;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,ph.prototype),this.error=n.error,this.error_description=n.error_description}}class n0 extends qn{name="InvalidClientException";$fault="client";error;error_description;constructor(n){super({name:"InvalidClientException",$fault:"client",...n});Object.setPrototypeOf(this,n0.prototype),this.error=n.error,this.error_description=n.error_description}}class t0 extends qn{name="InvalidGrantException";$fault="client";error;error_description;constructor(n){super({name:"InvalidGrantException",$fault:"client",...n});Object.setPrototypeOf(this,t0.prototype),this.error=n.error,this.error_description=n.error_description}}class i0 extends qn{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(n){super({name:"InvalidRequestException",$fault:"client",...n});Object.setPrototypeOf(this,i0.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class r0 extends qn{name="InvalidScopeException";$fault="client";error;error_description;constructor(n){super({name:"InvalidScopeException",$fault:"client",...n});Object.setPrototypeOf(this,r0.prototype),this.error=n.error,this.error_description=n.error_description}}class s0 extends qn{name="SlowDownException";$fault="client";error;error_description;constructor(n){super({name:"SlowDownException",$fault:"client",...n});Object.setPrototypeOf(this,s0.prototype),this.error=n.error,this.error_description=n.error_description}}class f0 extends qn{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(n){super({name:"UnauthorizedClientException",$fault:"client",...n});Object.setPrototypeOf(this,f0.prototype),this.error=n.error,this.error_description=n.error_description}}class _0 extends qn{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(n){super({name:"UnsupportedGrantTypeException",$fault:"client",...n});Object.setPrototypeOf(this,_0.prototype),this.error=n.error,this.error_description=n.error_description}}var NX="AccessDeniedException",bX="AuthorizationPendingException",SX="AccessToken",lX="ClientSecret",$X="CreateToken",UX="CreateTokenRequest",DX="CreateTokenResponse",BX="CodeVerifier",GX="ExpiredTokenException",HX="InvalidClientException",WX="InvalidGrantException",FX="InvalidRequestException",YX="InternalServerException",PX="InvalidScopeException",XX="IdToken",CX="RefreshToken",JX="SlowDownException",QX="UnauthorizedClientException",mX="UnsupportedGrantTypeException",zX="accessToken",pt="client",KX="clientId",VX="clientSecret",xX="codeVerifier",jX="code",qX="deviceCode",Dn="error",kX="expiresIn",Ht="error_description",aX="grantType",ZX="http",Wt="httpError",vX="idToken",e2="reason",O2="refreshToken",pX="redirectUri",L2="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",nC="scope",tC="server",iC="tokenType",Gn="com.amazonaws.ssooidc",I2=E2.for(L2),g2=[-3,L2,"SSOOIDCServiceException",0,[],[]];I2.registerError(g2,qn);var Tt=E2.for(Gn),N2=[-3,Gn,NX,{[Dn]:pt,[Wt]:400},[Dn,e2,Ht],[0,0,0]];Tt.registerError(N2,ah);var b2=[-3,Gn,bX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(b2,Zh);var S2=[-3,Gn,GX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(S2,vh);var l2=[-3,Gn,YX,{[Dn]:tC,[Wt]:500},[Dn,Ht],[0,0]];Tt.registerError(l2,ph);var $2=[-3,Gn,HX,{[Dn]:pt,[Wt]:401},[Dn,Ht],[0,0]];Tt.registerError($2,n0);var U2=[-3,Gn,WX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(U2,t0);var D2=[-3,Gn,FX,{[Dn]:pt,[Wt]:400},[Dn,e2,Ht],[0,0,0]];Tt.registerError(D2,i0);var B2=[-3,Gn,PX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(B2,r0);var G2=[-3,Gn,JX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(G2,s0);var H2=[-3,Gn,QX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(H2,f0);var W2=[-3,Gn,mX,{[Dn]:pt,[Wt]:400},[Dn,Ht],[0,0]];Tt.registerError(W2,_0);var F2=[I2,Tt],rC=[0,Gn,SX,8,0],sC=[0,Gn,lX,8,0],fC=[0,Gn,BX,8,0],_C=[0,Gn,XX,8,0],Y2=[0,Gn,CX,8,0],P2=[3,Gn,UX,0,[KX,VX,aX,qX,jX,O2,nC,pX,xX],[0,[()=>sC,0],0,0,0,[()=>Y2,0],64,0,[()=>fC,0]],3],X2=[3,Gn,DX,0,[zX,iC,kX,O2,vX],[[()=>rC,0],0,1,[()=>Y2,0],[()=>_C,0]]],C2=[9,Gn,$X,{[ZX]:["POST","/token",200]},()=>P2,()=>X2],hC=(n)=>{return{apiVersion:"2019-06-10",base64Decoder:n?.base64Decoder??sX,base64Encoder:n?.base64Encoder??rX,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??gX,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??yX,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new pP},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new MP}],logger:n?.logger??new IP,protocol:n?.protocol??oX,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:F2,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:n?.serviceId??"SSO OIDC",sha256:n?.sha256??wX,urlParser:n?.urlParser??mP,utf8Decoder:n?.utf8Decoder??iX,utf8Encoder:n?.utf8Encoder??tX}},oC=(n)=>{gP(process.version);let t=DP(n),i=()=>t().then(NP),r=hC(n);fP(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??gr(nX,s),bodyLengthChecker:n?.bodyLengthChecker??fX,defaultUserAgentProvider:n?.defaultUserAgentProvider??_P({serviceId:r.serviceId,clientVersion:TX.version}),maxAttempts:n?.maxAttempts??gr(qP,n),region:n?.region??gr(HP,{...WP,...s}),requestHandler:hX.create(n?.requestHandler??i),retryMode:n?.retryMode??gr({...jP,default:async()=>(await i()).retryMode||xP},n),streamCollector:n?.streamCollector??_X,useDualstackEndpoint:n?.useDualstackEndpoint??gr(GP,s),useFipsEndpoint:n?.useFipsEndpoint??gr(BP,s),userAgentAppId:n?.userAgentAppId??gr(hP,s)}},wC=(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}}},cC=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials()}},dC=(n,t)=>{let i=Object.assign(oP(n),bP(n),zP(n),wC(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,wP(i),SP(i),KP(i),cC(i))};class Td extends M2{config;constructor(...[n]){let t=oC(n||{});super(t);this.initConfig=t;let i=RX(t),r=cP(i),s=kP(r),f=FP(s),h=dP(f),_=JP(h),o=AX(_),w=dC(o,n?.extensions||[]);this.config=w,this.middlewareStack.use(ZP(this.config)),this.middlewareStack.use(uP(this.config)),this.middlewareStack.use(aP(this.config)),this.middlewareStack.use(VP(this.config)),this.middlewareStack.use(yP(this.config)),this.middlewareStack.use(AP(this.config)),this.middlewareStack.use(RP(this.config)),this.middlewareStack.use(EP(this.config,{httpAuthSchemeParametersProvider:cX,identityProviderConfigProvider:async(c)=>new TP({"aws.auth#sigv4":c.credentials})})),this.middlewareStack.use(eP(this.config))}destroy(){super.destroy()}}var uC=lP(MX,"AWSSSOOIDCService","SSOOIDCClient",QP),yC={},AC=(n,t,i,r)=>[];class ed extends uC(yC,AC,"CreateToken",C2){}var RC={CreateTokenCommand:ed};class Od extends Td{}$P(RC,Od);var MC={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},EC={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};TC.AccessDeniedException=ah;TC.AccessDeniedException$=N2;TC.AccessDeniedExceptionReason=MC;TC.AuthorizationPendingException=Zh;TC.AuthorizationPendingException$=b2;TC.CreateToken$=C2;TC.CreateTokenCommand=ed;TC.CreateTokenRequest$=P2;TC.CreateTokenResponse$=X2;TC.ExpiredTokenException=vh;TC.ExpiredTokenException$=S2;TC.InternalServerException=ph;TC.InternalServerException$=l2;TC.InvalidClientException=n0;TC.InvalidClientException$=$2;TC.InvalidGrantException=t0;TC.InvalidGrantException$=U2;TC.InvalidRequestException=i0;TC.InvalidRequestException$=D2;TC.InvalidRequestExceptionReason=EC;TC.InvalidScopeException=r0;TC.InvalidScopeException$=B2;TC.SSOOIDC=Od;TC.SSOOIDCClient=Td;TC.SSOOIDCServiceException=qn;TC.SSOOIDCServiceException$=g2;TC.SlowDownException=s0;TC.SlowDownException$=G2;TC.UnauthorizedClientException=f0;TC.UnauthorizedClientException$=H2;TC.UnsupportedGrantTypeException=_0;TC.UnsupportedGrantTypeException$=W2;TC.errorTypeRegistries=F2});import{Database as mO}from"bun:sqlite";import{existsSync as zO}from"fs";import{homedir as Tu}from"os";import{dirname as KO,join as o_}from"path";function gi(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 Ct(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 en(n){let t=n.overageCount??0;if(Number.isFinite(t)&&t>0)return!0;let i=n.usedCount??0,r=n.limitCount??0;return Number.isFinite(i)&&Number.isFinite(r)&&r>0&&i>=r}function It(n){return gi(n)}function Pr(n){let t=n&&n.length>0?n:"Account needs re-authentication";return gi(t)?t:`InvalidTokenException: ${t}`}var eu=5000,VO=30000,xO=25,jO=500,qO=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 js extends Error{constructor(n,t){super(n,t);this.name="OpenCodeAuthStoreError"}}function kO(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return String(n.code).toUpperCase().startsWith("SQLITE_BUSY")}function aO(n,t){let i=Math.min(xO*2**Math.min(n,5),jO,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 yt(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 ZO(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 qs(n=process.env){let t=process.platform==="win32"?n.APPDATA??o_(Tu(),"AppData","Roaming"):n.XDG_CONFIG_HOME??o_(Tu(),".config");return o_(t,"opencode","kiro.db")}function Ou(n){return o_(KO(n),"kiro-auth-plugin")}class x0{path;db;constructor(n=qs()){this.path=n;if(!zO(n))throw new js(`OpenCode Kiro auth database not found: ${n}. Run OpenCode Kiro authentication first or set auth_source to "local".`);this.db=new mO(n,{strict:!0}),this.db.run(`PRAGMA busy_timeout = ${eu}`),this.validateSchema()}getAccounts(){return this.db.query(`
|
|
47
|
+
>/`.includes(n.x[n.i]))t+=n.x[n.i++];let i=!1,r=Object.create(null);while(n.i<n.z){if(n.trim(),">/".includes(n.x[n.i]))break;let e="";while(n.i<n.z&&!`= \r
|
|
48
|
+
>/?`.includes(n.x[n.i]))e+=n.x[n.i++];if(n.trim(),n.x[n.i]!=="=")break;++n.i,n.trim(),r[e]=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=[],_=!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 _=!0,f.push(n.parseTag());else{let e="";while(n.i<n.z&&n.x[n.i]!=="<")e+=n.x[n.i++];s.push(n.decodeEntities(e))}}if(!n.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${t}>.`);n.i+=2;let o=n.readTo(">").trim();if(o!==t)throw Error(`@aws-sdk XML parse error: mismatched tags <${t}> and </${o}>.`);if(!i&&s.length===0&&!_)return{tag:t,value:""};if(!i&&!_){let e=s.length===1?s[0]:s.join("");if(e.trim()===""&&e.includes(`
|
|
49
|
+
`))return{tag:t,value:""};return{tag:t,value:e}}let h=Object.create(null);for(let e of s){if(e.trim()===""&&e.includes(`
|
|
50
|
+
`))continue;h["#text"]="#text"in h?h["#text"]+e:e}for(let e of f)if(e.tag in h)if(Array.isArray(h[e.tag]))h[e.tag].push(e.value);else h[e.tag]=[h[e.tag],e.value];else h[e.tag]=e.value;for(let[e,c]of Object.entries(r))h[e]=c;return Object.setPrototypeOf(h,Object.prototype),{tag:t,value:h}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let n=this;n.i+=9;let t=0;while(n.i<n.z){let i=n.x[n.i];if(i==="[")++t;else if(i==="]")--t;else if(i===">"&&t===0){++n.i;return}++n.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(n){return n.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(t,i,r,s)=>{if(i)return String.fromCharCode(parseInt(i,16));if(r)return String.fromCharCode(parseInt(r,10));return Rd.ENTITIES[s]??""})}}zP.XmlNode=ho;zP.XmlText=Ad;zP.parseXML=aP});var Ud=sn((h7)=>{var{SmithyRpcV2CborProtocol:jP,loadSmithyRpcV2CborErrorCode:qP}=k1(),{TypeRegistry:v1,NormalizedSchema:Gn,deref:sl}=Ji(),{decorateServiceException:p1,getValueFromTextNode:fl}=Ei(),{collectBody:Ed,determineTimestampFormat:rh,RpcProtocol:ol,HttpBindingProtocol:_l,HttpInterceptingShapeSerializer:hl,HttpInterceptingShapeDeserializer:el,FromStringShapeDeserializer:kP,extendedEncodeURIComponent:nl}=it(),{NumericValue:ii,toUtf8:cl,fromBase64:dl,LazyJsonString:ul,parseEpochTimestamp:ZP,parseRfc7231DateTime:vP,parseRfc3339DateTimeWithOffset:pP,toBase64:th,dateToUtcString:ih,generateIdempotencyToken:ld,expectUnion:n7}=tt(),{parseXML:wl,XmlNode:Ft,XmlText:tl}=Z1();class Ps{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:_,httpQueryParams:o,httpHeader:h,httpLabel:e,httpPrefixHeaders:c}=f.getMergedTraits();return!_&&!o&&!h&&!e&&c===void 0}))return n}}async getErrorSchemaOrThrowBaseException(n,t,i,r,s,f){let _=n;if(n.includes("#"))[,_]=n.split("#");let o={$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,_)??this.errorRegistry.getSchema(n),errorMetadata:o}}catch(h){r.message=r.message??r.Message??"UnknownError";let e=this.errorRegistry,c=e.getBaseException();if(c){let w=e.getErrorCtor(c)??Error;throw this.decorateServiceException(Object.assign(new w({name:_}),o),r)}let d=r,u=d?.message??d?.Message??d?.Error?.Message??d?.Error?.message;throw this.decorateServiceException(Object.assign(Error(u),{name:_},o),r)}}compose(n,t,i){let r=i;if(t.includes("#"))[r]=t.split("#");let s=v1.for(r),f=v1.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=p1(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 p1(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),_={Code:r,Type:s};n.Code=r,n.Type=s;for(let o=0;o<f.length;o++){let h=f[o];_[h==="message"?"Message":h]=n[h]}delete _.__type,n.Error=_}}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)=>Gn.of(r).getMergedTraits().awsQueryError?.[0]===t)}}}class yl extends jP{awsQueryCompatible;mixin;constructor({defaultNamespace:n,errorTypeRegistries:t,awsQueryCompatible:i}){super({defaultNamespace:n,errorTypeRegistries:t});this.awsQueryCompatible=!!i,this.mixin=new Ps(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 w=i.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return qP(i,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:_,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),h=Gn.of(_),e=r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({}),u={};for(let[w,A]of h.structIterator())if(r[w]!=null)u[w]=this.deserializer.readValue(A,r[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,u);throw this.mixin.decorateServiceException(Object.assign(d,o,{$fault:h.getMergedTraits().error,message:e},u),r)}}var t7=(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},i7=(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},r7=(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 Zi{serdeContext;setSerdeContext(n){this.serdeContext=n}}class Td{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 s7(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 ii(r,"bigDecimal");else return BigInt(r)}}return t}var Al=(n,t)=>Ed(n,t).then((i)=>(t?.utf8Encoder??cl)(i)),gd=(n,t)=>Al(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{}}),f7=async(n,t)=>{let i=await gd(n,t);return i.message=i.message??i.Message,i},il=(n,t)=>Object.keys(n).find((i)=>i.toLowerCase()===t.toLowerCase()),Md=(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},Rl=(n,t)=>{return El(n,t,["header","code","type"])},Ml=(n,t,i=!1)=>{return El(n,t,i?["code","header","type"]:["type","code","header"])},El=({headers:n},t,i)=>{while(i.length>0)switch(i.shift()){case"header":let s=il(n??{},"x-amzn-errortype");if(s!==void 0)return Md(n[s]);break;case"code":let f=il(t??{},"code");if(f&&t[f]!==void 0)return Md(t[f]);break;case"type":if(t?.__type!==void 0)return Md(t.__type);break}};class Od extends Zi{settings;constructor(n){super();this.settings=n}async read(n,t){return this._read(n,typeof t==="string"?JSON.parse(t,s7):await gd(t,this.serdeContext))}readObject(n,t){return this._read(n,t)}_read(n,t){let i=t!==null&&typeof t==="object",r=Gn.of(n);if(i){if(r.isStructSchema()){let f=t,_=r.isUnionSchema(),o={},h=void 0,{jsonName:e}=this.settings;if(e)h={};let c;if(_)c=new Td(f,o);for(let[d,u]of r.structIterator()){let w=d;if(e)w=u.getMergedTraits().jsonName??w,h[w]=d;if(_)c.mark(w);if(f[w]!=null)o[d]=this._read(u,f[w])}if(_)c.writeUnknown();else if(typeof f.__type==="string")for(let d in f){let u=f[d],w=e?h[d]??d:d;if(!(w in o))o[w]=u}return o}if(Array.isArray(t)&&r.isListSchema()){let f=r.getValueSchema(),_=[];for(let o of t)_.push(this._read(f,o));return _}if(r.isMapSchema()){let f=r.getValueSchema(),_={};for(let o in t)_[o]=this._read(f,t[o]);return _}}if(r.isBlobSchema()&&typeof t==="string")return dl(t);let s=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof t==="string"&&s){if(s==="application/json"||s.endsWith("+json"))return ul.from(t);return t}if(r.isTimestampSchema()&&t!=null)switch(rh(r,this.settings)){case 5:return pP(t);case 6:return vP(t);case 7:return ZP(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 ii)return t;let f=t;if(f.type==="bigDecimal"&&"string"in f)return new ii(f.string,f.type);return new ii(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 _ in t){let o=t[_];if(o instanceof ii)f[_]=o;else f[_]=this._read(r,o)}return f}else return structuredClone(t);return t}}var rl=String.fromCharCode(925);class ll{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 ii){let i=`${rl+"nv"+this.counter++}_`+t.string;return this.values.set(`"${i}"`,t.string),i}if(typeof t==="bigint"){let i=t.toString(),r=`${rl+"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 Ld extends Zi{settings;buffer;useReplacer=!1;rootSchema;constructor(n){super();this.settings=n}write(n,t){this.rootSchema=Gn.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 ll;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=Gn.of(n).getName(!0)}_write(n,t,i){let r=t!==null&&typeof t==="object",s=Gn.of(n);if(r){if(s.isStructSchema()){let f=t,_={},{jsonName:o}=this.settings,h=void 0;if(o)h={};let e=0;for(let[c,d]of s.structIterator()){let u=this._write(d,f[c],s);if(u!==void 0){let w=c;if(o)w=d.getMergedTraits().jsonName??c,h[c]=w;_[w]=u,e++}}if(s.isUnionSchema()&&e===0){let{$unknown:c}=f;if(Array.isArray(c)){let[d,u]=c;_[d]=this._write(15,u)}}else if(typeof f.__type==="string")for(let c in f){let d=f[c],u=o?h[c]??c:c;if(!(u in _))_[u]=this._write(15,d)}return _}if(Array.isArray(t)&&s.isListSchema()){let f=s.getValueSchema(),_=[],o=!!s.getMergedTraits().sparse;for(let h of t)if(o||h!=null)_.push(this._write(f,h));return _}if(s.isMapSchema()){let f=s.getValueSchema(),_={},o=!!s.getMergedTraits().sparse;for(let h in t){let e=t[h];if(o||e!=null)_[h]=this._write(f,e)}return _}if(t instanceof Uint8Array&&(s.isBlobSchema()||s.isDocumentSchema())){if(s===this.rootSchema)return t;return(this.serdeContext?.base64Encoder??th)(t)}if(t instanceof Date&&(s.isTimestampSchema()||s.isDocumentSchema()))switch(rh(s,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return ih(t);case 7:return t.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1000}if(t instanceof ii)this.useReplacer=!0}if(t===null&&i?.isStructSchema())return;if(s.isStringSchema()){if(typeof t>"u"&&s.isIdempotencyToken())return ld();let f=s.getMergedTraits().mediaType;if(t!=null&&f){if(f==="application/json"||f.endsWith("+json"))return ul.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??th)(t)}if(typeof t==="bigint")this.useReplacer=!0;if(s.isDocumentSchema())if(r){let f=Array.isArray(t)?[]:{};for(let _ in t){let o=t[_];if(o instanceof ii)this.useReplacer=!0,f[_]=o;else f[_]=this._write(s,o)}return f}else return structuredClone(t);return t}}class sh extends Zi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new Ld(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new Od(this.settings);return n.setSerdeContext(this.serdeContext),n}}class fh extends ol{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 sh({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new Ps(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(sl(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 _=Ml(i,r,f)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,_,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(_,this.options.defaultNamespace,i,r,s,f?this.mixin.findQueryCompatibleError:void 0),e=Gn.of(o),c=r.message??r.Message??"UnknownError",u=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[R,M]of e.structIterator())if(r[R]!=null)w[R]=A.readObject(M,r[R]);if(f)this.mixin.queryCompatOutput(r,w);throw this.mixin.decorateServiceException(Object.assign(u,h,{$fault:e.getMergedTraits().error,message:c},w),r)}}class Tl extends fh{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 gl extends fh{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 Ol extends _l{serializer;deserializer;codec;mixin=new Ps;constructor({defaultNamespace:n,errorTypeRegistries:t}){super({defaultNamespace:n,errorTypeRegistries:t});let i={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new sh(i),this.serializer=new hl(this.codec.createSerializer(),i),this.deserializer=new el(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=Gn.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=Gn.of(n.output);for(let[f,_]of s.structIterator())if(_.getMemberTraits().httpPayload&&!(f in r))r[f]=null;return r}async handleError(n,t,i,r,s){let f=Rl(i,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:_,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s),h=Gn.of(_),e=r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({});await this.deserializeHttpMessage(_,t,i,r);let u={},w=this.codec.createDeserializer();for(let[A,R]of h.structIterator()){let M=R.getMergedTraits().jsonName??A;u[A]=w.readObject(R,r[M])}throw this.mixin.decorateServiceException(Object.assign(d,o,{$fault:h.getMergedTraits().error,message:e},u),r)}getDefaultContentType(){return"application/json"}}var o7=(n)=>{if(n==null)return;if(typeof n==="object"&&"__type"in n)delete n.__type;return n7(n)};class oh extends Zi{settings;stringDeserializer;constructor(n){super();this.settings=n,this.stringDeserializer=new kP(n)}setSerdeContext(n){this.serdeContext=n,this.stringDeserializer.setSerdeContext(n)}read(n,t,i){let r=Gn.of(n),s=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(s).find((h)=>{return!!h.getMemberTraits().eventPayload})){let h={},e=Object.keys(s)[0];if(s[e].isBlobSchema())h[e]=t;else h[e]=this.read(s[e],t);return h}let _=(this.serdeContext?.utf8Encoder??cl)(t),o=this.parseXml(_);return this.readSchema(n,i?o[i]:o)}readSchema(n,t){let i=Gn.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 _=i.getValueSchema(),o=[],h=_.getMergedTraits().xmlName??"member",e=s?t:(t[0]??t)[h];if(e==null)return o;let c=Array.isArray(e)?e:[e];for(let d of c)o.push(this.readSchema(_,d));return o}let f={};if(i.isMapSchema()){let _=i.getKeySchema(),o=i.getValueSchema(),h;if(s)h=Array.isArray(t)?t:[t];else h=Array.isArray(t.entry)?t.entry:[t.entry];let e=_.getMergedTraits().xmlName??"key",c=o.getMergedTraits().xmlName??"value";for(let d of h){let u=d[e],w=d[c];f[u]=this.readSchema(o,w)}return f}if(i.isStructSchema()){let _=i.isUnionSchema(),o;if(_)o=new Td(t,f);for(let[h,e]of i.structIterator()){let c=e.getMergedTraits(),d=!c.httpPayload?e.getMemberTraits().xmlName??h:c.xmlName??e.getName();if(_)o.mark(d);if(t[d]!=null)f[h]=this.readSchema(e,t[d])}if(_)o.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=wl(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 fl(s)}return{}}}class Id extends Zi{settings;buffer;constructor(n){super();this.settings=n}write(n,t,i=""){if(this.buffer===void 0)this.buffer="";let r=Gn.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??th)(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(ld())}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 ii?t.string:String(t))}else if(r.isTimestampSchema()){if(t instanceof Date)switch(this.writeKey(i),rh(r,this.settings)){case 5:this.writeValue(t.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(ih(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,_=1;for(let o of t){if(o==null)continue;let h=s.getMergedTraits(),e=this.getKey("member",h.xmlName,h.ec2QueryName),c=f?`${i}${_}`:`${i}${e}.${_}`;this.write(s,o,c),++_}}}else if(r.isMapSchema()){if(t&&typeof t==="object"){let s=r.getKeySchema(),f=r.getValueSchema(),_=r.getMergedTraits().xmlFlattened,o=1;for(let h in t){let e=t[h];if(e==null)continue;let c=s.getMergedTraits(),d=this.getKey("key",c.xmlName,c.ec2QueryName),u=_?`${i}${o}.${d}`:`${i}entry.${o}.${d}`,w=f.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),R=_?`${i}${o}.${A}`:`${i}entry.${o}.${A}`;this.write(s,h,u),this.write(f,e,R),++o}}}else if(r.isStructSchema()){if(t&&typeof t==="object"){let s=!1;for(let[f,_]of r.structIterator()){if(t[f]==null&&!_.isIdempotencyToken())continue;let o=_.getMergedTraits(),h=this.getKey(f,o.xmlName,o.ec2QueryName,"struct"),e=`${i}${h}`;this.write(_,t[f],e),s=!0}if(!s&&r.isUnionSchema()){let{$unknown:f}=t;if(Array.isArray(f)){let[_,o]=f,h=`${i}${_}`;this.write(15,o,h)}}}}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 _=t??n;if(f&&r==="struct")return _[0].toUpperCase()+_.slice(1);return _}writeKey(n){if(n.endsWith("."))n=n.slice(0,n.length-1);this.buffer+=`&${nl(n)}=`}writeValue(n){this.buffer+=nl(n)}}class Sd extends ol{options;serializer;deserializer;mixin=new Ps;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 Id(t),this.deserializer=new oh(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",sl(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=Gn.of(n.output),f={};if(i.statusCode>=300){let e=await Ed(i.body,t);if(e.byteLength>0)Object.assign(f,await r.read(15,e));await this.handleError(n,t,i,f,this.deserializeMetadata(i))}for(let e in i.headers){let c=i.headers[e];delete i.headers[e],i.headers[e.toLowerCase()]=c}let _=n.name.split("#")[1]??n.name,o=s.isStructSchema()&&this.useNestedResult()?_+"Result":void 0,h=await Ed(i.body,t);if(h.byteLength>0)Object.assign(f,await r.read(s,h,o));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 _=this.loadQueryError(r)??{},o=this.loadQueryErrorMessage(r);_.message=o,_.Error={Type:_.Type,Code:_.Code,Message:o};let{errorSchema:h,errorMetadata:e}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,_,s,this.mixin.findQueryCompatibleError),c=Gn.of(h),u=new(this.compositeErrorRegistry.getErrorCtor(h)??Error)({}),w={Type:_.Error.Type,Code:_.Error.Code,Error:_.Error};for(let[A,R]of c.structIterator()){let M=R.getMergedTraits().xmlName??A,E=_[M]??r[M];w[A]=this.deserializer.readSchema(R,E)}throw this.mixin.decorateServiceException(Object.assign(u,e,{$fault:c.getMergedTraits().error,message:o},w),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 Ll extends Sd{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 Il=(n,t)=>Al(n,t).then((i)=>{if(i.length){let r;try{r=wl(i)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:i});throw o}let s="#text",f=Object.keys(r)[0],_=r[f];if(_[s])_[f]=_[s],delete _[s];return fl(_)}return{}}),_7=async(n,t)=>{let i=await Il(n,t);if(i.Error)i.Error.message=i.Error.message??i.Error.Message;return i},Sl=(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 bd extends Zi{settings;stringBuffer;byteBuffer;buffer;constructor(n){super();this.settings=n}write(n,t){let i=Gn.of(n);if(i.isStringSchema()&&typeof t==="string")this.stringBuffer=t;else if(i.isBlobSchema())this.byteBuffer="byteLength"in t?t:(this.serdeContext?.base64Decoder??dl)(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=Ft.of(s),[_,o]=this.getXmlnsAttribute(n,i);for(let[e,c]of n.structIterator()){let d=t[e];if(d!=null||c.isIdempotencyToken()){if(c.getMergedTraits().xmlAttribute){f.addAttribute(c.getMergedTraits().xmlName??e,this.writeSimple(c,d));continue}if(c.isListSchema())this.writeList(c,d,f,o);else if(c.isMapSchema())this.writeMap(c,d,f,o);else if(c.isStructSchema())f.addChildNode(this.writeStruct(c,d,o));else{let u=Ft.of(c.getMergedTraits().xmlName??c.getMemberName());this.writeSimpleInto(c,d,u,o),f.addChildNode(u)}}}let{$unknown:h}=t;if(h&&n.isUnionSchema()&&Array.isArray(h)&&Object.keys(t).length===1){let[e,c]=h,d=Ft.of(e);if(typeof c!=="string")if(t instanceof Ft||t instanceof tl)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,c,d,o),f.addChildNode(d)}if(o)f.addAttribute(_,o);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(),_=f.getMergedTraits(),o=!!_.sparse,h=!!s.xmlFlattened,[e,c]=this.getXmlnsAttribute(n,r),d=(u,w)=>{if(f.isListSchema())this.writeList(f,Array.isArray(w)?w:[w],u,c);else if(f.isMapSchema())this.writeMap(f,w,u,c);else if(f.isStructSchema()){let A=this.writeStruct(f,w,c);u.addChildNode(A.withName(h?s.xmlName??n.getMemberName():_.xmlName??"member"))}else{let A=Ft.of(h?s.xmlName??n.getMemberName():_.xmlName??"member");this.writeSimpleInto(f,w,A,c),u.addChildNode(A)}};if(h){for(let u of t)if(o||u!=null)d(i,u)}else{let u=Ft.of(s.xmlName??n.getMemberName());if(c)u.addAttribute(e,c);for(let w of t)if(o||w!=null)d(u,w);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(),_=n.getKeySchema(),h=_.getMergedTraits().xmlName??"key",e=n.getValueSchema(),c=e.getMergedTraits(),d=c.xmlName??"value",u=!!c.sparse,w=!!f.xmlFlattened,[A,R]=this.getXmlnsAttribute(n,r),M=(E,T,l)=>{let g=Ft.of(h,T),[O,N]=this.getXmlnsAttribute(_,R);if(N)g.addAttribute(O,N);E.addChildNode(g);let F=Ft.of(d);if(e.isListSchema())this.writeList(e,l,F,R);else if(e.isMapSchema())this.writeMap(e,l,F,R,!0);else if(e.isStructSchema())F=this.writeStruct(e,l,R);else this.writeSimpleInto(e,l,F,R);E.addChildNode(F)};if(w)for(let E in t){let T=t[E];if(u||T!=null){let l=Ft.of(f.xmlName??n.getMemberName());M(l,E,T),i.addChildNode(l)}}else{let E;if(!s){if(E=Ft.of(f.xmlName??n.getMemberName()),R)E.addAttribute(A,R);i.addChildNode(E)}for(let T in t){let l=t[T];if(u||l!=null){let g=Ft.of("entry");M(g,T,l),(s?i:E).addChildNode(g)}}}}writeSimple(n,t){if(t===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let i=Gn.of(n),r=null;if(t&&typeof t==="object")if(i.isBlobSchema())r=(this.serdeContext?.base64Encoder??th)(t);else if(i.isTimestampSchema()&&t instanceof Date)switch(rh(i,this.settings)){case 5:r=t.toISOString().replace(".000Z","Z");break;case 6:r=ih(t);break;case 7:r=String(t.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",t),r=ih(t);break}else if(i.isBigDecimalSchema()&&t){if(t instanceof ii)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=ld();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=Gn.of(n),_=new tl(s),[o,h]=this.getXmlnsAttribute(f,r);if(h)i.addAttribute(o,h);i.addChildNode(_)}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 Nd extends Zi{settings;constructor(n){super();this.settings=n}createSerializer(){let n=new bd(this.settings);return n.setSerdeContext(this.serdeContext),n}createDeserializer(){let n=new oh(this.settings);return n.setSerdeContext(this.serdeContext),n}}class bl extends _l{codec;serializer;deserializer;mixin=new Ps;constructor(n){super(n);let t={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:n.xmlNamespace,serviceNamespace:n.defaultNamespace};this.codec=new Nd(t),this.serializer=new hl(this.codec.createSerializer(),t),this.deserializer=new el(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=Gn.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=Sl(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:_,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,i,r,s),h=Gn.of(_),e=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",d=new(this.compositeErrorRegistry.getErrorCtor(_)??Error)({});await this.deserializeHttpMessage(_,t,i,r);let u={},w=this.codec.createDeserializer();for(let[A,R]of h.structIterator()){let M=R.getMergedTraits().xmlName??A,E=r.Error?.[M]??r[M];u[A]=w.readSchema(R,E)}throw this.mixin.decorateServiceException(Object.assign(d,o,{$fault:h.getMergedTraits().error,message:e},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}}h7.AwsEc2QueryProtocol=Ll;h7.AwsJson1_0Protocol=Tl;h7.AwsJson1_1Protocol=gl;h7.AwsJsonRpcProtocol=fh;h7.AwsQueryProtocol=Sd;h7.AwsRestJsonProtocol=Ol;h7.AwsRestXmlProtocol=bl;h7.AwsSmithyRpcV2CborProtocol=yl;h7.JsonCodec=sh;h7.JsonShapeDeserializer=Od;h7.JsonShapeSerializer=Ld;h7.QueryShapeSerializer=Id;h7.XmlCodec=Nd;h7.XmlShapeDeserializer=oh;h7.XmlShapeSerializer=bd;h7._toBool=i7;h7._toNum=r7;h7._toStr=t7;h7.awsExpectUnion=o7;h7.loadJsonRpcErrorCode=Ml;h7.loadRestJsonErrorCode=Rl;h7.loadRestXmlErrorCode=Sl;h7.parseJsonBody=gd;h7.parseJsonErrorBody=f7;h7.parseXmlBody=Il;h7.parseXmlErrorBody=_7});var Hd=sn((q9)=>{var{awsEndpointFunctions:W7,emitWarningIfUnsupportedVersion:F7,createDefaultUserAgentProvider:C7,NODE_APP_ID_CONFIG_OPTIONS:P7,getAwsRegionExtensionConfiguration:Y7,resolveAwsRegionExtensionConfiguration:X7,resolveUserAgentConfig:J7,resolveHostHeaderConfig:Q7,getUserAgentPlugin:a7,getHostHeaderPlugin:z7,getLoggerPlugin:K7,getRecursionDetectionPlugin:x7}=Ht(),{NoAuthSigner:V7,getHttpAuthSchemeEndpointRuleSetPlugin:j7,DefaultIdentityProviderConfig:q7,getHttpSigningPlugin:k7}=ji(),{normalizeProvider:Bl,getSmithyContext:Z7,ServiceException:v7,NoOpLogger:p7,emitWarningIfUnsupportedVersion:nY,loadConfigsForDefaultMode:tY,getDefaultExtensionConfiguration:iY,resolveDefaultRuntimeConfig:rY,Client:Gl,makeBuilder:sY,createAggregatedClient:fY}=Ei(),{Command:oY}=Ei();q9.$Command=oY;q9.__Client=Gl;var{resolveDefaultsModeConfig:_Y,loadConfig:Nr,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:hY,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:eY,NODE_REGION_CONFIG_OPTIONS:cY,NODE_REGION_CONFIG_FILE_OPTIONS:dY,resolveRegionConfig:uY}=nt(),{BinaryDecisionDiagram:wY,EndpointCache:yY,decideEndpoint:AY,customEndpointFunctions:RY,resolveEndpointConfig:MY,getEndpointPlugin:EY}=Tr(),{parseUrl:lY,getHttpHandlerExtensionConfiguration:TY,resolveHttpHandlerRuntimeConfig:gY,getContentLengthPlugin:OY}=it(),{DEFAULT_RETRY_MODE:LY,NODE_RETRY_MODE_CONFIG_OPTIONS:IY,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:SY,resolveRetryConfig:bY,getRetryPlugin:NY}=kf(),{TypeRegistry:ml,getSchemaSerdePlugin:UY}=Ji(),{resolveAwsSdkSigV4Config:$Y,AwsSdkSigV4Signer:DY,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:BY}=kc(),{toUtf8:GY,fromUtf8:mY,toBase64:HY,fromBase64:WY,calculateBodyLength:FY}=tt(),{streamCollector:CY,NodeHttpHandler:PY}=v_(),{AwsRestJsonProtocol:YY}=Ud(),{Sha256:XY}=tc(),JY=async(n,t,i)=>{return{operation:Z7(t).operation,region:await Bl(n.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function QY(n){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:n.region},propertiesExtractor:(t,i)=>({signingProperties:{config:t,context:i}})}}function aY(n){return{schemeId:"smithy.api#noAuth"}}var zY=(n)=>{let t=[];switch(n.operation){case"CreateToken":{t.push(aY());break}default:t.push(QY(n))}return t},KY=(n)=>{let t=$Y(n);return Object.assign(t,{authSchemePreference:Bl(n.authSchemePreference??[])})},xY=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},VY={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},jY="3.997.32",qY={version:jY},eo="ref",Ur=-1,_h=!0,Nl="isSet",Hl="PartitionResult",hh="booleanEquals",$d="getAttr",Ul={[eo]:"Endpoint"},Dd={[eo]:Hl},Ys={},$l=[{[eo]:"Region"}],Dl={conditions:[[Nl,[Ul]],[Nl,$l],["aws.partition",$l,Hl],[hh,[{[eo]:"UseFIPS"},_h]],[hh,[{[eo]:"UseDualStack"},_h]],[hh,[{fn:$d,argv:[Dd,"supportsDualStack"]},_h]],[hh,[{fn:$d,argv:[Dd,"supportsFIPS"]},_h]],["stringEquals",[{fn:$d,argv:[Dd,"name"]},"aws-us-gov"]]],results:[[Ur],[Ur,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ur,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[Ul,Ys],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ys],[Ur,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",Ys],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",Ys],[Ur,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",Ys],[Ur,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",Ys],[Ur,"Invalid Configuration: Missing Region"]]},kY=2,rt=1e8,ZY=new Int32Array([-1,1,-1,0,13,3,1,4,rt+12,2,5,rt+12,3,8,6,4,7,rt+11,5,rt+9,rt+10,4,11,9,6,10,rt+8,7,rt+6,rt+7,5,12,rt+5,6,rt+4,rt+5,3,rt+1,14,4,rt+2,rt+3]),vY=wY.from(ZY,kY,Dl.conditions,Dl.results),pY=new yY({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),n9=(n,t={})=>{return pY.get(n,()=>AY(vY,{endpointParams:n,logger:t.logger}))};RY.aws=W7;class qn extends v7{constructor(n){super(n);Object.setPrototypeOf(this,qn.prototype)}}class eh extends qn{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,eh.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class ch extends qn{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(n){super({name:"AuthorizationPendingException",$fault:"client",...n});Object.setPrototypeOf(this,ch.prototype),this.error=n.error,this.error_description=n.error_description}}class dh extends qn{name="ExpiredTokenException";$fault="client";error;error_description;constructor(n){super({name:"ExpiredTokenException",$fault:"client",...n});Object.setPrototypeOf(this,dh.prototype),this.error=n.error,this.error_description=n.error_description}}class uh extends qn{name="InternalServerException";$fault="server";error;error_description;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,uh.prototype),this.error=n.error,this.error_description=n.error_description}}class wh extends qn{name="InvalidClientException";$fault="client";error;error_description;constructor(n){super({name:"InvalidClientException",$fault:"client",...n});Object.setPrototypeOf(this,wh.prototype),this.error=n.error,this.error_description=n.error_description}}class yh extends qn{name="InvalidGrantException";$fault="client";error;error_description;constructor(n){super({name:"InvalidGrantException",$fault:"client",...n});Object.setPrototypeOf(this,yh.prototype),this.error=n.error,this.error_description=n.error_description}}class Ah extends qn{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(n){super({name:"InvalidRequestException",$fault:"client",...n});Object.setPrototypeOf(this,Ah.prototype),this.error=n.error,this.reason=n.reason,this.error_description=n.error_description}}class Rh extends qn{name="InvalidScopeException";$fault="client";error;error_description;constructor(n){super({name:"InvalidScopeException",$fault:"client",...n});Object.setPrototypeOf(this,Rh.prototype),this.error=n.error,this.error_description=n.error_description}}class Mh extends qn{name="SlowDownException";$fault="client";error;error_description;constructor(n){super({name:"SlowDownException",$fault:"client",...n});Object.setPrototypeOf(this,Mh.prototype),this.error=n.error,this.error_description=n.error_description}}class Eh extends qn{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(n){super({name:"UnauthorizedClientException",$fault:"client",...n});Object.setPrototypeOf(this,Eh.prototype),this.error=n.error,this.error_description=n.error_description}}class lh extends qn{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(n){super({name:"UnsupportedGrantTypeException",$fault:"client",...n});Object.setPrototypeOf(this,lh.prototype),this.error=n.error,this.error_description=n.error_description}}var t9="AccessDeniedException",i9="AuthorizationPendingException",r9="AccessToken",s9="ClientSecret",f9="CreateToken",o9="CreateTokenRequest",_9="CreateTokenResponse",h9="CodeVerifier",e9="ExpiredTokenException",c9="InvalidClientException",d9="InvalidGrantException",u9="InvalidRequestException",w9="InternalServerException",y9="InvalidScopeException",A9="IdToken",R9="RefreshToken",M9="SlowDownException",E9="UnauthorizedClientException",l9="UnsupportedGrantTypeException",T9="accessToken",ri="client",g9="clientId",O9="clientSecret",L9="codeVerifier",I9="code",S9="deviceCode",$n="error",b9="expiresIn",Ct="error_description",N9="grantType",U9="http",Pt="httpError",$9="idToken",Wl="reason",Fl="refreshToken",D9="redirectUri",Cl="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",B9="scope",G9="server",m9="tokenType",mn="com.amazonaws.ssooidc",Pl=ml.for(Cl),Yl=[-3,Cl,"SSOOIDCServiceException",0,[],[]];Pl.registerError(Yl,qn);var Ot=ml.for(mn),Xl=[-3,mn,t9,{[$n]:ri,[Pt]:400},[$n,Wl,Ct],[0,0,0]];Ot.registerError(Xl,eh);var Jl=[-3,mn,i9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(Jl,ch);var Ql=[-3,mn,e9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(Ql,dh);var al=[-3,mn,w9,{[$n]:G9,[Pt]:500},[$n,Ct],[0,0]];Ot.registerError(al,uh);var zl=[-3,mn,c9,{[$n]:ri,[Pt]:401},[$n,Ct],[0,0]];Ot.registerError(zl,wh);var Kl=[-3,mn,d9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(Kl,yh);var xl=[-3,mn,u9,{[$n]:ri,[Pt]:400},[$n,Wl,Ct],[0,0,0]];Ot.registerError(xl,Ah);var Vl=[-3,mn,y9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(Vl,Rh);var jl=[-3,mn,M9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(jl,Mh);var ql=[-3,mn,E9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(ql,Eh);var kl=[-3,mn,l9,{[$n]:ri,[Pt]:400},[$n,Ct],[0,0]];Ot.registerError(kl,lh);var Zl=[Pl,Ot],H9=[0,mn,r9,8,0],W9=[0,mn,s9,8,0],F9=[0,mn,h9,8,0],C9=[0,mn,A9,8,0],vl=[0,mn,R9,8,0],pl=[3,mn,o9,0,[g9,O9,N9,S9,I9,Fl,B9,D9,L9],[0,[()=>W9,0],0,0,0,[()=>vl,0],64,0,[()=>F9,0]],3],nT=[3,mn,_9,0,[T9,m9,b9,Fl,$9],[[()=>H9,0],0,1,[()=>vl,0],[()=>C9,0]]],tT=[9,mn,f9,{[U9]:["POST","/token",200]},()=>pl,()=>nT],P9=(n)=>{return{apiVersion:"2019-06-10",base64Decoder:n?.base64Decoder??WY,base64Encoder:n?.base64Encoder??HY,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??n9,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??zY,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(t)=>t.getIdentityProvider("aws.auth#sigv4"),signer:new DY},{schemeId:"smithy.api#noAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new V7}],logger:n?.logger??new p7,protocol:n?.protocol??YY,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:Zl,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:n?.serviceId??"SSO OIDC",sha256:n?.sha256??XY,urlParser:n?.urlParser??lY,utf8Decoder:n?.utf8Decoder??mY,utf8Encoder:n?.utf8Encoder??GY}},Y9=(n)=>{nY(process.version);let t=_Y(n),i=()=>t().then(tY),r=P9(n);F7(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??Nr(BY,s),bodyLengthChecker:n?.bodyLengthChecker??FY,defaultUserAgentProvider:n?.defaultUserAgentProvider??C7({serviceId:r.serviceId,clientVersion:qY.version}),maxAttempts:n?.maxAttempts??Nr(SY,n),region:n?.region??Nr(cY,{...dY,...s}),requestHandler:PY.create(n?.requestHandler??i),retryMode:n?.retryMode??Nr({...IY,default:async()=>(await i()).retryMode||LY},n),streamCollector:n?.streamCollector??CY,useDualstackEndpoint:n?.useDualstackEndpoint??Nr(eY,s),useFipsEndpoint:n?.useFipsEndpoint??Nr(hY,s),userAgentAppId:n?.userAgentAppId??Nr(P7,s)}},X9=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,credentials:r}=n;return{setHttpAuthScheme(s){let f=t.findIndex((_)=>_.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}}},J9=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),credentials:n.credentials()}},Q9=(n,t)=>{let i=Object.assign(Y7(n),iY(n),TY(n),X9(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,X7(i),rY(i),gY(i),J9(i))};class Bd extends Gl{config;constructor(...[n]){let t=Y9(n||{});super(t);this.initConfig=t;let i=xY(t),r=J7(i),s=bY(r),f=uY(s),_=Q7(f),o=MY(_),h=KY(o),e=Q9(h,n?.extensions||[]);this.config=e,this.middlewareStack.use(UY(this.config)),this.middlewareStack.use(a7(this.config)),this.middlewareStack.use(NY(this.config)),this.middlewareStack.use(OY(this.config)),this.middlewareStack.use(z7(this.config)),this.middlewareStack.use(K7(this.config)),this.middlewareStack.use(x7(this.config)),this.middlewareStack.use(j7(this.config,{httpAuthSchemeParametersProvider:JY,identityProviderConfigProvider:async(c)=>new q7({"aws.auth#sigv4":c.credentials})})),this.middlewareStack.use(k7(this.config))}destroy(){super.destroy()}}var a9=sY(VY,"AWSSSOOIDCService","SSOOIDCClient",EY),z9={},K9=(n,t,i,r)=>[];class Gd extends a9(z9,K9,"CreateToken",tT){}var x9={CreateTokenCommand:Gd};class md extends Bd{}fY(x9,md);var V9={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},j9={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};q9.AccessDeniedException=eh;q9.AccessDeniedException$=Xl;q9.AccessDeniedExceptionReason=V9;q9.AuthorizationPendingException=ch;q9.AuthorizationPendingException$=Jl;q9.CreateToken$=tT;q9.CreateTokenCommand=Gd;q9.CreateTokenRequest$=pl;q9.CreateTokenResponse$=nT;q9.ExpiredTokenException=dh;q9.ExpiredTokenException$=Ql;q9.InternalServerException=uh;q9.InternalServerException$=al;q9.InvalidClientException=wh;q9.InvalidClientException$=zl;q9.InvalidGrantException=yh;q9.InvalidGrantException$=Kl;q9.InvalidRequestException=Ah;q9.InvalidRequestException$=xl;q9.InvalidRequestExceptionReason=j9;q9.InvalidScopeException=Rh;q9.InvalidScopeException$=Vl;q9.SSOOIDC=md;q9.SSOOIDCClient=Bd;q9.SSOOIDCServiceException=qn;q9.SSOOIDCServiceException$=Yl;q9.SlowDownException=Mh;q9.SlowDownException$=jl;q9.UnauthorizedClientException=Eh;q9.UnauthorizedClientException$=ql;q9.UnsupportedGrantTypeException=lh;q9.UnsupportedGrantTypeException$=kl;q9.errorTypeRegistries=Zl});import{createInterface as zx}from"readline/promises";import{Database as lO}from"bun:sqlite";import{existsSync as TO}from"fs";import{homedir as Wu}from"os";import{dirname as gO,join as Oo}from"path";function $i(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 Qt(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 yn(n){let t=n.overageCount??0;if(Number.isFinite(t)&&t>0)return!0;let i=n.usedCount??0,r=n.limitCount??0;return Number.isFinite(i)&&Number.isFinite(r)&&r>0&&i>=r}function Zn(n){return $i(n)}function zr(n){let t=n&&n.length>0?n:"Account needs re-authentication";return $i(t)?t:`InvalidTokenException: ${t}`}var Fu=5000,OO=30000,LO=25,IO=500,SO=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 tf extends Error{constructor(n,t){super(n,t);this.name="OpenCodeAuthStoreError"}}function bO(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return String(n.code).toUpperCase().startsWith("SQLITE_BUSY")}function NO(n,t){let i=Math.min(LO*2**Math.min(n,5),IO,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 Rt(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 UO(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 rf(n=process.env){let t=process.platform==="win32"?n.APPDATA??Oo(Wu(),"AppData","Roaming"):n.XDG_CONFIG_HOME??Oo(Wu(),".config");return Oo(t,"opencode","kiro.db")}function Cu(n){return Oo(gO(n),"kiro-auth-plugin")}class _0{path;db;constructor(n=rf()){this.path=n;if(!TO(n))throw new tf(`OpenCode Kiro auth database not found: ${n}. Run OpenCode Kiro authentication first or set auth_source to "local".`);this.db=new lO(n,{strict:!0}),this.db.run(`PRAGMA busy_timeout = ${Fu}`),this.validateSchema()}getAccounts(){return this.db.query(`
|
|
51
51
|
SELECT accounts.*
|
|
52
52
|
FROM accounts
|
|
53
53
|
WHERE NOT EXISTS (
|
|
54
54
|
SELECT 1 FROM removed_accounts
|
|
55
55
|
WHERE removed_accounts.id = accounts.id
|
|
56
56
|
)
|
|
57
|
-
`).all().map(
|
|
57
|
+
`).all().map(Rt)}getById(n){let t=this.selectById(n);return t===void 0?void 0:Rt(t)}recordSelection(n,t){return this.withImmediateTransaction(()=>{if(this.db.query(`
|
|
58
58
|
UPDATE accounts
|
|
59
59
|
SET last_used = ?,
|
|
60
60
|
used_count = COALESCE(used_count, 0) + 1
|
|
@@ -63,11 +63,11 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
63
63
|
SELECT 1 FROM removed_accounts
|
|
64
64
|
WHERE removed_accounts.id = accounts.id
|
|
65
65
|
)
|
|
66
|
-
`).run(t,n).changes!==1)return;let r=this.selectById(n);return r===void 0?void 0:
|
|
66
|
+
`).run(t,n).changes!==1)return;let r=this.selectById(n);return r===void 0?void 0:Rt(r)})}markRateLimited(n,t){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
67
67
|
UPDATE accounts
|
|
68
68
|
SET rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
69
69
|
WHERE id = ?
|
|
70
|
-
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:
|
|
70
|
+
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:Rt(i)})}markQuotaExhausted(n,t){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
71
71
|
UPDATE accounts
|
|
72
72
|
SET used_count = CASE
|
|
73
73
|
WHEN COALESCE(limit_count, 0) > 0
|
|
@@ -76,11 +76,11 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
76
76
|
END,
|
|
77
77
|
rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
78
78
|
WHERE id = ?
|
|
79
|
-
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:
|
|
79
|
+
`).run(t,n);let i=this.selectById(n);return i===void 0?void 0:Rt(i)})}scheduleQuotaRecheck(n,t){return this.withImmediateTransaction(()=>{let i=this.selectById(n);if(i===void 0)return;let r=Rt(i);if(!yn(r))return r;this.db.query(`
|
|
80
80
|
UPDATE accounts
|
|
81
81
|
SET rate_limit_reset = MAX(COALESCE(rate_limit_reset, 0), ?)
|
|
82
82
|
WHERE id = ?
|
|
83
|
-
`).run(t,n);let s=this.selectById(n);return s===void 0?void 0:
|
|
83
|
+
`).run(t,n);let s=this.selectById(n);return s===void 0?void 0:Rt(s)})}updateQuotaUsage(n,t,i){return this.withImmediateTransaction(()=>{let r=this.selectById(n);if(r===void 0)return;let s=Rt(r);if((s.lastSync??0)>t.lastSync)return s;let f=yn(s),o=yn(t)?Math.max(s.rateLimitResetTime,i):f?0:s.rateLimitResetTime;this.db.query(`
|
|
84
84
|
UPDATE accounts
|
|
85
85
|
SET email = COALESCE(?, email),
|
|
86
86
|
used_count = ?,
|
|
@@ -89,7 +89,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
89
89
|
last_sync = ?,
|
|
90
90
|
rate_limit_reset = ?
|
|
91
91
|
WHERE id = ?
|
|
92
|
-
`).run(t.email??null,t.usedCount,t.limitCount,t.overageCount,t.lastSync,
|
|
92
|
+
`).run(t.email??null,t.usedCount,t.limitCount,t.overageCount,t.lastSync,o,n);let h=this.selectById(n);return h===void 0?void 0:Rt(h)})}markUnhealthy(n,t,i,r,s){return this.withImmediateTransaction(()=>{if(i)this.db.query(`
|
|
93
93
|
UPDATE accounts
|
|
94
94
|
SET fail_count = 10,
|
|
95
95
|
is_healthy = 0,
|
|
@@ -110,7 +110,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
110
110
|
END,
|
|
111
111
|
last_used = ?
|
|
112
112
|
WHERE id = ?
|
|
113
|
-
`).run(t,r??s+3600000,s,n);let f=this.selectById(n);return f===void 0?void 0:
|
|
113
|
+
`).run(t,r??s+3600000,s,n);let f=this.selectById(n);return f===void 0?void 0:Rt(f)})}persistRefreshedAccount(n,t){return this.withImmediateTransaction(()=>{let i=this.selectById(n.id);if(i===void 0)return;let r=Rt(i);if(!UO(n,r))return r;this.db.query(`
|
|
114
114
|
UPDATE accounts
|
|
115
115
|
SET email = ?,
|
|
116
116
|
oidc_region = ?,
|
|
@@ -127,7 +127,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
127
127
|
fail_count = 0,
|
|
128
128
|
last_used = ?
|
|
129
129
|
WHERE id = ?
|
|
130
|
-
`).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:
|
|
130
|
+
`).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:Rt(s)})}close(){this.db.close()}selectById(n){let t=this.db.query(`
|
|
131
131
|
SELECT accounts.*
|
|
132
132
|
FROM accounts
|
|
133
133
|
WHERE accounts.id = ?
|
|
@@ -135,18 +135,18 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
135
135
|
SELECT 1 FROM removed_accounts
|
|
136
136
|
WHERE removed_accounts.id = accounts.id
|
|
137
137
|
)
|
|
138
|
-
`).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 js(`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=[...qO].filter((r)=>!t.has(r));if(i.length>0)throw new js(`OpenCode Kiro auth database ${this.path} is missing required account columns: ${i.join(", ")}`)}withImmediateTransaction(n){let t=Date.now()+VO,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 = ${eu}`)}if(!r){if(!kO(s))throw s;let f=t-Date.now();if(f<=0)throw new js(`Timed out waiting for the OpenCode Kiro auth database write lock: ${this.path}`,{cause:s});aO(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 c8,readFileSync as d8}from"fs";import{homedir as u8}from"os";import{join as Gu}from"path";var A={};QO(A,{void:()=>FL,util:()=>hn,unknown:()=>HL,union:()=>CL,undefined:()=>DL,tuple:()=>mL,transformer:()=>vL,symbol:()=>UL,string:()=>Uu,strictObject:()=>XL,setErrorMap:()=>nL,set:()=>VL,record:()=>zL,quotelessJson:()=>vO,promise:()=>ZL,preprocess:()=>t8,pipeline:()=>i8,ostring:()=>r8,optional:()=>pL,onumber:()=>s8,oboolean:()=>f8,objectUtil:()=>j0,object:()=>PL,number:()=>Du,nullable:()=>n8,null:()=>BL,never:()=>WL,nativeEnum:()=>aL,nan:()=>SL,map:()=>KL,makeIssue:()=>ks,literal:()=>qL,lazy:()=>jL,late:()=>NL,isValid:()=>Ni,isDirty:()=>c_,isAsync:()=>Cr,isAborted:()=>w_,intersection:()=>QL,instanceof:()=>bL,getParsedType:()=>Jt,getErrorMap:()=>Xr,function:()=>xL,enum:()=>kL,effect:()=>vL,discriminatedUnion:()=>JL,defaultErrorMap:()=>ri,datetimeRegex:()=>Su,date:()=>$L,custom:()=>$u,coerce:()=>_8,boolean:()=>Bu,bigint:()=>lL,array:()=>YL,any:()=>GL,addIssueToContext:()=>D,ZodVoid:()=>Zs,ZodUnknown:()=>bi,ZodUnion:()=>Vr,ZodUndefined:()=>zr,ZodType:()=>sn,ZodTuple:()=>mt,ZodTransformer:()=>lt,ZodSymbol:()=>as,ZodString:()=>gt,ZodSet:()=>nr,ZodSchema:()=>sn,ZodRecord:()=>vs,ZodReadonly:()=>vr,ZodPromise:()=>tr,ZodPipeline:()=>tf,ZodParsedType:()=>$,ZodOptional:()=>bt,ZodObject:()=>bn,ZodNumber:()=>Si,ZodNullable:()=>fi,ZodNull:()=>Kr,ZodNever:()=>Qt,ZodNativeEnum:()=>kr,ZodNaN:()=>nf,ZodMap:()=>ps,ZodLiteral:()=>qr,ZodLazy:()=>jr,ZodIssueCode:()=>S,ZodIntersection:()=>xr,ZodFunction:()=>Qr,ZodFirstPartyTypeKind:()=>q,ZodError:()=>an,ZodEnum:()=>$i,ZodEffects:()=>lt,ZodDiscriminatedUnion:()=>d_,ZodDefault:()=>ar,ZodDate:()=>vi,ZodCatch:()=>Zr,ZodBranded:()=>u_,ZodBoolean:()=>mr,ZodBigInt:()=>li,ZodArray:()=>Nt,ZodAny:()=>pi,Schema:()=>sn,ParseStatus:()=>Xn,OK:()=>Kn,NEVER:()=>h8,INVALID:()=>x,EMPTY_PATH:()=>tL,DIRTY:()=>Zi,BRAND:()=>gL});var hn;(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}})(hn||(hn={}));var j0;(function(n){n.mergeShapes=(t,i)=>{return{...t,...i}}})(j0||(j0={}));var $=hn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Jt=(n)=>{switch(typeof n){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(n)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(n))return $.array;if(n===null)return $.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return $.promise;if(typeof Map<"u"&&n instanceof Map)return $.map;if(typeof Set<"u"&&n instanceof Set)return $.set;if(typeof Date<"u"&&n instanceof Date)return $.date;return $.object;default:return $.unknown}};var S=hn.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"]),vO=(n)=>{return JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:")};class an 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 o=f.path[_];if(_!==f.path.length-1)h[o]=h[o]||{_errors:[]};else h[o]=h[o]||{_errors:[]},h[o]._errors.push(t(f));h=h[o],_++}}};return r(this),i}static assert(n){if(!(n instanceof an))throw Error(`Not a ZodError: ${n}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,hn.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()}}an.create=(n)=>{return new an(n)};var pO=(n,t)=>{let i;switch(n.code){case S.invalid_type:if(n.received===$.undefined)i="Required";else i=`Expected ${n.expected}, received ${n.received}`;break;case S.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,hn.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:i=`Unrecognized key(s) in object: ${hn.joinValues(n.keys,", ")}`;break;case S.invalid_union:i="Invalid input";break;case S.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${hn.joinValues(n.options)}`;break;case S.invalid_enum_value:i=`Invalid enum value. Expected ${hn.joinValues(n.options)}, received '${n.received}'`;break;case S.invalid_arguments:i="Invalid function arguments";break;case S.invalid_return_type:i="Invalid function return type";break;case S.invalid_date:i="Invalid date";break;case S.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 hn.assertNever(n.validation);else if(n.validation!=="regex")i=`Invalid ${n.validation}`;else i="Invalid";break;case S.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 S.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 S.custom:i="Invalid input";break;case S.invalid_intersection_types:i="Intersection results could not be merged";break;case S.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case S.not_finite:i="Number must be finite";break;default:i=t.defaultError,hn.assertNever(n)}return{message:i}},ri=pO;var Lu=ri;function nL(n){Lu=n}function Xr(){return Lu}var ks=(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 _="",o=r.filter((w)=>!!w).slice().reverse();for(let w of o)_=w(h,{data:t,defaultError:_}).message;return{...s,path:f,message:_}},tL=[];function D(n,t){let i=Xr(),r=ks({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,i,i===ri?void 0:ri].filter((s)=>!!s)});n.common.issues.push(r)}class Xn{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 x;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 Xn.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 x;if(f.status==="aborted")return x;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 x=Object.freeze({status:"aborted"}),Zi=(n)=>({status:"dirty",value:n}),Kn=(n)=>({status:"valid",value:n}),w_=(n)=>n.status==="aborted",c_=(n)=>n.status==="dirty",Ni=(n)=>n.status==="valid",Cr=(n)=>typeof Promise<"u"&&n instanceof Promise;var Q;(function(n){n.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},n.toString=(t)=>typeof t==="string"?t:t?.message})(Q||(Q={}));class St{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 Iu=(n,t)=>{if(Ni(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 an(n.common.issues);return this._error=i,this._error}}}};function p(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:o}=n;if(h.code==="invalid_enum_value")return{message:o??_.defaultError};if(typeof _.data>"u")return{message:o??r??_.defaultError};if(h.code!=="invalid_type")return{message:_.defaultError};return{message:o??i??_.defaultError}},description:s}}class sn{get description(){return this._def.description}_getType(n){return Jt(n.data)}_getOrReturnCtx(n,t){return t||{common:n.parent.common,data:n.data,parsedType:Jt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new Xn,ctx:{common:n.parent.common,data:n.data,parsedType:Jt(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let t=this._parse(n);if(Cr(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:Jt(n)},r=this._parseSync({data:n,path:i.path,parent:i});return Iu(i,r)}"~validate"(n){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:Jt(n)};if(!this["~standard"].async)try{let i=this._parseSync({data:n,path:[],parent:t});return Ni(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)=>Ni(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:Jt(n)},r=this._parse({data:n,path:i.path,parent:i}),s=await(Cr(r)?r:Promise.resolve(r));return Iu(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:S.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 lt({schema:this,typeName:q.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 bt.create(this,this._def)}nullable(){return fi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nt.create(this)}promise(){return tr.create(this,this._def)}or(n){return Vr.create([this,n],this._def)}and(n){return xr.create(this,n,this._def)}transform(n){return new lt({...p(this._def),schema:this,typeName:q.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let t=typeof n==="function"?n:()=>n;return new ar({...p(this._def),innerType:this,defaultValue:t,typeName:q.ZodDefault})}brand(){return new u_({typeName:q.ZodBranded,type:this,...p(this._def)})}catch(n){let t=typeof n==="function"?n:()=>n;return new Zr({...p(this._def),innerType:this,catchValue:t,typeName:q.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return tf.create(this,n)}readonly(){return vr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var iL=/^c[^\s-]{8,}$/i,rL=/^[0-9a-z]+$/,sL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fL=/^[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,_L=/^[a-z0-9_-]{21}$/i,hL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oL=/^[-+]?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)?)??$/,wL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,cL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",q0,dL=/^(?:(?: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])$/,uL=/^(?:(?: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])$/,yL=/^(([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]))$/,AL=/^(([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])$/,RL=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ML=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nu="((\\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])))",EL=new RegExp(`^${Nu}$`);function bu(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 TL(n){return new RegExp(`^${bu(n)}$`)}function Su(n){let t=`${Nu}T${bu(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 eL(n,t){if((t==="v4"||!t)&&dL.test(n))return!0;if((t==="v6"||!t)&&yL.test(n))return!0;return!1}function OL(n,t){if(!hL.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 LL(n,t){if((t==="v4"||!t)&&uL.test(n))return!0;if((t==="v6"||!t)&&AL.test(n))return!0;return!1}class gt extends sn{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==$.string){let s=this._getOrReturnCtx(n);return D(s,{code:S.invalid_type,expected:$.string,received:s.parsedType}),x}let i=new Xn,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),D(r,{code:S.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),D(r,{code:S.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)D(r,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});else if(h)D(r,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});i.dirty()}}else if(s.kind==="email"){if(!wL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"email",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="emoji"){if(!q0)q0=new RegExp(cL,"u");if(!q0.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"emoji",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="uuid"){if(!fL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"uuid",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="nanoid"){if(!_L.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"nanoid",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid"){if(!iL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"cuid",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid2"){if(!rL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"cuid2",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ulid"){if(!sL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"ulid",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="url")try{new URL(n.data)}catch{r=this._getOrReturnCtx(n,r),D(r,{validation:"url",code:S.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),D(r,{validation:"regex",code:S.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),D(r,{code:S.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),D(r,{code:S.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),D(r,{code:S.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()}else if(s.kind==="datetime"){if(!Su(s).test(n.data))r=this._getOrReturnCtx(n,r),D(r,{code:S.invalid_string,validation:"datetime",message:s.message}),i.dirty()}else if(s.kind==="date"){if(!EL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{code:S.invalid_string,validation:"date",message:s.message}),i.dirty()}else if(s.kind==="time"){if(!TL(s).test(n.data))r=this._getOrReturnCtx(n,r),D(r,{code:S.invalid_string,validation:"time",message:s.message}),i.dirty()}else if(s.kind==="duration"){if(!oL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"duration",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ip"){if(!eL(n.data,s.version))r=this._getOrReturnCtx(n,r),D(r,{validation:"ip",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="jwt"){if(!OL(n.data,s.alg))r=this._getOrReturnCtx(n,r),D(r,{validation:"jwt",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cidr"){if(!LL(n.data,s.version))r=this._getOrReturnCtx(n,r),D(r,{validation:"cidr",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64"){if(!RL.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"base64",code:S.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64url"){if(!ML.test(n.data))r=this._getOrReturnCtx(n,r),D(r,{validation:"base64url",code:S.invalid_string,message:s.message}),i.dirty()}else hn.assertNever(s);return{status:i.value,value:n.data}}_regex(n,t,i){return this.refinement((r)=>n.test(r),{validation:t,code:S.invalid_string,...Q.errToObj(i)})}_addCheck(n){return new gt({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...Q.errToObj(n)})}url(n){return this._addCheck({kind:"url",...Q.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...Q.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...Q.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...Q.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...Q.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...Q.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...Q.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...Q.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...Q.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...Q.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...Q.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...Q.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,...Q.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,...Q.errToObj(n?.message)})}duration(n){return this._addCheck({kind:"duration",...Q.errToObj(n)})}regex(n,t){return this._addCheck({kind:"regex",regex:n,...Q.errToObj(t)})}includes(n,t){return this._addCheck({kind:"includes",value:n,position:t?.position,...Q.errToObj(t?.message)})}startsWith(n,t){return this._addCheck({kind:"startsWith",value:n,...Q.errToObj(t)})}endsWith(n,t){return this._addCheck({kind:"endsWith",value:n,...Q.errToObj(t)})}min(n,t){return this._addCheck({kind:"min",value:n,...Q.errToObj(t)})}max(n,t){return this._addCheck({kind:"max",value:n,...Q.errToObj(t)})}length(n,t){return this._addCheck({kind:"length",value:n,...Q.errToObj(t)})}nonempty(n){return this.min(1,Q.errToObj(n))}trim(){return new gt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new gt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new gt({...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}}gt.create=(n)=>{return new gt({checks:[],typeName:q.ZodString,coerce:n?.coerce??!1,...p(n)})};function IL(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 Si extends sn{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)!==$.number){let s=this._getOrReturnCtx(n);return D(s,{code:S.invalid_type,expected:$.number,received:s.parsedType}),x}let i=void 0,r=new Xn;for(let s of this._def.checks)if(s.kind==="int"){if(!hn.isInteger(n.data))i=this._getOrReturnCtx(n,i),D(i,{code:S.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),D(i,{code:S.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),D(i,{code:S.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="multipleOf"){if(IL(n.data,s.value)!==0)i=this._getOrReturnCtx(n,i),D(i,{code:S.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),D(i,{code:S.not_finite,message:s.message}),r.dirty()}else hn.assertNever(s);return{status:r.value,value:n.data}}gte(n,t){return this.setLimit("min",n,!0,Q.toString(t))}gt(n,t){return this.setLimit("min",n,!1,Q.toString(t))}lte(n,t){return this.setLimit("max",n,!0,Q.toString(t))}lt(n,t){return this.setLimit("max",n,!1,Q.toString(t))}setLimit(n,t,i,r){return new Si({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:Q.toString(r)}]})}_addCheck(n){return new Si({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:Q.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Q.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Q.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Q.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Q.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:Q.toString(t)})}finite(n){return this._addCheck({kind:"finite",message:Q.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Q.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Q.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"&&hn.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)}}Si.create=(n)=>{return new Si({checks:[],typeName:q.ZodNumber,coerce:n?.coerce||!1,...p(n)})};class li extends sn{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)!==$.bigint)return this._getInvalidInput(n);let i=void 0,r=new Xn;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),D(i,{code:S.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),D(i,{code:S.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),D(i,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()}else hn.assertNever(s);return{status:r.value,value:n.data}}_getInvalidInput(n){let t=this._getOrReturnCtx(n);return D(t,{code:S.invalid_type,expected:$.bigint,received:t.parsedType}),x}gte(n,t){return this.setLimit("min",n,!0,Q.toString(t))}gt(n,t){return this.setLimit("min",n,!1,Q.toString(t))}lte(n,t){return this.setLimit("max",n,!0,Q.toString(t))}lt(n,t){return this.setLimit("max",n,!1,Q.toString(t))}setLimit(n,t,i,r){return new li({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:Q.toString(r)}]})}_addCheck(n){return new li({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Q.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Q.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Q.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Q.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:Q.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}}li.create=(n)=>{return new li({checks:[],typeName:q.ZodBigInt,coerce:n?.coerce??!1,...p(n)})};class mr extends sn{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==$.boolean){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.boolean,received:i.parsedType}),x}return Kn(n.data)}}mr.create=(n)=>{return new mr({typeName:q.ZodBoolean,coerce:n?.coerce||!1,...p(n)})};class vi extends sn{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==$.date){let s=this._getOrReturnCtx(n);return D(s,{code:S.invalid_type,expected:$.date,received:s.parsedType}),x}if(Number.isNaN(n.data.getTime())){let s=this._getOrReturnCtx(n);return D(s,{code:S.invalid_date}),x}let i=new Xn,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),D(r,{code:S.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),D(r,{code:S.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()}else hn.assertNever(s);return{status:i.value,value:new Date(n.data.getTime())}}_addCheck(n){return new vi({...this._def,checks:[...this._def.checks,n]})}min(n,t){return this._addCheck({kind:"min",value:n.getTime(),message:Q.toString(t)})}max(n,t){return this._addCheck({kind:"max",value:n.getTime(),message:Q.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}}vi.create=(n)=>{return new vi({checks:[],coerce:n?.coerce||!1,typeName:q.ZodDate,...p(n)})};class as extends sn{_parse(n){if(this._getType(n)!==$.symbol){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.symbol,received:i.parsedType}),x}return Kn(n.data)}}as.create=(n)=>{return new as({typeName:q.ZodSymbol,...p(n)})};class zr extends sn{_parse(n){if(this._getType(n)!==$.undefined){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.undefined,received:i.parsedType}),x}return Kn(n.data)}}zr.create=(n)=>{return new zr({typeName:q.ZodUndefined,...p(n)})};class Kr extends sn{_parse(n){if(this._getType(n)!==$.null){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.null,received:i.parsedType}),x}return Kn(n.data)}}Kr.create=(n)=>{return new Kr({typeName:q.ZodNull,...p(n)})};class pi extends sn{constructor(){super(...arguments);this._any=!0}_parse(n){return Kn(n.data)}}pi.create=(n)=>{return new pi({typeName:q.ZodAny,...p(n)})};class bi extends sn{constructor(){super(...arguments);this._unknown=!0}_parse(n){return Kn(n.data)}}bi.create=(n)=>{return new bi({typeName:q.ZodUnknown,...p(n)})};class Qt extends sn{_parse(n){let t=this._getOrReturnCtx(n);return D(t,{code:S.invalid_type,expected:$.never,received:t.parsedType}),x}}Qt.create=(n)=>{return new Qt({typeName:q.ZodNever,...p(n)})};class Zs extends sn{_parse(n){if(this._getType(n)!==$.undefined){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.void,received:i.parsedType}),x}return Kn(n.data)}}Zs.create=(n)=>{return new Zs({typeName:q.ZodVoid,...p(n)})};class Nt extends sn{_parse(n){let{ctx:t,status:i}=this._processInputParams(n),r=this._def;if(t.parsedType!==$.array)return D(t,{code:S.invalid_type,expected:$.array,received:t.parsedType}),x;if(r.exactLength!==null){let f=t.data.length>r.exactLength.value,h=t.data.length<r.exactLength.value;if(f||h)D(t,{code:f?S.too_big:S.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)D(t,{code:S.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)D(t,{code:S.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 St(t,f,t.path,h))})).then((f)=>{return Xn.mergeArray(i,f)});let s=[...t.data].map((f,h)=>{return r.type._parseSync(new St(t,f,t.path,h))});return Xn.mergeArray(i,s)}get element(){return this._def.type}min(n,t){return new Nt({...this._def,minLength:{value:n,message:Q.toString(t)}})}max(n,t){return new Nt({...this._def,maxLength:{value:n,message:Q.toString(t)}})}length(n,t){return new Nt({...this._def,exactLength:{value:n,message:Q.toString(t)}})}nonempty(n){return this.min(1,n)}}Nt.create=(n,t)=>{return new Nt({type:n,minLength:null,maxLength:null,exactLength:null,typeName:q.ZodArray,...p(t)})};function Jr(n){if(n instanceof bn){let t={};for(let i in n.shape){let r=n.shape[i];t[i]=bt.create(Jr(r))}return new bn({...n._def,shape:()=>t})}else if(n instanceof Nt)return new Nt({...n._def,type:Jr(n.element)});else if(n instanceof bt)return bt.create(Jr(n.unwrap()));else if(n instanceof fi)return fi.create(Jr(n.unwrap()));else if(n instanceof mt)return mt.create(n.items.map((t)=>Jr(t)));else return n}class bn extends sn{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=hn.objectKeys(n);return this._cached={shape:n,keys:t},this._cached}_parse(n){if(this._getType(n)!==$.object){let o=this._getOrReturnCtx(n);return D(o,{code:S.invalid_type,expected:$.object,received:o.parsedType}),x}let{status:i,ctx:r}=this._processInputParams(n),{shape:s,keys:f}=this._getCached(),h=[];if(!(this._def.catchall instanceof Qt&&this._def.unknownKeys==="strip")){for(let o in r.data)if(!f.includes(o))h.push(o)}let _=[];for(let o of f){let w=s[o],c=r.data[o];_.push({key:{status:"valid",value:o},value:w._parse(new St(r,c,r.path,o)),alwaysSet:o in r.data})}if(this._def.catchall instanceof Qt){let o=this._def.unknownKeys;if(o==="passthrough")for(let w of h)_.push({key:{status:"valid",value:w},value:{status:"valid",value:r.data[w]}});else if(o==="strict"){if(h.length>0)D(r,{code:S.unrecognized_keys,keys:h}),i.dirty()}else if(o==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let o=this._def.catchall;for(let w of h){let c=r.data[w];_.push({key:{status:"valid",value:w},value:o._parse(new St(r,c,r.path,w)),alwaysSet:w in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let o=[];for(let w of _){let c=await w.key,d=await w.value;o.push({key:c,value:d,alwaysSet:w.alwaysSet})}return o}).then((o)=>{return Xn.mergeObjectSync(i,o)});else return Xn.mergeObjectSync(i,_)}get shape(){return this._def.shape()}strict(n){return Q.errToObj,new bn({...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:Q.errToObj(n).message??r};return{message:r}}}:{}})}strip(){return new bn({...this._def,unknownKeys:"strip"})}passthrough(){return new bn({...this._def,unknownKeys:"passthrough"})}extend(n){return new bn({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new bn({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:q.ZodObject})}setKey(n,t){return this.augment({[n]:t})}catchall(n){return new bn({...this._def,catchall:n})}pick(n){let t={};for(let i of hn.objectKeys(n))if(n[i]&&this.shape[i])t[i]=this.shape[i];return new bn({...this._def,shape:()=>t})}omit(n){let t={};for(let i of hn.objectKeys(this.shape))if(!n[i])t[i]=this.shape[i];return new bn({...this._def,shape:()=>t})}deepPartial(){return Jr(this)}partial(n){let t={};for(let i of hn.objectKeys(this.shape)){let r=this.shape[i];if(n&&!n[i])t[i]=r;else t[i]=r.optional()}return new bn({...this._def,shape:()=>t})}required(n){let t={};for(let i of hn.objectKeys(this.shape))if(n&&!n[i])t[i]=this.shape[i];else{let s=this.shape[i];while(s instanceof bt)s=s._def.innerType;t[i]=s}return new bn({...this._def,shape:()=>t})}keyof(){return lu(hn.objectKeys(this.shape))}}bn.create=(n,t)=>{return new bn({shape:()=>n,unknownKeys:"strip",catchall:Qt.create(),typeName:q.ZodObject,...p(t)})};bn.strictCreate=(n,t)=>{return new bn({shape:()=>n,unknownKeys:"strict",catchall:Qt.create(),typeName:q.ZodObject,...p(t)})};bn.lazycreate=(n,t)=>{return new bn({shape:n,unknownKeys:"strip",catchall:Qt.create(),typeName:q.ZodObject,...p(t)})};class Vr extends sn{_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 an(h.ctx.common.issues));return D(t,{code:S.invalid_union,unionErrors:f}),x}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 o={...t,common:{...t.common,issues:[]},parent:null},w=_._parseSync({data:t.data,path:t.path,parent:o});if(w.status==="valid")return w;else if(w.status==="dirty"&&!s)s={result:w,ctx:o};if(o.common.issues.length)f.push(o.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let h=f.map((_)=>new an(_));return D(t,{code:S.invalid_union,unionErrors:h}),x}}get options(){return this._def.options}}Vr.create=(n,t)=>{return new Vr({options:n,typeName:q.ZodUnion,...p(t)})};var si=(n)=>{if(n instanceof jr)return si(n.schema);else if(n instanceof lt)return si(n.innerType());else if(n instanceof qr)return[n.value];else if(n instanceof $i)return n.options;else if(n instanceof kr)return hn.objectValues(n.enum);else if(n instanceof ar)return si(n._def.innerType);else if(n instanceof zr)return[void 0];else if(n instanceof Kr)return[null];else if(n instanceof bt)return[void 0,...si(n.unwrap())];else if(n instanceof fi)return[null,...si(n.unwrap())];else if(n instanceof u_)return si(n.unwrap());else if(n instanceof vr)return si(n.unwrap());else if(n instanceof Zr)return si(n._def.innerType);else return[]};class d_ extends sn{_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.object)return D(t,{code:S.invalid_type,expected:$.object,received:t.parsedType}),x;let i=this.discriminator,r=t.data[i],s=this.optionsMap.get(r);if(!s)return D(t,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),x;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=si(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 d_({typeName:q.ZodDiscriminatedUnion,discriminator:n,options:t,optionsMap:r,...p(i)})}}function k0(n,t){let i=Jt(n),r=Jt(t);if(n===t)return{valid:!0,data:n};else if(i===$.object&&r===$.object){let s=hn.objectKeys(t),f=hn.objectKeys(n).filter((_)=>s.indexOf(_)!==-1),h={...n,...t};for(let _ of f){let o=k0(n[_],t[_]);if(!o.valid)return{valid:!1};h[_]=o.data}return{valid:!0,data:h}}else if(i===$.array&&r===$.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],o=k0(h,_);if(!o.valid)return{valid:!1};s.push(o.data)}return{valid:!0,data:s}}else if(i===$.date&&r===$.date&&+n===+t)return{valid:!0,data:n};else return{valid:!1}}class xr extends sn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n),r=(s,f)=>{if(w_(s)||w_(f))return x;let h=k0(s.value,f.value);if(!h.valid)return D(i,{code:S.invalid_intersection_types}),x;if(c_(s)||c_(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}))}}xr.create=(n,t,i)=>{return new xr({left:n,right:t,typeName:q.ZodIntersection,...p(i)})};class mt extends sn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==$.array)return D(i,{code:S.invalid_type,expected:$.array,received:i.parsedType}),x;if(i.data.length<this._def.items.length)return D(i,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;if(!this._def.rest&&i.data.length>this._def.items.length)D(i,{code:S.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 St(i,f,i.path,h))}).filter((f)=>!!f);if(i.common.async)return Promise.all(s).then((f)=>{return Xn.mergeArray(t,f)});else return Xn.mergeArray(t,s)}get items(){return this._def.items}rest(n){return new mt({...this._def,rest:n})}}mt.create=(n,t)=>{if(!Array.isArray(n))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:n,typeName:q.ZodTuple,rest:null,...p(t)})};class vs extends sn{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!==$.object)return D(i,{code:S.invalid_type,expected:$.object,received:i.parsedType}),x;let r=[],s=this._def.keyType,f=this._def.valueType;for(let h in i.data)r.push({key:s._parse(new St(i,h,i.path,h)),value:f._parse(new St(i,i.data[h],i.path,h)),alwaysSet:h in i.data});if(i.common.async)return Xn.mergeObjectAsync(t,r);else return Xn.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(n,t,i){if(t instanceof sn)return new vs({keyType:n,valueType:t,typeName:q.ZodRecord,...p(i)});return new vs({keyType:gt.create(),valueType:n,typeName:q.ZodRecord,...p(t)})}}class ps extends sn{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!==$.map)return D(i,{code:S.invalid_type,expected:$.map,received:i.parsedType}),x;let r=this._def.keyType,s=this._def.valueType,f=[...i.data.entries()].map(([h,_],o)=>{return{key:r._parse(new St(i,h,i.path,[o,"key"])),value:s._parse(new St(i,_,i.path,[o,"value"]))}});if(i.common.async){let h=new Map;return Promise.resolve().then(async()=>{for(let _ of f){let o=await _.key,w=await _.value;if(o.status==="aborted"||w.status==="aborted")return x;if(o.status==="dirty"||w.status==="dirty")t.dirty();h.set(o.value,w.value)}return{status:t.value,value:h}})}else{let h=new Map;for(let _ of f){let{key:o,value:w}=_;if(o.status==="aborted"||w.status==="aborted")return x;if(o.status==="dirty"||w.status==="dirty")t.dirty();h.set(o.value,w.value)}return{status:t.value,value:h}}}}ps.create=(n,t,i)=>{return new ps({valueType:t,keyType:n,typeName:q.ZodMap,...p(i)})};class nr extends sn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==$.set)return D(i,{code:S.invalid_type,expected:$.set,received:i.parsedType}),x;let r=this._def;if(r.minSize!==null){if(i.data.size<r.minSize.value)D(i,{code:S.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)D(i,{code:S.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 o=new Set;for(let w of _){if(w.status==="aborted")return x;if(w.status==="dirty")t.dirty();o.add(w.value)}return{status:t.value,value:o}}let h=[...i.data.values()].map((_,o)=>s._parse(new St(i,_,i.path,o)));if(i.common.async)return Promise.all(h).then((_)=>f(_));else return f(h)}min(n,t){return new nr({...this._def,minSize:{value:n,message:Q.toString(t)}})}max(n,t){return new nr({...this._def,maxSize:{value:n,message:Q.toString(t)}})}size(n,t){return this.min(n,t).max(n,t)}nonempty(n){return this.min(1,n)}}nr.create=(n,t)=>{return new nr({valueType:n,minSize:null,maxSize:null,typeName:q.ZodSet,...p(t)})};class Qr extends sn{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.function)return D(t,{code:S.invalid_type,expected:$.function,received:t.parsedType}),x;function i(h,_){return ks({data:h,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xr(),ri].filter((o)=>!!o),issueData:{code:S.invalid_arguments,argumentsError:_}})}function r(h,_){return ks({data:h,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xr(),ri].filter((o)=>!!o),issueData:{code:S.invalid_return_type,returnTypeError:_}})}let s={errorMap:t.common.contextualErrorMap},f=t.data;if(this._def.returns instanceof tr){let h=this;return Kn(async function(..._){let o=new an([]),w=await h._def.args.parseAsync(_,s).catch((u)=>{throw o.addIssue(i(_,u)),o}),c=await Reflect.apply(f,this,w);return await h._def.returns._def.type.parseAsync(c,s).catch((u)=>{throw o.addIssue(r(c,u)),o})})}else{let h=this;return Kn(function(..._){let o=h._def.args.safeParse(_,s);if(!o.success)throw new an([i(_,o.error)]);let w=Reflect.apply(f,this,o.data),c=h._def.returns.safeParse(w,s);if(!c.success)throw new an([r(w,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new Qr({...this._def,args:mt.create(n).rest(bi.create())})}returns(n){return new Qr({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,t,i){return new Qr({args:n?n:mt.create([]).rest(bi.create()),returns:t||bi.create(),typeName:q.ZodFunction,...p(i)})}}class jr extends sn{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})}}jr.create=(n,t)=>{return new jr({getter:n,typeName:q.ZodLazy,...p(t)})};class qr extends sn{_parse(n){if(n.data!==this._def.value){let t=this._getOrReturnCtx(n);return D(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:n.data}}get value(){return this._def.value}}qr.create=(n,t)=>{return new qr({value:n,typeName:q.ZodLiteral,...p(t)})};function lu(n,t){return new $i({values:n,typeName:q.ZodEnum,...p(t)})}class $i extends sn{_parse(n){if(typeof n.data!=="string"){let t=this._getOrReturnCtx(n),i=this._def.values;return D(t,{expected:hn.joinValues(i),received:t.parsedType,code:S.invalid_type}),x}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 D(t,{received:t.data,code:S.invalid_enum_value,options:i}),x}return Kn(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 $i.create(n,{...this._def,...t})}exclude(n,t=this._def){return $i.create(this.options.filter((i)=>!n.includes(i)),{...this._def,...t})}}$i.create=lu;class kr extends sn{_parse(n){let t=hn.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(n);if(i.parsedType!==$.string&&i.parsedType!==$.number){let r=hn.objectValues(t);return D(i,{expected:hn.joinValues(r),received:i.parsedType,code:S.invalid_type}),x}if(!this._cache)this._cache=new Set(hn.getValidEnumValues(this._def.values));if(!this._cache.has(n.data)){let r=hn.objectValues(t);return D(i,{received:i.data,code:S.invalid_enum_value,options:r}),x}return Kn(n.data)}get enum(){return this._def.values}}kr.create=(n,t)=>{return new kr({values:n,typeName:q.ZodNativeEnum,...p(t)})};class tr extends sn{unwrap(){return this._def.type}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.promise&&t.common.async===!1)return D(t,{code:S.invalid_type,expected:$.promise,received:t.parsedType}),x;let i=t.parsedType===$.promise?t.data:Promise.resolve(t.data);return Kn(i.then((r)=>{return this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})}))}}tr.create=(n,t)=>{return new tr({type:n,typeName:q.ZodPromise,...p(t)})};class lt extends sn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===q.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(D(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 x;let _=await this._def.schema._parseAsync({data:h,path:i.path,parent:i});if(_.status==="aborted")return x;if(_.status==="dirty")return Zi(_.value);if(t.value==="dirty")return Zi(_.value);return _});else{if(t.value==="aborted")return x;let h=this._def.schema._parseSync({data:f,path:i.path,parent:i});if(h.status==="aborted")return x;if(h.status==="dirty")return Zi(h.value);if(t.value==="dirty")return Zi(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 x;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 x;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(!Ni(f))return x;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(!Ni(f))return x;return Promise.resolve(r.transform(f.value,s)).then((h)=>({status:t.value,value:h}))});hn.assertNever(r)}}lt.create=(n,t,i)=>{return new lt({schema:n,typeName:q.ZodEffects,effect:t,...p(i)})};lt.createWithPreprocess=(n,t,i)=>{return new lt({schema:t,effect:{type:"preprocess",transform:n},typeName:q.ZodEffects,...p(i)})};class bt extends sn{_parse(n){if(this._getType(n)===$.undefined)return Kn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}bt.create=(n,t)=>{return new bt({innerType:n,typeName:q.ZodOptional,...p(t)})};class fi extends sn{_parse(n){if(this._getType(n)===$.null)return Kn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}fi.create=(n,t)=>{return new fi({innerType:n,typeName:q.ZodNullable,...p(t)})};class ar extends sn{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;if(t.parsedType===$.undefined)i=this._def.defaultValue();return this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ar.create=(n,t)=>{return new ar({innerType:n,typeName:q.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...p(t)})};class Zr extends sn{_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(Cr(r))return r.then((s)=>{return{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new an(i.common.issues)},input:i.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new an(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Zr.create=(n,t)=>{return new Zr({innerType:n,typeName:q.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...p(t)})};class nf extends sn{_parse(n){if(this._getType(n)!==$.nan){let i=this._getOrReturnCtx(n);return D(i,{code:S.invalid_type,expected:$.nan,received:i.parsedType}),x}return{status:"valid",value:n.data}}}nf.create=(n)=>{return new nf({typeName:q.ZodNaN,...p(n)})};var gL=Symbol("zod_brand");class u_ extends sn{_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 tf extends sn{_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 x;if(s.status==="dirty")return t.dirty(),Zi(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 x;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 tf({in:n,out:t,typeName:q.ZodPipeline})}}class vr extends sn{_parse(n){let t=this._def.innerType._parse(n),i=(r)=>{if(Ni(r))r.value=Object.freeze(r.value);return r};return Cr(t)?t.then((r)=>i(r)):i(t)}unwrap(){return this._def.innerType}}vr.create=(n,t)=>{return new vr({innerType:n,typeName:q.ZodReadonly,...p(t)})};function gu(n,t){let i=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n;return typeof i==="string"?{message:i}:i}function $u(n,t={},i){if(n)return pi.create().superRefine((r,s)=>{let f=n(r);if(f instanceof Promise)return f.then((h)=>{if(!h){let _=gu(t,r),o=_.fatal??i??!0;s.addIssue({code:"custom",..._,fatal:o})}});if(!f){let h=gu(t,r),_=h.fatal??i??!0;s.addIssue({code:"custom",...h,fatal:_})}return});return pi.create()}var NL={object:bn.lazycreate},q;(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"})(q||(q={}));var bL=(n,t={message:`Input not instance of ${n.name}`})=>$u((i)=>i instanceof n,t),Uu=gt.create,Du=Si.create,SL=nf.create,lL=li.create,Bu=mr.create,$L=vi.create,UL=as.create,DL=zr.create,BL=Kr.create,GL=pi.create,HL=bi.create,WL=Qt.create,FL=Zs.create,YL=Nt.create,PL=bn.create,XL=bn.strictCreate,CL=Vr.create,JL=d_.create,QL=xr.create,mL=mt.create,zL=vs.create,KL=ps.create,VL=nr.create,xL=Qr.create,jL=jr.create,qL=qr.create,kL=$i.create,aL=kr.create,ZL=tr.create,vL=lt.create,pL=bt.create,n8=fi.create,t8=lt.createWithPreprocess,i8=tf.create,r8=()=>Uu().optional(),s8=()=>Du().optional(),f8=()=>Bu().optional(),_8={string:(n)=>gt.create({...n,coerce:!0}),number:(n)=>Si.create({...n,coerce:!0}),boolean:(n)=>mr.create({...n,coerce:!0}),bigint:(n)=>li.create({...n,coerce:!0}),date:(n)=>vi.create({...n,coerce:!0})};var h8=x;var y_=A.enum(["low","medium","high","xhigh","max"]),ir=A.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 o8=A.array(A.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"}),w8=A.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,A.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),a0=A.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,A.string().trim().min(1).nullable()).default(null),Z0=A.object({host:A.string().default("127.0.0.1"),port:A.number().default(8787),api_keys:o8,enable_legacy_chat_completions:A.boolean().default(!1),protocol_projection_mode:A.enum(["safe","legacy-user-prefix"]).default("safe"),session_affinity_mode:A.enum(["explicit-only","legacy-initial-input"]).default("explicit-only"),proxy_url:w8,sdk_http_keep_alive:A.boolean().default(!1),enforce_single_instance:A.boolean().default(!0),instance_lock_path:a0,runtime_endpoint_mode:A.enum(["legacy-q","kiro-runtime"]).default("kiro-runtime"),dynamic_model_catalog:A.boolean().default(!0),model_catalog_ttl_ms:A.number().int().min(1).max(2147483647).default(900000),model_catalog_stale_ttl_ms:A.number().int().min(1).max(2147483647).default(86400000),model_catalog_request_timeout_ms:A.number().int().min(1).max(2147483647).default(1e4),auth_source:A.enum(["opencode-shared","local"]).default("local"),opencode_auth_db_path:a0,default_region:A.string().default("us-east-1"),account_selection_strategy:A.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:A.number().default(3),rate_limit_retry_delay_ms:A.number().default(5000),quota_recheck_interval_ms:A.number().int().min(1).max(2147483647).default(900000),quota_recheck_timeout_ms:A.number().int().min(1).max(2147483647).default(1e4),quota_recheck_concurrency:A.number().int().min(1).max(32).default(4),account_maintenance_enabled:A.boolean().default(!0),account_maintenance_interval_ms:A.number().int().min(1000).max(2147483647).default(60000),account_maintenance_timeout_ms:A.number().int().min(1000).max(2147483647).default(120000),account_maintenance_concurrency:A.number().int().min(1).max(32).default(4),usage_refresh_interval_ms:A.number().int().min(1000).max(2147483647).default(900000),max_request_iterations:A.number().default(20),request_timeout_ms:A.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:A.number().int().min(1).max(2147483647).default(60000),max_request_body_bytes:A.number().default(10485760),token_expiry_buffer_ms:A.number().default(300000),session_affinity_ttl_ms:A.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:A.number().int().min(1).max(1e6).default(1e4),reasoning_replay_key_path:a0,reasoning_replay_keys:A.array(A.string().trim().min(1)).default([]),reasoning_replay_ttl_ms:A.number().int().min(1).max(2147483647).default(86400000),reasoning_replay_max_entries:A.number().int().min(1).max(1e6).default(1e4),effort:y_.nullable().default(null),auto_effort_mapping:A.boolean().default(!0),log_level:A.string().default("info"),test_upstream_endpoint:A.string().url().optional()});class rf extends Error{constructor(n,t){super(n,t);this.name="ConfigLoadError"}}var y8=Z0.partial();function A8(n){let t=n.XDG_CONFIG_HOME??Gu(u8(),".config");return Gu(t,"kiro-provider","config.json")}function R8(n){if(!c8(n))return{};try{let t=JSON.parse(d8(n,"utf8"));return y8.parse(t)}catch(t){if(t instanceof A.ZodError)throw new rf(`Invalid configuration file ${n}: ${Hu(t)}`,{cause:t});if(t instanceof Error)throw new rf(`Unable to read configuration file ${n}: ${t.message}`,{cause:t});throw t}}function M8(n){let t=n.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;return n}function E8(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_RUNTIME_ENDPOINT_MODE:"runtime_endpoint_mode",KIRO_PROVIDER_INSTANCE_LOCK_PATH:"instance_lock_path",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[c,d]of Object.entries(i)){let u=n[c];if(u!==void 0)t[d]=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_QUOTA_RECHECK_INTERVAL_MS:"quota_recheck_interval_ms",KIRO_PROVIDER_QUOTA_RECHECK_TIMEOUT_MS:"quota_recheck_timeout_ms",KIRO_PROVIDER_QUOTA_RECHECK_CONCURRENCY:"quota_recheck_concurrency",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_INTERVAL_MS:"account_maintenance_interval_ms",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_TIMEOUT_MS:"account_maintenance_timeout_ms",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_CONCURRENCY:"account_maintenance_concurrency",KIRO_PROVIDER_USAGE_REFRESH_INTERVAL_MS:"usage_refresh_interval_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_MODEL_CATALOG_TTL_MS:"model_catalog_ttl_ms",KIRO_PROVIDER_MODEL_CATALOG_STALE_TTL_MS:"model_catalog_stale_ttl_ms",KIRO_PROVIDER_MODEL_CATALOG_REQUEST_TIMEOUT_MS:"model_catalog_request_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[c,d]of Object.entries(r)){let u=n[c];if(u!==void 0)t[d]=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 o=n.KIRO_PROVIDER_REASONING_REPLAY_KEYS;if(o!==void 0)t.reasoning_replay_keys=o.split(",").map((c)=>c.trim()).filter((c)=>c.length>0);let w={KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS:"enable_legacy_chat_completions",KIRO_PROVIDER_SDK_HTTP_KEEP_ALIVE:"sdk_http_keep_alive",KIRO_PROVIDER_ENFORCE_SINGLE_INSTANCE:"enforce_single_instance",KIRO_PROVIDER_DYNAMIC_MODEL_CATALOG:"dynamic_model_catalog",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_ENABLED:"account_maintenance_enabled",KIRO_PROVIDER_AUTO_EFFORT_MAPPING:"auto_effort_mapping"};for(let[c,d]of Object.entries(w)){let u=n[c];if(u!==void 0)t[d]=M8(u)}return t}function Hu(n){return n.issues.map((t)=>`${t.path.length>0?t.path.join("."):"config"}: ${t.message}`).join(", ")}function Wu(n={}){let t=n.env??process.env,i=n.configPath??A8(t);try{return Z0.parse({...R8(i),...E8(t),...n.overrides})}catch(r){if(r instanceof rf)throw r;if(r instanceof A.ZodError)throw new rf(`Invalid configuration: ${Hu(r)}`,{cause:r});throw r}}function pr(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 rr(n,t=120000){if(!n.access||!n.expires)return!0;return Date.now()>=n.expires-t}function A_(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`}import{createHash as T8}from"crypto";function Rn(n){return T8("sha256").update("kiro-provider-audit-v1\x00").update(n).digest("hex").slice(0,16)}function k(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}))}function Fu(n){if(typeof n==="object"&&n!==null&&"unref"in n&&typeof n.unref==="function")n.unref()}function e8(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0,i=n instanceof Error?n.message:String(n);return t?`${t}: ${i}`:i}function Yu(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0;return{error_name:n instanceof Error?n.name:"UnknownError",error_code:t}}class R_{options;initialTimer;intervalTimer;lifecycleController=new AbortController;inFlight;constructor(n){this.options=n}start(){if(!this.options.enabled||this.initialTimer!==void 0||this.intervalTimer!==void 0)return;this.lifecycleController=new AbortController;let n=()=>{this.runOnce(this.lifecycleController.signal).catch((t)=>{if(this.lifecycleController.signal.aborted)return;k("warn","account_maintenance_pass_failed",{...Yu(t)})})};this.initialTimer=setTimeout(()=>{this.initialTimer=void 0,n()},this.options.initialDelayMs??5000),this.intervalTimer=setInterval(n,this.options.intervalMs),Fu(this.initialTimer),Fu(this.intervalTimer),k("info","account_maintenance_started",{interval_ms:this.options.intervalMs,timeout_ms:this.options.timeoutMs,concurrency:this.options.concurrency})}stop(){if(this.initialTimer!==void 0)clearTimeout(this.initialTimer),this.initialTimer=void 0;if(this.intervalTimer!==void 0)clearInterval(this.intervalTimer),this.intervalTimer=void 0;if(!this.lifecycleController.signal.aborted)this.lifecycleController.abort(new DOMException("Account maintenance stopped","AbortError"));k("info","account_maintenance_stopped",{})}runOnce(n){if(!this.options.enabled)return Promise.resolve();if(this.inFlight)return this.inFlight;let t=this.runPass(n).finally(()=>{if(this.inFlight===t)this.inFlight=void 0});return this.inFlight=t,t}async runPass(n){let t=Date.now(),i=AbortSignal.timeout(this.options.timeoutMs),r=n?AbortSignal.any([n,i]):i,f=this.options.accountManager.reconcileFromDb().filter((u)=>!It(u.unhealthyReason)&&!en(u)&&rr(this.options.accountManager.toAuthDetails(u),this.options.tokenExpiryBufferMs)),h=0,_=0,o=0,w=async()=>{for(;;){if(r.aborted)throw r.reason;let u=f[o];if(o+=1,!u)return;try{await this.options.tokenRefresher.refreshIfNeeded(u,this.options.accountManager.toAuthDetails(u),r),h+=1}catch(y){_+=1;let R=e8(y);if(gi(R))try{this.options.accountManager.markUnhealthy(u,Pr(R))}catch{}k("warn","account_maintenance_token_refresh_failed",{account_hash:Rn(u.id),...Yu(y)})}}};await Promise.all(Array.from({length:Math.min(this.options.concurrency,f.length)},w));let c=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.recheckDueAccounts(c,r);let d=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.syncDueAccounts(d,r),k("info","account_maintenance_pass_completed",{account_count:d.length,token_due_count:f.length,token_refreshed_count:h,token_failed_count:_,duration_ms:Date.now()-t})}}function Pu(n,t){if(!t)return n;t.start();let i=n.stop.bind(n),r=(s)=>{try{t.stop()}finally{i(s)}};try{Object.defineProperty(n,"stop",{configurable:!0,value:r})}catch(s){try{t.stop()}finally{i(!0)}throw s}return n}var v0=4;class p0 extends Error{accountId;constructor(n){super(`Account ${n} changed too frequently to update`);this.accountId=n;this.name="AccountConcurrentUpdateError"}}function O8(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function sr(n){return{...n}}function no(n){return{refresh:A_({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 to{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(n,t,i){this.strategy=t;this.database=i;this.accounts=n.map(sr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(sr)}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:sr(i)}),this.stickyId&&!this.accounts.some(({id:i})=>i===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(n,t){let i=Date.now(),r=this.accounts.filter((f)=>this.isSelectable(f,i)).filter((f)=>t?.has(f.id)??!0).sort((f,h)=>f.id.localeCompare(h.id));if(r.length===0)return null;let s=r.find(({id:f})=>f===n)??this.selectCandidate(r);return this.patchAccount(s.id,(f)=>({...f,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:i,usedCount:(f.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(n,t){return this.patchAccount(n.id,(i)=>({...i,rateLimitResetTime:t}))}markQuotaExhausted(n,t){return this.patchAccount(n.id,(i)=>({...i,usedCount:(i.limitCount??0)>0?Math.max(i.usedCount??0,i.limitCount??0):i.usedCount,rateLimitResetTime:Math.max(i.rateLimitResetTime,t)}))}scheduleQuotaRecheck(n,t){return this.patchAccount(n.id,(i)=>en(i)?{...i,rateLimitResetTime:Math.max(i.rateLimitResetTime,t)}:i)}updateQuotaUsage(n,t,i){for(let r=0;r<v0;r+=1){let s=this.database.getById(n.id);if(!s){this.accounts=this.accounts.filter((o)=>o.id!==n.id);return}if((s.lastSync??0)>t.lastSync)return this.replaceAccount(s),sr(s);let f=en(s),h=en(t),_={...s,email:t.email??s.email,usedCount:t.usedCount,limitCount:t.limitCount,overageCount:t.overageCount,lastSync:t.lastSync,rateLimitResetTime:h?Math.max(s.rateLimitResetTime,i):f?0:s.rateLimitResetTime};if(this.database.updateExistingAccounts([_])===1){let o={..._,generation:s.generation+1};return this.replaceAccount(o),sr(o)}}throw this.reconcileFromDb(),new p0(n.id)}markUnhealthy(n,t,i){let r=Date.now();return this.patchAccount(n.id,(s)=>{if(It(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=pr(t.refresh);for(let r=0;r<v0;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),sr(h)}}this.reconcileFromDb();return}toAuthDetails(n){return no(n)}isSelectable(n,t){if(It(n.unhealthyReason))return!1;if(en(n))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Ct(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 O8(this.strategy)}}patchAccount(n,t){for(let i=0;i<v0;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),sr(f)}}throw this.reconcileFromDb(),new p0(n)}replaceAccount(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(n);else this.accounts[t]=n}}var cy=Z(To(),1);import{existsSync as o6,promises as wy}from"fs";import{join as w6}from"path";var c6={stale:15000,retries:0,realpath:!1},d6=15000,u6=25,y6=250;function A6(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return n.code==="ELOCKED"||n.code==="ENOENT"}function eo(n){return n.reason??new DOMException("The operation was aborted","AbortError")}function R6(n,t){if(t?.aborted)return Promise.reject(eo(t));return new Promise((i,r)=>{let s=setTimeout(()=>{t?.removeEventListener("abort",f),i()},n),f=()=>{clearTimeout(s),r(eo(t))};t?.addEventListener("abort",f,{once:!0})})}function M6(n,t){let i=t.replace(/[^A-Za-z0-9_-]/g,"");return w6(n,`.kiro-refresh-${i}.lock`)}async function E6(n,t){let i=Date.now()+d6,r=0;for(;;){if(t?.aborted)throw eo(t);try{return await cy.default.lock(n,c6)}catch(s){let f=i-Date.now();if(!A6(s)||f<=0)throw s;let h=Math.min(u6*2**Math.min(r,4),y6,f),_=Math.max(1,Math.floor(h/2)),o=_+Math.floor(Math.random()*(h-_+1));r+=1,await R6(o,t)}}}async function dy(n,t,i,r){let s=M6(n,t);if(await wy.mkdir(n,{recursive:!0}),!o6(s))await(await wy.open(s,"a")).close();let f=await E6(s,r);try{return await i()}finally{try{await f()}catch{}}}var Sy=Z(Io(),1);import*as Kt from"net";import*as cf from"tls";import p6 from"assert";import*as Ly from"net";import*as Iy from"http";import{Agent as v6}from"https";var zt=Symbol("AgentBaseInternalState");class go extends Iy.Agent{constructor(n){super(n);this[zt]={}}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(`
|
|
139
|
-
`).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
|
|
138
|
+
`).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 tf(`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=[...SO].filter((r)=>!t.has(r));if(i.length>0)throw new tf(`OpenCode Kiro auth database ${this.path} is missing required account columns: ${i.join(", ")}`)}withImmediateTransaction(n){let t=Date.now()+OO,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 = ${Fu}`)}if(!r){if(!bO(s))throw s;let f=t-Date.now();if(f<=0)throw new tf(`Timed out waiting for the OpenCode Kiro auth database write lock: ${this.path}`,{cause:s});NO(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 J4,readFileSync as Q4}from"fs";import{homedir as a4}from"os";import{join as qu}from"path";var y={};EO(y,{void:()=>u4,util:()=>_n,unknown:()=>c4,union:()=>R4,undefined:()=>_4,tuple:()=>l4,transformer:()=>$4,symbol:()=>o4,string:()=>xu,strictObject:()=>A4,setErrorMap:()=>BO,set:()=>O4,record:()=>T4,quotelessJson:()=>$O,promise:()=>U4,preprocess:()=>G4,pipeline:()=>m4,ostring:()=>H4,optional:()=>D4,onumber:()=>W4,oboolean:()=>F4,objectUtil:()=>h0,object:()=>y4,number:()=>Vu,nullable:()=>B4,null:()=>h4,never:()=>d4,nativeEnum:()=>N4,nan:()=>r4,map:()=>g4,makeIssue:()=>sf,literal:()=>S4,lazy:()=>I4,late:()=>t4,isValid:()=>Di,isDirty:()=>Io,isAsync:()=>xr,isAborted:()=>Lo,intersection:()=>E4,instanceof:()=>i4,getParsedType:()=>at,getErrorMap:()=>Kr,function:()=>L4,enum:()=>b4,effect:()=>$4,discriminatedUnion:()=>M4,defaultErrorMap:()=>_i,datetimeRegex:()=>au,date:()=>f4,custom:()=>Ku,coerce:()=>C4,boolean:()=>ju,bigint:()=>s4,array:()=>w4,any:()=>e4,addIssueToContext:()=>G,ZodVoid:()=>of,ZodUnknown:()=>Bi,ZodUnion:()=>vr,ZodUndefined:()=>kr,ZodType:()=>fn,ZodTuple:()=>Kt,ZodTransformer:()=>Bt,ZodSymbol:()=>ff,ZodString:()=>Nt,ZodSet:()=>sr,ZodSchema:()=>fn,ZodRecord:()=>_f,ZodReadonly:()=>fs,ZodPromise:()=>fr,ZodPipeline:()=>cf,ZodParsedType:()=>$,ZodOptional:()=>$t,ZodObject:()=>In,ZodNumber:()=>Gi,ZodNullable:()=>ei,ZodNull:()=>Zr,ZodNever:()=>zt,ZodNativeEnum:()=>is,ZodNaN:()=>ef,ZodMap:()=>hf,ZodLiteral:()=>ts,ZodLazy:()=>ns,ZodIssueCode:()=>U,ZodIntersection:()=>pr,ZodFunction:()=>jr,ZodFirstPartyTypeKind:()=>j,ZodError:()=>vn,ZodEnum:()=>Hi,ZodEffects:()=>Bt,ZodDiscriminatedUnion:()=>So,ZodDefault:()=>rs,ZodDate:()=>ir,ZodCatch:()=>ss,ZodBranded:()=>bo,ZodBoolean:()=>qr,ZodBigInt:()=>mi,ZodArray:()=>Ut,ZodAny:()=>rr,Schema:()=>fn,ParseStatus:()=>Pn,OK:()=>zn,NEVER:()=>P4,INVALID:()=>x,EMPTY_PATH:()=>GO,DIRTY:()=>tr,BRAND:()=>n4});var _n;(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 _ of s)f[_]=_;return f},n.getValidEnumValues=(s)=>{let f=n.objectKeys(s).filter((o)=>typeof s[s[o]]!=="number"),_={};for(let o of f)_[o]=s[o];return n.objectValues(_)},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 _ in s)if(Object.prototype.hasOwnProperty.call(s,_))f.push(_);return f},n.find=(s,f)=>{for(let _ of s)if(f(_))return _;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((_)=>typeof _==="string"?`'${_}'`:_).join(f)}n.joinValues=r,n.jsonStringifyReplacer=(s,f)=>{if(typeof f==="bigint")return f.toString();return f}})(_n||(_n={}));var h0;(function(n){n.mergeShapes=(t,i)=>{return{...t,...i}}})(h0||(h0={}));var $=_n.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=(n)=>{switch(typeof n){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(n)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(n))return $.array;if(n===null)return $.null;if(n.then&&typeof n.then==="function"&&n.catch&&typeof n.catch==="function")return $.promise;if(typeof Map<"u"&&n instanceof Map)return $.map;if(typeof Set<"u"&&n instanceof Set)return $.set;if(typeof Date<"u"&&n instanceof Date)return $.date;return $.object;default:return $.unknown}};var U=_n.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"]),$O=(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 _=i,o=0;while(o<f.path.length){let h=f.path[o];if(o!==f.path.length-1)_[h]=_[h]||{_errors:[]};else _[h]=_[h]||{_errors:[]},_[h]._errors.push(t(f));_=_[h],o++}}};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,_n.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 DO=(n,t)=>{let i;switch(n.code){case U.invalid_type:if(n.received===$.undefined)i="Required";else i=`Expected ${n.expected}, received ${n.received}`;break;case U.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(n.expected,_n.jsonStringifyReplacer)}`;break;case U.unrecognized_keys:i=`Unrecognized key(s) in object: ${_n.joinValues(n.keys,", ")}`;break;case U.invalid_union:i="Invalid input";break;case U.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${_n.joinValues(n.options)}`;break;case U.invalid_enum_value:i=`Invalid enum value. Expected ${_n.joinValues(n.options)}, received '${n.received}'`;break;case U.invalid_arguments:i="Invalid function arguments";break;case U.invalid_return_type:i="Invalid function return type";break;case U.invalid_date:i="Invalid date";break;case U.invalid_string:if(typeof n.validation==="object")if("includes"in n.validation){if(i=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position==="number")i=`${i} at one or more positions greater than or equal to ${n.validation.position}`}else if("startsWith"in n.validation)i=`Invalid input: must start with "${n.validation.startsWith}"`;else if("endsWith"in n.validation)i=`Invalid input: must end with "${n.validation.endsWith}"`;else _n.assertNever(n.validation);else if(n.validation!=="regex")i=`Invalid ${n.validation}`;else i="Invalid";break;case U.too_small:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="bigint")i=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`;else i="Invalid input";break;case U.too_big:if(n.type==="array")i=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`;else if(n.type==="string")i=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`;else if(n.type==="number")i=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="bigint")i=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`;else if(n.type==="date")i=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`;else i="Invalid input";break;case U.custom:i="Invalid input";break;case U.invalid_intersection_types:i="Intersection results could not be merged";break;case U.not_multiple_of:i=`Number must be a multiple of ${n.multipleOf}`;break;case U.not_finite:i="Number must be finite";break;default:i=t.defaultError,_n.assertNever(n)}return{message:i}},_i=DO;var Pu=_i;function BO(n){Pu=n}function Kr(){return Pu}var sf=(n)=>{let{data:t,path:i,errorMaps:r,issueData:s}=n,f=[...i,...s.path||[]],_={...s,path:f};if(s.message!==void 0)return{...s,path:f,message:s.message};let o="",h=r.filter((e)=>!!e).slice().reverse();for(let e of h)o=e(_,{data:t,defaultError:o}).message;return{...s,path:f,message:o}},GO=[];function G(n,t){let i=Kr(),r=sf({issueData:t,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,i,i===_i?void 0:_i].filter((s)=>!!s)});n.common.issues.push(r)}class Pn{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 x;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 Pn.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 x;if(f.status==="aborted")return x;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 x=Object.freeze({status:"aborted"}),tr=(n)=>({status:"dirty",value:n}),zn=(n)=>({status:"valid",value:n}),Lo=(n)=>n.status==="aborted",Io=(n)=>n.status==="dirty",Di=(n)=>n.status==="valid",xr=(n)=>typeof Promise<"u"&&n instanceof Promise;var X;(function(n){n.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},n.toString=(t)=>typeof t==="string"?t:t?.message})(X||(X={}));class Dt{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 Yu=(n,t)=>{if(Di(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 p(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:(_,o)=>{let{message:h}=n;if(_.code==="invalid_enum_value")return{message:h??o.defaultError};if(typeof o.data>"u")return{message:h??r??o.defaultError};if(_.code!=="invalid_type")return{message:o.defaultError};return{message:h??i??o.defaultError}},description:s}}class fn{get description(){return this._def.description}_getType(n){return at(n.data)}_getOrReturnCtx(n,t){return t||{common:n.parent.common,data:n.data,parsedType:at(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}_processInputParams(n){return{status:new Pn,ctx:{common:n.parent.common,data:n.data,parsedType:at(n.data),schemaErrorMap:this._def.errorMap,path:n.path,parent:n.parent}}}_parseSync(n){let t=this._parse(n);if(xr(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:at(n)},r=this._parseSync({data:n,path:i.path,parent:i});return Yu(i,r)}"~validate"(n){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:n,parsedType:at(n)};if(!this["~standard"].async)try{let i=this._parseSync({data:n,path:[],parent:t});return Di(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)=>Di(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:at(n)},r=this._parse({data:n,path:i.path,parent:i}),s=await(xr(r)?r:Promise.resolve(r));return Yu(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),_=()=>s.addIssue({code:U.custom,...i(r)});if(typeof Promise<"u"&&f instanceof Promise)return f.then((o)=>{if(!o)return _(),!1;else return!0});if(!f)return _(),!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 Bt({schema:this,typeName:j.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 $t.create(this,this._def)}nullable(){return ei.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ut.create(this)}promise(){return fr.create(this,this._def)}or(n){return vr.create([this,n],this._def)}and(n){return pr.create(this,n,this._def)}transform(n){return new Bt({...p(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:n}})}default(n){let t=typeof n==="function"?n:()=>n;return new rs({...p(this._def),innerType:this,defaultValue:t,typeName:j.ZodDefault})}brand(){return new bo({typeName:j.ZodBranded,type:this,...p(this._def)})}catch(n){let t=typeof n==="function"?n:()=>n;return new ss({...p(this._def),innerType:this,catchValue:t,typeName:j.ZodCatch})}describe(n){return new this.constructor({...this._def,description:n})}pipe(n){return cf.create(this,n)}readonly(){return fs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var mO=/^c[^\s-]{8,}$/i,HO=/^[0-9a-z]+$/,WO=/^[0-9A-HJKMNP-TV-Z]{26}$/i,FO=/^[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,CO=/^[a-z0-9_-]{21}$/i,PO=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,YO=/^[-+]?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)?)??$/,XO=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",e0,QO=/^(?:(?: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])$/,aO=/^(?:(?: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])$/,zO=/^(([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]))$/,KO=/^(([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])$/,xO=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,VO=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ju="((\\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])))",jO=new RegExp(`^${Ju}$`);function Qu(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 qO(n){return new RegExp(`^${Qu(n)}$`)}function au(n){let t=`${Ju}T${Qu(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 kO(n,t){if((t==="v4"||!t)&&QO.test(n))return!0;if((t==="v6"||!t)&&zO.test(n))return!0;return!1}function ZO(n,t){if(!PO.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 vO(n,t){if((t==="v4"||!t)&&aO.test(n))return!0;if((t==="v6"||!t)&&KO.test(n))return!0;return!1}class Nt extends fn{_parse(n){if(this._def.coerce)n.data=String(n.data);if(this._getType(n)!==$.string){let s=this._getOrReturnCtx(n);return G(s,{code:U.invalid_type,expected:$.string,received:s.parsedType}),x}let i=new Pn,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),G(r,{code:U.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),G(r,{code:U.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,_=n.data.length<s.value;if(f||_){if(r=this._getOrReturnCtx(n,r),f)G(r,{code:U.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});else if(_)G(r,{code:U.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message});i.dirty()}}else if(s.kind==="email"){if(!XO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"email",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="emoji"){if(!e0)e0=new RegExp(JO,"u");if(!e0.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"emoji",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="uuid"){if(!FO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"uuid",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="nanoid"){if(!CO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"nanoid",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid"){if(!mO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"cuid",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cuid2"){if(!HO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"cuid2",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ulid"){if(!WO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"ulid",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="url")try{new URL(n.data)}catch{r=this._getOrReturnCtx(n,r),G(r,{validation:"url",code:U.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),G(r,{validation:"regex",code:U.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),G(r,{code:U.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),G(r,{code:U.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),G(r,{code:U.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()}else if(s.kind==="datetime"){if(!au(s).test(n.data))r=this._getOrReturnCtx(n,r),G(r,{code:U.invalid_string,validation:"datetime",message:s.message}),i.dirty()}else if(s.kind==="date"){if(!jO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{code:U.invalid_string,validation:"date",message:s.message}),i.dirty()}else if(s.kind==="time"){if(!qO(s).test(n.data))r=this._getOrReturnCtx(n,r),G(r,{code:U.invalid_string,validation:"time",message:s.message}),i.dirty()}else if(s.kind==="duration"){if(!YO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"duration",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="ip"){if(!kO(n.data,s.version))r=this._getOrReturnCtx(n,r),G(r,{validation:"ip",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="jwt"){if(!ZO(n.data,s.alg))r=this._getOrReturnCtx(n,r),G(r,{validation:"jwt",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="cidr"){if(!vO(n.data,s.version))r=this._getOrReturnCtx(n,r),G(r,{validation:"cidr",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64"){if(!xO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"base64",code:U.invalid_string,message:s.message}),i.dirty()}else if(s.kind==="base64url"){if(!VO.test(n.data))r=this._getOrReturnCtx(n,r),G(r,{validation:"base64url",code:U.invalid_string,message:s.message}),i.dirty()}else _n.assertNever(s);return{status:i.value,value:n.data}}_regex(n,t,i){return this.refinement((r)=>n.test(r),{validation:t,code:U.invalid_string,...X.errToObj(i)})}_addCheck(n){return new Nt({...this._def,checks:[...this._def.checks,n]})}email(n){return this._addCheck({kind:"email",...X.errToObj(n)})}url(n){return this._addCheck({kind:"url",...X.errToObj(n)})}emoji(n){return this._addCheck({kind:"emoji",...X.errToObj(n)})}uuid(n){return this._addCheck({kind:"uuid",...X.errToObj(n)})}nanoid(n){return this._addCheck({kind:"nanoid",...X.errToObj(n)})}cuid(n){return this._addCheck({kind:"cuid",...X.errToObj(n)})}cuid2(n){return this._addCheck({kind:"cuid2",...X.errToObj(n)})}ulid(n){return this._addCheck({kind:"ulid",...X.errToObj(n)})}base64(n){return this._addCheck({kind:"base64",...X.errToObj(n)})}base64url(n){return this._addCheck({kind:"base64url",...X.errToObj(n)})}jwt(n){return this._addCheck({kind:"jwt",...X.errToObj(n)})}ip(n){return this._addCheck({kind:"ip",...X.errToObj(n)})}cidr(n){return this._addCheck({kind:"cidr",...X.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,...X.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,...X.errToObj(n?.message)})}duration(n){return this._addCheck({kind:"duration",...X.errToObj(n)})}regex(n,t){return this._addCheck({kind:"regex",regex:n,...X.errToObj(t)})}includes(n,t){return this._addCheck({kind:"includes",value:n,position:t?.position,...X.errToObj(t?.message)})}startsWith(n,t){return this._addCheck({kind:"startsWith",value:n,...X.errToObj(t)})}endsWith(n,t){return this._addCheck({kind:"endsWith",value:n,...X.errToObj(t)})}min(n,t){return this._addCheck({kind:"min",value:n,...X.errToObj(t)})}max(n,t){return this._addCheck({kind:"max",value:n,...X.errToObj(t)})}length(n,t){return this._addCheck({kind:"length",value:n,...X.errToObj(t)})}nonempty(n){return this.min(1,X.errToObj(n))}trim(){return new Nt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Nt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Nt({...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}}Nt.create=(n)=>{return new Nt({checks:[],typeName:j.ZodString,coerce:n?.coerce??!1,...p(n)})};function pO(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(".","")),_=Number.parseInt(t.toFixed(s).replace(".",""));return f%_/10**s}class Gi extends fn{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)!==$.number){let s=this._getOrReturnCtx(n);return G(s,{code:U.invalid_type,expected:$.number,received:s.parsedType}),x}let i=void 0,r=new Pn;for(let s of this._def.checks)if(s.kind==="int"){if(!_n.isInteger(n.data))i=this._getOrReturnCtx(n,i),G(i,{code:U.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),G(i,{code:U.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),G(i,{code:U.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),r.dirty()}else if(s.kind==="multipleOf"){if(pO(n.data,s.value)!==0)i=this._getOrReturnCtx(n,i),G(i,{code:U.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),G(i,{code:U.not_finite,message:s.message}),r.dirty()}else _n.assertNever(s);return{status:r.value,value:n.data}}gte(n,t){return this.setLimit("min",n,!0,X.toString(t))}gt(n,t){return this.setLimit("min",n,!1,X.toString(t))}lte(n,t){return this.setLimit("max",n,!0,X.toString(t))}lt(n,t){return this.setLimit("max",n,!1,X.toString(t))}setLimit(n,t,i,r){return new Gi({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:X.toString(r)}]})}_addCheck(n){return new Gi({...this._def,checks:[...this._def.checks,n]})}int(n){return this._addCheck({kind:"int",message:X.toString(n)})}positive(n){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X.toString(n)})}negative(n){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:X.toString(t)})}finite(n){return this._addCheck({kind:"finite",message:X.toString(n)})}safe(n){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X.toString(n)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X.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"&&_n.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)}}Gi.create=(n)=>{return new Gi({checks:[],typeName:j.ZodNumber,coerce:n?.coerce||!1,...p(n)})};class mi extends fn{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)!==$.bigint)return this._getInvalidInput(n);let i=void 0,r=new Pn;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),G(i,{code:U.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),G(i,{code:U.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),G(i,{code:U.not_multiple_of,multipleOf:s.value,message:s.message}),r.dirty()}else _n.assertNever(s);return{status:r.value,value:n.data}}_getInvalidInput(n){let t=this._getOrReturnCtx(n);return G(t,{code:U.invalid_type,expected:$.bigint,received:t.parsedType}),x}gte(n,t){return this.setLimit("min",n,!0,X.toString(t))}gt(n,t){return this.setLimit("min",n,!1,X.toString(t))}lte(n,t){return this.setLimit("max",n,!0,X.toString(t))}lt(n,t){return this.setLimit("max",n,!1,X.toString(t))}setLimit(n,t,i,r){return new mi({...this._def,checks:[...this._def.checks,{kind:n,value:t,inclusive:i,message:X.toString(r)}]})}_addCheck(n){return new mi({...this._def,checks:[...this._def.checks,n]})}positive(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X.toString(n)})}negative(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X.toString(n)})}nonpositive(n){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X.toString(n)})}nonnegative(n){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X.toString(n)})}multipleOf(n,t){return this._addCheck({kind:"multipleOf",value:n,message:X.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}}mi.create=(n)=>{return new mi({checks:[],typeName:j.ZodBigInt,coerce:n?.coerce??!1,...p(n)})};class qr extends fn{_parse(n){if(this._def.coerce)n.data=Boolean(n.data);if(this._getType(n)!==$.boolean){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.boolean,received:i.parsedType}),x}return zn(n.data)}}qr.create=(n)=>{return new qr({typeName:j.ZodBoolean,coerce:n?.coerce||!1,...p(n)})};class ir extends fn{_parse(n){if(this._def.coerce)n.data=new Date(n.data);if(this._getType(n)!==$.date){let s=this._getOrReturnCtx(n);return G(s,{code:U.invalid_type,expected:$.date,received:s.parsedType}),x}if(Number.isNaN(n.data.getTime())){let s=this._getOrReturnCtx(n);return G(s,{code:U.invalid_date}),x}let i=new Pn,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),G(r,{code:U.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),G(r,{code:U.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()}else _n.assertNever(s);return{status:i.value,value:new Date(n.data.getTime())}}_addCheck(n){return new ir({...this._def,checks:[...this._def.checks,n]})}min(n,t){return this._addCheck({kind:"min",value:n.getTime(),message:X.toString(t)})}max(n,t){return this._addCheck({kind:"max",value:n.getTime(),message:X.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}}ir.create=(n)=>{return new ir({checks:[],coerce:n?.coerce||!1,typeName:j.ZodDate,...p(n)})};class ff extends fn{_parse(n){if(this._getType(n)!==$.symbol){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.symbol,received:i.parsedType}),x}return zn(n.data)}}ff.create=(n)=>{return new ff({typeName:j.ZodSymbol,...p(n)})};class kr extends fn{_parse(n){if(this._getType(n)!==$.undefined){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.undefined,received:i.parsedType}),x}return zn(n.data)}}kr.create=(n)=>{return new kr({typeName:j.ZodUndefined,...p(n)})};class Zr extends fn{_parse(n){if(this._getType(n)!==$.null){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.null,received:i.parsedType}),x}return zn(n.data)}}Zr.create=(n)=>{return new Zr({typeName:j.ZodNull,...p(n)})};class rr extends fn{constructor(){super(...arguments);this._any=!0}_parse(n){return zn(n.data)}}rr.create=(n)=>{return new rr({typeName:j.ZodAny,...p(n)})};class Bi extends fn{constructor(){super(...arguments);this._unknown=!0}_parse(n){return zn(n.data)}}Bi.create=(n)=>{return new Bi({typeName:j.ZodUnknown,...p(n)})};class zt extends fn{_parse(n){let t=this._getOrReturnCtx(n);return G(t,{code:U.invalid_type,expected:$.never,received:t.parsedType}),x}}zt.create=(n)=>{return new zt({typeName:j.ZodNever,...p(n)})};class of extends fn{_parse(n){if(this._getType(n)!==$.undefined){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.void,received:i.parsedType}),x}return zn(n.data)}}of.create=(n)=>{return new of({typeName:j.ZodVoid,...p(n)})};class Ut extends fn{_parse(n){let{ctx:t,status:i}=this._processInputParams(n),r=this._def;if(t.parsedType!==$.array)return G(t,{code:U.invalid_type,expected:$.array,received:t.parsedType}),x;if(r.exactLength!==null){let f=t.data.length>r.exactLength.value,_=t.data.length<r.exactLength.value;if(f||_)G(t,{code:f?U.too_big:U.too_small,minimum:_?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)G(t,{code:U.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)G(t,{code:U.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,_)=>{return r.type._parseAsync(new Dt(t,f,t.path,_))})).then((f)=>{return Pn.mergeArray(i,f)});let s=[...t.data].map((f,_)=>{return r.type._parseSync(new Dt(t,f,t.path,_))});return Pn.mergeArray(i,s)}get element(){return this._def.type}min(n,t){return new Ut({...this._def,minLength:{value:n,message:X.toString(t)}})}max(n,t){return new Ut({...this._def,maxLength:{value:n,message:X.toString(t)}})}length(n,t){return new Ut({...this._def,exactLength:{value:n,message:X.toString(t)}})}nonempty(n){return this.min(1,n)}}Ut.create=(n,t)=>{return new Ut({type:n,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...p(t)})};function Vr(n){if(n instanceof In){let t={};for(let i in n.shape){let r=n.shape[i];t[i]=$t.create(Vr(r))}return new In({...n._def,shape:()=>t})}else if(n instanceof Ut)return new Ut({...n._def,type:Vr(n.element)});else if(n instanceof $t)return $t.create(Vr(n.unwrap()));else if(n instanceof ei)return ei.create(Vr(n.unwrap()));else if(n instanceof Kt)return Kt.create(n.items.map((t)=>Vr(t)));else return n}class In extends fn{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=_n.objectKeys(n);return this._cached={shape:n,keys:t},this._cached}_parse(n){if(this._getType(n)!==$.object){let h=this._getOrReturnCtx(n);return G(h,{code:U.invalid_type,expected:$.object,received:h.parsedType}),x}let{status:i,ctx:r}=this._processInputParams(n),{shape:s,keys:f}=this._getCached(),_=[];if(!(this._def.catchall instanceof zt&&this._def.unknownKeys==="strip")){for(let h in r.data)if(!f.includes(h))_.push(h)}let o=[];for(let h of f){let e=s[h],c=r.data[h];o.push({key:{status:"valid",value:h},value:e._parse(new Dt(r,c,r.path,h)),alwaysSet:h in r.data})}if(this._def.catchall instanceof zt){let h=this._def.unknownKeys;if(h==="passthrough")for(let e of _)o.push({key:{status:"valid",value:e},value:{status:"valid",value:r.data[e]}});else if(h==="strict"){if(_.length>0)G(r,{code:U.unrecognized_keys,keys:_}),i.dirty()}else if(h==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let h=this._def.catchall;for(let e of _){let c=r.data[e];o.push({key:{status:"valid",value:e},value:h._parse(new Dt(r,c,r.path,e)),alwaysSet:e in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let h=[];for(let e of o){let c=await e.key,d=await e.value;h.push({key:c,value:d,alwaysSet:e.alwaysSet})}return h}).then((h)=>{return Pn.mergeObjectSync(i,h)});else return Pn.mergeObjectSync(i,o)}get shape(){return this._def.shape()}strict(n){return X.errToObj,new In({...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:X.errToObj(n).message??r};return{message:r}}}:{}})}strip(){return new In({...this._def,unknownKeys:"strip"})}passthrough(){return new In({...this._def,unknownKeys:"passthrough"})}extend(n){return new In({...this._def,shape:()=>({...this._def.shape(),...n})})}merge(n){return new In({unknownKeys:n._def.unknownKeys,catchall:n._def.catchall,shape:()=>({...this._def.shape(),...n._def.shape()}),typeName:j.ZodObject})}setKey(n,t){return this.augment({[n]:t})}catchall(n){return new In({...this._def,catchall:n})}pick(n){let t={};for(let i of _n.objectKeys(n))if(n[i]&&this.shape[i])t[i]=this.shape[i];return new In({...this._def,shape:()=>t})}omit(n){let t={};for(let i of _n.objectKeys(this.shape))if(!n[i])t[i]=this.shape[i];return new In({...this._def,shape:()=>t})}deepPartial(){return Vr(this)}partial(n){let t={};for(let i of _n.objectKeys(this.shape)){let r=this.shape[i];if(n&&!n[i])t[i]=r;else t[i]=r.optional()}return new In({...this._def,shape:()=>t})}required(n){let t={};for(let i of _n.objectKeys(this.shape))if(n&&!n[i])t[i]=this.shape[i];else{let s=this.shape[i];while(s instanceof $t)s=s._def.innerType;t[i]=s}return new In({...this._def,shape:()=>t})}keyof(){return zu(_n.objectKeys(this.shape))}}In.create=(n,t)=>{return new In({shape:()=>n,unknownKeys:"strip",catchall:zt.create(),typeName:j.ZodObject,...p(t)})};In.strictCreate=(n,t)=>{return new In({shape:()=>n,unknownKeys:"strict",catchall:zt.create(),typeName:j.ZodObject,...p(t)})};In.lazycreate=(n,t)=>{return new In({shape:n,unknownKeys:"strip",catchall:zt.create(),typeName:j.ZodObject,...p(t)})};class vr extends fn{_parse(n){let{ctx:t}=this._processInputParams(n),i=this._def.options;function r(s){for(let _ of s)if(_.result.status==="valid")return _.result;for(let _ of s)if(_.result.status==="dirty")return t.common.issues.push(..._.ctx.common.issues),_.result;let f=s.map((_)=>new vn(_.ctx.common.issues));return G(t,{code:U.invalid_union,unionErrors:f}),x}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 o of i){let h={...t,common:{...t.common,issues:[]},parent:null},e=o._parseSync({data:t.data,path:t.path,parent:h});if(e.status==="valid")return e;else if(e.status==="dirty"&&!s)s={result:e,ctx:h};if(h.common.issues.length)f.push(h.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let _=f.map((o)=>new vn(o));return G(t,{code:U.invalid_union,unionErrors:_}),x}}get options(){return this._def.options}}vr.create=(n,t)=>{return new vr({options:n,typeName:j.ZodUnion,...p(t)})};var hi=(n)=>{if(n instanceof ns)return hi(n.schema);else if(n instanceof Bt)return hi(n.innerType());else if(n instanceof ts)return[n.value];else if(n instanceof Hi)return n.options;else if(n instanceof is)return _n.objectValues(n.enum);else if(n instanceof rs)return hi(n._def.innerType);else if(n instanceof kr)return[void 0];else if(n instanceof Zr)return[null];else if(n instanceof $t)return[void 0,...hi(n.unwrap())];else if(n instanceof ei)return[null,...hi(n.unwrap())];else if(n instanceof bo)return hi(n.unwrap());else if(n instanceof fs)return hi(n.unwrap());else if(n instanceof ss)return hi(n._def.innerType);else return[]};class So extends fn{_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.object)return G(t,{code:U.invalid_type,expected:$.object,received:t.parsedType}),x;let i=this.discriminator,r=t.data[i],s=this.optionsMap.get(r);if(!s)return G(t,{code:U.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),x;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=hi(s.shape[n]);if(!f.length)throw Error(`A discriminator value for key \`${n}\` could not be extracted from all schema options`);for(let _ of f){if(r.has(_))throw Error(`Discriminator property ${String(n)} has duplicate value ${String(_)}`);r.set(_,s)}}return new So({typeName:j.ZodDiscriminatedUnion,discriminator:n,options:t,optionsMap:r,...p(i)})}}function c0(n,t){let i=at(n),r=at(t);if(n===t)return{valid:!0,data:n};else if(i===$.object&&r===$.object){let s=_n.objectKeys(t),f=_n.objectKeys(n).filter((o)=>s.indexOf(o)!==-1),_={...n,...t};for(let o of f){let h=c0(n[o],t[o]);if(!h.valid)return{valid:!1};_[o]=h.data}return{valid:!0,data:_}}else if(i===$.array&&r===$.array){if(n.length!==t.length)return{valid:!1};let s=[];for(let f=0;f<n.length;f++){let _=n[f],o=t[f],h=c0(_,o);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else if(i===$.date&&r===$.date&&+n===+t)return{valid:!0,data:n};else return{valid:!1}}class pr extends fn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n),r=(s,f)=>{if(Lo(s)||Lo(f))return x;let _=c0(s.value,f.value);if(!_.valid)return G(i,{code:U.invalid_intersection_types}),x;if(Io(s)||Io(f))t.dirty();return{status:t.value,value:_.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}))}}pr.create=(n,t,i)=>{return new pr({left:n,right:t,typeName:j.ZodIntersection,...p(i)})};class Kt extends fn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==$.array)return G(i,{code:U.invalid_type,expected:$.array,received:i.parsedType}),x;if(i.data.length<this._def.items.length)return G(i,{code:U.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;if(!this._def.rest&&i.data.length>this._def.items.length)G(i,{code:U.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let s=[...i.data].map((f,_)=>{let o=this._def.items[_]||this._def.rest;if(!o)return null;return o._parse(new Dt(i,f,i.path,_))}).filter((f)=>!!f);if(i.common.async)return Promise.all(s).then((f)=>{return Pn.mergeArray(t,f)});else return Pn.mergeArray(t,s)}get items(){return this._def.items}rest(n){return new Kt({...this._def,rest:n})}}Kt.create=(n,t)=>{if(!Array.isArray(n))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Kt({items:n,typeName:j.ZodTuple,rest:null,...p(t)})};class _f extends fn{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!==$.object)return G(i,{code:U.invalid_type,expected:$.object,received:i.parsedType}),x;let r=[],s=this._def.keyType,f=this._def.valueType;for(let _ in i.data)r.push({key:s._parse(new Dt(i,_,i.path,_)),value:f._parse(new Dt(i,i.data[_],i.path,_)),alwaysSet:_ in i.data});if(i.common.async)return Pn.mergeObjectAsync(t,r);else return Pn.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(n,t,i){if(t instanceof fn)return new _f({keyType:n,valueType:t,typeName:j.ZodRecord,...p(i)});return new _f({keyType:Nt.create(),valueType:n,typeName:j.ZodRecord,...p(t)})}}class hf extends fn{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!==$.map)return G(i,{code:U.invalid_type,expected:$.map,received:i.parsedType}),x;let r=this._def.keyType,s=this._def.valueType,f=[...i.data.entries()].map(([_,o],h)=>{return{key:r._parse(new Dt(i,_,i.path,[h,"key"])),value:s._parse(new Dt(i,o,i.path,[h,"value"]))}});if(i.common.async){let _=new Map;return Promise.resolve().then(async()=>{for(let o of f){let h=await o.key,e=await o.value;if(h.status==="aborted"||e.status==="aborted")return x;if(h.status==="dirty"||e.status==="dirty")t.dirty();_.set(h.value,e.value)}return{status:t.value,value:_}})}else{let _=new Map;for(let o of f){let{key:h,value:e}=o;if(h.status==="aborted"||e.status==="aborted")return x;if(h.status==="dirty"||e.status==="dirty")t.dirty();_.set(h.value,e.value)}return{status:t.value,value:_}}}}hf.create=(n,t,i)=>{return new hf({valueType:t,keyType:n,typeName:j.ZodMap,...p(i)})};class sr extends fn{_parse(n){let{status:t,ctx:i}=this._processInputParams(n);if(i.parsedType!==$.set)return G(i,{code:U.invalid_type,expected:$.set,received:i.parsedType}),x;let r=this._def;if(r.minSize!==null){if(i.data.size<r.minSize.value)G(i,{code:U.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)G(i,{code:U.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(o){let h=new Set;for(let e of o){if(e.status==="aborted")return x;if(e.status==="dirty")t.dirty();h.add(e.value)}return{status:t.value,value:h}}let _=[...i.data.values()].map((o,h)=>s._parse(new Dt(i,o,i.path,h)));if(i.common.async)return Promise.all(_).then((o)=>f(o));else return f(_)}min(n,t){return new sr({...this._def,minSize:{value:n,message:X.toString(t)}})}max(n,t){return new sr({...this._def,maxSize:{value:n,message:X.toString(t)}})}size(n,t){return this.min(n,t).max(n,t)}nonempty(n){return this.min(1,n)}}sr.create=(n,t)=>{return new sr({valueType:n,minSize:null,maxSize:null,typeName:j.ZodSet,...p(t)})};class jr extends fn{constructor(){super(...arguments);this.validate=this.implement}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.function)return G(t,{code:U.invalid_type,expected:$.function,received:t.parsedType}),x;function i(_,o){return sf({data:_,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Kr(),_i].filter((h)=>!!h),issueData:{code:U.invalid_arguments,argumentsError:o}})}function r(_,o){return sf({data:_,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Kr(),_i].filter((h)=>!!h),issueData:{code:U.invalid_return_type,returnTypeError:o}})}let s={errorMap:t.common.contextualErrorMap},f=t.data;if(this._def.returns instanceof fr){let _=this;return zn(async function(...o){let h=new vn([]),e=await _._def.args.parseAsync(o,s).catch((u)=>{throw h.addIssue(i(o,u)),h}),c=await Reflect.apply(f,this,e);return await _._def.returns._def.type.parseAsync(c,s).catch((u)=>{throw h.addIssue(r(c,u)),h})})}else{let _=this;return zn(function(...o){let h=_._def.args.safeParse(o,s);if(!h.success)throw new vn([i(o,h.error)]);let e=Reflect.apply(f,this,h.data),c=_._def.returns.safeParse(e,s);if(!c.success)throw new vn([r(e,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...n){return new jr({...this._def,args:Kt.create(n).rest(Bi.create())})}returns(n){return new jr({...this._def,returns:n})}implement(n){return this.parse(n)}strictImplement(n){return this.parse(n)}static create(n,t,i){return new jr({args:n?n:Kt.create([]).rest(Bi.create()),returns:t||Bi.create(),typeName:j.ZodFunction,...p(i)})}}class ns extends fn{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})}}ns.create=(n,t)=>{return new ns({getter:n,typeName:j.ZodLazy,...p(t)})};class ts extends fn{_parse(n){if(n.data!==this._def.value){let t=this._getOrReturnCtx(n);return G(t,{received:t.data,code:U.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:n.data}}get value(){return this._def.value}}ts.create=(n,t)=>{return new ts({value:n,typeName:j.ZodLiteral,...p(t)})};function zu(n,t){return new Hi({values:n,typeName:j.ZodEnum,...p(t)})}class Hi extends fn{_parse(n){if(typeof n.data!=="string"){let t=this._getOrReturnCtx(n),i=this._def.values;return G(t,{expected:_n.joinValues(i),received:t.parsedType,code:U.invalid_type}),x}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 G(t,{received:t.data,code:U.invalid_enum_value,options:i}),x}return zn(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 Hi.create(n,{...this._def,...t})}exclude(n,t=this._def){return Hi.create(this.options.filter((i)=>!n.includes(i)),{...this._def,...t})}}Hi.create=zu;class is extends fn{_parse(n){let t=_n.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(n);if(i.parsedType!==$.string&&i.parsedType!==$.number){let r=_n.objectValues(t);return G(i,{expected:_n.joinValues(r),received:i.parsedType,code:U.invalid_type}),x}if(!this._cache)this._cache=new Set(_n.getValidEnumValues(this._def.values));if(!this._cache.has(n.data)){let r=_n.objectValues(t);return G(i,{received:i.data,code:U.invalid_enum_value,options:r}),x}return zn(n.data)}get enum(){return this._def.values}}is.create=(n,t)=>{return new is({values:n,typeName:j.ZodNativeEnum,...p(t)})};class fr extends fn{unwrap(){return this._def.type}_parse(n){let{ctx:t}=this._processInputParams(n);if(t.parsedType!==$.promise&&t.common.async===!1)return G(t,{code:U.invalid_type,expected:$.promise,received:t.parsedType}),x;let i=t.parsedType===$.promise?t.data:Promise.resolve(t.data);return zn(i.then((r)=>{return this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})}))}}fr.create=(n,t)=>{return new fr({type:n,typeName:j.ZodPromise,...p(t)})};class Bt extends fn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.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(G(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(_)=>{if(t.value==="aborted")return x;let o=await this._def.schema._parseAsync({data:_,path:i.path,parent:i});if(o.status==="aborted")return x;if(o.status==="dirty")return tr(o.value);if(t.value==="dirty")return tr(o.value);return o});else{if(t.value==="aborted")return x;let _=this._def.schema._parseSync({data:f,path:i.path,parent:i});if(_.status==="aborted")return x;if(_.status==="dirty")return tr(_.value);if(t.value==="dirty")return tr(_.value);return _}}if(r.type==="refinement"){let f=(_)=>{let o=r.refinement(_,s);if(i.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return _};if(i.common.async===!1){let _=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(_.status==="aborted")return x;if(_.status==="dirty")t.dirty();return f(_.value),{status:t.value,value:_.value}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((_)=>{if(_.status==="aborted")return x;if(_.status==="dirty")t.dirty();return f(_.value).then(()=>{return{status:t.value,value:_.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(!Di(f))return x;let _=r.transform(f.value,s);if(_ instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:_}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then((f)=>{if(!Di(f))return x;return Promise.resolve(r.transform(f.value,s)).then((_)=>({status:t.value,value:_}))});_n.assertNever(r)}}Bt.create=(n,t,i)=>{return new Bt({schema:n,typeName:j.ZodEffects,effect:t,...p(i)})};Bt.createWithPreprocess=(n,t,i)=>{return new Bt({schema:t,effect:{type:"preprocess",transform:n},typeName:j.ZodEffects,...p(i)})};class $t extends fn{_parse(n){if(this._getType(n)===$.undefined)return zn(void 0);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}$t.create=(n,t)=>{return new $t({innerType:n,typeName:j.ZodOptional,...p(t)})};class ei extends fn{_parse(n){if(this._getType(n)===$.null)return zn(null);return this._def.innerType._parse(n)}unwrap(){return this._def.innerType}}ei.create=(n,t)=>{return new ei({innerType:n,typeName:j.ZodNullable,...p(t)})};class rs extends fn{_parse(n){let{ctx:t}=this._processInputParams(n),i=t.data;if(t.parsedType===$.undefined)i=this._def.defaultValue();return this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}rs.create=(n,t)=>{return new rs({innerType:n,typeName:j.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...p(t)})};class ss extends fn{_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(xr(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}}ss.create=(n,t)=>{return new ss({innerType:n,typeName:j.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...p(t)})};class ef extends fn{_parse(n){if(this._getType(n)!==$.nan){let i=this._getOrReturnCtx(n);return G(i,{code:U.invalid_type,expected:$.nan,received:i.parsedType}),x}return{status:"valid",value:n.data}}}ef.create=(n)=>{return new ef({typeName:j.ZodNaN,...p(n)})};var n4=Symbol("zod_brand");class bo extends fn{_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 cf extends fn{_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 x;if(s.status==="dirty")return t.dirty(),tr(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 x;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 cf({in:n,out:t,typeName:j.ZodPipeline})}}class fs extends fn{_parse(n){let t=this._def.innerType._parse(n),i=(r)=>{if(Di(r))r.value=Object.freeze(r.value);return r};return xr(t)?t.then((r)=>i(r)):i(t)}unwrap(){return this._def.innerType}}fs.create=(n,t)=>{return new fs({innerType:n,typeName:j.ZodReadonly,...p(t)})};function Xu(n,t){let i=typeof n==="function"?n(t):typeof n==="string"?{message:n}:n;return typeof i==="string"?{message:i}:i}function Ku(n,t={},i){if(n)return rr.create().superRefine((r,s)=>{let f=n(r);if(f instanceof Promise)return f.then((_)=>{if(!_){let o=Xu(t,r),h=o.fatal??i??!0;s.addIssue({code:"custom",...o,fatal:h})}});if(!f){let _=Xu(t,r),o=_.fatal??i??!0;s.addIssue({code:"custom",..._,fatal:o})}return});return rr.create()}var t4={object:In.lazycreate},j;(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"})(j||(j={}));var i4=(n,t={message:`Input not instance of ${n.name}`})=>Ku((i)=>i instanceof n,t),xu=Nt.create,Vu=Gi.create,r4=ef.create,s4=mi.create,ju=qr.create,f4=ir.create,o4=ff.create,_4=kr.create,h4=Zr.create,e4=rr.create,c4=Bi.create,d4=zt.create,u4=of.create,w4=Ut.create,y4=In.create,A4=In.strictCreate,R4=vr.create,M4=So.create,E4=pr.create,l4=Kt.create,T4=_f.create,g4=hf.create,O4=sr.create,L4=jr.create,I4=ns.create,S4=ts.create,b4=Hi.create,N4=is.create,U4=fr.create,$4=Bt.create,D4=$t.create,B4=ei.create,G4=Bt.createWithPreprocess,m4=cf.create,H4=()=>xu().optional(),W4=()=>Vu().optional(),F4=()=>ju().optional(),C4={string:(n)=>Nt.create({...n,coerce:!0}),number:(n)=>Gi.create({...n,coerce:!0}),boolean:(n)=>qr.create({...n,coerce:!0}),bigint:(n)=>mi.create({...n,coerce:!0}),date:(n)=>ir.create({...n,coerce:!0})};var P4=x;var No=y.enum(["low","medium","high","xhigh","max"]),or=y.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 Y4=y.array(y.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"}),X4=y.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,y.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),d0=y.preprocess((n)=>typeof n==="string"&&n.trim().length===0?null:n,y.string().trim().min(1).nullable()).default(null),u0=y.object({host:y.string().default("127.0.0.1"),port:y.number().default(8787),api_keys:Y4,enable_legacy_chat_completions:y.boolean().default(!1),protocol_projection_mode:y.enum(["safe","legacy-user-prefix"]).default("safe"),session_affinity_mode:y.enum(["explicit-only","legacy-initial-input"]).default("explicit-only"),proxy_url:X4,sdk_http_keep_alive:y.boolean().default(!1),enforce_single_instance:y.boolean().default(!0),instance_lock_path:d0,runtime_endpoint_mode:y.enum(["legacy-q","kiro-runtime"]).default("kiro-runtime"),dynamic_model_catalog:y.boolean().default(!0),model_catalog_ttl_ms:y.number().int().min(1).max(2147483647).default(900000),model_catalog_stale_ttl_ms:y.number().int().min(1).max(2147483647).default(86400000),model_catalog_request_timeout_ms:y.number().int().min(1).max(2147483647).default(1e4),auth_source:y.enum(["opencode-shared","local"]).default("local"),opencode_auth_db_path:d0,default_region:y.string().default("us-east-1"),account_selection_strategy:y.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:y.number().default(3),rate_limit_retry_delay_ms:y.number().default(5000),quota_recheck_interval_ms:y.number().int().min(1).max(2147483647).default(900000),quota_recheck_timeout_ms:y.number().int().min(1).max(2147483647).default(1e4),quota_recheck_concurrency:y.number().int().min(1).max(32).default(4),account_maintenance_enabled:y.boolean().default(!0),account_maintenance_interval_ms:y.number().int().min(1000).max(2147483647).default(60000),account_maintenance_timeout_ms:y.number().int().min(1000).max(2147483647).default(120000),account_maintenance_concurrency:y.number().int().min(1).max(32).default(4),usage_refresh_interval_ms:y.number().int().min(1000).max(2147483647).default(900000),max_request_iterations:y.number().default(20),request_timeout_ms:y.number().int().min(1).max(2147483647).default(120000),stream_idle_timeout_ms:y.number().int().min(1).max(2147483647).default(60000),max_request_body_bytes:y.number().default(10485760),token_expiry_buffer_ms:y.number().default(300000),session_affinity_ttl_ms:y.number().int().min(1).max(2147483647).default(86400000),session_affinity_max_entries:y.number().int().min(1).max(1e6).default(1e4),reasoning_replay_key_path:d0,reasoning_replay_keys:y.array(y.string().trim().min(1)).default([]),reasoning_replay_ttl_ms:y.number().int().min(1).max(2147483647).default(86400000),reasoning_replay_max_entries:y.number().int().min(1).max(1e6).default(1e4),effort:No.nullable().default(null),auto_effort_mapping:y.boolean().default(!0),log_level:y.string().default("info"),test_upstream_endpoint:y.string().url().optional()});class df extends Error{constructor(n,t){super(n,t);this.name="ConfigLoadError"}}var z4=u0.partial();function K4(n){let t=n.XDG_CONFIG_HOME??qu(a4(),".config");return qu(t,"kiro-provider","config.json")}function x4(n){if(!J4(n))return{};try{let t=JSON.parse(Q4(n,"utf8"));return z4.parse(t)}catch(t){if(t instanceof y.ZodError)throw new df(`Invalid configuration file ${n}: ${ku(t)}`,{cause:t});if(t instanceof Error)throw new df(`Unable to read configuration file ${n}: ${t.message}`,{cause:t});throw t}}function V4(n){let t=n.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1;return n}function j4(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_RUNTIME_ENDPOINT_MODE:"runtime_endpoint_mode",KIRO_PROVIDER_INSTANCE_LOCK_PATH:"instance_lock_path",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[c,d]of Object.entries(i)){let u=n[c];if(u!==void 0)t[d]=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_QUOTA_RECHECK_INTERVAL_MS:"quota_recheck_interval_ms",KIRO_PROVIDER_QUOTA_RECHECK_TIMEOUT_MS:"quota_recheck_timeout_ms",KIRO_PROVIDER_QUOTA_RECHECK_CONCURRENCY:"quota_recheck_concurrency",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_INTERVAL_MS:"account_maintenance_interval_ms",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_TIMEOUT_MS:"account_maintenance_timeout_ms",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_CONCURRENCY:"account_maintenance_concurrency",KIRO_PROVIDER_USAGE_REFRESH_INTERVAL_MS:"usage_refresh_interval_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_MODEL_CATALOG_TTL_MS:"model_catalog_ttl_ms",KIRO_PROVIDER_MODEL_CATALOG_STALE_TTL_MS:"model_catalog_stale_ttl_ms",KIRO_PROVIDER_MODEL_CATALOG_REQUEST_TIMEOUT_MS:"model_catalog_request_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[c,d]of Object.entries(r)){let u=n[c];if(u!==void 0)t[d]=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 _=n.KIRO_PROVIDER_OPENCODE_AUTH_DB_PATH;if(_!==void 0)t.opencode_auth_db_path=_.trim();let o=n.KIRO_PROVIDER_REASONING_REPLAY_KEY_PATH;if(o!==void 0)t.reasoning_replay_key_path=o.trim();let h=n.KIRO_PROVIDER_REASONING_REPLAY_KEYS;if(h!==void 0)t.reasoning_replay_keys=h.split(",").map((c)=>c.trim()).filter((c)=>c.length>0);let e={KIRO_PROVIDER_ENABLE_LEGACY_CHAT_COMPLETIONS:"enable_legacy_chat_completions",KIRO_PROVIDER_SDK_HTTP_KEEP_ALIVE:"sdk_http_keep_alive",KIRO_PROVIDER_ENFORCE_SINGLE_INSTANCE:"enforce_single_instance",KIRO_PROVIDER_DYNAMIC_MODEL_CATALOG:"dynamic_model_catalog",KIRO_PROVIDER_ACCOUNT_MAINTENANCE_ENABLED:"account_maintenance_enabled",KIRO_PROVIDER_AUTO_EFFORT_MAPPING:"auto_effort_mapping"};for(let[c,d]of Object.entries(e)){let u=n[c];if(u!==void 0)t[d]=V4(u)}return t}function ku(n){return n.issues.map((t)=>`${t.path.length>0?t.path.join("."):"config"}: ${t.message}`).join(", ")}function Zu(n={}){let t=n.env??process.env,i=n.configPath??K4(t);try{return u0.parse({...x4(i),...j4(t),...n.overrides})}catch(r){if(r instanceof df)throw r;if(r instanceof y.ZodError)throw new df(`Invalid configuration: ${ku(r)}`,{cause:r});throw r}}function os(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 _r(n,t=120000){if(!n.access||!n.expires)return!0;return Date.now()>=n.expires-t}function _s(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`}import{createHash as q4}from"crypto";function wn(n){return q4("sha256").update("kiro-provider-audit-v1\x00").update(n).digest("hex").slice(0,16)}function V(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}))}function vu(n){if(typeof n==="object"&&n!==null&&"unref"in n&&typeof n.unref==="function")n.unref()}function k4(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0,i=n instanceof Error?n.message:String(n);return t?`${t}: ${i}`:i}function pu(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0;return{error_name:n instanceof Error?n.name:"UnknownError",error_code:t}}class Uo{options;initialTimer;intervalTimer;lifecycleController=new AbortController;inFlight;constructor(n){this.options=n}start(){if(!this.options.enabled||this.initialTimer!==void 0||this.intervalTimer!==void 0)return;this.lifecycleController=new AbortController;let n=()=>{this.runOnce(this.lifecycleController.signal).catch((t)=>{if(this.lifecycleController.signal.aborted)return;V("warn","account_maintenance_pass_failed",{...pu(t)})})};this.initialTimer=setTimeout(()=>{this.initialTimer=void 0,n()},this.options.initialDelayMs??5000),this.intervalTimer=setInterval(n,this.options.intervalMs),vu(this.initialTimer),vu(this.intervalTimer),V("info","account_maintenance_started",{interval_ms:this.options.intervalMs,timeout_ms:this.options.timeoutMs,concurrency:this.options.concurrency})}stop(){if(this.initialTimer!==void 0)clearTimeout(this.initialTimer),this.initialTimer=void 0;if(this.intervalTimer!==void 0)clearInterval(this.intervalTimer),this.intervalTimer=void 0;if(!this.lifecycleController.signal.aborted)this.lifecycleController.abort(new DOMException("Account maintenance stopped","AbortError"));V("info","account_maintenance_stopped",{})}runOnce(n){if(!this.options.enabled)return Promise.resolve();if(this.inFlight)return this.inFlight;let t=this.runPass(n).finally(()=>{if(this.inFlight===t)this.inFlight=void 0});return this.inFlight=t,t}async runPass(n){let t=Date.now(),i=AbortSignal.timeout(this.options.timeoutMs),r=n?AbortSignal.any([n,i]):i,f=this.options.accountManager.reconcileFromDb().filter((u)=>!Zn(u.unhealthyReason)&&!yn(u)&&_r(this.options.accountManager.toAuthDetails(u),this.options.tokenExpiryBufferMs)),_=0,o=0,h=0,e=async()=>{for(;;){if(r.aborted)throw r.reason;let u=f[h];if(h+=1,!u)return;try{await this.options.tokenRefresher.refreshIfNeeded(u,this.options.accountManager.toAuthDetails(u),r),_+=1}catch(w){o+=1;let A=k4(w);if($i(A))try{this.options.accountManager.markUnhealthy(u,zr(A))}catch{}V("warn","account_maintenance_token_refresh_failed",{account_hash:wn(u.id),...pu(w)})}}};await Promise.all(Array.from({length:Math.min(this.options.concurrency,f.length)},e));let c=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.recheckDueAccounts(c,r);let d=this.options.accountManager.reconcileFromDb();await this.options.usageRefresher.syncDueAccounts(d,r),V("info","account_maintenance_pass_completed",{account_count:d.length,token_due_count:f.length,token_refreshed_count:_,token_failed_count:o,duration_ms:Date.now()-t})}}function nw(n,t){if(!t)return n;t.start();let i=n.stop.bind(n),r=(s)=>{try{t.stop()}finally{i(s)}};try{Object.defineProperty(n,"stop",{configurable:!0,value:r})}catch(s){try{t.stop()}finally{i(!0)}throw s}return n}var w0=4;class y0 extends Error{accountId;constructor(n){super(`Account ${n} changed too frequently to update`);this.accountId=n;this.name="AccountConcurrentUpdateError"}}function Z4(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function hr(n){return{...n}}function A0(n){return{refresh:_s({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 uf{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(n,t,i){this.strategy=t;this.database=i;this.accounts=n.map(hr)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(hr)}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:hr(i)}),this.stickyId&&!this.accounts.some(({id:i})=>i===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(n,t){let i=Date.now(),r=this.accounts.filter((f)=>this.isSelectable(f,i)).filter((f)=>t?.has(f.id)??!0).sort((f,_)=>f.id.localeCompare(_.id));if(r.length===0)return null;let s=r.find(({id:f})=>f===n)??this.selectCandidate(r);return this.patchAccount(s.id,(f)=>({...f,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:i,usedCount:(f.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(n,t){return this.patchAccount(n.id,(i)=>({...i,rateLimitResetTime:t}))}markQuotaExhausted(n,t){return this.patchAccount(n.id,(i)=>({...i,usedCount:(i.limitCount??0)>0?Math.max(i.usedCount??0,i.limitCount??0):i.usedCount,rateLimitResetTime:Math.max(i.rateLimitResetTime,t)}))}scheduleQuotaRecheck(n,t){return this.patchAccount(n.id,(i)=>yn(i)?{...i,rateLimitResetTime:Math.max(i.rateLimitResetTime,t)}:i)}updateQuotaUsage(n,t,i){for(let r=0;r<w0;r+=1){let s=this.database.getById(n.id);if(!s){this.accounts=this.accounts.filter((h)=>h.id!==n.id);return}if((s.lastSync??0)>t.lastSync)return this.replaceAccount(s),hr(s);let f=yn(s),_=yn(t),o={...s,email:t.email??s.email,usedCount:t.usedCount,limitCount:t.limitCount,overageCount:t.overageCount,lastSync:t.lastSync,rateLimitResetTime:_?Math.max(s.rateLimitResetTime,i):f?0:s.rateLimitResetTime};if(this.database.updateExistingAccounts([o])===1){let h={...o,generation:s.generation+1};return this.replaceAccount(h),hr(h)}}throw this.reconcileFromDb(),new y0(n.id)}markUnhealthy(n,t,i){let r=Date.now();return this.patchAccount(n.id,(s)=>{if(Zn(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=os(t.refresh);for(let r=0;r<w0;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 _={...f,generation:s.generation+1};return this.replaceAccount(_),hr(_)}}this.reconcileFromDb();return}toAuthDetails(n){return A0(n)}isSelectable(n,t){if(Zn(n.unhealthyReason))return!1;if(yn(n))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Qt(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 Z4(this.strategy)}}patchAccount(n,t){for(let i=0;i<w0;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),hr(f)}}throw this.reconcileFromDb(),new y0(n)}replaceAccount(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(n);else this.accounts[t]=n}}var Nw=k(B0(),1);import{existsSync as YL,promises as bw}from"fs";import{join as XL}from"path";var JL={stale:15000,retries:0,realpath:!1},QL=15000,aL=25,zL=250;function KL(n){if(typeof n!=="object"||n===null||!("code"in n))return!1;return n.code==="ELOCKED"||n.code==="ENOENT"}function G0(n){return n.reason??new DOMException("The operation was aborted","AbortError")}function xL(n,t){if(t?.aborted)return Promise.reject(G0(t));return new Promise((i,r)=>{let s=setTimeout(()=>{t?.removeEventListener("abort",f),i()},n),f=()=>{clearTimeout(s),r(G0(t))};t?.addEventListener("abort",f,{once:!0})})}function VL(n,t){let i=t.replace(/[^A-Za-z0-9_-]/g,"");return XL(n,`.kiro-refresh-${i}.lock`)}async function jL(n,t){let i=Date.now()+QL,r=0;for(;;){if(t?.aborted)throw G0(t);try{return await Nw.default.lock(n,JL)}catch(s){let f=i-Date.now();if(!KL(s)||f<=0)throw s;let _=Math.min(aL*2**Math.min(r,4),zL,f),o=Math.max(1,Math.floor(_/2)),h=o+Math.floor(Math.random()*(_-o+1));r+=1,await xL(h,t)}}}async function Uw(n,t,i,r){let s=VL(n,t);if(await bw.mkdir(n,{recursive:!0}),!YL(s))await(await bw.open(s,"a")).close();let f=await jL(s,r);try{return await i()}finally{try{await f()}catch{}}}var aw=k(W0(),1);import*as Vt from"net";import*as lf from"tls";import DI from"assert";import*as Pw from"net";import*as Yw from"http";import{Agent as $I}from"https";var xt=Symbol("AgentBaseInternalState");class F0 extends Yw.Agent{constructor(n){super(n);this[xt]={}}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(`
|
|
139
|
+
`).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 Pw.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 $I.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((_)=>{if(this.decrementSockets(s,f),typeof _.addRequest==="function")try{return _.addRequest(n,r)}catch(o){return i(o)}this[xt].currentSocket=_,super.createSocket(n,t,i)},(_)=>{this.decrementSockets(s,f),i(_)})}createConnection(){let n=this[xt].currentSocket;if(this[xt].currentSocket=void 0,!n)throw Error("No socket was returned in the `connect()` function");return n}get defaultPort(){return this[xt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(n){if(this[xt])this[xt].defaultPort=n}get protocol(){return this[xt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(n){if(this[xt])this[xt].protocol=n}}import{URL as BI}from"url";var Xw=k(W0(),1),zo=Xw.default("https-proxy-agent:parse-proxy-response");function C0(n){return new Promise((t,i)=>{let r=0,s=[];function f(){let c=n.read();if(c)e(c);else n.once("readable",f)}function _(){n.removeListener("end",o),n.removeListener("error",h),n.removeListener("readable",f)}function o(){_(),zo("onend"),i(Error("Proxy connection ended before receiving CONNECT response"))}function h(c){_(),zo("onerror %o",c),i(c)}function e(c){s.push(c),r+=c.length;let d=Buffer.concat(s,r),u=d.indexOf(`\r
|
|
140
140
|
\r
|
|
141
|
-
`);if(u===-1){
|
|
142
|
-
`),
|
|
143
|
-
`;if(i.username||i.password){let d=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(d).toString("base64")}`}if(s.Host=`${f}:${t.port}`,!s["Proxy-Connection"])s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let d of Object.keys(s))
|
|
144
|
-
`;let
|
|
145
|
-
`);let{connect:
|
|
146
|
-
`;if(r.username||r.password){let c=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;f["Proxy-Authorization"]=`Basic ${Buffer.from(c).toString("base64")}`}if(Object.assign(f,i),f.Host=`${
|
|
147
|
-
`;let
|
|
148
|
-
`);let{connect:w}=await o;if(n.emit("proxyConnect",w),this.emit("proxyConnect",w,n),w.statusCode===200){if(n.once("socket",by),t.secureEndpoint)return dr("Upgrading socket connection to TLS"),cf.connect({...bo(G_(t),"host","path","port"),socket:s});return s}throw s.destroy(),Error(`Proxy authentication failed with status ${w.statusCode} after retry`)}}df.protocols=["http","https"];function by(n){setImmediate(()=>{n.resume()})}function bo(n,...t){let i={},r;for(r in n)if(!t.includes(r))i[r]=n[r];return i}function hs(n){return n.proxy_url||void 0}function os(n){return n===void 0?{}:{proxy:n}}var tI=ir.options;function ly(n){return tI.includes(n)}function So(n){if(!n||!ly(n))return"us-east-1";return n}function uf(n,t){let i=n.replace("{{region}}",t);try{return new URL(i),i}catch{throw Error(`Invalid URL generated: ${i}`)}}function $y(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 ly(i)?i:void 0}var In={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",RUNTIME_ENDPOINT:"https://runtime.{{region}}.kiro.dev",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"},H_={"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","claude-opus-5":"claude-opus-5","claude-opus-5-thinking":"claude-opus-5",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"},Uy=Object.keys(H_),Vj=new Set(Object.keys(H_).filter((n)=>n.includes("-1m")));var iI=200000,rI={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,"claude-opus-5":1e6,"deepseek-3.2":164000,"glm-5":200000,"minimax-m2.5":196000,"minimax-m2.1":196000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function C(n){return rI[n]??iI}var yf={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 Gi extends Error{code;originalError;constructor(n,t,i){super(n);this.name="KiroTokenRefreshError",this.code=t,this.originalError=i}}function lo(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function W_(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 sI(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 fI(n,t){let i;try{i=JSON.parse(n)}catch{return{message:n,code:`HTTP_${t}`}}if(!lo(i))return{message:n,code:`HTTP_${t}`};let r=W_(i,"message","error_description")??n,s=W_(i,"__type","error")??`HTTP_${t}`;return{message:r,code:s}}function Dy(n){let t=n.userInfo;if(!lo(t))return;let i=t.email;return typeof i==="string"?i:void 0}async function F_(n,t,i){let r=pr(n.refresh),s=n.authMethod==="idc",f=s?n.oidcRegion??n.region:n.region,h=uf(s?In.REFRESH_IDC_URL:In.REFRESH_URL,f);if(s&&(!r.clientId||!r.clientSecret))throw new Gi("Missing creds","MISSING_CREDENTIALS");let _=s?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},o=s?`aws-sdk-js/${In.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${In.SDK_VERSION} m/E ${In.USER_AGENT}`:`aws-sdk-js/3.0.0 ${In.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let w=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":o,Connection:"close"},body:JSON.stringify(_),...t?{signal:t}:{},...os(i)});if(!w.ok){let y=fI(await w.text(),w.status);throw new Gi(`Refresh failed: ${y.message}`,y.code)}let c=await w.json();if(!lo(c))throw new Gi("No access token","INVALID_RESPONSE");let d=W_(c,"access_token","accessToken");if(!d)throw new Gi("No access token","INVALID_RESPONSE");let u={refreshToken:W_(c,"refresh_token","refreshToken")??r.refreshToken,authMethod:n.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:A_(u),access:d,expires:Date.now()+(sI(c,"expires_in","expiresIn")??3600)*1000,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.profileArn?{profileArn:n.profileArn}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email||Dy(c)?{email:n.email??Dy(c)}:{}}}catch(w){if(w instanceof Gi)throw w;if(w instanceof Error&&w.name==="AbortError")throw w;throw new Gi(`Token refresh failed: ${w instanceof Error?w.message:"Unknown error"}`,"NETWORK_ERROR",w instanceof Error?w:void 0)}}class Hi extends Error{accountId;constructor(n){super(`Account ${n} is no longer available`);this.accountId=n;this.name="AccountUnavailableError"}}class $o{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(!rr(t,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:s})=>s===n.id);if(!r)throw new Hi(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 Hi(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 F_(t,i,this.proxyUrl),s=this.accountManager.updateFromAuth(n,r);if(!s)throw new Hi(n.id);return s}}function hi(n){return{...n}}function _I(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function hI(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 Uo{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(hi)}selectHealthyAccount(n,t){for(let i=0;i<2;i+=1){let r=Date.now(),s=this.accounts.filter((_)=>this.isSelectable(_,r)).filter((_)=>t?.has(_.id)??!0).sort((_,o)=>_.id.localeCompare(o.id));if(s.length===0)return null;let f=s.find(({id:_})=>_===n)??this.selectCandidate(s),h=this.store.recordSelection(f.id,r);if(h)return this.publishLatest(h),hi(h);this.reconcileFromDb()}return null}getAccountCount(){return this.accounts.length}toAuthDetails(n){return no(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:hi(i)}markQuotaExhausted(n,t){let i=this.store.markQuotaExhausted(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:hi(i)}scheduleQuotaRecheck(n,t){let i=this.store.scheduleQuotaRecheck(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:hi(i)}updateQuotaUsage(n,t,i){let r=this.store.updateQuotaUsage(n.id,t,i);if(r)this.publishLatest(r);else this.reconcileFromDb();return r===void 0?void 0:hi(r)}markUnhealthy(n,t,i){let r=this.store.markUnhealthy(n.id,t,It(t),i,Date.now());if(r)this.publishLatest(r);else this.reconcileFromDb();return r===void 0?void 0:hi(r)}publishLatest(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(hi(n));else this.accounts[t]=hi(n)}isSelectable(n,t){if(It(n.unhealthyReason))return!1;if(en(n))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Ct(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 _I(this.strategy)}}}class Do{accountManager;store;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;lockDirectory;constructor(n,t,i,r,s=Ou(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 Hi(n.id);if(this.accountManager.publishLatest(r),!rr(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 dy(this.lockDirectory,n.id,async()=>{let r=this.store.getById(n.id);if(!r)throw new Hi(n.id);let s=this.accountManager.toAuthDetails(r);if(t&&!hI(n,r)||!t&&!rr(s,this.tokenExpiryBufferMs))return this.accountManager.publishLatest(r),r;try{let f=await F_(s,i,this.proxyUrl),h=pr(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}:{}},o=this.store.persistRefreshedAccount(r,_);if(!o)throw new Hi(n.id);return this.accountManager.publishLatest(o),o}catch(f){let h=typeof f==="object"&&f!==null&&"code"in f?String(f.code):"",_=f instanceof Error?f.message:String(f),o=h?`${h}: ${_}`:_;if(gi(o))this.accountManager.markUnhealthy(r,Pr(o));throw f}},i)}}var oI=A.object({usageBreakdownList:A.array(A.object({currentUsage:A.number().optional(),usageLimit:A.number().optional(),currentOverages:A.number().optional(),freeTrialInfo:A.object({currentUsage:A.number().optional(),usageLimit:A.number().optional()}).passthrough().nullable().optional()}).passthrough()).optional(),userInfo:A.object({email:A.string().optional()}).passthrough().optional()}).passthrough(),By=[{resourceType:"AGENTIC_REQUEST",origin:"AI_EDITOR"},{origin:"AI_EDITOR"},{resourceType:"CONVERSATION",origin:"AI_EDITOR"},{}];class oi extends Error{status;upstreamCode;name="KiroUsageError";constructor(n,t,i,r){super(n,r);this.status=t;this.upstreamCode=i}}function Gy(n){return n.reason instanceof Error?n.reason:new DOMException("Kiro usage request was aborted","AbortError")}function wI(n){return n.headers.get("x-amzn-requestid")??n.headers.get("x-amzn-request-id")??n.headers.get("x-amz-request-id")??void 0}function cI(n){return n.headers.get("x-amzn-errortype")??n.headers.get("x-amzn-error-type")??void 0}function dI(n){let t=oI.safeParse(n);if(!t.success)throw new oi("Kiro usage service returned an invalid response shape");let i=0,r=0,s=0;for(let f of t.data.usageBreakdownList??[]){if(f.freeTrialInfo)i+=f.freeTrialInfo.currentUsage??0,r+=f.freeTrialInfo.usageLimit??0;i+=f.currentUsage??0,r+=f.usageLimit??0,s+=f.currentOverages??0}return{usedCount:i,limitCount:r,overageCount:s,...t.data.userInfo?.email?{email:t.data.userInfo.email}:{}}}function Hy(n){return n instanceof oi&&(n.status===401||n.status===403&&Ct(n.message))}async function Wy(n,t={}){let i=AbortSignal.timeout(t.timeoutMs??1e4),r=t.signal===void 0?i:AbortSignal.any([t.signal,i]),s;for(let[f,h]of By.entries()){if(r.aborted)throw Gy(r);let _=new URL(`https://q.${n.region}.amazonaws.com/getUsageLimits`);if(_.searchParams.set("isEmailRequired","true"),h.origin)_.searchParams.set("origin",h.origin);if(h.resourceType)_.searchParams.set("resourceType",h.resourceType);if(n.profileArn)_.searchParams.set("profileArn",n.profileArn);let o;try{o=await fetch(_,{method:"GET",signal:r,headers:{Authorization:`Bearer ${n.access}`,"Content-Type":"application/json","x-amzn-kiro-agent-mode":"vibe","amz-sdk-request":"attempt=1; max=1"},...os(t.proxyUrl)})}catch(c){if(r.aborted)throw Gy(r);s=c instanceof Error?c:new oi(String(c));continue}if(!o.ok){let c=await o.text().catch(()=>""),d=wI(o),u=cI(o),y=c.length>0?`${c.slice(0,2000)}${c.length>2000?"\u2026":""}`:`HTTP ${o.status}`,R=new oi(`Kiro usage service returned HTTP ${o.status}${u?` (${u})`:""}${d?` [${d}]`:""}: ${y}`,o.status,u);if(c.includes("FEATURE_NOT_SUPPORTED")&&f<By.length-1){s=R;continue}if(o.status===401||o.status===403)throw R;s=R;continue}let w;try{w=await o.json()}catch(c){throw new oi("Kiro usage service returned invalid JSON",o.status,void 0,{cause:c})}return dI(w)}throw s??new oi("All Kiro usage service request variants failed")}var uI=new Map,yI=new Map;function $t(n){return n.reason instanceof Error?n.reason:new DOMException("The request was aborted","AbortError")}function wi(n,t){if(t.aborted)return Promise.reject($t(t));return new Promise((i,r)=>{let s=()=>r($t(t));t.addEventListener("abort",s,{once:!0}),n.then((f)=>{t.removeEventListener("abort",s),i(f)},(f)=>{t.removeEventListener("abort",s),r(f)})})}function Bo(n,t){if(n<=0)return Promise.resolve();return wi(Bun.sleep(n),t)}async function Fy(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((d)=>{h=d});if(!h)throw TypeError("Queue release was not initialized");let o=h;s.waiters+=1,s.tail=f.catch(()=>{return}).then(()=>_);let w=()=>{if(s.waiters-=1,s.waiters!==0)return;s.tail.finally(()=>{if(s.waiters===0&&n.get(t)===s)n.delete(t)})};try{await wi(f,i)}catch(d){throw o(),w(),d}let c=!1;return()=>{if(c)return;c=!0,o(),w()}}function Go(n,t){return Fy(uI,n,t)}function Yy(n,t){return Fy(yI,n,t)}function Py(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 Xy(n,t){return en(n)&&!It(n.unhealthyReason)&&n.rateLimitResetTime<=t}function AI(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0,i=n instanceof Error?n.message:String(n);return t?`${t}: ${i}`:i}function RI(n){if(n instanceof oi)return{error_name:n.name,error_status:n.status,error_code:n.upstreamCode};let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0;return{error_name:n instanceof Error?n.name:"UnknownError",error_code:t}}class Y_{options;inFlight=new Map;usageRetryAfter=new Map;now;fetchUsage;constructor(n){this.options=n;this.now=n.now??Date.now,this.fetchUsage=n.fetchUsage??Wy}async recheckDueAccounts(n,t,i){let r=this.now(),s=n.filter((f)=>Xy(f,r)).sort((f,h)=>Number(h.id===i)-Number(f.id===i)||f.rateLimitResetTime-h.rateLimitResetTime||(f.lastSync??0)-(h.lastSync??0)||f.id.localeCompare(h.id));if(s.length===0)return;await this.runBatch(s,t,"quota_recheck",!0,i)}async syncDueAccounts(n,t){let i=this.now(),r=n.filter((s)=>this.isUsageRefreshDue(s,i)).sort((s,f)=>(s.lastSync??0)-(f.lastSync??0)||s.id.localeCompare(f.id));if(r.length===0)return;await this.runBatch(r,t,"usage_refresh",!1)}async runBatch(n,t,i,r,s){k("info",`${i}_batch_started`,{account_count:n.length,concurrency:this.options.concurrency,preferred_account_present:s!==void 0&&n.some(({id:c})=>c===s)});let f=r?AbortSignal.timeout(this.options.timeoutMs):void 0,h=f?AbortSignal.any([t,f]):t,_=0,o={updated:0,recovered:0,exhausted:0,failed:0,skipped:0},w=async()=>{for(;;){if(h.aborted)throw $t(h);let c=n[_];if(_+=1,!c)return;let d=await wi(this.startOrJoin(c),h);o[d]+=1}};try{await Promise.all(Array.from({length:Math.min(this.options.concurrency,n.length)},w))}catch(c){if(t.aborted)throw $t(t);if(!f?.aborted)throw c;k("warn",`${i}_batch_timeout`,{account_count:n.length,started_count:Math.min(_,n.length),timeout_ms:this.options.timeoutMs});return}k("info",`${i}_batch_completed`,{account_count:n.length,updated_count:o.updated,recovered_count:o.recovered,exhausted_count:o.exhausted,failed_count:o.failed,skipped_count:o.skipped})}isUsageRefreshDue(n,t){if(It(n.unhealthyReason)||en(n))return!1;if((this.usageRetryAfter.get(n.id)??0)>t)return!1;return(n.lastSync??0)+this.options.usageRefreshIntervalMs<=t}startOrJoin(n){let t=this.inFlight.get(n.id);if(t)return t;let i=this.runProbe(n).finally(()=>{if(this.inFlight.get(n.id)===i)this.inFlight.delete(n.id)});return this.inFlight.set(n.id,i),i}async runProbe(n){let t=AbortSignal.timeout(this.options.timeoutMs),i=n;try{let r=this.options.accountManager.toAuthDetails(n);if(i=await this.options.tokenRefresher.refreshIfNeeded(n,r,t),!Xy(i,this.now())&&!this.isUsageRefreshDue(i,this.now()))return"skipped";let s=en(i),f=this.options.accountManager.toAuthDetails(i),h;try{h=await this.fetchUsage(f,{proxyUrl:this.options.proxyUrl,signal:t,timeoutMs:this.options.timeoutMs})}catch(u){if(!Hy(u))throw u;i=await this.options.tokenRefresher.forceRefresh(i,t),f=this.options.accountManager.toAuthDetails(i),h=await this.fetchUsage(f,{proxyUrl:this.options.proxyUrl,signal:t,timeoutMs:this.options.timeoutMs})}let _=this.now(),w=en(h)?_+this.options.intervalMs:0,c=this.options.accountManager.updateQuotaUsage(i,{...h,lastSync:_},w);if(!c)return"skipped";if(this.usageRetryAfter.delete(i.id),en(c))return k("info",s?"quota_recheck_still_exhausted":"usage_refresh_detected_exhaustion",{account_hash:Rn(i.id),next_recheck_at:c.rateLimitResetTime}),"exhausted";if(s)return k("info","quota_exhausted_account_recovered",{account_hash:Rn(i.id)}),"recovered";return"updated"}catch(r){let s=this.now()+this.options.intervalMs,f=AI(r);if(gi(f)){try{this.options.accountManager.markUnhealthy(i,Pr(f))}catch{}this.usageRetryAfter.delete(i.id)}else if(en(i))try{this.options.accountManager.scheduleQuotaRecheck(i,s)}catch{}else this.usageRetryAfter.set(i.id,s);return k("warn",en(i)?"quota_recheck_failed":"usage_refresh_failed",{account_hash:Rn(n.id),next_recheck_at:s,...RI(r)}),"failed"}}}var Cy=500;function MI(n){k("warn","stream_cleanup_failed",{error_type:n instanceof Error?n.name:typeof n})}function Jy(n,t){try{n()}catch(i){let r=t??MI;try{r(i)}catch{}}}function Vn(...n){for(let t of n)Jy(t)}function Mn(n){let t,i=Promise.resolve().then(n).then(()=>{return},()=>{return}),r=new Promise((s)=>{t=setTimeout(s,Cy)});return Promise.race([i,r]).then(()=>{if(t!==void 0)clearTimeout(t)},()=>{if(t!==void 0)clearTimeout(t)})}class Wi extends Error{status;name="KiroManagementError";constructor(n,t,i){super(n,i);this.status=t}}function Af(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Qy(n){return typeof n==="number"&&Number.isInteger(n)&&n>0?n:void 0}function EI(n){if(!Af(n))return;let t=typeof n.modelId==="string"?n.modelId.trim():"",i=typeof n.modelName==="string"?n.modelName.trim():"";if(t.length===0||i.length===0||!Af(n.tokenLimits))return;let r=Qy(n.tokenLimits.maxInputTokens),s=Qy(n.tokenLimits.maxOutputTokens);if(r===void 0||s===void 0)return;let f=Array.isArray(n.supportedInputTypes)?n.supportedInputTypes.filter((h)=>h==="TEXT"||h==="IMAGE"):[];return{modelId:t,modelName:i,...typeof n.description==="string"?{description:n.description}:{},supportedInputTypes:f,tokenLimits:{maxInputTokens:r,maxOutputTokens:s},...typeof n.rateMultiplier==="number"?{rateMultiplier:n.rateMultiplier}:{},...Af(n.additionalModelRequestFieldsSchema)?{additionalModelRequestFieldsSchema:n.additionalModelRequestFieldsSchema}:{}}}function TI(n){if(!Af(n)||!Array.isArray(n.models))throw new Wi("Kiro model catalog response has an invalid shape");let t=n.models.flatMap((r)=>{let s=EI(r);return s===void 0?[]:[s]});if(t.length===0)throw new Wi("Kiro model catalog response contains no valid models");let i=Af(n.defaultModel)&&typeof n.defaultModel.modelId==="string"?n.defaultModel.modelId:void 0;return{...i!==void 0?{defaultModelId:i}:{},models:t}}async function my(n,t,i={}){let r=new URL(`https://management.${t}.kiro.dev/`);if(r.searchParams.set("origin",In.ORIGIN_AI_EDITOR),n.profileArn)r.searchParams.set("profileArn",n.profileArn);let s=AbortSignal.timeout(i.timeoutMs??1e4),f=i.signal===void 0?s:AbortSignal.any([i.signal,s]),h;try{h=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${n.access}`,"Content-Type":"application/x-amz-json-1.0","x-amz-target":"AmazonCodeWhispererService.ListAvailableModels","user-agent":In.USER_AGENT},body:JSON.stringify({origin:In.ORIGIN_AI_EDITOR,...n.profileArn?{profileArn:n.profileArn}:{}}),signal:f,...os(i.proxyUrl)})}catch(o){throw new Wi("Unable to reach the Kiro model catalog service",void 0,{cause:o})}if(!h.ok)throw new Wi(`Kiro model catalog returned HTTP ${h.status}`,h.status);let _;try{_=await h.json()}catch(o){throw new Wi("Kiro model catalog returned invalid JSON",h.status,{cause:o})}return TI(_)}var zy=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),$n=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),on=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),Sq=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","claude-opus-5","claude-opus-5-low","claude-opus-5-medium","claude-opus-5-high","claude-opus-5-xhigh","claude-opus-5-max","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"]),Rf=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:C("auto"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:C("claude-sonnet-4"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:C("claude-sonnet-4-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:C("claude-sonnet-4-6"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:C("claude-sonnet-4-6"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:C("claude-sonnet-4-6"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:C("claude-sonnet-4-6"),outputLimit:64000,modalities:on},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:C("claude-sonnet-4-6"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:C("claude-sonnet-5"),outputLimit:64000,modalities:on},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:C("claude-haiku-4-5"),outputLimit:64000,modalities:$n},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:C("claude-opus-4-5"),outputLimit:64000,modalities:on},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:C("claude-opus-4-6"),outputLimit:64000,modalities:on},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:C("claude-opus-4-7"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:C("claude-opus-4-8"),outputLimit:128000,modalities:on},{id:"claude-opus-5",wireId:"claude-opus-5",name:"Claude Opus 5 (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"claude-opus-5-low",wireId:"claude-opus-5",name:"Claude Opus 5 (low) (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"claude-opus-5-medium",wireId:"claude-opus-5",name:"Claude Opus 5 (medium) (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"claude-opus-5-high",wireId:"claude-opus-5",name:"Claude Opus 5 (high) (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"claude-opus-5-xhigh",wireId:"claude-opus-5",name:"Claude Opus 5 (xhigh) (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"claude-opus-5-max",wireId:"claude-opus-5",name:"Claude Opus 5 (max) (2.2x)",contextLimit:C("claude-opus-5"),outputLimit:128000,modalities:on},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:C("deepseek-3.2"),outputLimit:64000,modalities:$n},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:C("glm-5"),outputLimit:64000,modalities:zy},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:C("minimax-m2.5"),outputLimit:64000,modalities:zy},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:C("minimax-m2.1"),outputLimit:64000,modalities:$n},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:C("qwen3-coder-next"),outputLimit:64000,modalities:$n},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:C("gpt-5.6-sol"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.0x)",contextLimit:C("gpt-5.6-terra"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low) (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium) (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high) (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh) (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max) (0.1x)",contextLimit:C("gpt-5.6-luna"),outputLimit:128000,modalities:$n}]);function eI(n){return{input:n.supportedInputTypes.includes("IMAGE")?["text","image"]:["text"],output:["text"]}}function Ky(n){let t=new Map;for(let i of Rf){let r=t.get(i.wireId)??[];r.push(i),t.set(i.wireId,r)}return n.flatMap((i)=>{let r={contextLimit:i.tokenLimits.maxInputTokens,outputLimit:i.tokenLimits.maxOutputTokens,modalities:eI(i),...i.description!==void 0?{description:i.description}:{},...i.rateMultiplier!==void 0?{rateMultiplier:i.rateMultiplier}:{},...i.additionalModelRequestFieldsSchema!==void 0?{additionalModelRequestFieldsSchema:i.additionalModelRequestFieldsSchema}:{}},s=t.get(i.modelId);if(s&&s.length>0)return s.map((f)=>({...f,...r}));return[{id:i.modelId,wireId:i.modelId,name:i.modelName,...r}]})}var Ho=new Map;function xy(n){return H_[n]??Ho.get(n)}function Mf(n){for(let t of n){let i=t.trim();if(i.length===0)continue;Ho.set(i,i)}}function jy(n){try{return ci(n),!0}catch{return!1}}function Vy(n){let t=xy(n);if(!t){let i=[...Uy,...Ho.keys()];throw Error(`Unsupported model: ${n}. Supported models: ${i.join(", ")}`)}return t}var qy=new Set(["claude-opus-5","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"]),ky=["low","medium","high","xhigh","max"];function ci(n){for(let t of ky){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(qy.has(r))return{wireId:Vy(r),effort:t}}}return{wireId:Vy(n),effort:void 0}}function OI(n){for(let t of ky){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(qy.has(r))return r}}if(n.endsWith("-thinking")){let t=n.slice(0,-9);if(xy(t))return t}return n}function ay(n){return C(OI(n))}function P_(n){try{return ci(n).wireId}catch{return}}class Wo{config;listModels;snapshots=new Map;inFlight=new Map;failedAt=new Map;lastSuccessAt;constructor(n,t=my){this.config=n;this.listModels=t}async ensureAccountModel(n,t,i,r){if(!this.config.dynamic_model_catalog){let h=P_(i);return h===void 0?{supported:!1,source:"disabled"}:{supported:!0,source:"disabled",wireModel:h}}let s=await this.refreshAccount(n,t,r);if(s!==void 0){Mf(s.models.keys());let h=P_(i);if(h!==void 0&&s.models.has(h))return{supported:!0,source:this.isFresh(s)?"live":"stale",wireModel:h};return{supported:!1,source:this.isFresh(s)?"live":"stale"}}let f=P_(i);return f===void 0?{supported:!1,source:"static"}:{supported:!0,source:"static",wireModel:f}}eligibleAccountIds(n,t){if(!this.config.dynamic_model_catalog)return;this.registerUsableModels();let i=P_(n),r=Date.now(),s=new Set,f=!1;for(let h of t){let _=this.snapshots.get(h);if(!_||!this.isUsable(_,r)){s.add(h);continue}if(f=!0,i!==void 0&&_.models.has(i))s.add(h)}return f?s:void 0}isKnownModel(n){return this.registerUsableModels(),jy(n)}catalog(){let n=new Map,t=Date.now();for(let i of this.snapshots.values()){if(!this.isUsable(i,t))continue;for(let[r,s]of i.models)n.set(r,s)}if(n.size===0)return Rf;return Mf(n.keys()),Ky([...n.values()])}readiness(){if(!this.config.dynamic_model_catalog)return{enabled:!1,usable:!0,source:"disabled",freshAccounts:0,staleAccounts:0};let n=Date.now(),t=0,i=0;for(let r of this.snapshots.values())if(this.isFresh(r,n))t+=1;else if(this.isUsable(r,n))i+=1;return{enabled:!0,usable:!0,source:t>0?"live":i>0?"stale":"static",freshAccounts:t,staleAccounts:i,...this.lastSuccessAt!==void 0?{lastSuccessAt:this.lastSuccessAt}:{}}}async refreshAccounts(n,t,i){await Promise.allSettled(n.map((r)=>this.refreshAccount(r,t(r),i)))}async refreshAccount(n,t,i){let r=this.snapshots.get(n.id);if(r&&this.isFresh(r))return r;let s=this.inFlight.get(n.id);if(s)try{return await s}catch{return this.usableSnapshot(n.id)}let f=this.fetchSnapshot(n,t,i).finally(()=>{if(this.inFlight.get(n.id)===f)this.inFlight.delete(n.id)});this.inFlight.set(n.id,f);try{return await f}catch(h){let _=Date.now(),o=this.failedAt.get(n.id)??0;if(this.failedAt.set(n.id,_),_-o>=this.config.model_catalog_ttl_ms)k("warn","model_catalog_refresh_failed",{account_hash:Rn(n.id),status:h instanceof Wi?h.status:void 0,stale_available:this.usableSnapshot(n.id,_)!==void 0});return this.usableSnapshot(n.id,_)}}async fetchSnapshot(n,t,i){let r=await this.listModels(t,n.region,{proxyUrl:this.config.proxy_url||void 0,signal:i,timeoutMs:this.config.model_catalog_request_timeout_ms}),s=Date.now(),f={accountId:n.id,fetchedAt:s,models:new Map(r.models.map((h)=>[h.modelId,h]))};return this.snapshots.set(n.id,f),this.failedAt.delete(n.id),this.lastSuccessAt=s,Mf(f.models.keys()),k("info","model_catalog_refreshed",{account_hash:Rn(n.id),model_count:f.models.size,default_model:r.defaultModelId}),f}registerUsableModels(){let n=Date.now();for(let t of this.snapshots.values())if(this.isUsable(t,n))Mf(t.models.keys())}usableSnapshot(n,t=Date.now()){let i=this.snapshots.get(n);return i&&this.isUsable(i,t)?i:void 0}isFresh(n,t=Date.now()){return t-n.fetchedAt<=this.config.model_catalog_ttl_ms}isUsable(n,t=Date.now()){return t-n.fetchedAt<=this.config.model_catalog_stale_ttl_ms}}import{createCipheriv as WI,createDecipheriv as FI,createHash as YI,randomBytes as rA,timingSafeEqual as PI}from"crypto";import{createHash as LI,randomBytes as Zy}from"crypto";import{chmodSync as nA,closeSync as II,existsSync as X_,fsyncSync as gI,mkdirSync as NI,openSync as bI,readFileSync as SI,renameSync as lI,unlinkSync as vy,writeFileSync as $I}from"fs";import{homedir as py}from"os";import{dirname as UI,join as Fo}from"path";function DI(){let n=process.platform==="win32"?process.env.APPDATA??Fo(py(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??Fo(py(),".config");return Fo(n,"kiro-provider","reasoning-replay-keys.json")}var BI=DI();function Yo(n){return`rk_${LI("sha256").update(n).digest("hex").slice(0,16)}`}function GI(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 tA(n,t){let i=n.indexOf(":"),r=i>0?n.slice(0,i):void 0,s=i>0?n.slice(i+1):n,f=GI(s,t),h=r??Yo(f);if(!/^[A-Za-z0-9._-]{1,128}$/.test(h))throw TypeError(`${t} contains an invalid key id`);return{id:h,key:f}}function Xo(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 Po(n){let t;try{t=JSON.parse(SI(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 tA(`${r.id}:${r.key}`,`${n} keys.${s}`)});if(process.platform!=="win32")nA(n,384);return Xo(i,"file",n)}function HI(n){NI(UI(n),{recursive:!0});let t=Uint8Array.from(Zy(32)),i={version:1,keys:[{id:Yo(t),key:Buffer.from(t).toString("base64url")}]},r=`${n}.tmp-${process.pid}-${Zy(6).toString("hex")}`,s=bI(r,"wx",384);try{$I(s,`${JSON.stringify(i,null,2)}
|
|
149
|
-
`,"utf8"),
|
|
141
|
+
`);if(u===-1){zo("have not received end of HTTP headers yet..."),f();return}let w=d.slice(0,u).toString("ascii").split(`\r
|
|
142
|
+
`),A=w.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(" "),T={};for(let l of w){if(!l)continue;let g=l.indexOf(":");if(g===-1)return n.destroy(),i(Error(`Invalid header from proxy CONNECT response: "${l}"`));let O=l.slice(0,g).toLowerCase(),N=l.slice(g+1).trimStart(),F=T[O];if(typeof F==="string")T[O]=[F,N];else if(Array.isArray(F))F.push(N);else T[O]=N}zo("got proxy server response: %o %o",A,T),_(),t({connect:{statusCode:M,statusText:E,headers:T},buffered:d})}n.on("error",h),n.on("end",o),f()})}function Jw(){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,o=await(await i.initializeClient("HTTP@proxy",{mechOID:i.GSS_MECH_OID_SPNEGO})).step(f||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var Ar=aw.default("https-proxy-agent"),Ko=(n)=>{if(n.servername===void 0&&n.host&&!Vt.isIP(n.host))return{...n,servername:n.host};return n};class Tf extends F0{constructor(n,t){super(t);if(this.options={path:void 0},this.proxy=typeof n==="string"?new BI(n):n,this.proxyHeaders=t?.headers??{},Ar("Creating new HttpsProxyAgent instance: %o",this.proxy.href),t?.negotiate)this.onProxyAuth=Jw();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?P0(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:")Ar("Creating `tls.Socket`: %o",this.connectOpts),r=lf.connect(Ko(this.connectOpts));else Ar("Creating `net.Socket`: %o",this.connectOpts),r=Vt.connect(this.connectOpts);let s=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=Vt.isIPv6(t.host)?`[${t.host}]`:t.host,_=`CONNECT ${f}:${t.port} HTTP/1.1\r
|
|
143
|
+
`;if(i.username||i.password){let d=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(d).toString("base64")}`}if(s.Host=`${f}:${t.port}`,!s["Proxy-Connection"])s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let d of Object.keys(s))_+=`${d}: ${s[d]}\r
|
|
144
|
+
`;let o=C0(r);r.write(`${_}\r
|
|
145
|
+
`);let{connect:h,buffered:e}=await o;if(n.emit("proxyConnect",h),this.emit("proxyConnect",h,n),n.emit("proxy",{proxy:this.proxy.href,socket:r}),h.statusCode===200){if(n.once("socket",Qw),t.secureEndpoint)return Ar("Upgrading socket connection to TLS"),lf.connect({...P0(Ko(t),"host","path","port"),socket:r});return r}if(h.statusCode===407&&this.onProxyAuth){Ar("Got 407 response, invoking onProxyAuth callback"),r.destroy();let d=h.headers["proxy-authenticate"]||"",u=Array.isArray(d)?d[0].split(/\s/)[0]:d.split(/\s/)[0],w=await this.onProxyAuth({response:h,scheme:u});return this._connectWithAuth(n,t,w.headers)}r.destroy();let c=new Vt.Socket({writable:!1});return c.readable=!0,n.once("socket",(d)=>{Ar("Replaying proxy buffer for failed request"),DI(d.listenerCount("data")>0),d.push(e),d.push(null)}),c}async _connectWithAuth(n,t,i){let{proxy:r}=this,s;if(r.protocol==="https:")s=lf.connect(Ko(this.connectOpts));else s=Vt.connect(this.connectOpts);let f=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},_=Vt.isIPv6(t.host)?`[${t.host}]`:t.host,o=`CONNECT ${_}:${t.port} HTTP/1.1\r
|
|
146
|
+
`;if(r.username||r.password){let c=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;f["Proxy-Authorization"]=`Basic ${Buffer.from(c).toString("base64")}`}if(Object.assign(f,i),f.Host=`${_}:${t.port}`,!f["Proxy-Connection"])f["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let c of Object.keys(f))o+=`${c}: ${f[c]}\r
|
|
147
|
+
`;let h=C0(s);s.write(`${o}\r
|
|
148
|
+
`);let{connect:e}=await h;if(n.emit("proxyConnect",e),this.emit("proxyConnect",e,n),e.statusCode===200){if(n.once("socket",Qw),t.secureEndpoint)return Ar("Upgrading socket connection to TLS"),lf.connect({...P0(Ko(t),"host","path","port"),socket:s});return s}throw s.destroy(),Error(`Proxy authentication failed with status ${e.statusCode} after retry`)}}Tf.protocols=["http","https"];function Qw(n){setImmediate(()=>{n.resume()})}function P0(n,...t){let i={},r;for(r in n)if(!t.includes(r))i[r]=n[r];return i}function di(n){return n.proxy_url||void 0}function As(n){return n===void 0?{}:{proxy:n}}var GI=or.options;function zw(n){return GI.includes(n)}function Y0(n){if(!n||!zw(n))return"us-east-1";return n}function gf(n,t){let i=n.replace("{{region}}",t);try{return new URL(i),i}catch{throw Error(`Invalid URL generated: ${i}`)}}function Kw(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 zw(i)?i:void 0}var On={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",RUNTIME_ENDPOINT:"https://runtime.{{region}}.kiro.dev",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"},xo={"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","claude-opus-5":"claude-opus-5","claude-opus-5-thinking":"claude-opus-5",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"},xw=Object.keys(xo),$j=new Set(Object.keys(xo).filter((n)=>n.includes("-1m")));var mI=200000,HI={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,"claude-opus-5":1e6,"deepseek-3.2":164000,"glm-5":200000,"minimax-m2.5":196000,"minimax-m2.1":196000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function Y(n){return HI[n]??mI}var Of={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 Pi extends Error{code;originalError;constructor(n,t,i){super(n);this.name="KiroTokenRefreshError",this.code=t,this.originalError=i}}function X0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Vo(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 WI(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 FI(n,t){let i;try{i=JSON.parse(n)}catch{return{message:n,code:`HTTP_${t}`}}if(!X0(i))return{message:n,code:`HTTP_${t}`};let r=Vo(i,"message","error_description")??n,s=Vo(i,"__type","error")??`HTTP_${t}`;return{message:r,code:s}}function Vw(n){let t=n.userInfo;if(!X0(t))return;let i=t.email;return typeof i==="string"?i:void 0}async function jo(n,t,i){let r=os(n.refresh),s=n.authMethod==="idc",f=s?n.oidcRegion??n.region:n.region,_=gf(s?On.REFRESH_IDC_URL:On.REFRESH_URL,f);if(s&&(!r.clientId||!r.clientSecret))throw new Pi("Missing creds","MISSING_CREDENTIALS");let o=s?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},h=s?`aws-sdk-js/${On.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${On.SDK_VERSION} m/E ${On.USER_AGENT}`:`aws-sdk-js/3.0.0 ${On.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let e=await fetch(_,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":h,Connection:"close"},body:JSON.stringify(o),...t?{signal:t}:{},...As(i)});if(!e.ok){let w=FI(await e.text(),e.status);throw new Pi(`Refresh failed: ${w.message}`,w.code)}let c=await e.json();if(!X0(c))throw new Pi("No access token","INVALID_RESPONSE");let d=Vo(c,"access_token","accessToken");if(!d)throw new Pi("No access token","INVALID_RESPONSE");let u={refreshToken:Vo(c,"refresh_token","refreshToken")??r.refreshToken,authMethod:n.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:_s(u),access:d,expires:Date.now()+(WI(c,"expires_in","expiresIn")??3600)*1000,authMethod:n.authMethod,region:n.region,...n.oidcRegion?{oidcRegion:n.oidcRegion}:{},...n.profileArn?{profileArn:n.profileArn}:{},...n.clientId?{clientId:n.clientId}:{},...n.clientSecret?{clientSecret:n.clientSecret}:{},...n.email||Vw(c)?{email:n.email??Vw(c)}:{}}}catch(e){if(e instanceof Pi)throw e;if(e instanceof Error&&e.name==="AbortError")throw e;throw new Pi(`Token refresh failed: ${e instanceof Error?e.message:"Unknown error"}`,"NETWORK_ERROR",e instanceof Error?e:void 0)}}class Yi extends Error{accountId;constructor(n){super(`Account ${n} is no longer available`);this.accountId=n;this.name="AccountUnavailableError"}}class Lf{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(!_r(t,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:s})=>s===n.id);if(!r)throw new Yi(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 Yi(n.id);let r={...n,generation:n.generation},s=`${r.id}:${r.generation}`,f=this.inFlight.get(s);if(f)return f;let _=this.runRefresh(r,t,i).finally(()=>{if(this.inFlight.get(s)===_)this.inFlight.delete(s)});return this.inFlight.set(s,_),_}async runRefresh(n,t,i){let r=await jo(t,i,this.proxyUrl),s=this.accountManager.updateFromAuth(n,r);if(!s)throw new Yi(n.id);return s}}function ui(n){return{...n}}function CI(n){throw TypeError(`Unsupported account selection strategy: ${String(n)}`)}function PI(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 J0{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(ui)}selectHealthyAccount(n,t){for(let i=0;i<2;i+=1){let r=Date.now(),s=this.accounts.filter((o)=>this.isSelectable(o,r)).filter((o)=>t?.has(o.id)??!0).sort((o,h)=>o.id.localeCompare(h.id));if(s.length===0)return null;let f=s.find(({id:o})=>o===n)??this.selectCandidate(s),_=this.store.recordSelection(f.id,r);if(_)return this.publishLatest(_),ui(_);this.reconcileFromDb()}return null}getAccountCount(){return this.accounts.length}toAuthDetails(n){return A0(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:ui(i)}markQuotaExhausted(n,t){let i=this.store.markQuotaExhausted(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:ui(i)}scheduleQuotaRecheck(n,t){let i=this.store.scheduleQuotaRecheck(n.id,t);if(i)this.publishLatest(i);else this.reconcileFromDb();return i===void 0?void 0:ui(i)}updateQuotaUsage(n,t,i){let r=this.store.updateQuotaUsage(n.id,t,i);if(r)this.publishLatest(r);else this.reconcileFromDb();return r===void 0?void 0:ui(r)}markUnhealthy(n,t,i){let r=this.store.markUnhealthy(n.id,t,Zn(t),i,Date.now());if(r)this.publishLatest(r);else this.reconcileFromDb();return r===void 0?void 0:ui(r)}publishLatest(n){let t=this.accounts.findIndex(({id:i})=>i===n.id);if(t===-1)this.accounts.push(ui(n));else this.accounts[t]=ui(n)}isSelectable(n,t){if(Zn(n.unhealthyReason))return!1;if(yn(n))return!1;if(n.rateLimitResetTime>t)return!1;if(n.isHealthy||Qt(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 CI(this.strategy)}}}class Q0{accountManager;store;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;lockDirectory;constructor(n,t,i,r,s=Cu(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 Yi(n.id);if(this.accountManager.publishLatest(r),!_r(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 Uw(this.lockDirectory,n.id,async()=>{let r=this.store.getById(n.id);if(!r)throw new Yi(n.id);let s=this.accountManager.toAuthDetails(r);if(t&&!PI(n,r)||!t&&!_r(s,this.tokenExpiryBufferMs))return this.accountManager.publishLatest(r),r;try{let f=await jo(s,i,this.proxyUrl),_=os(f.refresh),o={...r,refreshToken:_.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}:{},..._.clientId?{clientId:_.clientId}:{},..._.clientSecret?{clientSecret:_.clientSecret}:{}},h=this.store.persistRefreshedAccount(r,o);if(!h)throw new Yi(n.id);return this.accountManager.publishLatest(h),h}catch(f){let _=typeof f==="object"&&f!==null&&"code"in f?String(f.code):"",o=f instanceof Error?f.message:String(f),h=_?`${_}: ${o}`:o;if($i(h))this.accountManager.markUnhealthy(r,zr(h));throw f}},i)}}var YI=y.object({usageBreakdownList:y.array(y.object({currentUsage:y.number().optional(),usageLimit:y.number().optional(),currentOverages:y.number().optional(),freeTrialInfo:y.object({currentUsage:y.number().optional(),usageLimit:y.number().optional()}).passthrough().nullable().optional()}).passthrough()).optional(),userInfo:y.object({email:y.string().optional()}).passthrough().optional()}).passthrough(),jw=[{resourceType:"AGENTIC_REQUEST",origin:"AI_EDITOR"},{origin:"AI_EDITOR"},{resourceType:"CONVERSATION",origin:"AI_EDITOR"},{}];class wi extends Error{status;upstreamCode;name="KiroUsageError";constructor(n,t,i,r){super(n,r);this.status=t;this.upstreamCode=i}}function qw(n){return n.reason instanceof Error?n.reason:new DOMException("Kiro usage request was aborted","AbortError")}function XI(n){return n.headers.get("x-amzn-requestid")??n.headers.get("x-amzn-request-id")??n.headers.get("x-amz-request-id")??void 0}function JI(n){return n.headers.get("x-amzn-errortype")??n.headers.get("x-amzn-error-type")??void 0}function QI(n){let t=YI.safeParse(n);if(!t.success)throw new wi("Kiro usage service returned an invalid response shape");let i=0,r=0,s=0;for(let f of t.data.usageBreakdownList??[]){if(f.freeTrialInfo)i+=f.freeTrialInfo.currentUsage??0,r+=f.freeTrialInfo.usageLimit??0;i+=f.currentUsage??0,r+=f.usageLimit??0,s+=f.currentOverages??0}return{usedCount:i,limitCount:r,overageCount:s,...t.data.userInfo?.email?{email:t.data.userInfo.email}:{}}}function kw(n){return n instanceof wi&&(n.status===401||n.status===403&&Qt(n.message))}async function qo(n,t={}){let i=AbortSignal.timeout(t.timeoutMs??1e4),r=t.signal===void 0?i:AbortSignal.any([t.signal,i]),s;for(let[f,_]of jw.entries()){if(r.aborted)throw qw(r);let o=new URL(`https://q.${n.region}.amazonaws.com/getUsageLimits`);if(o.searchParams.set("isEmailRequired","true"),_.origin)o.searchParams.set("origin",_.origin);if(_.resourceType)o.searchParams.set("resourceType",_.resourceType);if(n.profileArn)o.searchParams.set("profileArn",n.profileArn);let h;try{h=await fetch(o,{method:"GET",signal:r,headers:{Authorization:`Bearer ${n.access}`,"Content-Type":"application/json","x-amzn-kiro-agent-mode":"vibe","amz-sdk-request":"attempt=1; max=1"},...As(t.proxyUrl)})}catch(c){if(r.aborted)throw qw(r);s=c instanceof Error?c:new wi(String(c));continue}if(!h.ok){let c=await h.text().catch(()=>""),d=XI(h),u=JI(h),w=c.length>0?`${c.slice(0,2000)}${c.length>2000?"\u2026":""}`:`HTTP ${h.status}`,A=new wi(`Kiro usage service returned HTTP ${h.status}${u?` (${u})`:""}${d?` [${d}]`:""}: ${w}`,h.status,u);if(c.includes("FEATURE_NOT_SUPPORTED")&&f<jw.length-1){s=A;continue}if(h.status===401||h.status===403)throw A;s=A;continue}let e;try{e=await h.json()}catch(c){throw new wi("Kiro usage service returned invalid JSON",h.status,void 0,{cause:c})}return QI(e)}throw s??new wi("All Kiro usage service request variants failed")}var aI=new Map,zI=new Map;function Gt(n){return n.reason instanceof Error?n.reason:new DOMException("The request was aborted","AbortError")}function jt(n,t){if(t.aborted)return Promise.reject(Gt(t));return new Promise((i,r)=>{let s=()=>r(Gt(t));t.addEventListener("abort",s,{once:!0}),n.then((f)=>{t.removeEventListener("abort",s),i(f)},(f)=>{t.removeEventListener("abort",s),r(f)})})}function a0(n,t){if(n<=0)return Promise.resolve();return jt(Bun.sleep(n),t)}async function Zw(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,_,o=new Promise((d)=>{_=d});if(!_)throw TypeError("Queue release was not initialized");let h=_;s.waiters+=1,s.tail=f.catch(()=>{return}).then(()=>o);let e=()=>{if(s.waiters-=1,s.waiters!==0)return;s.tail.finally(()=>{if(s.waiters===0&&n.get(t)===s)n.delete(t)})};try{await jt(f,i)}catch(d){throw h(),e(),d}let c=!1;return()=>{if(c)return;c=!0,h(),e()}}function z0(n,t){return Zw(aI,n,t)}function vw(n,t){return Zw(zI,n,t)}function pw(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 ny(n,t){return yn(n)&&!Zn(n.unhealthyReason)&&n.rateLimitResetTime<=t}function KI(n){let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0,i=n instanceof Error?n.message:String(n);return t?`${t}: ${i}`:i}function xI(n){if(n instanceof wi)return{error_name:n.name,error_status:n.status,error_code:n.upstreamCode};let t=typeof n==="object"&&n!==null&&"code"in n&&typeof n.code==="string"?n.code:void 0;return{error_name:n instanceof Error?n.name:"UnknownError",error_code:t}}function Rr(n){return{usedCount:n.usedCount??0,limitCount:n.limitCount??0,overageCount:n.overageCount??0}}function Rs(n){let t=Rr(n);if(t.limitCount<=0)return"unknown";return yn(t)?"exhausted":"available"}function K0(n){return n.reason instanceof DOMException&&n.reason.name==="TimeoutError"?"timeout":"aborted"}class Ms{options;inFlight=new Map;usageRetryAfter=new Map;now;fetchUsage;constructor(n){this.options=n;this.now=n.now??Date.now,this.fetchUsage=n.fetchUsage??qo}async recheckDueAccounts(n,t,i){let r=this.now(),s=n.filter((f)=>ny(f,r)).sort((f,_)=>Number(_.id===i)-Number(f.id===i)||f.rateLimitResetTime-_.rateLimitResetTime||(f.lastSync??0)-(_.lastSync??0)||f.id.localeCompare(_.id));if(s.length===0)return;await this.runBatch(s,t,"quota_recheck",!0,i)}async syncDueAccounts(n,t){let i=this.now(),r=n.filter((s)=>this.isUsageRefreshDue(s,i)).sort((s,f)=>(s.lastSync??0)-(f.lastSync??0)||s.id.localeCompare(f.id));if(r.length===0)return;await this.runBatch(r,t,"usage_refresh",!1)}async refreshAccounts(n,t){let i=this.now(),r=[...n].sort((e,c)=>e.email.localeCompare(c.email)||e.id.localeCompare(c.id)),s=new Map,f=0;V("info","manual_account_refresh_started",{account_count:r.length,concurrency:this.options.concurrency});let _=async()=>{for(;;){if(t.aborted)return;let e=r[f];if(f+=1,!e)return;try{let c=await jt(this.startOrJoin(e,!0,t),t);s.set(e.id,c.account)}catch(c){if(t.aborted)return;throw c}}};if(await Promise.all(Array.from({length:Math.min(this.options.concurrency,r.length)},_)),t.aborted){let e=K0(t);for(let c of r)if(!s.has(c.id))s.set(c.id,this.terminalAccountResult(c,e,e==="timeout"?"Account refresh timed out.":"Account refresh was aborted."))}let o=r.map(({id:e})=>s.get(e)).filter((e)=>e!==void 0),h={startedAt:i,completedAt:this.now(),totalAccounts:r.length,tokenRenewed:o.filter((e)=>e.tokenStatus==="renewed").length,usageUpdated:o.filter((e)=>e.usageStatus==="updated").length,failed:o.filter((e)=>e.usageStatus!=="updated").length,timedOut:t.aborted&&K0(t)==="timeout",accounts:o};return V("info","manual_account_refresh_completed",{account_count:h.totalAccounts,token_renewed_count:h.tokenRenewed,usage_updated_count:h.usageUpdated,failed_count:h.failed,timed_out:h.timedOut,duration_ms:h.completedAt-h.startedAt}),h}async runBatch(n,t,i,r,s){V("info",`${i}_batch_started`,{account_count:n.length,concurrency:this.options.concurrency,preferred_account_present:s!==void 0&&n.some(({id:c})=>c===s)});let f=r?AbortSignal.timeout(this.options.timeoutMs):void 0,_=f?AbortSignal.any([t,f]):t,o=0,h={updated:0,recovered:0,exhausted:0,failed:0,skipped:0},e=async()=>{for(;;){if(_.aborted)throw Gt(_);let c=n[o];if(o+=1,!c)return;let d=await jt(this.startOrJoin(c,!1),_);h[d.result]+=1}};try{await Promise.all(Array.from({length:Math.min(this.options.concurrency,n.length)},e))}catch(c){if(t.aborted)throw Gt(t);if(!f?.aborted)throw c;V("warn",`${i}_batch_timeout`,{account_count:n.length,started_count:Math.min(o,n.length),timeout_ms:this.options.timeoutMs});return}V("info",`${i}_batch_completed`,{account_count:n.length,updated_count:h.updated,recovered_count:h.recovered,exhausted_count:h.exhausted,failed_count:h.failed,skipped_count:h.skipped})}isUsageRefreshDue(n,t){if(Zn(n.unhealthyReason)||yn(n))return!1;if((this.usageRetryAfter.get(n.id)??0)>t)return!1;return(n.lastSync??0)+this.options.usageRefreshIntervalMs<=t}startOrJoin(n,t,i){let r=`${n.id}:force`;if(!t){let o=this.inFlight.get(r);if(o)return o}let s=t?r:`${n.id}:scheduled`,f=this.inFlight.get(s);if(f)return f;let _=this.runProbe(n,t,i).finally(()=>{if(this.inFlight.get(s)===_)this.inFlight.delete(s)});return this.inFlight.set(s,_),_}async runProbe(n,t,i){let r=Rr(n),s=n,f="not_needed",_="token";if(t&&Zn(n.unhealthyReason))return{result:"failed",account:{accountId:n.id,email:n.email,before:r,after:r,tokenStatus:"skipped_unhealthy",usageStatus:"skipped",quotaStatus:Rs(n),error:"Account needs re-login before its usage can be refreshed."}};let o=AbortSignal.timeout(this.options.timeoutMs),h=i?AbortSignal.any([i,o]):o;try{let e=this.options.accountManager.toAuthDetails(n),c=n.accessToken,d=n.expiresAt;if(s=await this.options.tokenRefresher.refreshIfNeeded(n,e,h),s.accessToken!==c||s.expiresAt!==d)f="renewed";if(!t&&!ny(s,this.now())&&!this.isUsageRefreshDue(s,this.now()))return{result:"skipped",account:{accountId:s.id,email:s.email,before:r,after:Rr(s),tokenStatus:f,usageStatus:"skipped",quotaStatus:Rs(s)}};_="usage";let u=yn(s),w=this.options.accountManager.toAuthDetails(s),A;try{A=await this.fetchUsage(w,{proxyUrl:this.options.proxyUrl,signal:h,timeoutMs:this.options.timeoutMs})}catch(O){if(!kw(O))throw O;s=await this.options.tokenRefresher.forceRefresh(s,h),f="renewed",w=this.options.accountManager.toAuthDetails(s),A=await this.fetchUsage(w,{proxyUrl:this.options.proxyUrl,signal:h,timeoutMs:this.options.timeoutMs})}let R=this.now(),E=yn(A)?R+this.options.intervalMs:0,T=this.options.accountManager.updateQuotaUsage(s,{...A,lastSync:R},E);if(!T)return{result:"skipped",account:{accountId:s.id,email:s.email,before:r,after:Rr(s),tokenStatus:f,usageStatus:"skipped",quotaStatus:Rs(s),error:"Account was removed while its usage was being refreshed."}};this.usageRetryAfter.delete(s.id);let l=yn(T),g="updated";if(l)V("info",u?"quota_recheck_still_exhausted":"usage_refresh_detected_exhaustion",{account_hash:wn(s.id),next_recheck_at:T.rateLimitResetTime}),g="exhausted";else if(u)V("info","quota_exhausted_account_recovered",{account_hash:wn(s.id)}),g="recovered";return{result:g,account:{accountId:T.id,email:T.email,before:r,after:Rr(T),tokenStatus:f,usageStatus:"updated",quotaStatus:Rs(T)}}}catch(e){let c=this.now()+this.options.intervalMs,d=KI(e);if($i(d)){try{this.options.accountManager.markUnhealthy(s,zr(d))}catch{}this.usageRetryAfter.delete(s.id)}else if(yn(s))try{this.options.accountManager.scheduleQuotaRecheck(s,c)}catch{}else this.usageRetryAfter.set(s.id,c);V("warn",yn(s)?"quota_recheck_failed":"usage_refresh_failed",{account_hash:wn(n.id),next_recheck_at:c,...xI(e)});let u=h.aborted?K0(h):void 0;return{result:"failed",account:{accountId:s.id,email:s.email,before:r,after:Rr(s),tokenStatus:u&&_==="token"?u:_==="token"?"failed":f,usageStatus:u??(_==="token"?"skipped":"failed"),quotaStatus:Rs(s),error:d}}}}terminalAccountResult(n,t,i){let r=Rr(n);return{accountId:n.id,email:n.email,before:r,after:r,tokenStatus:t,usageStatus:t,quotaStatus:Rs(n),error:i}}}var ty=500;function VI(n){V("warn","stream_cleanup_failed",{error_type:n instanceof Error?n.name:typeof n})}function iy(n,t){try{n()}catch(i){let r=t??VI;try{r(i)}catch{}}}function Kn(...n){for(let t of n)iy(t)}function Mn(n){let t,i=Promise.resolve().then(n).then(()=>{return},()=>{return}),r=new Promise((s)=>{t=setTimeout(s,ty)});return Promise.race([i,r]).then(()=>{if(t!==void 0)clearTimeout(t)},()=>{if(t!==void 0)clearTimeout(t)})}class Xi extends Error{status;name="KiroManagementError";constructor(n,t,i){super(n,i);this.status=t}}function If(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ry(n){return typeof n==="number"&&Number.isInteger(n)&&n>0?n:void 0}function jI(n){if(!If(n))return;let t=typeof n.modelId==="string"?n.modelId.trim():"",i=typeof n.modelName==="string"?n.modelName.trim():"";if(t.length===0||i.length===0||!If(n.tokenLimits))return;let r=ry(n.tokenLimits.maxInputTokens),s=ry(n.tokenLimits.maxOutputTokens);if(r===void 0||s===void 0)return;let f=Array.isArray(n.supportedInputTypes)?n.supportedInputTypes.filter((_)=>_==="TEXT"||_==="IMAGE"):[];return{modelId:t,modelName:i,...typeof n.description==="string"?{description:n.description}:{},supportedInputTypes:f,tokenLimits:{maxInputTokens:r,maxOutputTokens:s},...typeof n.rateMultiplier==="number"?{rateMultiplier:n.rateMultiplier}:{},...If(n.additionalModelRequestFieldsSchema)?{additionalModelRequestFieldsSchema:n.additionalModelRequestFieldsSchema}:{}}}function qI(n){if(!If(n)||!Array.isArray(n.models))throw new Xi("Kiro model catalog response has an invalid shape");let t=n.models.flatMap((r)=>{let s=jI(r);return s===void 0?[]:[s]});if(t.length===0)throw new Xi("Kiro model catalog response contains no valid models");let i=If(n.defaultModel)&&typeof n.defaultModel.modelId==="string"?n.defaultModel.modelId:void 0;return{...i!==void 0?{defaultModelId:i}:{},models:t}}async function sy(n,t,i={}){let r=new URL(`https://management.${t}.kiro.dev/`);if(r.searchParams.set("origin",On.ORIGIN_AI_EDITOR),n.profileArn)r.searchParams.set("profileArn",n.profileArn);let s=AbortSignal.timeout(i.timeoutMs??1e4),f=i.signal===void 0?s:AbortSignal.any([i.signal,s]),_;try{_=await fetch(r,{method:"POST",headers:{Authorization:`Bearer ${n.access}`,"Content-Type":"application/x-amz-json-1.0","x-amz-target":"AmazonCodeWhispererService.ListAvailableModels","user-agent":On.USER_AGENT},body:JSON.stringify({origin:On.ORIGIN_AI_EDITOR,...n.profileArn?{profileArn:n.profileArn}:{}}),signal:f,...As(i.proxyUrl)})}catch(h){throw new Xi("Unable to reach the Kiro model catalog service",void 0,{cause:h})}if(!_.ok)throw new Xi(`Kiro model catalog returned HTTP ${_.status}`,_.status);let o;try{o=await _.json()}catch(h){throw new Xi("Kiro model catalog returned invalid JSON",_.status,{cause:h})}return qI(o)}var fy=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),Nn=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),hn=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),cq=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","claude-opus-5","claude-opus-5-low","claude-opus-5-medium","claude-opus-5-high","claude-opus-5-xhigh","claude-opus-5-max","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"]),Sf=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:Y("auto"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:Y("claude-sonnet-4"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:Y("claude-sonnet-4-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:Y("claude-sonnet-4-6"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:Y("claude-sonnet-4-6"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:Y("claude-sonnet-4-6"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:Y("claude-sonnet-4-6"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:Y("claude-sonnet-4-6"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:Y("claude-sonnet-5"),outputLimit:64000,modalities:hn},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:Y("claude-haiku-4-5"),outputLimit:64000,modalities:Nn},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:Y("claude-opus-4-5"),outputLimit:64000,modalities:hn},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:Y("claude-opus-4-6"),outputLimit:64000,modalities:hn},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:Y("claude-opus-4-7"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:Y("claude-opus-4-8"),outputLimit:128000,modalities:hn},{id:"claude-opus-5",wireId:"claude-opus-5",name:"Claude Opus 5 (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"claude-opus-5-low",wireId:"claude-opus-5",name:"Claude Opus 5 (low) (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"claude-opus-5-medium",wireId:"claude-opus-5",name:"Claude Opus 5 (medium) (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"claude-opus-5-high",wireId:"claude-opus-5",name:"Claude Opus 5 (high) (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"claude-opus-5-xhigh",wireId:"claude-opus-5",name:"Claude Opus 5 (xhigh) (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"claude-opus-5-max",wireId:"claude-opus-5",name:"Claude Opus 5 (max) (2.2x)",contextLimit:Y("claude-opus-5"),outputLimit:128000,modalities:hn},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:Y("deepseek-3.2"),outputLimit:64000,modalities:Nn},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:Y("glm-5"),outputLimit:64000,modalities:fy},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:Y("minimax-m2.5"),outputLimit:64000,modalities:fy},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:Y("minimax-m2.1"),outputLimit:64000,modalities:Nn},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:Y("qwen3-coder-next"),outputLimit:64000,modalities:Nn},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:Y("gpt-5.6-sol"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.0x)",contextLimit:Y("gpt-5.6-terra"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low) (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium) (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high) (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh) (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max) (0.1x)",contextLimit:Y("gpt-5.6-luna"),outputLimit:128000,modalities:Nn}]);function kI(n){return{input:n.supportedInputTypes.includes("IMAGE")?["text","image"]:["text"],output:["text"]}}function oy(n){let t=new Map;for(let i of Sf){let r=t.get(i.wireId)??[];r.push(i),t.set(i.wireId,r)}return n.flatMap((i)=>{let r={contextLimit:i.tokenLimits.maxInputTokens,outputLimit:i.tokenLimits.maxOutputTokens,modalities:kI(i),...i.description!==void 0?{description:i.description}:{},...i.rateMultiplier!==void 0?{rateMultiplier:i.rateMultiplier}:{},...i.additionalModelRequestFieldsSchema!==void 0?{additionalModelRequestFieldsSchema:i.additionalModelRequestFieldsSchema}:{}},s=t.get(i.modelId);if(s&&s.length>0)return s.map((f)=>({...f,...r}));return[{id:i.modelId,wireId:i.modelId,name:i.modelName,...r}]})}var x0=new Map;function hy(n){return xo[n]??x0.get(n)}function bf(n){for(let t of n){let i=t.trim();if(i.length===0)continue;x0.set(i,i)}}function ey(n){try{return yi(n),!0}catch{return!1}}function _y(n){let t=hy(n);if(!t){let i=[...xw,...x0.keys()];throw Error(`Unsupported model: ${n}. Supported models: ${i.join(", ")}`)}return t}var cy=new Set(["claude-opus-5","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"]),dy=["low","medium","high","xhigh","max"];function yi(n){for(let t of dy){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(cy.has(r))return{wireId:_y(r),effort:t}}}return{wireId:_y(n),effort:void 0}}function ZI(n){for(let t of dy){let i=`-${t}`;if(n.endsWith(i)){let r=n.slice(0,-i.length);if(cy.has(r))return r}}if(n.endsWith("-thinking")){let t=n.slice(0,-9);if(hy(t))return t}return n}function uy(n){return Y(ZI(n))}function ko(n){try{return yi(n).wireId}catch{return}}class V0{config;listModels;snapshots=new Map;inFlight=new Map;failedAt=new Map;lastSuccessAt;constructor(n,t=sy){this.config=n;this.listModels=t}async ensureAccountModel(n,t,i,r){if(!this.config.dynamic_model_catalog){let _=ko(i);return _===void 0?{supported:!1,source:"disabled"}:{supported:!0,source:"disabled",wireModel:_}}let s=await this.refreshAccount(n,t,r);if(s!==void 0){bf(s.models.keys());let _=ko(i);if(_!==void 0&&s.models.has(_))return{supported:!0,source:this.isFresh(s)?"live":"stale",wireModel:_};return{supported:!1,source:this.isFresh(s)?"live":"stale"}}let f=ko(i);return f===void 0?{supported:!1,source:"static"}:{supported:!0,source:"static",wireModel:f}}eligibleAccountIds(n,t){if(!this.config.dynamic_model_catalog)return;this.registerUsableModels();let i=ko(n),r=Date.now(),s=new Set,f=!1;for(let _ of t){let o=this.snapshots.get(_);if(!o||!this.isUsable(o,r)){s.add(_);continue}if(f=!0,i!==void 0&&o.models.has(i))s.add(_)}return f?s:void 0}isKnownModel(n){return this.registerUsableModels(),ey(n)}catalog(){let n=new Map,t=Date.now();for(let i of this.snapshots.values()){if(!this.isUsable(i,t))continue;for(let[r,s]of i.models)n.set(r,s)}if(n.size===0)return Sf;return bf(n.keys()),oy([...n.values()])}readiness(){if(!this.config.dynamic_model_catalog)return{enabled:!1,usable:!0,source:"disabled",freshAccounts:0,staleAccounts:0};let n=Date.now(),t=0,i=0;for(let r of this.snapshots.values())if(this.isFresh(r,n))t+=1;else if(this.isUsable(r,n))i+=1;return{enabled:!0,usable:!0,source:t>0?"live":i>0?"stale":"static",freshAccounts:t,staleAccounts:i,...this.lastSuccessAt!==void 0?{lastSuccessAt:this.lastSuccessAt}:{}}}async refreshAccounts(n,t,i){await Promise.allSettled(n.map((r)=>this.refreshAccount(r,t(r),i)))}async refreshAccount(n,t,i){let r=this.snapshots.get(n.id);if(r&&this.isFresh(r))return r;let s=this.inFlight.get(n.id);if(s)try{return await s}catch{return this.usableSnapshot(n.id)}let f=this.fetchSnapshot(n,t,i).finally(()=>{if(this.inFlight.get(n.id)===f)this.inFlight.delete(n.id)});this.inFlight.set(n.id,f);try{return await f}catch(_){let o=Date.now(),h=this.failedAt.get(n.id)??0;if(this.failedAt.set(n.id,o),o-h>=this.config.model_catalog_ttl_ms)V("warn","model_catalog_refresh_failed",{account_hash:wn(n.id),status:_ instanceof Xi?_.status:void 0,stale_available:this.usableSnapshot(n.id,o)!==void 0});return this.usableSnapshot(n.id,o)}}async fetchSnapshot(n,t,i){let r=await this.listModels(t,n.region,{proxyUrl:this.config.proxy_url||void 0,signal:i,timeoutMs:this.config.model_catalog_request_timeout_ms}),s=Date.now(),f={accountId:n.id,fetchedAt:s,models:new Map(r.models.map((_)=>[_.modelId,_]))};return this.snapshots.set(n.id,f),this.failedAt.delete(n.id),this.lastSuccessAt=s,bf(f.models.keys()),V("info","model_catalog_refreshed",{account_hash:wn(n.id),model_count:f.models.size,default_model:r.defaultModelId}),f}registerUsableModels(){let n=Date.now();for(let t of this.snapshots.values())if(this.isUsable(t,n))bf(t.models.keys())}usableSnapshot(n,t=Date.now()){let i=this.snapshots.get(n);return i&&this.isUsable(i,t)?i:void 0}isFresh(n,t=Date.now()){return t-n.fetchedAt<=this.config.model_catalog_ttl_ms}isUsable(n,t=Date.now()){return t-n.fetchedAt<=this.config.model_catalog_stale_ttl_ms}}import{createCipheriv as d8,createDecipheriv as u8,createHash as w8,randomBytes as ly,timingSafeEqual as y8}from"crypto";import{createHash as vI,randomBytes as wy}from"crypto";import{chmodSync as Ry,closeSync as pI,existsSync as Zo,fsyncSync as n8,mkdirSync as t8,openSync as i8,readFileSync as r8,renameSync as s8,unlinkSync as yy,writeFileSync as f8}from"fs";import{homedir as Ay}from"os";import{dirname as o8,join as j0}from"path";function _8(){let n=process.platform==="win32"?process.env.APPDATA??j0(Ay(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??j0(Ay(),".config");return j0(n,"kiro-provider","reasoning-replay-keys.json")}var h8=_8();function q0(n){return`rk_${vI("sha256").update(n).digest("hex").slice(0,16)}`}function e8(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 My(n,t){let i=n.indexOf(":"),r=i>0?n.slice(0,i):void 0,s=i>0?n.slice(i+1):n,f=e8(s,t),_=r??q0(f);if(!/^[A-Za-z0-9._-]{1,128}$/.test(_))throw TypeError(`${t} contains an invalid key id`);return{id:_,key:f}}function Z0(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(r8(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 My(`${r.id}:${r.key}`,`${n} keys.${s}`)});if(process.platform!=="win32")Ry(n,384);return Z0(i,"file",n)}function c8(n){t8(o8(n),{recursive:!0});let t=Uint8Array.from(wy(32)),i={version:1,keys:[{id:q0(t),key:Buffer.from(t).toString("base64url")}]},r=`${n}.tmp-${process.pid}-${wy(6).toString("hex")}`,s=i8(r,"wx",384);try{f8(s,`${JSON.stringify(i,null,2)}
|
|
149
|
+
`,"utf8"),n8(s)}finally{pI(s)}try{if(Zo(n))return yy(r),k0(n);if(s8(r,n),process.platform!=="win32")Ry(n,384)}catch(f){if(Zo(r))yy(r);if(Zo(n))return k0(n);throw f}return Z0([{id:q0(t),key:t}],"file",n)}function Ey(n){if(n.reasoning_replay_keys.length>0)return Z0(n.reasoning_replay_keys.map((i,r)=>My(i,`KIRO_PROVIDER_REASONING_REPLAY_KEYS[${r}]`)),"environment");let t=n.reasoning_replay_key_path??h8;return Zo(t)?k0(t):c8(t)}class bn extends Error{code;retryable;name="ReasoningReplayError";constructor(n,t,i=!1){super(n);this.code=t;this.retryable=i}}function v0(n,...t){let i=w8("sha256").update(n).update("\x00");for(let r of t)i.update(r).update("\x00");return i.digest("hex")}function Ty(n){return v0("kiro-provider-reasoning-token-v1",n)}function gy(n){return v0("kiro-provider-reasoning-fingerprint-v1",n)}function Oy(n,t){return v0("kiro-provider-reasoning-chat-lookup-v1",n,t)}function Ly(n,t){let i=Buffer.from(n),r=Buffer.from(t);return i.byteLength===r.byteLength&&y8(i,r)}function Iy(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 A8(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 R8(n){if(n.redactedContent!==void 0){if(n.signature!==void 0||n.text!==void 0)throw new bn("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 bn("Reasoning replay does not contain complete signed upstream material","reasoning_replay_incomplete")}class p0{#n;#t;#i;#r;constructor(n,t,i=Ey(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 bn("Upstream returned both signed text and redacted reasoning payloads","reasoning_replay_ambiguous");let f=`kr1_${ly(32).toString("base64url")}`,_=Ty(f),o=gy(t.outputFingerprint),h=i+this.#i,e=this.#t.active,c=ly(12),d={version:1,outputFingerprint:t.outputFingerprint,...s?{text:n.text,signature:n.signature}:{},...r?{redactedContent:Buffer.from(n.redactedContent).toString("base64")}:{}},u=d8("aes-256-gcm",e.key,c);u.setAAD(Iy({...t,fingerprintHash:o,expiresAt:h,keyId:e.id}));let w=Buffer.concat([u.update(JSON.stringify(d),"utf8"),u.final()]),A=u.getAuthTag();return this.#n.insertReasoningReplay({tokenHash:_,chatLookupHash:s?Oy(n.text,t.outputFingerprint):null,fingerprintHash:o,tenantId:t.tenantId,accountId:t.accountId,conversationId:t.conversationId,model:t.model,keyId:e.id,nonce:Uint8Array.from(c),ciphertext:Uint8Array.from(w),authTag:Uint8Array.from(A),createdAt:i,lastSeen:i,expiresAt:h},this.#r,i),f}resolveResponses(n,t,i){if(!n.startsWith("kr1_"))throw new bn("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 V("info","reasoning_replay_miss",{lookup:"responses-token",token_hash:s.slice(0,16)}),new bn("Reasoning replay token was not found","reasoning_replay_not_found");if(f.expiresAt<=r)throw V("info","reasoning_replay_expired",{lookup:"responses-token",token_hash:s.slice(0,16)}),new bn("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,Oy(n,t.outputFingerprint),r);if(t.accountId!==void 0)s=s.filter((_)=>_.accountId===t.accountId);if(t.conversationId!==void 0)s=s.filter((_)=>_.conversationId===t.conversationId);if(s.length===0)throw V("info","reasoning_replay_miss",{lookup:"chat-hash",tenant_hash:wn(t.tenantId)}),new bn("No exact signed reasoning record matches reasoning_content and assistant output","reasoning_replay_not_found");if(s.length!==1)throw new bn("Reasoning replay lookup is ambiguous across accounts or conversations","reasoning_replay_ambiguous");let f=s[0];if(!f)throw new bn("Reasoning replay lookup failed","reasoning_replay_not_found");return this.resolveRecord(f,t,i,r)}resolveRecord(n,t,i,r){let s=gy(t.outputFingerprint);if(!Ly(n.tenantId,t.tenantId)||n.model!==t.model||!Ly(n.fingerprintHash,s)||t.accountId!==void 0&&n.accountId!==t.accountId||t.conversationId!==void 0&&n.conversationId!==t.conversationId)throw new bn("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 bn("Reasoning replay decryption key is unavailable","reasoning_replay_key_unavailable");let _;try{let o=u8("aes-256-gcm",f.key,n.nonce);o.setAAD(Iy({tenantId:n.tenantId,model:n.model,accountId:n.accountId,conversationId:n.conversationId,fingerprintHash:n.fingerprintHash,expiresAt:n.expiresAt,keyId:n.keyId})),o.setAuthTag(n.authTag);let h=Buffer.concat([o.update(n.ciphertext),o.final()]).toString("utf8");_=A8(h)}catch(o){if(o instanceof bn)throw o;throw new bn("Reasoning replay authentication or decryption failed","reasoning_replay_decryption_failed")}if(_.outputFingerprint!==t.outputFingerprint)throw new bn("Reasoning replay output fingerprint does not match","reasoning_replay_context_mismatch");return this.#n.touchReasoningReplay(n.tokenHash,r),V("info","reasoning_replay_hit",{key_id:n.keyId,account_hash:wn(n.accountId),conversation_hash:wn(n.conversationId),model:n.model}),{accountId:n.accountId,conversationId:n.conversationId,replay:{insertBeforeMessage:i,content:R8(_)}}}}import{Database as M8}from"bun:sqlite";import{chmodSync as E8,existsSync as l8,mkdirSync as T8}from"fs";import{homedir as Sy}from"os";import{dirname as g8,join as ie}from"path";function ne(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 vo(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 te(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 re(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 O8(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 se(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 L8(){let n=process.platform==="win32"?process.env.APPDATA??ie(Sy(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??ie(Sy(),".config");return ie(n,"kiro-provider","accounts.db")}var Et=L8();class Ai{db;path;constructor(n=Et){if(this.path=n,n!==":memory:")T8(g8(n),{recursive:!0});this.db=new M8(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(`
|
|
150
150
|
CREATE TABLE IF NOT EXISTS accounts (
|
|
151
151
|
id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
|
|
152
152
|
region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
|
|
@@ -226,19 +226,19 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
226
226
|
WHERE NOT EXISTS (
|
|
227
227
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
228
228
|
)
|
|
229
|
-
`).all().map(
|
|
229
|
+
`).all().map(vo)}getById(n){let t=this.db.query(`
|
|
230
230
|
SELECT accounts.* FROM accounts
|
|
231
231
|
WHERE accounts.id = ? AND NOT EXISTS (
|
|
232
232
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
233
233
|
)
|
|
234
|
-
`).get(n);return t===null?void 0:
|
|
234
|
+
`).get(n);return t===null?void 0:vo(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=ne(n,r);return this.db.query(`
|
|
235
235
|
INSERT OR REPLACE INTO accounts (
|
|
236
236
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
237
237
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
238
238
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
239
239
|
last_used, used_count, limit_count, last_sync, overage_count, generation
|
|
240
240
|
) VALUES (${Array.from({length:23},()=>"?").join(", ")})
|
|
241
|
-
`).run(...
|
|
241
|
+
`).run(...te(s)),this.clearRemovedAccountInternal(n.id),vo(s)})}updateExistingAccounts(n){return this.withImmediateTransaction(()=>{let t=0,i=this.db.query(`
|
|
242
242
|
UPDATE accounts SET
|
|
243
243
|
email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
|
|
244
244
|
client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
|
|
@@ -249,13 +249,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
249
249
|
WHERE id = ? AND generation = ? AND NOT EXISTS (
|
|
250
250
|
SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
|
|
251
251
|
)
|
|
252
|
-
`);for(let r of n){let s=
|
|
252
|
+
`);for(let r of n){let s=te(ne(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 output_lineage WHERE account_id = ?").run(n),this.db.query("DELETE FROM reasoning_replay WHERE account_id = ?").run(n),this.db.query(`
|
|
253
253
|
INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
|
|
254
254
|
VALUES (?, ?, ?)
|
|
255
255
|
`).run(n,Date.now(),r)})}clearRemovedAccount(n){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(n))}getSessionAffinity(n,t=Date.now()){let i=this.db.query(`
|
|
256
256
|
SELECT * FROM session_affinity
|
|
257
257
|
WHERE key_hash = ? AND expires_at > ?
|
|
258
|
-
`).get(n,t);return i===null?void 0:
|
|
258
|
+
`).get(n,t);return i===null?void 0:re(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(`
|
|
259
259
|
INSERT OR IGNORE INTO session_affinity (
|
|
260
260
|
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
261
261
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
@@ -263,7 +263,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
263
263
|
UPDATE session_affinity
|
|
264
264
|
SET last_seen = ?, expires_at = ?
|
|
265
265
|
WHERE key_hash = ?
|
|
266
|
-
`).run(r,r+s,n),this.pruneSessionAffinitiesInternal(r,f,n);let
|
|
266
|
+
`).run(r,r+s,n),this.pruneSessionAffinitiesInternal(r,f,n);let _=this.selectSessionAffinity(n);if(_===void 0)throw TypeError("Session affinity claim did not persist");return re(_)})}rebindSessionAffinity(n,t,i,r,s,f){return this.withImmediateTransaction(()=>{this.db.query(`
|
|
267
267
|
INSERT INTO session_affinity (
|
|
268
268
|
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
269
269
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
@@ -273,12 +273,12 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
273
273
|
created_at = excluded.created_at,
|
|
274
274
|
last_seen = excluded.last_seen,
|
|
275
275
|
expires_at = excluded.expires_at
|
|
276
|
-
`).run(n,t,i,r,r,r+s),this.pruneSessionAffinitiesInternal(r,f,n);let
|
|
276
|
+
`).run(n,t,i,r,r,r+s),this.pruneSessionAffinitiesInternal(r,f,n);let _=this.selectSessionAffinity(n);if(_===void 0)throw TypeError("Session affinity rebind did not persist");return re(_)})}pruneSessionAffinities(n=Date.now(),t=1e4){return this.withImmediateTransaction(()=>this.pruneSessionAffinitiesInternal(n,t))}resolveOutputLineage(n,t=Date.now()){let i=this.db.query(`
|
|
277
277
|
SELECT * FROM output_lineage
|
|
278
278
|
WHERE key_hash = ? AND expires_at > ?
|
|
279
279
|
ORDER BY last_seen DESC, account_id ASC, conversation_id ASC
|
|
280
280
|
LIMIT 2
|
|
281
|
-
`).all(n,t);return i.length===1?
|
|
281
|
+
`).all(n,t);return i.length===1?O8(i[0]):void 0}recordOutputLineage(n,t,i,r,s,f){this.withImmediateTransaction(()=>{this.db.query("DELETE FROM output_lineage WHERE expires_at <= ?").run(r),this.db.query(`
|
|
282
282
|
INSERT INTO output_lineage (
|
|
283
283
|
key_hash, account_id, conversation_id, created_at, last_seen, expires_at
|
|
284
284
|
) VALUES (?, ?, ?, ?, ?, ?)
|
|
@@ -294,14 +294,14 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
294
294
|
`).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(`
|
|
295
295
|
SELECT * FROM reasoning_replay
|
|
296
296
|
WHERE token_hash = ? AND expires_at > ?
|
|
297
|
-
`).get(n,t);return i===null?void 0:
|
|
297
|
+
`).get(n,t);return i===null?void 0:se(i)}getReasoningReplayRecord(n){let t=this.db.query("SELECT * FROM reasoning_replay WHERE token_hash = ?").get(n);return t===null?void 0:se(t)}findReasoningReplayByChatHash(n,t,i,r=Date.now()){return this.db.query(`
|
|
298
298
|
SELECT * FROM reasoning_replay
|
|
299
299
|
WHERE tenant_id = ? AND model = ? AND chat_lookup_hash = ? AND expires_at > ?
|
|
300
300
|
ORDER BY last_seen DESC, token_hash ASC
|
|
301
|
-
`).all(n,t,i,r).map(
|
|
301
|
+
`).all(n,t,i,r).map(se)}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(`
|
|
302
302
|
SELECT DISTINCT key_id FROM reasoning_replay
|
|
303
303
|
WHERE expires_at > ? ORDER BY key_id ASC
|
|
304
|
-
`).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
|
|
304
|
+
`).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 _=i?this.db.query(`
|
|
305
305
|
DELETE FROM session_affinity
|
|
306
306
|
WHERE key_hash IN (
|
|
307
307
|
SELECT key_hash FROM session_affinity
|
|
@@ -316,7 +316,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
316
316
|
ORDER BY last_seen ASC, key_hash ASC
|
|
317
317
|
LIMIT ?
|
|
318
318
|
)
|
|
319
|
-
`);r+=(i?
|
|
319
|
+
`);r+=(i?_.run(i,f):_.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 _=i?this.db.query(`
|
|
320
320
|
DELETE FROM reasoning_replay
|
|
321
321
|
WHERE token_hash IN (
|
|
322
322
|
SELECT token_hash FROM reasoning_replay
|
|
@@ -331,7 +331,7 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
331
331
|
ORDER BY last_seen ASC, token_hash ASC
|
|
332
332
|
LIMIT ?
|
|
333
333
|
)
|
|
334
|
-
`);return r+=(i?
|
|
334
|
+
`);return r+=(i?_.run(i,f):_.run(f)).changes,r}pruneOutputLineageInternal(n,t,i,r,s){let f=this.db.query("DELETE FROM output_lineage WHERE expires_at <= ?").run(n).changes,_=this.db.query("SELECT COUNT(*) AS count FROM output_lineage").get(),o=Math.max(0,(_?.count??0)-t);if(o<=0)return f;let h=i!==void 0&&r!==void 0&&s!==void 0,e=h?this.db.query(`
|
|
335
335
|
DELETE FROM output_lineage
|
|
336
336
|
WHERE rowid IN (
|
|
337
337
|
SELECT rowid FROM output_lineage
|
|
@@ -348,46 +348,50 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
|
|
|
348
348
|
ORDER BY last_seen ASC, key_hash ASC, account_id ASC, conversation_id ASC
|
|
349
349
|
LIMIT ?
|
|
350
350
|
)
|
|
351
|
-
`);return f+=(
|
|
351
|
+
`);return f+=(h?e.run(i,r,s,o):e.run(o)).changes,f}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(l8(n))E8(n,384)}}import{randomUUID as I8}from"crypto";function Wn(n,t,i){return Response.json({type:"error",error:{type:i,message:t},request_id:`req_${I8()}`},{status:n})}function by(n,t){return`event: error
|
|
352
352
|
data: ${JSON.stringify({type:"error",error:{type:t,message:n}})}
|
|
353
353
|
|
|
354
|
-
`}import{createHash as qI,timingSafeEqual as kI}from"crypto";function nn(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 dA="Bearer ";function uA(n,t){let i=Buffer.from(n);for(let r of t){let s=Buffer.from(r);if(i.byteLength===s.byteLength&&kI(i,s))return r}return}function yA(n){return qI("sha256").update("kiro-provider-tenant-v1\x00").update(n).digest("hex")}function xo(n,t,i=nn){let r=n.headers.get("Authorization");if(r===null){let h=n.headers.get("x-api-key"),_=h===null?void 0:uA(h,t);if(_!==void 0)return{ok:!0,tenantId:yA(_)};return{ok:!1,response:i(401,"Missing Authorization or x-api-key header.","authentication_error","missing_api_key")}}if(!r.startsWith(dA))return{ok:!1,response:i(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let s=r.slice(dA.length),f=uA(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:yA(f)}}var Ki=Z(Dt(),1);var mf=Z(Dt(),1);var zf=Z(Dt(),1);var Ti=Z(Dt(),1);var wt=Z(Dt(),1);var En=Z(vn(),1);var Ws=Z(zi(),1),$e=Z(Yi(),1);var Nc=Z(Mh(),1);var Kf=Z(nt(),1);var Rt=Z(Mr(),1);var On=Z(Jf(),1);var fn=Z(yi(),1);var gs=Z(zi(),1);var Is=Z(yi(),1);var L1=async(n,t,i)=>{return{operation:Is.getSmithyContext(t).operation}};function U7(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 I1=(n)=>{let t=[];switch(n.operation){default:t.push(U7(n))}return t},g1=(n)=>{let t=gs.memoizeIdentityProvider(n.token,gs.isIdentityExpired,gs.doesIdentityRequireRefresh);return Object.assign(n,{authSchemePreference:Is.normalizeProvider(n.authSchemePreference??[]),token:t})};var N1=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},b1={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var S1={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 Le=Z(Dt(),1),Ie=Z(Pc(),1);var Bs=Z(vn(),1);var it=Z(vn(),1);var dT=300000,bs="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var J2=async(n,t={},i)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => Z(Ld(),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 Q2=async(n,t,i={},r)=>{let{CreateTokenCommand:s}=await Promise.resolve().then(() => Z(Ld(),1));return(await J2(t,i,r)).send(new s({clientId:n.clientId,clientSecret:n.clientSecret,refreshToken:n.refreshToken,grantType:"refresh_token"}))};var m2=Z(vn(),1);var Id=(n)=>{if(n.expiration&&n.expiration.getTime()<Date.now())throw new m2.TokenProviderError(`Token is expired. ${bs}`,!1)};var z2=Z(vn(),1);var ji=(n,t,i=!1)=>{if(typeof t>"u")throw new z2.TokenProviderError(`Value not present for '${n}' in SSO Token${i?". Cannot refresh":""}. ${bs}`,!1)};var K2=Z(vn(),1);import{promises as nJ}from"fs";var{writeFile:tJ}=nJ,V2=(n,t)=>{let i=K2.getSSOTokenFilepath(n),r=JSON.stringify(t,null,2);return tJ(i,r)};var x2=new Date(0),j2=(n={})=>async({callerClientConfig:t}={})=>{n.logger?.debug("@aws-sdk/token-providers - fromSso");let i=await it.parseKnownFiles(n),r=it.getProfileName({profile:n.profile??t?.profile}),s=i[r];if(!s)throw new it.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!s.sso_session)throw new it.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let f=s.sso_session,_=(await it.loadSsoSessionData(n))[f];if(!_)throw new it.TokenProviderError(`Sso session '${f}' could not be found in shared credentials file.`,!1);for(let R of["sso_start_url","sso_region"])if(!_[R])throw new it.TokenProviderError(`Sso session '${f}' is missing required property '${R}'.`,!1);let{sso_start_url:o,sso_region:w}=_,c;try{c=await it.getSSOTokenFromFile(f)}catch(R){throw new it.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${bs}`,!1)}ji("accessToken",c.accessToken),ji("expiresAt",c.expiresAt);let{accessToken:d,expiresAt:u}=c,y={token:d,expiration:new Date(u)};if(y.expiration.getTime()-Date.now()>dT)return y;if(Date.now()-x2.getTime()<30000)return Id(y),y;ji("clientId",c.clientId,!0),ji("clientSecret",c.clientSecret,!0),ji("refreshToken",c.refreshToken,!0);try{x2.setTime(Date.now());let R=await Q2(c,w,n,t);ji("accessToken",R.accessToken),ji("expiresIn",R.expiresIn);let M=new Date(Date.now()+R.expiresIn*1000);try{await V2(f,{...c,accessToken:R.accessToken,expiresAt:M.toISOString(),refreshToken:R.refreshToken})}catch(E){}return{token:R.accessToken,expiration:M}}catch(R){return Id(y),y}};var gd=(n={})=>Bs.memoize(Bs.chain(j2(n),async()=>{throw new Bs.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 ni=Z(Dt(),1);var ge=Z(zi(),1);var h0=Z(Mh(),1);var Nd=Z(pn(),1);var ei=Z(vn(),1);var O0=Z(Ch(),1);var bd=Z(pn(),1);var Sd=Z(vn(),1);var Yn=Z(Jf(),1);var Te=Z(Rd(),1),ee=Z(zi(),1);var ld=Z(nt(),1);var Gs=Z(pn(),1);var br=Z(pn(),1);var jn=Z(Mr(),1);var n_="ref",Sr=-1,o0=!0,q2="isSet",v2="PartitionResult",w0="booleanEquals",$d="getAttr",k2={[n_]:"Endpoint"},Ud={[n_]:v2},Hs={},a2=[{[n_]:"Region"}],Z2={conditions:[[q2,[k2]],[q2,a2],["aws.partition",a2,v2],[w0,[{[n_]:"UseFIPS"},o0]],[w0,[{[n_]:"UseDualStack"},o0]],[w0,[{fn:$d,argv:[Ud,"supportsDualStack"]},o0]],[w0,[{fn:$d,argv:[Ud,"supportsFIPS"]},o0]],["stringEquals",[{fn:$d,argv:[Ud,"name"]},"aws-us-gov"]]],results:[[Sr],[Sr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Sr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[k2,Hs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Hs],[Sr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Hs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Hs],[Sr,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Hs],[Sr,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Hs],[Sr,"Invalid Configuration: Missing Region"]]},iJ=2,rt=1e8,rJ=new Int32Array([-1,1,-1,0,13,3,1,4,rt+12,2,5,rt+12,3,8,6,4,7,rt+11,5,rt+9,rt+10,4,11,9,6,10,rt+8,7,rt+6,rt+7,5,12,rt+5,6,rt+4,rt+5,3,rt+1,14,4,rt+2,rt+3]),p2=jn.BinaryDecisionDiagram.from(rJ,iJ,Z2.conditions,Z2.results);var sJ=new jn.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),ne=(n,t={})=>{return sJ.get(n,()=>jn.decideEndpoint(p2,{endpointParams:n,logger:t.logger}))};jn.customEndpointFunctions.aws=wt.awsEndpointFunctions;var Gd=Z(Yi(),1);class st extends fn.ServiceException{constructor(n){super(n);Object.setPrototypeOf(this,st.prototype)}}class c0 extends st{name="AccessDeniedException";$fault="client";reason;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,c0.prototype),this.reason=n.reason}}class d0 extends st{name="ConflictException";$fault="client";reason;constructor(n){super({name:"ConflictException",$fault:"client",...n});Object.setPrototypeOf(this,d0.prototype),this.reason=n.reason}}class u0 extends st{name="InternalServerException";$fault="server";$retryable={};reason;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,u0.prototype),this.reason=n.reason}}class y0 extends st{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(n){super({name:"ThrottlingException",$fault:"client",...n});Object.setPrototypeOf(this,y0.prototype),this.reason=n.reason}}class A0 extends st{name="ValidationException";$fault="client";reason;constructor(n){super({name:"ValidationException",$fault:"client",...n});Object.setPrototypeOf(this,A0.prototype),this.reason=n.reason}}class R0 extends st{name="ResourceNotFoundException";$fault="client";constructor(n){super({name:"ResourceNotFoundException",$fault:"client",...n});Object.setPrototypeOf(this,R0.prototype)}}class M0 extends st{name="ServiceUnavailableException";$fault="server";constructor(n){super({name:"ServiceUnavailableException",$fault:"server",...n});Object.setPrototypeOf(this,M0.prototype)}}class E0 extends st{name="ServiceQuotaExceededException";$fault="client";reason;constructor(n){super({name:"ServiceQuotaExceededException",$fault:"client",...n});Object.setPrototypeOf(this,E0.prototype),this.reason=n.reason}}class T0 extends st{name="DryRunOperationException";$fault="client";responseCode;constructor(n){super({name:"DryRunOperationException",$fault:"client",...n});Object.setPrototypeOf(this,T0.prototype),this.responseCode=n.responseCode}}var te=Gd.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),fJ=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];te.registerError(fJ,st);var ti=Gd.TypeRegistry.for("com.amazon.aws.codewhisperer"),_J=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];ti.registerError(_J,c0);var hJ=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];ti.registerError(hJ,d0);var oJ=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];ti.registerError(oJ,T0);var ie=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];ti.registerError(ie,u0);var wJ=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];ti.registerError(wJ,R0);var cJ=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];ti.registerError(cJ,E0);var dJ=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];ti.registerError(dJ,M0);var uJ=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];ti.registerError(uJ,y0);var yJ=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];ti.registerError(yJ,A0);var re=[te,ti];var Hd=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],z=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],AJ=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],e0=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],An=[0,"com.amazon.aws.q","SensitiveString",8,0],RJ=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>z,0],[()=>z,0],[()=>z,0]],2],MJ=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>z,0],[()=>z,0],[()=>z,0],[()=>z,0]],3],EJ=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>z,0],0],1],TJ=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>z,0],0,[()=>Re,0],()=>Ae,[()=>se,0],[()=>ZQ,0],()=>Wd,[()=>Lm,0]],1];var Wd=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],eJ=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>Am,[()=>z,0],[()=>z,0]],2],OJ=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],LJ=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>z,0]],1],IJ=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>z,0]],1],gJ=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>Ae]],NJ=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>z,0],0,0,0,[()=>z,0],[()=>z,0]]],bJ=[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"],[[()=>Me,0],0,0,0,[()=>JQ,0],0,0,0],2],lJ=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>z,0],()=>Fd],2],$J=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>lJ,0],[()=>z,0]],2],UJ=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>Tm,0]],3],DJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>z,0],[()=>z,0],[()=>Em,0],[()=>zQ,0]]],BJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],GJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>z,0]]],Dd=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],HJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>z,0],[()=>z,0]]],WJ=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],FJ=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],YJ=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>he,0],()=>Rm,[()=>xQ,0],2,[()=>vQ,0]]],PJ=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>z,0],[()=>z,0]]],XJ=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>z,0],[()=>KQ,0],1]],se=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>z,0],0],1],CJ=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>se,0]]],JJ=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>z,0]]],QJ=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>em,0]],2],mJ=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>dm,0]]],zJ=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],KJ=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],VJ=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>dQ]],xJ=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Bd=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],fe=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Fd=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Bd,()=>Bd],2],jJ=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>z,0],21,[()=>z,0]]],qJ=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>z,0],[()=>z,0]],1],kJ=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>_e]],aJ=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>z,0],()=>fe,[()=>z,0],()=>ye,0],1],ZJ=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>z,0],0,[()=>z,0]],3],vJ=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>z,0],[()=>z,0],1,[()=>z,0],[()=>z,0]],1],pJ=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>jQ,0]],1],_e=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],nQ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>z,0],[()=>z,0],[()=>z,0]],2],tQ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>Re,0]]],he=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>z,0],()=>fe,[()=>z,0],()=>ye],1],iQ=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>he,0],()=>Fd,[()=>z,0],0,[()=>z,0],[()=>z,0],[()=>LJ,0],64,[()=>QQ,0],[()=>z,0]],5],rQ=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>Hd,0]]],oe=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>qQ,0],0,[()=>e0,0]],2],sQ=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>oe,0]]],fQ=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>rQ,0],[()=>e0,0],[()=>AJ,0]],2],_Q=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>e0,0],[()=>Hd,0]],3],hQ=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>e0,0],[()=>z,0],2],2];var oQ=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>z,0],[()=>wQ,0],0,0,[()=>VQ,0],[()=>mQ,0],0,()=>Wd,()=>OJ],1],wQ=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>YJ,0],[()=>pJ,0],[()=>JJ,0],[()=>XJ,0],[()=>MJ,0],[()=>Mm,0],[()=>NJ,0],()=>cQ,[()=>CQ,0],[()=>kQ,0],[()=>aQ,0]]],cQ=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var dQ=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var uQ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>SJ,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],yQ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>ym,16]],2];var AQ=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>im,0]],1],Yd=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>XQ,0],[()=>NQ,0]]],Pd=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>pQ,0]],2],RQ=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>t_,0]]],MQ=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>tm,0],2],1],EQ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>An,0],[()=>An,0]],2],TQ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>An,0],[()=>nm,0],2,2],2],eQ=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>An,0],[()=>An,0],[()=>An,0]],2],we=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>OQ,0]]],OQ=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>An,0],[()=>An,0]],2],LQ=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>An,0],[()=>An,0],[()=>An,0],[()=>An,0]],4],IQ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>t_,0],[()=>Pd,0],[()=>we,0],[()=>ce,0],[()=>ue,0],[()=>FQ,0],()=>PQ,[()=>DQ,0],[()=>SQ,0],[()=>Xd,0],[()=>de,0],[()=>Yd,0],[()=>MQ,0],[()=>LQ,0]]],gQ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>IQ,0],0],1],NQ=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>eQ,0]]],ce=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>rm,0]],1],bQ=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>ue,0]]],Xd=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>An,0],[()=>An,0],[()=>An,0],[()=>An,0],[()=>An,0],[()=>An,0]],6],de=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>sm,0],[()=>Yd,0]],1],SQ=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>An,0],[()=>fm,0],[()=>Yd,0]],2],lQ=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>t_,0],[()=>Pd,0],[()=>Xd,0],[()=>de,0]]],ue=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>An,0],[()=>_m,0]],3],$Q=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>t_,0]]],UQ=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>An,0]],1],DQ=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>hm,0]],1],BQ=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>An,0],[()=>um,0],[()=>HQ,0],2,2,[()=>GQ,0]],2],GQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>An,0]]],HQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>An,0],0],1],WQ=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>t_,0],[()=>we,0],[()=>Pd,0],[()=>ce,0]]],FQ=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>YQ,0],[()=>wm,0],[()=>om,0]],2],YQ=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>An,0],[()=>An,0]],2],PQ=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],t_=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>An,0]],1],XQ=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>An,0],[()=>An,0]],2];var CQ=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>RJ,0]],JQ=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>Me,0]],QQ=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>$J,0]];var mQ=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>UJ,0]],zQ=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>GJ,0]],ye=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>WJ],KQ=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>PJ,0]],VQ=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>QJ,0]],Ae=[1,"com.amazon.aws.codewhisperer","References",0,()=>kJ],xQ=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>aJ,0]],jQ=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>vJ,0]],Re=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>nQ,0]],qQ=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>gm,0]],kQ=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>oe,0]],aQ=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>Im,0]],ZQ=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>_Q,0]],vQ=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>z,0]],pQ=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>RQ,0]],nm=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>EQ,0]],tm=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>TQ,0]],im=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>gQ,0]],rm=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>bQ,0]],sm=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>Xd,0]],fm=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>lQ,0]],_m=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>$Q,0]],hm=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>UQ,0]],om=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>BQ,0]],wm=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>WQ,0]],cm=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>Om],dm=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>cm,0]],um=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>An,0]],Me=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>oQ,0],[()=>TJ,0]]],ym=[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"],[()=>KJ,[()=>EJ,0],[()=>jJ,0],()=>FJ,()=>gJ,[()=>tQ,0],[()=>CJ,0],[()=>IJ,0],[()=>mJ,0],[()=>AQ,0],[()=>hQ,0],[()=>sQ,0],()=>VJ,()=>xJ,()=>bJ,[()=>eJ,0],[()=>DJ,0],()=>zJ,[()=>ie,0]]],Am=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>_e]],Rm=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Bd,()=>Fd]],Mm=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>iQ,0],[()=>ZJ,0]]],Em=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>Dd,()=>Dd,()=>Dd,()=>BJ,[()=>HJ,0]]],Tm=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var em=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],Om=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],Lm=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>qJ,0],21]];var Im=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>fQ,0],()=>Wd]],gm=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>z,0],[()=>Hd,0]]];var Ee=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>uQ,()=>yQ];var Oe=(n)=>{return{apiVersion:"2023-11-27",base64Decoder:n?.base64Decoder??Gs.fromBase64,base64Encoder:n?.base64Encoder??Gs.toBase64,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??ne,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??I1,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new ee.HttpBearerAuthSigner}],logger:n?.logger??new fn.NoOpLogger,protocol:n?.protocol??Te.AwsRestJsonProtocol,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:re,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:n?.serviceId??"CodeWhispererStreaming",urlParser:n?.urlParser??ld.parseUrl,utf8Decoder:n?.utf8Decoder??br.fromUtf8,utf8Encoder:n?.utf8Encoder??br.toUtf8}};var Ne=(n)=>{fn.emitWarningIfUnsupportedVersion(process.version);let t=Sd.resolveDefaultsModeConfig(n),i=()=>t().then(fn.loadConfigsForDefaultMode),r=Oe(n);Le.emitWarningIfUnsupportedVersion(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??ei.loadConfig(Ie.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:n?.bodyLengthChecker??bd.calculateBodyLength,defaultUserAgentProvider:n?.defaultUserAgentProvider??ni.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:S1.version}),eventStreamSerdeProvider:n?.eventStreamSerdeProvider??h0.eventStreamSerdeProvider,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(f)=>f.getIdentityProvider("smithy.api#httpBearerAuth")||(async(h)=>{return await gd(h)(h)}),signer:new ge.HttpBearerAuthSigner}],maxAttempts:n?.maxAttempts??ei.loadConfig(On.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,n),region:n?.region??ei.loadConfig(En.NODE_REGION_CONFIG_OPTIONS,{...En.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:O0.NodeHttpHandler.create(n?.requestHandler??i),retryMode:n?.retryMode??ei.loadConfig({...On.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||Yn.DEFAULT_RETRY_MODE},n),sha256:n?.sha256??Nd.Hash.bind(null,"sha256"),streamCollector:n?.streamCollector??O0.streamCollector,useDualstackEndpoint:n?.useDualstackEndpoint??ei.loadConfig(En.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:n?.useFipsEndpoint??ei.loadConfig(En.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:n?.userAgentAppId??ei.loadConfig(ni.NODE_APP_ID_CONFIG_OPTIONS,s)}};var ct=Z(Dt(),1);var ft=Z(nt(),1);var be=(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}}},Se=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),token:n.token()}};var le=(n,t)=>{let i=Object.assign(ct.getAwsRegionExtensionConfiguration(n),fn.getDefaultExtensionConfiguration(n),ft.getHttpHandlerExtensionConfiguration(n),be(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,ct.resolveAwsRegionExtensionConfiguration(i),fn.resolveDefaultRuntimeConfig(i),ft.resolveHttpHandlerRuntimeConfig(i),Se(i))};class Cd extends fn.Client{config;constructor(...[n]){let t=Ne(n||{});super(t);this.initConfig=t;let i=N1(t),r=Ti.resolveUserAgentConfig(i),s=On.resolveRetryConfig(r),f=En.resolveRegionConfig(s),h=Ki.resolveHostHeaderConfig(f),_=Rt.resolveEndpointConfig(h),o=wt.resolveDefaultAwsRegionalEndpointsConfig(_),w=Nc.resolveEventStreamSerdeConfig(o),c=g1(w),d=le(c,n?.extensions||[]);this.config=d,this.middlewareStack.use($e.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Ti.getUserAgentPlugin(this.config)),this.middlewareStack.use(On.getRetryPlugin(this.config)),this.middlewareStack.use(Kf.getContentLengthPlugin(this.config)),this.middlewareStack.use(Ki.getHostHeaderPlugin(this.config)),this.middlewareStack.use(mf.getLoggerPlugin(this.config)),this.middlewareStack.use(zf.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(Ws.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:L1,identityProviderConfigProvider:async(u)=>new Ws.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":u.token})})),this.middlewareStack.use(Ws.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class Jd extends fn.Command.classBuilder().ep(b1).m(function(n,t,i,r){return[Rt.getEndpointPlugin(i,n.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(Ee).build(){}import{randomUUID as kd}from"crypto";import{createHash as Nm}from"crypto";function Ue(n){return typeof n==="object"&&n!==null&&"canonicalVersion"in n&&n.canonicalVersion===1&&"messages"in n&&Array.isArray(n.messages)}function Qd(n){if(Array.isArray(n))return n.map(Qd);if(typeof n!=="object"||n===null)return n;return Object.fromEntries(Object.entries(n).sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,Qd(i)]))}function i_(n){return Nm("sha256").update(JSON.stringify(Qd(n))).digest("hex")}function et(n){return i_({text:n.text,toolCalls:n.toolCalls.map((t)=>({id:t.id,name:t.name,input:t.input}))})}function bm(n){try{return JSON.parse(n)}catch{return n}}function Sm(n,t){let i=new Map(n.tools.map((r)=>[r.wireName,r]));return{text:t.text,toolCalls:t.toolCalls.map((r)=>{let s=i.get(r.name),f=bm(r.input);if(s?.publicType==="custom"&&typeof f==="object"&&f!==null&&!Array.isArray(f)&&Object.keys(f).length===1&&typeof f.input==="string")f=f.input;return{id:r.id,name:s?.name??r.name,input:f}})}}function md(n,t){return i_(Sm(n,t))}function De(n){let t=[],i=[];for(let r of n.messages){if(r.role==="assistant"){i.push(r),t=i;continue}i=[]}if(t.length===0)return;return md(n,{text:t.map((r)=>ii(r.content)).join(""),toolCalls:t.flatMap((r)=>r.toolCalls.map((s)=>({id:s.id,name:s.name,input:JSON.stringify(s.input)})))})}function ii(n){return n.filter((t)=>t.type==="text").map((t)=>t.text).join("")}var ut=1,Fs="application/x-kiro-provider-output+json",Ys="application/x-kiro-provider-output+ndjson",Be="application/x-kiro-provider-output+json; charset=utf-8",Ge="application/x-kiro-provider-output+ndjson; charset=utf-8";function s_(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Ft(n,t){return Object.keys(n).every((i)=>t.has(i))}function dt(n){return typeof n==="string"&&n.length>0}function r_(n){return typeof n==="number"&&Number.isSafeInteger(n)&&n>=0}function He(n){if(!s_(n)||!Ft(n,new Set(["inputTokens","outputTokens","totalTokens"]))||!r_(n.inputTokens)||!r_(n.outputTokens)||!r_(n.totalTokens)||n.totalTokens!==n.inputTokens+n.outputTokens)return;return{inputTokens:n.inputTokens,outputTokens:n.outputTokens,totalTokens:n.totalTokens}}function lm(n){if(n===void 0)return;if(!s_(n)||!Ft(n,new Set(["text","signature","redactedContent","encryptedContent"])))return;for(let t of["text","signature","redactedContent","encryptedContent"])if(n[t]!==void 0&&!dt(n[t]))return;return{...typeof n.text==="string"?{text:n.text}:{},...typeof n.signature==="string"?{signature:n.signature}:{},...typeof n.redactedContent==="string"?{redactedContent:n.redactedContent}:{},...typeof n.encryptedContent==="string"?{encryptedContent:n.encryptedContent}:{}}}function $m(n){if(!s_(n)||!Ft(n,new Set(["id","name","input"]))||!dt(n.id)||!dt(n.name)||typeof n.input!=="string")return;return{id:n.id,name:n.name,input:n.input}}function Ps(n){if(!s_(n)||!Ft(n,new Set(["canonicalOutputVersion","conversationId","model","createdAt","text","reasoning","toolCalls","finishReason","usage"]))||n.canonicalOutputVersion!==1||!dt(n.conversationId)||!dt(n.model)||!r_(n.createdAt)||typeof n.text!=="string"||!Array.isArray(n.toolCalls)||n.finishReason!=="stop"&&n.finishReason!=="tool_calls")return;let t=lm(n.reasoning);if(n.reasoning!==void 0&&t===void 0)return;let i=[];for(let f of n.toolCalls){let h=$m(f);if(!h)return;i.push(h)}let r=i.length>0?"tool_calls":"stop";if(n.finishReason!==r)return;let s=He(n.usage);if(!s)return;return{canonicalOutputVersion:1,conversationId:n.conversationId,model:n.model,createdAt:n.createdAt,text:n.text,...t!==void 0?{reasoning:t}:{},toolCalls:i,finishReason:n.finishReason,usage:s}}function Um(n){if(!s_(n)||n.canonicalOutputVersion!==1||typeof n.type!=="string")return;let t={canonicalOutputVersion:1};switch(n.type){case"started":if(!Ft(n,new Set(["canonicalOutputVersion","type","conversationId","model","createdAt"]))||!dt(n.conversationId)||!dt(n.model)||!r_(n.createdAt))return;return{...t,type:"started",conversationId:n.conversationId,model:n.model,createdAt:n.createdAt};case"reasoning_delta":case"text_delta":if(!Ft(n,new Set(["canonicalOutputVersion","type","text"]))||!dt(n.text))return;return{...t,type:n.type,text:n.text};case"reasoning_signature":if(!Ft(n,new Set(["canonicalOutputVersion","type","signature"]))||!dt(n.signature))return;return{...t,type:"reasoning_signature",signature:n.signature};case"reasoning_redacted":if(!Ft(n,new Set(["canonicalOutputVersion","type","data"]))||!dt(n.data))return;return{...t,type:"reasoning_redacted",data:n.data};case"reasoning_encrypted":if(!Ft(n,new Set(["canonicalOutputVersion","type","encryptedContent"]))||!dt(n.encryptedContent))return;return{...t,type:"reasoning_encrypted",encryptedContent:n.encryptedContent};case"tool_call_delta":{if(!Ft(n,new Set(["canonicalOutputVersion","type","index","id","name","arguments"]))||!Number.isSafeInteger(n.index)||n.index<0||n.id!==void 0&&!dt(n.id)||n.name!==void 0&&!dt(n.name)||typeof n.arguments!=="string")return;return{...t,type:"tool_call_delta",index:n.index,...typeof n.id==="string"?{id:n.id}:{},...typeof n.name==="string"?{name:n.name}:{},arguments:n.arguments}}case"completed":{if(!Ft(n,new Set(["canonicalOutputVersion","type","finishReason","usage"]))||n.finishReason!=="stop"&&n.finishReason!=="tool_calls")return;let i=He(n.usage);if(!i)return;return{...t,type:"completed",finishReason:n.finishReason,usage:i}}default:return}}function Oi(n){try{return Um(JSON.parse(n))}catch(t){if(t instanceof SyntaxError)return;throw t}}var Dm=["low","medium","high","xhigh","max"];function Bm(n){return typeof n==="string"&&Dm.some((t)=>t===n)}var We=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Fe=new Set(["claude-opus-5","claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...We]),Gm=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...Fe]);function lr(n){return Gm.has(n)}function zd(n){return Fe.has(n)}function Ye(n,t){if(We.has(n))return{reasoning:{effort:t}};return{output_config:{effort:t}}}function Hm(n,t){if(!lr(n))return;if(t==="xhigh"&&!zd(n))return"max";return t}function Wm(n,t){if(!lr(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 Pe(n){let t;if(lr(n.model))t={wireId:n.model,effort:void 0};else try{t=ci(n.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!lr(t.wireId))return;let i=[t.effort,n.reasoningEffort,n.configEffort];for(let r of i)if(Bm(r))return Hm(t.wireId,r);if(!n.think)return;if(n.autoEffortMapping??!0)return Wm(n.budget,t.wireId);return"medium"}var Xe=1024,Ce=128000,Fm=new Set(["claude-sonnet-5","claude-opus-5"]);function qi(n,t){let i;try{i=ci(n).wireId}catch{return{ok:!1,code:"unsupported_output_token_limit",message:`Output-token limiting is not available for unsupported model ${n}`}}if(!Fm.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<Xe||t>Ce)return{ok:!1,code:"invalid_output_token_limit",message:`Kiro requires output-token limits for ${n} to be an integer from ${Xe} through ${Ce}`};return{ok:!0,wireModel:i,additionalModelRequestFields:{max_tokens:t}}}class cn extends Error{code;param;name="RequestTransformError";constructor(n,t="invalid_request",i){super(n);this.code=t;this.param=i}}import{randomUUID as ae}from"crypto";var Ym=["csv","doc","docx","html","md","pdf","txt","xls","xlsx"],Pm=new Set(Ym),Xm={"application/pdf":"pdf","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/csv":"csv","text/html":"html","text/markdown":"md","text/plain":"txt"};function Cm(n){return n===" "||n==="-"||n==="_"||n==="("||n===")"||n==="["||n==="]"||/[A-Za-z0-9]/.test(n)}function Je(n,t,i){let r=`.${t}`,s=n.toLowerCase().endsWith(r)?n.slice(0,-r.length):n,f=Array.from(s).length;if(f<1||f>200||s.startsWith(" ")||s.endsWith(" ")||s.includes(" ")||Array.from(s).some((h)=>!Cm(h)))throw new cn(`Inline document ${i} cannot be represented by Kiro's native document name field`,"invalid_file_name",i);return s}function Jm(n){let t=n.split(".").at(-1)?.toLowerCase();return t!==void 0&&Pm.has(t)?t:void 0}function Qm(n){if(!n.startsWith("data:"))return{base64:n};let t=n.indexOf(",");if(t<0)throw new cn("Inline document data URL is missing its payload","invalid_file_data");let r=n.slice(5,t).split(";");if(!r.includes("base64"))throw new cn("Inline document data URLs must use base64 encoding","unsupported_file_encoding");return{...r[0]?{mediaType:r[0].toLowerCase()}:{},base64:n.slice(t+1)}}function Qe(n,t){if(n.length===0)throw new cn(`Inline document ${t} contains no data`,"invalid_file_data",t);try{let i=atob(n),r=new Uint8Array(i.length);for(let s=0;s<i.length;s+=1)r[s]=i.charCodeAt(s);return r}catch(i){if(!(i instanceof DOMException))throw i;throw new cn(`Inline document ${t} contains invalid base64 data`,"invalid_file_data",t)}}function me(n,t,i,r=i){let s=Qm(t),f=Jm(n)??(s.mediaType===void 0?void 0:Xm[s.mediaType]);if(f===void 0)throw new cn(`Inline document ${i} has an unsupported file format`,"unsupported_file_format",i);return Je(n,f,r),Qe(s.base64,i),{name:n,format:f,data:s.base64,path:i}}function ze(n){return{name:Je(n.name,n.format,n.path),format:n.format,source:{bytes:Qe(n.data,n.path)}}}function mm(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 Ke(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:mm(r.data)}})),omitted:n.length-t.length}}function zm(n,t){if(!n.startsWith("data:"))throw new cn(`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 cn(`Image ${t} contains an invalid data URL`,"invalid_image");return{mediaType:i.split(";")[0]?.replace("data:","")||"image/jpeg",data:r}}function Km(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(zm(i.url,i.path))}return t}function Vm(n){return n.flatMap((t)=>t.type==="document"?[ze({name:t.name,format:t.format,data:t.data,path:t.path})]:[])}function xm(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 Ve(n,t){let i={content:ii(n.content),modelId:t,origin:In.ORIGIN_AI_EDITOR},r=xm(n.content);if(r.length>0)i.userInputMessageContext={toolResults:r};let s=Km(n.content);if(s.length>0){let h=Ke(s);if(h.omitted>0)throw new cn(`Message ${n.path} exceeds Kiro's limit of 4 images and 3.75 MB of base64 image data`,"too_many_images");i.images=h.images}let f=Vm(n.content);if(f.length>0)i.documents=f;return i}function jm(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 qm(n,t){let i=jm(t),r={content:ii(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 xe(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:qm(h,r.get(f))});continue}if(h.role==="user"||h.role==="tool")s.push({userInputMessage:Ve(h,t)})}return s}function je(n){return n.some((t)=>Boolean(t.assistantResponseMessage?.toolUses)||Boolean(t.userInputMessage?.userInputMessageContext?.toolResults))}function qe(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 ke(n,t){return Ve(n,t)}function Ze(n,t){return{type:"text",text:n,path:t}}function km(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 am(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||t.content.every((s)=>s.type==="text"))continue;let r=i[1];throw new cn(`Message ${t.path} interleaves multiple text content blocks with non-text content, but Kiro exposes only one text field and cannot preserve their ordering`,"unsupported_content_block_projection",r?.path??t.path)}}function Zm(n){let t=n.messages.filter((_)=>_.role==="system"||_.role==="developer");if(t.length>0&&n.projectionMode==="safe")throw new cn("Kiro accepted additionalContext structurally but did not preserve instruction content or priority; safe mode cannot project system/developer/instructions","unsupported_instruction_projection");for(let _ of t)if(_.content.some((o)=>o.type!=="text")||_.toolCalls.length>0)throw new cn(`Instruction ${_.path} contains non-text content that legacy projection cannot represent`,"unsupported_instruction_projection");let i=[],r=new Map;for(let[_,o]of n.messages.entries()){if(o.role==="system"||o.role==="developer")continue;r.set(_,i.length),i.push(km(o))}if(t.length===0)return{messages:i,projectedIndexByOriginal:r};let s=t.flatMap((_)=>_.content.map((o)=>o.type==="text"?o.text:"")).join(`
|
|
354
|
+
`}import{createHash as S8,timingSafeEqual as b8}from"crypto";function tn(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 Ny="Bearer ";function Uy(n,t){let i=Buffer.from(n);for(let r of t){let s=Buffer.from(r);if(i.byteLength===s.byteLength&&b8(i,s))return r}return}function $y(n){return S8("sha256").update("kiro-provider-tenant-v1\x00").update(n).digest("hex")}function fe(n,t,i=tn){let r=n.headers.get("Authorization");if(r===null){let _=n.headers.get("x-api-key"),o=_===null?void 0:Uy(_,t);if(o!==void 0)return{ok:!0,tenantId:$y(o)};return{ok:!1,response:i(401,"Missing Authorization or x-api-key header.","authentication_error","missing_api_key")}}if(!r.startsWith(Ny))return{ok:!1,response:i(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let s=r.slice(Ny.length),f=Uy(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:$y(f)}}var qi=k(Ht(),1);var vf=k(Ht(),1);var pf=k(Ht(),1);var Li=k(Ht(),1);var ut=k(Ht(),1);var En=k(nt(),1);var as=k(ji(),1),zT=k(Ji(),1);var Cc=k($_(),1);var no=k(it(),1);var lt=k(Tr(),1);var Tn=k(kf(),1);var on=k(Ei(),1);var Gs=k(ji(),1);var Bs=k(Ei(),1);var CE=async(n,t,i)=>{return{operation:Bs.getSmithyContext(t).operation}};function oF(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 PE=(n)=>{let t=[];switch(n.operation){default:t.push(oF(n))}return t},YE=(n)=>{let t=Gs.memoizeIdentityProvider(n.token,Gs.isIdentityExpired,Gs.doesIdentityRequireRefresh);return Object.assign(n,{authSchemePreference:Bs.normalizeProvider(n.authSchemePreference??[]),token:t})};var XE=(n)=>{return Object.assign(n,{useDualstackEndpoint:n.useDualstackEndpoint??!1,useFipsEndpoint:n.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},JE={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var QE={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 CT=k(Ht(),1),PT=k(kc(),1);var Xs=k(nt(),1);var st=k(nt(),1);var N1=300000,Hs="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var iT=async(n,t={},i)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => k(Hd(),1)),s=(_)=>t.clientConfig?.[_]??t.parentClientConfig?.[_]??i?.[_];return new r(Object.assign({},t.clientConfig??{},{region:n??t.clientConfig?.region,logger:s("logger"),userAgentAppId:s("userAgentAppId")}))};var rT=async(n,t,i={},r)=>{let{CreateTokenCommand:s}=await Promise.resolve().then(() => k(Hd(),1));return(await iT(t,i,r)).send(new s({clientId:n.clientId,clientSecret:n.clientSecret,refreshToken:n.refreshToken,grantType:"refresh_token"}))};var sT=k(nt(),1);var Wd=(n)=>{if(n.expiration&&n.expiration.getTime()<Date.now())throw new sT.TokenProviderError(`Token is expired. ${Hs}`,!1)};var fT=k(nt(),1);var vi=(n,t,i=!1)=>{if(typeof t>"u")throw new fT.TokenProviderError(`Value not present for '${n}' in SSO Token${i?". Cannot refresh":""}. ${Hs}`,!1)};var oT=k(nt(),1);import{promises as BX}from"fs";var{writeFile:GX}=BX,_T=(n,t)=>{let i=oT.getSSOTokenFilepath(n),r=JSON.stringify(t,null,2);return GX(i,r)};var hT=new Date(0),eT=(n={})=>async({callerClientConfig:t}={})=>{n.logger?.debug("@aws-sdk/token-providers - fromSso");let i=await st.parseKnownFiles(n),r=st.getProfileName({profile:n.profile??t?.profile}),s=i[r];if(!s)throw new st.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!s.sso_session)throw new st.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let f=s.sso_session,o=(await st.loadSsoSessionData(n))[f];if(!o)throw new st.TokenProviderError(`Sso session '${f}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new st.TokenProviderError(`Sso session '${f}' is missing required property '${A}'.`,!1);let{sso_start_url:h,sso_region:e}=o,c;try{c=await st.getSSOTokenFromFile(f)}catch(A){throw new st.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${Hs}`,!1)}vi("accessToken",c.accessToken),vi("expiresAt",c.expiresAt);let{accessToken:d,expiresAt:u}=c,w={token:d,expiration:new Date(u)};if(w.expiration.getTime()-Date.now()>N1)return w;if(Date.now()-hT.getTime()<30000)return Wd(w),w;vi("clientId",c.clientId,!0),vi("clientSecret",c.clientSecret,!0),vi("refreshToken",c.refreshToken,!0);try{hT.setTime(Date.now());let A=await rT(c,e,n,t);vi("accessToken",A.accessToken),vi("expiresIn",A.expiresIn);let R=new Date(Date.now()+A.expiresIn*1000);try{await _T(f,{...c,accessToken:A.accessToken,expiresAt:R.toISOString(),refreshToken:A.refreshToken})}catch(M){}return{token:A.accessToken,expiration:R}}catch(A){return Wd(w),w}};var Fd=(n={})=>Xs.memoize(Xs.chain(eT(n),async()=>{throw new Xs.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 si=k(Ht(),1);var YT=k(ji(),1);var Th=k($_(),1);var Cd=k(tt(),1);var Ii=k(nt(),1);var mh=k(v_(),1);var Pd=k(tt(),1);var Yd=k(nt(),1);var Fn=k(kf(),1);var HT=k(Ud(),1),WT=k(ji(),1);var Xd=k(it(),1);var Js=k(tt(),1);var $r=k(tt(),1);var Vn=k(Tr(),1);var co="ref",Dr=-1,gh=!0,cT="isSet",yT="PartitionResult",Oh="booleanEquals",Jd="getAttr",dT={[co]:"Endpoint"},Qd={[co]:yT},Qs={},uT=[{[co]:"Region"}],wT={conditions:[[cT,[dT]],[cT,uT],["aws.partition",uT,yT],[Oh,[{[co]:"UseFIPS"},gh]],[Oh,[{[co]:"UseDualStack"},gh]],[Oh,[{fn:Jd,argv:[Qd,"supportsDualStack"]},gh]],[Oh,[{fn:Jd,argv:[Qd,"supportsFIPS"]},gh]],["stringEquals",[{fn:Jd,argv:[Qd,"name"]},"aws-us-gov"]]],results:[[Dr],[Dr,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Dr,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[dT,Qs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Qs],[Dr,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",Qs],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",Qs],[Dr,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",Qs],[Dr,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",Qs],[Dr,"Invalid Configuration: Missing Region"]]},mX=2,ft=1e8,HX=new Int32Array([-1,1,-1,0,13,3,1,4,ft+12,2,5,ft+12,3,8,6,4,7,ft+11,5,ft+9,ft+10,4,11,9,6,10,ft+8,7,ft+6,ft+7,5,12,ft+5,6,ft+4,ft+5,3,ft+1,14,4,ft+2,ft+3]),AT=Vn.BinaryDecisionDiagram.from(HX,mX,wT.conditions,wT.results);var WX=new Vn.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),RT=(n,t={})=>{return WX.get(n,()=>Vn.decideEndpoint(AT,{endpointParams:n,logger:t.logger}))};Vn.customEndpointFunctions.aws=ut.awsEndpointFunctions;var Kd=k(Ji(),1);class ot extends on.ServiceException{constructor(n){super(n);Object.setPrototypeOf(this,ot.prototype)}}class Lh extends ot{name="AccessDeniedException";$fault="client";reason;constructor(n){super({name:"AccessDeniedException",$fault:"client",...n});Object.setPrototypeOf(this,Lh.prototype),this.reason=n.reason}}class Ih extends ot{name="ConflictException";$fault="client";reason;constructor(n){super({name:"ConflictException",$fault:"client",...n});Object.setPrototypeOf(this,Ih.prototype),this.reason=n.reason}}class Sh extends ot{name="InternalServerException";$fault="server";$retryable={};reason;constructor(n){super({name:"InternalServerException",$fault:"server",...n});Object.setPrototypeOf(this,Sh.prototype),this.reason=n.reason}}class bh extends ot{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(n){super({name:"ThrottlingException",$fault:"client",...n});Object.setPrototypeOf(this,bh.prototype),this.reason=n.reason}}class Nh extends ot{name="ValidationException";$fault="client";reason;constructor(n){super({name:"ValidationException",$fault:"client",...n});Object.setPrototypeOf(this,Nh.prototype),this.reason=n.reason}}class Uh extends ot{name="ResourceNotFoundException";$fault="client";constructor(n){super({name:"ResourceNotFoundException",$fault:"client",...n});Object.setPrototypeOf(this,Uh.prototype)}}class $h extends ot{name="ServiceUnavailableException";$fault="server";constructor(n){super({name:"ServiceUnavailableException",$fault:"server",...n});Object.setPrototypeOf(this,$h.prototype)}}class Dh extends ot{name="ServiceQuotaExceededException";$fault="client";reason;constructor(n){super({name:"ServiceQuotaExceededException",$fault:"client",...n});Object.setPrototypeOf(this,Dh.prototype),this.reason=n.reason}}class Bh extends ot{name="DryRunOperationException";$fault="client";responseCode;constructor(n){super({name:"DryRunOperationException",$fault:"client",...n});Object.setPrototypeOf(this,Bh.prototype),this.responseCode=n.responseCode}}var MT=Kd.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),FX=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];MT.registerError(FX,ot);var fi=Kd.TypeRegistry.for("com.amazon.aws.codewhisperer"),CX=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];fi.registerError(CX,Lh);var PX=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];fi.registerError(PX,Ih);var YX=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];fi.registerError(YX,Bh);var ET=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];fi.registerError(ET,Sh);var XX=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];fi.registerError(XX,Uh);var JX=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];fi.registerError(JX,Dh);var QX=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];fi.registerError(QX,$h);var aX=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];fi.registerError(aX,bh);var zX=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];fi.registerError(zX,Nh);var lT=[MT,fi];var xd=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],a=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],KX=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Gh=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],Rn=[0,"com.amazon.aws.q","SensitiveString",8,0],xX=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>a,0],[()=>a,0],[()=>a,0]],2],VX=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>a,0],[()=>a,0],[()=>a,0],[()=>a,0]],3],jX=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>a,0],0],1],qX=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>a,0],0,[()=>BT,0],()=>DT,[()=>TT,0],[()=>UQ,0],()=>Vd,[()=>vQ,0]],1];var Vd=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],kX=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>KQ,[()=>a,0],[()=>a,0]],2],ZX=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],vX=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>a,0]],1],pX=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>a,0]],1],nJ=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>DT]],tJ=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>a,0],0,0,0,[()=>a,0],[()=>a,0]]],iJ=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],rJ=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>GT,0],0,0,0,[()=>MQ,0],0,0,0],2],sJ=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>a,0],()=>jd],2],fJ=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>sJ,0],[()=>a,0]],2],oJ=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>qQ,0]],3],_J=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>a,0],[()=>a,0],[()=>jQ,0],[()=>TQ,0]]],hJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],eJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>a,0]]],ad=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],cJ=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>a,0],[()=>a,0]]],dJ=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],uJ=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],wJ=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>LT,0],()=>xQ,[()=>LQ,0],2,[()=>$Q,0]]],yJ=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>a,0],[()=>a,0]]],AJ=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>a,0],[()=>gQ,0],1]],TT=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>a,0],0],1],RJ=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>TT,0]]],MJ=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>a,0]]],EJ=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>kQ,0]],2],lJ=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>QQ,0]]],TJ=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],gJ=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],OJ=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>QJ]],LJ=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],zd=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],gT=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],jd=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>zd,()=>zd],2],IJ=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>a,0],21,[()=>a,0]]],SJ=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>a,0],[()=>a,0]],1],bJ=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>OT]],NJ=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>a,0],()=>gT,[()=>a,0],()=>$T,0],1],UJ=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>a,0],0,[()=>a,0]],3],$J=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>a,0],[()=>a,0],1,[()=>a,0],[()=>a,0]],1],DJ=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>IQ,0]],1],OT=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],BJ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>a,0],[()=>a,0],[()=>a,0]],2],GJ=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>BT,0]]],LT=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>a,0],()=>gT,[()=>a,0],()=>$T],1],mJ=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>LT,0],()=>jd,[()=>a,0],0,[()=>a,0],[()=>a,0],[()=>vX,0],64,[()=>EQ,0],[()=>a,0]],5],HJ=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>xd,0]]],IT=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>SQ,0],0,[()=>Gh,0]],2],WJ=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>IT,0]]],FJ=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>HJ,0],[()=>Gh,0],[()=>KX,0]],2],CJ=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Gh,0],[()=>xd,0]],3],PJ=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Gh,0],[()=>a,0],2],2];var YJ=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>a,0],[()=>XJ,0],0,0,[()=>OQ,0],[()=>lQ,0],0,()=>Vd,()=>ZX],1],XJ=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>wJ,0],[()=>DJ,0],[()=>MJ,0],[()=>AJ,0],[()=>VX,0],[()=>VQ,0],[()=>tJ,0],()=>JJ,[()=>RQ,0],[()=>bQ,0],[()=>NQ,0]]],JJ=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var QJ=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var aJ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>rJ,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],zJ=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>zQ,16]],2];var KJ=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>mQ,0]],1],qd=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>AQ,0],[()=>tQ,0]]],kd=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>DQ,0]],2],xJ=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>uo,0]]],VJ=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>GQ,0],2],1],jJ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>Rn,0],[()=>Rn,0]],2],qJ=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>Rn,0],[()=>BQ,0],2,2],2],kJ=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>Rn,0],[()=>Rn,0],[()=>Rn,0]],2],ST=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>ZJ,0]]],ZJ=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>Rn,0],[()=>Rn,0]],2],vJ=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>Rn,0],[()=>Rn,0],[()=>Rn,0],[()=>Rn,0]],4],pJ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>uo,0],[()=>kd,0],[()=>ST,0],[()=>bT,0],[()=>UT,0],[()=>uQ,0],()=>yQ,[()=>_Q,0],[()=>rQ,0],[()=>Zd,0],[()=>NT,0],[()=>qd,0],[()=>VJ,0],[()=>vJ,0]]],nQ=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>pJ,0],0],1],tQ=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>kJ,0]]],bT=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>HQ,0]],1],iQ=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>UT,0]]],Zd=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>Rn,0],[()=>Rn,0],[()=>Rn,0],[()=>Rn,0],[()=>Rn,0],[()=>Rn,0]],6],NT=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>WQ,0],[()=>qd,0]],1],rQ=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>Rn,0],[()=>FQ,0],[()=>qd,0]],2],sQ=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>uo,0],[()=>kd,0],[()=>Zd,0],[()=>NT,0]]],UT=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>Rn,0],[()=>CQ,0]],3],fQ=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>uo,0]]],oQ=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>Rn,0]],1],_Q=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>PQ,0]],1],hQ=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>Rn,0],[()=>aQ,0],[()=>cQ,0],2,2,[()=>eQ,0]],2],eQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>Rn,0]]],cQ=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>Rn,0],0],1],dQ=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>uo,0],[()=>ST,0],[()=>kd,0],[()=>bT,0]]],uQ=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>wQ,0],[()=>XQ,0],[()=>YQ,0]],2],wQ=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>Rn,0],[()=>Rn,0]],2],yQ=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],uo=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>Rn,0]],1],AQ=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>Rn,0],[()=>Rn,0]],2];var RQ=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>xX,0]],MQ=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>GT,0]],EQ=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>fJ,0]];var lQ=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>oJ,0]],TQ=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>eJ,0]],$T=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>dJ],gQ=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>yJ,0]],OQ=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>EJ,0]],DT=[1,"com.amazon.aws.codewhisperer","References",0,()=>bJ],LQ=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>NJ,0]],IQ=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>$J,0]],BT=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>BJ,0]],SQ=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>na,0]],bQ=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>IT,0]],NQ=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>pQ,0]],UQ=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>CJ,0]],$Q=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>a,0]],DQ=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>xJ,0]],BQ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>jJ,0]],GQ=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>qJ,0]],mQ=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>nQ,0]],HQ=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>iQ,0]],WQ=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>Zd,0]],FQ=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>sQ,0]],CQ=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>fQ,0]],PQ=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>oQ,0]],YQ=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>hQ,0]],XQ=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>dQ,0]],JQ=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>ZQ],QQ=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>JQ,0]],aQ=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>Rn,0]],GT=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>YJ,0],[()=>qX,0]]],zQ=[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"],[()=>gJ,[()=>jX,0],[()=>IJ,0],()=>uJ,()=>nJ,[()=>GJ,0],[()=>RJ,0],[()=>pX,0],[()=>lJ,0],[()=>KJ,0],[()=>PJ,0],[()=>WJ,0],()=>OJ,()=>LJ,()=>iJ,[()=>kX,0],[()=>_J,0],()=>TJ,[()=>ET,0]]],KQ=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>OT]],xQ=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>zd,()=>jd]],VQ=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>mJ,0],[()=>UJ,0]]],jQ=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>ad,()=>ad,()=>ad,()=>hJ,[()=>cJ,0]]],qQ=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var kQ=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],ZQ=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],vQ=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>SJ,0],21]];var pQ=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>FJ,0],()=>Vd]],na=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>a,0],[()=>xd,0]]];var mT=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>aJ,()=>zJ];var FT=(n)=>{return{apiVersion:"2023-11-27",base64Decoder:n?.base64Decoder??Js.fromBase64,base64Encoder:n?.base64Encoder??Js.toBase64,disableHostPrefix:n?.disableHostPrefix??!1,endpointProvider:n?.endpointProvider??RT,extensions:n?.extensions??[],httpAuthSchemeProvider:n?.httpAuthSchemeProvider??PE,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(t)=>t.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new WT.HttpBearerAuthSigner}],logger:n?.logger??new on.NoOpLogger,protocol:n?.protocol??HT.AwsRestJsonProtocol,protocolSettings:n?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:lT,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:n?.serviceId??"CodeWhispererStreaming",urlParser:n?.urlParser??Xd.parseUrl,utf8Decoder:n?.utf8Decoder??$r.fromUtf8,utf8Encoder:n?.utf8Encoder??$r.toUtf8}};var XT=(n)=>{on.emitWarningIfUnsupportedVersion(process.version);let t=Yd.resolveDefaultsModeConfig(n),i=()=>t().then(on.loadConfigsForDefaultMode),r=FT(n);CT.emitWarningIfUnsupportedVersion(process.version);let s={profile:n?.profile,logger:r.logger};return{...r,...n,runtime:"node",defaultsMode:t,authSchemePreference:n?.authSchemePreference??Ii.loadConfig(PT.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,s),bodyLengthChecker:n?.bodyLengthChecker??Pd.calculateBodyLength,defaultUserAgentProvider:n?.defaultUserAgentProvider??si.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:QE.version}),eventStreamSerdeProvider:n?.eventStreamSerdeProvider??Th.eventStreamSerdeProvider,httpAuthSchemes:n?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(f)=>f.getIdentityProvider("smithy.api#httpBearerAuth")||(async(_)=>{return await Fd(_)(_)}),signer:new YT.HttpBearerAuthSigner}],maxAttempts:n?.maxAttempts??Ii.loadConfig(Tn.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,n),region:n?.region??Ii.loadConfig(En.NODE_REGION_CONFIG_OPTIONS,{...En.NODE_REGION_CONFIG_FILE_OPTIONS,...s}),requestHandler:mh.NodeHttpHandler.create(n?.requestHandler??i),retryMode:n?.retryMode??Ii.loadConfig({...Tn.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await i()).retryMode||Fn.DEFAULT_RETRY_MODE},n),sha256:n?.sha256??Cd.Hash.bind(null,"sha256"),streamCollector:n?.streamCollector??mh.streamCollector,useDualstackEndpoint:n?.useDualstackEndpoint??Ii.loadConfig(En.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,s),useFipsEndpoint:n?.useFipsEndpoint??Ii.loadConfig(En.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,s),userAgentAppId:n?.userAgentAppId??Ii.loadConfig(si.NODE_APP_ID_CONFIG_OPTIONS,s)}};var wt=k(Ht(),1);var _t=k(it(),1);var JT=(n)=>{let{httpAuthSchemes:t,httpAuthSchemeProvider:i,token:r}=n;return{setHttpAuthScheme(s){let f=t.findIndex((_)=>_.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}}},QT=(n)=>{return{httpAuthSchemes:n.httpAuthSchemes(),httpAuthSchemeProvider:n.httpAuthSchemeProvider(),token:n.token()}};var aT=(n,t)=>{let i=Object.assign(wt.getAwsRegionExtensionConfiguration(n),on.getDefaultExtensionConfiguration(n),_t.getHttpHandlerExtensionConfiguration(n),JT(n));return t.forEach((r)=>r.configure(i)),Object.assign(n,wt.resolveAwsRegionExtensionConfiguration(i),on.resolveDefaultRuntimeConfig(i),_t.resolveHttpHandlerRuntimeConfig(i),QT(i))};class vd extends on.Client{config;constructor(...[n]){let t=XT(n||{});super(t);this.initConfig=t;let i=XE(t),r=Li.resolveUserAgentConfig(i),s=Tn.resolveRetryConfig(r),f=En.resolveRegionConfig(s),_=qi.resolveHostHeaderConfig(f),o=lt.resolveEndpointConfig(_),h=ut.resolveDefaultAwsRegionalEndpointsConfig(o),e=Cc.resolveEventStreamSerdeConfig(h),c=YE(e),d=aT(c,n?.extensions||[]);this.config=d,this.middlewareStack.use(zT.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Li.getUserAgentPlugin(this.config)),this.middlewareStack.use(Tn.getRetryPlugin(this.config)),this.middlewareStack.use(no.getContentLengthPlugin(this.config)),this.middlewareStack.use(qi.getHostHeaderPlugin(this.config)),this.middlewareStack.use(vf.getLoggerPlugin(this.config)),this.middlewareStack.use(pf.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(as.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:CE,identityProviderConfigProvider:async(u)=>new as.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":u.token})})),this.middlewareStack.use(as.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class pd extends on.Command.classBuilder().ep(JE).m(function(n,t,i,r){return[lt.getEndpointPlugin(i,n.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(mT).build(){}import{randomUUID as cu}from"crypto";import{createHash as ta}from"crypto";function KT(n){return typeof n==="object"&&n!==null&&"canonicalVersion"in n&&n.canonicalVersion===1&&"messages"in n&&Array.isArray(n.messages)}function nu(n){if(Array.isArray(n))return n.map(nu);if(typeof n!=="object"||n===null)return n;return Object.fromEntries(Object.entries(n).sort(([t],[i])=>t.localeCompare(i)).map(([t,i])=>[t,nu(i)]))}function wo(n){return ta("sha256").update(JSON.stringify(nu(n))).digest("hex")}function Lt(n){return wo({text:n.text,toolCalls:n.toolCalls.map((t)=>({id:t.id,name:t.name,input:t.input}))})}function ia(n){try{return JSON.parse(n)}catch{return n}}function ra(n,t){let i=new Map(n.tools.map((r)=>[r.wireName,r]));return{text:t.text,toolCalls:t.toolCalls.map((r)=>{let s=i.get(r.name),f=ia(r.input);if(s?.publicType==="custom"&&typeof f==="object"&&f!==null&&!Array.isArray(f)&&Object.keys(f).length===1&&typeof f.input==="string")f=f.input;return{id:r.id,name:s?.name??r.name,input:f}})}}function tu(n,t){return wo(ra(n,t))}function xT(n){let t=[],i=[];for(let r of n.messages){if(r.role==="assistant"){i.push(r),t=i;continue}i=[]}if(t.length===0)return;return tu(n,{text:t.map((r)=>oi(r.content)).join(""),toolCalls:t.flatMap((r)=>r.toolCalls.map((s)=>({id:s.id,name:s.name,input:JSON.stringify(s.input)})))})}function oi(n){return n.filter((t)=>t.type==="text").map((t)=>t.text).join("")}var At=1,zs="application/x-kiro-provider-output+json",Ks="application/x-kiro-provider-output+ndjson",VT="application/x-kiro-provider-output+json; charset=utf-8",jT="application/x-kiro-provider-output+ndjson; charset=utf-8";function Ao(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Yt(n,t){return Object.keys(n).every((i)=>t.has(i))}function yt(n){return typeof n==="string"&&n.length>0}function yo(n){return typeof n==="number"&&Number.isSafeInteger(n)&&n>=0}function qT(n){if(!Ao(n)||!Yt(n,new Set(["inputTokens","outputTokens","totalTokens"]))||!yo(n.inputTokens)||!yo(n.outputTokens)||!yo(n.totalTokens)||n.totalTokens!==n.inputTokens+n.outputTokens)return;return{inputTokens:n.inputTokens,outputTokens:n.outputTokens,totalTokens:n.totalTokens}}function sa(n){if(n===void 0)return;if(!Ao(n)||!Yt(n,new Set(["text","signature","redactedContent","encryptedContent"])))return;for(let t of["text","signature","redactedContent","encryptedContent"])if(n[t]!==void 0&&!yt(n[t]))return;return{...typeof n.text==="string"?{text:n.text}:{},...typeof n.signature==="string"?{signature:n.signature}:{},...typeof n.redactedContent==="string"?{redactedContent:n.redactedContent}:{},...typeof n.encryptedContent==="string"?{encryptedContent:n.encryptedContent}:{}}}function fa(n){if(!Ao(n)||!Yt(n,new Set(["id","name","input"]))||!yt(n.id)||!yt(n.name)||typeof n.input!=="string")return;return{id:n.id,name:n.name,input:n.input}}function xs(n){if(!Ao(n)||!Yt(n,new Set(["canonicalOutputVersion","conversationId","model","createdAt","text","reasoning","toolCalls","finishReason","usage"]))||n.canonicalOutputVersion!==1||!yt(n.conversationId)||!yt(n.model)||!yo(n.createdAt)||typeof n.text!=="string"||!Array.isArray(n.toolCalls)||n.finishReason!=="stop"&&n.finishReason!=="tool_calls")return;let t=sa(n.reasoning);if(n.reasoning!==void 0&&t===void 0)return;let i=[];for(let f of n.toolCalls){let _=fa(f);if(!_)return;i.push(_)}let r=i.length>0?"tool_calls":"stop";if(n.finishReason!==r)return;let s=qT(n.usage);if(!s)return;return{canonicalOutputVersion:1,conversationId:n.conversationId,model:n.model,createdAt:n.createdAt,text:n.text,...t!==void 0?{reasoning:t}:{},toolCalls:i,finishReason:n.finishReason,usage:s}}function oa(n){if(!Ao(n)||n.canonicalOutputVersion!==1||typeof n.type!=="string")return;let t={canonicalOutputVersion:1};switch(n.type){case"started":if(!Yt(n,new Set(["canonicalOutputVersion","type","conversationId","model","createdAt"]))||!yt(n.conversationId)||!yt(n.model)||!yo(n.createdAt))return;return{...t,type:"started",conversationId:n.conversationId,model:n.model,createdAt:n.createdAt};case"reasoning_delta":case"text_delta":if(!Yt(n,new Set(["canonicalOutputVersion","type","text"]))||!yt(n.text))return;return{...t,type:n.type,text:n.text};case"reasoning_signature":if(!Yt(n,new Set(["canonicalOutputVersion","type","signature"]))||!yt(n.signature))return;return{...t,type:"reasoning_signature",signature:n.signature};case"reasoning_redacted":if(!Yt(n,new Set(["canonicalOutputVersion","type","data"]))||!yt(n.data))return;return{...t,type:"reasoning_redacted",data:n.data};case"reasoning_encrypted":if(!Yt(n,new Set(["canonicalOutputVersion","type","encryptedContent"]))||!yt(n.encryptedContent))return;return{...t,type:"reasoning_encrypted",encryptedContent:n.encryptedContent};case"tool_call_delta":{if(!Yt(n,new Set(["canonicalOutputVersion","type","index","id","name","arguments"]))||!Number.isSafeInteger(n.index)||n.index<0||n.id!==void 0&&!yt(n.id)||n.name!==void 0&&!yt(n.name)||typeof n.arguments!=="string")return;return{...t,type:"tool_call_delta",index:n.index,...typeof n.id==="string"?{id:n.id}:{},...typeof n.name==="string"?{name:n.name}:{},arguments:n.arguments}}case"completed":{if(!Yt(n,new Set(["canonicalOutputVersion","type","finishReason","usage"]))||n.finishReason!=="stop"&&n.finishReason!=="tool_calls")return;let i=qT(n.usage);if(!i)return;return{...t,type:"completed",finishReason:n.finishReason,usage:i}}default:return}}function Si(n){try{return oa(JSON.parse(n))}catch(t){if(t instanceof SyntaxError)return;throw t}}var _a=["low","medium","high","xhigh","max"];function ha(n){return typeof n==="string"&&_a.some((t)=>t===n)}var kT=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),ZT=new Set(["claude-opus-5","claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...kT]),ea=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...ZT]);function Br(n){return ea.has(n)}function iu(n){return ZT.has(n)}function vT(n,t){if(kT.has(n))return{reasoning:{effort:t}};return{output_config:{effort:t}}}function ca(n,t){if(!Br(n))return;if(t==="xhigh"&&!iu(n))return"max";return t}function da(n,t){if(!Br(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 pT(n){let t;if(Br(n.model))t={wireId:n.model,effort:void 0};else try{t=yi(n.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!Br(t.wireId))return;let i=[t.effort,n.reasoningEffort,n.configEffort];for(let r of i)if(ha(r))return ca(t.wireId,r);if(!n.think)return;if(n.autoEffortMapping??!0)return da(n.budget,t.wireId);return"medium"}var ng=1024,tg=128000,ua=new Set(["claude-sonnet-5","claude-opus-5"]);function pi(n,t){let i;try{i=yi(n).wireId}catch{return{ok:!1,code:"unsupported_output_token_limit",message:`Output-token limiting is not available for unsupported model ${n}`}}if(!ua.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<ng||t>tg)return{ok:!1,code:"invalid_output_token_limit",message:`Kiro requires output-token limits for ${n} to be an integer from ${ng} through ${tg}`};return{ok:!0,wireModel:i,additionalModelRequestFields:{max_tokens:t}}}class dn extends Error{code;param;name="RequestTransformError";constructor(n,t="invalid_request",i){super(n);this.code=t;this.param=i}}import{randomUUID as ug}from"crypto";var wa=["csv","doc","docx","html","md","pdf","txt","xls","xlsx"],ya=new Set(wa),Aa={"application/pdf":"pdf","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/csv":"csv","text/html":"html","text/markdown":"md","text/plain":"txt"};function Ra(n){return n===" "||n==="-"||n==="_"||n==="("||n===")"||n==="["||n==="]"||/[A-Za-z0-9]/.test(n)}function ig(n,t,i){let r=`.${t}`,s=n.toLowerCase().endsWith(r)?n.slice(0,-r.length):n,f=Array.from(s).length;if(f<1||f>200||s.startsWith(" ")||s.endsWith(" ")||s.includes(" ")||Array.from(s).some((_)=>!Ra(_)))throw new dn(`Inline document ${i} cannot be represented by Kiro's native document name field`,"invalid_file_name",i);return s}function Ma(n){let t=n.split(".").at(-1)?.toLowerCase();return t!==void 0&&ya.has(t)?t:void 0}function Ea(n){if(!n.startsWith("data:"))return{base64:n};let t=n.indexOf(",");if(t<0)throw new dn("Inline document data URL is missing its payload","invalid_file_data");let r=n.slice(5,t).split(";");if(!r.includes("base64"))throw new dn("Inline document data URLs must use base64 encoding","unsupported_file_encoding");return{...r[0]?{mediaType:r[0].toLowerCase()}:{},base64:n.slice(t+1)}}function rg(n,t){if(n.length===0)throw new dn(`Inline document ${t} contains no data`,"invalid_file_data",t);try{let i=atob(n),r=new Uint8Array(i.length);for(let s=0;s<i.length;s+=1)r[s]=i.charCodeAt(s);return r}catch(i){if(!(i instanceof DOMException))throw i;throw new dn(`Inline document ${t} contains invalid base64 data`,"invalid_file_data",t)}}function sg(n,t,i,r=i){let s=Ea(t),f=Ma(n)??(s.mediaType===void 0?void 0:Aa[s.mediaType]);if(f===void 0)throw new dn(`Inline document ${i} has an unsupported file format`,"unsupported_file_format",i);return ig(n,f,r),rg(s.base64,i),{name:n,format:f,data:s.base64,path:i}}function fg(n){return{name:ig(n.name,n.format,n.path),format:n.format,source:{bytes:rg(n.data,n.path)}}}function la(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 og(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:la(r.data)}})),omitted:n.length-t.length}}function Ta(n,t){if(!n.startsWith("data:"))throw new dn(`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 dn(`Image ${t} contains an invalid data URL`,"invalid_image");return{mediaType:i.split(";")[0]?.replace("data:","")||"image/jpeg",data:r}}function ga(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(Ta(i.url,i.path))}return t}function Oa(n){return n.flatMap((t)=>t.type==="document"?[fg({name:t.name,format:t.format,data:t.data,path:t.path})]:[])}function La(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 _g(n,t){let i={content:oi(n.content),modelId:t,origin:On.ORIGIN_AI_EDITOR},r=La(n.content);if(r.length>0)i.userInputMessageContext={toolResults:r};let s=ga(n.content);if(s.length>0){let _=og(s);if(_.omitted>0)throw new dn(`Message ${n.path} exceeds Kiro's limit of 4 images and 3.75 MB of base64 image data`,"too_many_images");i.images=_.images}let f=Oa(n.content);if(f.length>0)i.documents=f;return i}function Ia(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 Sa(n,t){let i=Ia(t),r={content:oi(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 hg(n,t,i=[]){let r=new Map(i.map((f)=>[f.insertBeforeMessage,f])),s=[];for(let[f,_]of n.entries()){if(_.role==="assistant"){s.push({assistantResponseMessage:Sa(_,r.get(f))});continue}if(_.role==="user"||_.role==="tool")s.push({userInputMessage:_g(_,t)})}return s}function eg(n){return n.some((t)=>Boolean(t.assistantResponseMessage?.toolUses)||Boolean(t.userInputMessage?.userInputMessageContext?.toolResults))}function cg(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 dg(n,t){return _g(n,t)}function wg(n,t){return{type:"text",text:n,path:t}}function ba(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 Na(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||t.content.every((s)=>s.type==="text"))continue;let r=i[1];throw new dn(`Message ${t.path} interleaves multiple text content blocks with non-text content, but Kiro exposes only one text field and cannot preserve their ordering`,"unsupported_content_block_projection",r?.path??t.path)}}function Ua(n){let t=n.messages.filter((o)=>o.role==="system"||o.role==="developer");if(t.length>0&&n.projectionMode==="safe")throw new dn("Kiro accepted additionalContext structurally but did not preserve instruction content or priority; safe mode cannot project system/developer/instructions","unsupported_instruction_projection");for(let o of t)if(o.content.some((h)=>h.type!=="text")||o.toolCalls.length>0)throw new dn(`Instruction ${o.path} contains non-text content that legacy projection cannot represent`,"unsupported_instruction_projection");let i=[],r=new Map;for(let[o,h]of n.messages.entries()){if(h.role==="system"||h.role==="developer")continue;r.set(o,i.length),i.push(ba(h))}if(t.length===0)return{messages:i,projectedIndexByOriginal:r};let s=t.flatMap((o)=>o.content.map((h)=>h.type==="text"?h.text:"")).join(`
|
|
355
355
|
|
|
356
|
-
`),f=i.findIndex((
|
|
356
|
+
`),f=i.findIndex((o)=>o.role==="user");if(f<0){i.unshift({role:"user",content:[wg(s,"legacy-user-prefix")],toolCalls:[],path:"legacy-user-prefix"});for(let[o,h]of r)r.set(o,h+1);return{messages:i,projectedIndexByOriginal:r}}let _=i[f];if(!_)return{messages:i,projectedIndexByOriginal:r};return i[f]={..._,content:[wg(`${s}
|
|
357
357
|
|
|
358
|
-
`,"legacy-user-prefix"),...h.content]},{messages:i,projectedIndexByOriginal:r}}function vm(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((o)=>o.type==="tool_use"?[{id:o.id,name:o.name,input:o.input,path:o.path}]:[])];for(let o of _){if(!i.has(o.name))throw new cn(`Tool call ${o.id} references ${o.name} without an exact declaration`,"missing_tool_declaration");if(r.has(o.id))throw new cn(`Duplicate tool call id ${o.id}`,"invalid_tool_history");r.set(o.id,{name:o.name,index:f})}for(let o of h.content){if(o.type!=="tool_result")continue;let w=r.get(o.toolCallId);if(!w||w.index>=f||s.has(o.toolCallId))throw new cn(`Tool result ${o.toolCallId} has no earlier unique matching call`,"invalid_tool_history");s.add(o.toolCallId)}}}function pm(n){return n.map((t)=>({toolSpecification:{name:t.wireName,description:t.description??"",inputSchema:{json:{...t.inputSchema}}}}))}function ve(n,t,i,r=!1,s=20000,f={}){if(!Ue(n))throw new cn("CanonicalRequest is required before Kiro projection","canonical_request_required");let h=n;if(h.model!==t)throw new cn(`CanonicalRequest model ${h.model} does not match pipeline model ${t}`,"canonical_model_mismatch");if(h.messages.length===0)throw new cn("No messages","empty_input");am(h.messages);let _,o;try{let L=ci(t);_=L.wireId,o=L.effort}catch(L){if(L instanceof Error&&L.message.startsWith("Unsupported model:"))throw new cn(L.message,"unsupported_model","model");throw L}let w=Zm(h);if(w.messages.length===0)throw new cn("No executable messages","empty_input");vm(w.messages,h.tools);let c=(f.resolvedReasoningReplays??[]).map((L)=>{let N=w.projectedIndexByOriginal.get(L.insertBeforeMessage);if(N===void 0)throw new cn("Reasoning replay does not reference an assistant output message","invalid_reasoning_replay");return{...L,insertBeforeMessage:N}}),d=w.messages.at(-1);if(!d)throw new cn("No executable messages","empty_input");let u=d.role==="assistant",y=u?w.messages:w.messages.slice(0,-1),R=c.filter((L)=>L.insertBeforeMessage<y.length),M=xe(y,_,R),E=u?{content:"",modelId:_,origin:In.ORIGIN_AI_EDITOR}:ke(d,_),T=h.toolChoice==="auto"?pm(h.tools):[];if(T.length>0)E.userInputMessageContext??={},E.userInputMessageContext.tools=T;if(je(M)&&h.toolChoice==="auto"){let L=new Set(T.map((l)=>l.toolSpecification.name)),N=[...qe(M)].filter((l)=>!L.has(l));if(N.length>0)throw new cn(`Tool history is missing exact declarations for: ${N.join(", ")}`,"missing_tool_declaration")}let O=f.conversationId??ae(),e={conversationState:{chatTriggerType:In.CHAT_TRIGGER_TYPE_MANUAL,conversationId:O,agentContinuationId:ae(),agentTaskType:"vibe",currentMessage:{userInputMessage:E},...M.length>0?{history:M}:{}},...i.profileArn?{profileArn:i.profileArn}:{}};return o===void 0?{request:e,resolved:_,convId:O}:{request:e,resolved:_,convId:O,variantEffort:o}}function pe(n,t,i,r=!1,s=20000,f){let{request:h,resolved:_,convId:o}=ve(n,t,i,r,s,{conversationId:f?.conversationId,resolvedReasoningReplays:f?.resolvedReasoningReplays}),w=Pe({model:t,think:r,budget:s,reasoningEffort:n.reasoningEffort,configEffort:f?.effort,autoEffortMapping:f?.autoEffortMapping}),c=n.outputTokenLimit,d=c===void 0?void 0:qi(t,c);if(d?.ok===!1)throw new cn(d.message,d.code);return{conversationState:h.conversationState,...h.profileArn?{profileArn:h.profileArn}:{},...d?.ok===!0?{additionalModelRequestFields:d.additionalModelRequestFields}:{},streaming:!0,effectiveModel:_,conversationId:o,region:$y(i.profileArn)??i.region,...w?{effort:w}:{}}}function L0(n){return Math.ceil(n.length/4)}var nz=new Set(["assistantResponseEvent","contextUsageEvent","messageMetadataEvent","metadataEvent","meteringEvent","reasoningContentEvent","toolUseEvent"]);class $r extends Error{name="SemanticStreamTruncationError";code="upstream_stream_incomplete";constructor(){super("Kiro event stream ended before an authoritative completion witness")}}class Ot extends Error{code;name="SdkStreamProtocolError";constructor(n,t){super(n);this.code=t}}function Kd(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 I0(n){let t=n.metadataEvent?.tokenUsage;return typeof t==="object"&&t!==null}function g0(n){let t=n.meteringEvent;return typeof t?.usage==="number"&&Number.isFinite(t.usage)&&t.usage>=0&&typeof t.unit==="string"&&t.unit.length>0}function N0(n){let t=Kd(n);if(n.error!==void 0)throw new Ot("Kiro returned an embedded stream error","upstream_stream_error");if(n.invalidStateEvent!==void 0)throw new Ot("Kiro returned an invalid stream state","upstream_invalid_state");if(n.$unknown!==void 0||t.includes("unknown"))throw new Ot("Kiro returned an unknown stream event","unsupported_upstream_event");let i=t.find((r)=>!nz.has(r));if(i!==void 0)throw new Ot(`Kiro returned unsupported stream event type ${i}`,"unsupported_upstream_event")}function b0(){return{text:"",signature:"",signatureConflict:!1,redactedChunks:[]}}function S0(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 f_(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 l0(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 $0(n,t){if(!t)return;if(!t.name||!t.toolUseId)throw new Ot("Kiro emitted a tool call without both name and toolUseId","invalid_upstream_tool_call");let i=n.get(t.toolUseId);if(i){if(i.name!==t.name)throw new Ot("Kiro changed a tool name while streaming one tool call","invalid_upstream_tool_call");if(i.stopped&&(t.input??"").length>0)throw new Ot("Kiro emitted tool arguments after the tool call stopped","invalid_upstream_tool_call");i.input+=t.input??"",i.stopped||=t.stop===!0;return}n.set(t.toolUseId,{toolUseId:t.toolUseId,name:t.name,input:t.input??"",stopped:t.stop===!0})}function U0(n){for(let t of n.values()){if(!t.stopped)throw new Ot(`Kiro ended before tool call ${t.toolUseId} emitted its stop marker`,"incomplete_upstream_tool_call");try{JSON.parse(t.input)}catch{throw new Ot(`Kiro returned invalid JSON arguments for tool call ${t.toolUseId}`,"invalid_upstream_tool_call")}}}function D0(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 B0(n,t,i){let r=n.outputTokens??L0(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(ay(i)*n.contextUsagePercentage/100);s=Math.max(0,f-r)}return{inputTokens:s??0,outputTokens:r}}class n4 extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function t4(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new n4;let h=f[Symbol.asyncIterator](),_=new Map,o={},w="",c=b0(),d=!1,u=!1,y=!1;try{while(!0){let L=await l0(h,r);if(L.kind==="aborted"){if(h.return)await h.return();u=!0;break}if(L.result.done){d=!0;break}let N=L.result.value;if(N0(N),D0(o,N),S0(c,N.reasoningContentEvent),I0(N)){y=!0,u=!0;try{let l=h.return?.();if(l)Promise.resolve(l).catch(()=>{return})}catch{}break}if(g0(N))y=!0;w+=N.assistantResponseEvent?.content??"",$0(_,N.toolUseEvent)}}finally{if(!d&&!u&&h.return)await h.return()}if(r?.aborted)throw r.reason;if(!y)throw new $r;U0(_);let R=B0(o,w,t),M=f_(c),E={text:w,toolCalls:Array.from(_.values(),(L)=>({id:L.toolUseId,name:L.name,input:L.input}))},T=(s.fingerprintOutput??et)(E),O=s.captureReasoning?.(M,T);s.captureOutput?.(E,T);let e={...M.text?{text:M.text}:{},...s.emitAnthropicReasoningMetadata&&M.signature!==void 0?{signature:M.signature}:{},...s.emitAnthropicReasoningMetadata&&M.redactedContent!==void 0?{redactedContent:Buffer.from(M.redactedContent).toString("base64")}:{},...s.emitEncryptedReasoning&&O!==void 0?{encryptedContent:O}:{}};return{canonicalOutputVersion:ut,conversationId:i,model:t,createdAt:Math.floor(Date.now()/1000),text:w,...Object.keys(e).length>0?{reasoning:e}:{},toolCalls:E.toolCalls,finishReason:_.size>0?"tool_calls":"stop",usage:{inputTokens:R.inputTokens,outputTokens:R.outputTokens,totalTokens:R.inputTokens+R.outputTokens}}}var tz=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],iz=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function H0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function G0(n,t){let i=n[t];return typeof i==="string"?i:void 0}function rz(n){let t=n.$metadata;if(!H0(t))return;let i=t.httpStatusCode;return typeof i==="number"?i:void 0}function sz(n){let t=n.$response;if(!H0(t))return;let i=t.headers;if(!H0(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 Vd(n){if(!H0(n))return{message:n instanceof Error?n.message:String(n)};let t=rz(n),i=G0(n,"message")??String(n),r=G0(n,"code")??G0(n,"name"),s=G0(n,"reason"),f=sz(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 fz(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 _z(n){return tz.some((t)=>t.test(n))}function i4(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:_z(n.message)?413:400};case 401:if(!t.forcedRefreshAccountIds.has(t.accountId))return t.forcedRefreshAccountIds.add(t.accountId),{action:"refresh-then-retry",status:401};return t.accountCount>1?{action:"switch",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return t.accountCount>1?{action:"switch",status:402}:{action:"fail",status:402,terminalStatus:402};case 403:if(Ct(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=fz(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(iz.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}}}class r4 extends Error{name="MissingSdkOutputStreamError";constructor(){super("SDK response has no event stream")}}function hz(n){try{let t=n.return?.();if(t)Promise.resolve(t).catch(()=>{return})}catch{}}async function*s4(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new r4;let h=new Map,_={},o=b0(),w=f[Symbol.asyncIterator](),c="",d=!1,u=!1,y=!1,R=!1,M=!1,E=!1,T;try{yield{canonicalOutputVersion:ut,type:"started",conversationId:i,model:t,createdAt:Math.floor(Date.now()/1000)};while(!0){let V=await l0(w,r);if(V.kind==="aborted"){if(w.return)await w.return();E=!0;return}if(V.result.done){M=!0;break}let b=V.result.value;if(s.onRawEvent?.(Kd(b)),N0(b),D0(_,b),S0(o,b.reasoningContentEvent),I0(b)){T="token-usage-metadata",s.onCompletionWitness?.(T),E=!0,hz(w);break}if(g0(b))T="metering-clean-eof";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(u&&d&&b.reasoningContentEvent?.signature!==void 0&&b.reasoningContentEvent.signature.length>0)throw TypeError("Kiro emitted a reasoning signature after assistant output began")}let H=b.reasoningContentEvent?.text;if(H)d=!0,yield{canonicalOutputVersion:ut,type:"reasoning_delta",text:H};let g=b.assistantResponseEvent?.content;if(g){if(s.emitAnthropicReasoningMetadata){let I=f_(o);if(d&&!y&&I.signature!==void 0)y=!0,yield{canonicalOutputVersion:ut,type:"reasoning_signature",signature:I.signature};if(!d&&!R&&I.redactedContent!==void 0)R=!0,yield{canonicalOutputVersion:ut,type:"reasoning_redacted",data:Buffer.from(I.redactedContent).toString("base64")}}u=!0,c+=g,yield{canonicalOutputVersion:ut,type:"text_delta",text:g}}if(b.toolUseEvent)$0(h,b.toolUseEvent)}}finally{if(!M&&!E&&w.return)await w.return()}if(T===void 0)throw new $r;if(T==="metering-clean-eof")s.onCompletionWitness?.(T);U0(h);let O=f_(o);if(s.emitAnthropicReasoningMetadata){if(d&&!y&&O.signature!==void 0)yield{canonicalOutputVersion:ut,type:"reasoning_signature",signature:O.signature};if(!R&&O.redactedContent!==void 0)yield{canonicalOutputVersion:ut,type:"reasoning_redacted",data:Buffer.from(O.redactedContent).toString("base64")}}let e=0;for(let V of h.values())yield{canonicalOutputVersion:ut,type:"tool_call_delta",index:e,id:V.toolUseId,name:V.name,arguments:V.input},e+=1;let L={text:c,toolCalls:[...h.values()].map((V)=>({id:V.toolUseId,name:V.name,input:V.input}))},N=(s.fingerprintOutput??et)(L),l=s.captureReasoning?.(O,N);if(s.captureOutput?.(L,N),s.emitEncryptedReasoning&&l!==void 0)yield{canonicalOutputVersion:ut,type:"reasoning_encrypted",encryptedContent:l};let Y=B0(_,c,t);yield{canonicalOutputVersion:ut,type:"completed",finishReason:h.size>0?"tool_calls":"stop",usage:{inputTokens:Y.inputTokens,outputTokens:Y.outputTokens,totalTokens:Y.inputTokens+Y.outputTokens}}}class f4 extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(n){super(`SDK stream idle timeout after ${n}ms`);this.timeoutMs=n}}function _4(n,t,i,r){let s=new Map,f=0,h,_=()=>JSON.stringify(Object.fromEntries([...s.entries()].sort())),o=()=>({model:n.model,conversation_hash:Rn(n.conversationId),raw_event_count:f,last_event_type:h,event_type_counts:_()}),w=new AbortController,c=AbortSignal.any([t,w.signal]),d=s4(n.sdkResponse,n.model,n.conversationId,c,{...n.captureReasoning?{captureReasoning:n.captureReasoning}:{},emitEncryptedReasoning:n.emitEncryptedReasoning,emitAnthropicReasoningMetadata:n.emitAnthropicReasoningMetadata,...n.fingerprintOutput?{fingerprintOutput:n.fingerprintOutput}:{},...n.captureOutput?{captureOutput:n.captureOutput}:{},onCompletionWitness:(l)=>{k("info","sdk_stream_completion_witness",{model:n.model,conversation_hash:Rn(n.conversationId),witness_kind:l})},onRawEvent:(l)=>{f+=1,h=l.join("+");for(let Y of l)s.set(Y,(s.get(Y)??0)+1)}})[Symbol.asyncIterator](),u=d.next(),y=new TextEncoder,R,M,E,T=()=>{if(M===void 0)return;clearTimeout(M),M=void 0},O=(l)=>{if(R!==void 0)return!1;return R=l,!0},e=()=>{c.removeEventListener("abort",N)},L=(l,Y)=>{if(!O(l))return;if(Vn(e,T,()=>{if(l==="normal-complete")E?.close();else if(l!=="consumer-cancel")E?.error(Y)},r),l!=="normal-complete"&&l!=="consumer-cancel")Vn(()=>{if(!w.signal.aborted)w.abort(Y)});Mn(()=>d.return?.(void 0))},N=()=>{L("external-abort",$t(c))};return new Response(new ReadableStream({start(l){if(E=l,c.addEventListener("abort",N,{once:!0}),c.aborted)N()},async pull(l){if(R!==void 0)return;M=setTimeout(()=>{M=void 0;let Y=new f4(i);k("warn","sdk_stream_idle_timeout",{...o(),idle_timeout_ms:i}),L("idle-timeout",Y)},i);try{let Y=u??d.next();u=void 0;let V=await Y;if(R!==void 0)return;if(T(),V.done){k("info","sdk_stream_completed",o()),L("normal-complete");return}l.enqueue(y.encode(`${JSON.stringify(V.value)}
|
|
359
|
-
`))}catch(Y){if(R!==void 0)return;let V=Y instanceof Error?Y:TypeError("SDK stream failed with a non-Error reason",{cause:Y});k("warn","sdk_stream_upstream_error",{...o(),error_type:V.name}),L("upstream-error",V)}},cancel(l){L("consumer-cancel",l)}}),{headers:{"Content-Type":Ge}})}import{createHash as o4}from"crypto";import{Agent as oz}from"http";import{Agent as wz}from"https";var qd=Z(Ch(),1);var xd=new Map,h4=new Map,cz=3,jd=50;function Ur(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function dz(n){let t=n.conversationState;if(!Ur(t))return;let i=t.currentMessage;if(!Ur(i))return;let r=i.userInputMessage;if(!Ur(r))return;let s=r.modelId;return typeof s==="string"?s:void 0}function w4(n,t){let i=Ur(n)?{...n}:{};for(let[r,s]of Object.entries(t)){let f=i[r];i[r]=Ur(f)&&Ur(s)?w4(f,s):s}return i}function uz(n,t,i,r,s=c4(r,!1)){return{region:t,endpoint:i,token:()=>Promise.resolve({token:n.access}),maxAttempts:cz,retryMode:"standard",customUserAgent:[[In.USER_AGENT]],requestHandler:s}}function c4(n,t){if(n){let i=new df(n,{keepAlive:t,maxSockets:jd});return new qd.NodeHttpHandler({httpAgent:i,httpsAgent:i})}return new qd.NodeHttpHandler({httpAgent:new oz({keepAlive:t,maxSockets:jd}),httpsAgent:new wz({keepAlive:t,maxSockets:jd})})}function yz(n){return o4("sha256").update("kiro-provider-sdk-account-v1\x00").update(n.email??n.refresh).digest("hex")}function Az(n){return o4("sha256").update("kiro-provider-sdk-access-token-v1\x00").update(n).digest("hex")}function d4(n,t,i,r,s,f,h=!1){let _=r??`https://q.${t}.amazonaws.com`,o=JSON.stringify([f??yz(n),t,_,s??null,h]),w=h4.get(o),c=w!==void 0;if(!w)w={handler:c4(s,h)},h4.set(o,w);let d=JSON.stringify([o,i??null]),u=xd.get(d),y=Az(n.access),R=u!==void 0&&u.accessTokenHash!==y;if(R)xd.delete(d);let M=R?void 0:u;if(f!==void 0)k("info","sdk_connection_pool_selected",{account_hash:Rn(f),region:t,effort:i??null,http_keep_alive:h,transport_pool_hit:c,sdk_client_pool_hit:M!==void 0,sdk_client_rebuilt_for_token_change:R});if(M)return M.client;let E=new Cd(uz(n,t,_,s,w.handler));if(E.middlewareStack.add((T)=>async(O)=>{if(O.request instanceof ft.HttpRequest)O.request.headers["x-amzn-kiro-agent-mode"]="vibe";return T(O)},{step:"build",name:"addKiroHeaders"}),i)E.middlewareStack.add((T)=>async(O)=>{if(O.request instanceof ft.HttpRequest&&typeof O.request.body==="string")try{let e=JSON.parse(O.request.body);if(Ur(e)){let L=dz(e);if(L)e.additionalModelRequestFields=w4(e.additionalModelRequestFields,Ye(L,i)),O.request.body=JSON.stringify(e)}}catch(e){if(!(e instanceof SyntaxError))throw e}return T(O)},{step:"build",name:"addEffortConfig",priority:"high"});return xd.set(d,{client:E,accessTokenHash:y}),E}function F0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Rz(n){if(!F0(n))return!1;let t=n.conversationState;return F0(t)&&typeof t.conversationId==="string"&&F0(t.currentMessage)&&typeof t.chatTriggerType==="string"}function Mz(n,t){return{think:t.endsWith("-thinking")||n.thinking?.enabled===!0,budget:n.thinking?.budgetTokens??20000}}function Dr(n,t,i){return nn(n,t,"upstream_error",i)}function u4(n,t){let i=Date.now()+n.config.quota_recheck_interval_ms;if(n.accountManager.markQuotaExhausted)n.accountManager.markQuotaExhausted(t,i);else n.accountManager.markRateLimited(t,i);k("warn","quota_exhausted_account_persisted",{account_hash:Rn(t.id),recheck_after:i})}function Ez(n){let t=n.modelCapabilities?.isKnownModel(n.model)??!1;return{kind:"response",response:nn(t?503:400,t?`Model ${n.model} is not available to any currently usable Kiro account`:`Model ${n.model} is not supported by Kiro`,t?"service_unavailable":"invalid_request_error",t?"model_unavailable_for_accounts":"unsupported_model","model")}}function Tz(n,t){if(n.config.test_upstream_endpoint)return n.config.test_upstream_endpoint;return n.config.runtime_endpoint_mode==="kiro-runtime"?In.RUNTIME_ENDPOINT.replace("{{region}}",t):void 0}function y4(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(F0(h)&&Object.keys(h).length===1&&typeof h.input==="string")f=h.input}catch{}return{...r,name:s.name,input:f}})})}function W0(){return{kind:"response",response:nn(503,"The account bound to signed reasoning replay is currently unavailable","service_unavailable","reasoning_replay_account_unavailable")}}function ez(n,t){if(n.body.reasoningReplays.length===0)return{replays:[]};if(!n.tenantId)throw new ln("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 ln("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 ln("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}:{}},o=f.lookup.kind==="responses-token"?h.resolveResponses(f.lookup.encryptedContent,_,f.insertBeforeMessage):h.resolveChat(f.lookup.reasoningText,_,f.insertBeforeMessage);if(i!==void 0&&i!==o.accountId||r!==void 0&&r!==o.conversationId)throw new ln("Reasoning replay items resolve to different accounts or conversations","reasoning_replay_context_mismatch");i=o.accountId,r=o.conversationId,s.push(o.replay)}return{...i!==void 0?{accountId:i}:{},...r!==void 0?{conversationId:r}:{},replays:s}}function Oz(n,t,i){let r=n.body,s=r.includeEncryptedReasoning===!0,f=r.protocol==="anthropic-messages",h=n.lineage&&n.affinityStore?(_)=>{if(_.text.length===0&&_.toolCalls.length===0)return;let o=md(r,_),w=n.lineage?.outputKeyHash(o);if(w===void 0)return;n.affinityStore?.recordOutputLineage(w,t,i,Date.now(),n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),k("info","output_lineage_recorded",{protocol:r.protocol,lineage_source:n.lineage?.source,lineage_hash:Rn(w),account_hash:Rn(t),conversation_hash:Rn(i)})}:void 0;if(!n.reasoningReplayStore||!n.tenantId)return{emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,...r?{fingerprintOutput:y4(r)}:{},...h?{captureOutput:h}:{}};return{captureReasoning:(_,o)=>n.reasoningReplayStore?.store(_,{tenantId:n.tenantId,model:r.model,accountId:t,conversationId:i,outputFingerprint:o}),emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,fingerprintOutput:y4(r),...h?{captureOutput:h}:{}}}async function Lz(n,t){let{think:i,budget:r}=Mz(n.body,n.model),s=new Set,f=new Map,h=new Set,_=new Set,o,w,c=0,d=0,u=n.affinity&&n.affinityStore?n.affinityStore.getSessionAffinity(n.affinity.keyHash):void 0,y=u===void 0&&n.lineage?.lookupKeyHash!==void 0&&n.affinityStore?n.affinityStore.resolveOutputLineage(n.lineage.lookupKeyHash):void 0,R=u??y,M=ez(n,R),E=M.accountId!==void 0,T=M.accountId??R?.accountId,O=M.accountId??R?.accountId,e=M.conversationId??R?.conversationId,L=new Set;if(n.quotaRechecker)await n.quotaRechecker.recheckDueAccounts(n.accountManager.reconcileFromDb(),t,M.accountId??R?.accountId);while(!0){if(t.aborted)throw $t(t);if(d+=1,d>n.config.max_request_iterations){if(o)return{kind:"response",response:Dr(o.status??403,o.message,o.code??"upstream_authentication_failed")};if(w)return{kind:"response",response:Dr(402,w.message,w.code??"quota_exhausted")};return{kind:"response",response:nn(500,`Exceeded max iterations (${n.config.max_request_iterations})`,"request_error","max_request_iterations")}}let l=n.accountManager.reconcileFromDb().filter((U)=>!L.has(U.id)&&!h.has(U.id)),Y=l.filter(en),V=Y.filter((U)=>!_.has(U.id));for(let U of V)_.add(U.id);if(V.length>0)k("info","quota_exhausted_accounts_excluded",{account_count:V.length});let b=l.filter((U)=>!en(U)).map((U)=>U.id),H=n.modelCapabilities?.eligibleAccountIds(n.model,b),g=new Set([...H??b].filter((U)=>!L.has(U))),I=n.accountManager.selectHealthyAccount(T,g);if(!I||M.accountId!==void 0&&I.id!==M.accountId){if(E)return W0();if(b.length===0&&o)return{kind:"response",response:Dr(o.status??403,o.message,o.code??"upstream_authentication_failed")};if(b.length===0&&(Y.length>0||w))return{kind:"response",response:Dr(402,w?.message??"All eligible Kiro accounts have exhausted their quota",w?.code??"quota_exhausted")};if(L.size>0||H!==void 0&&g.size===0)return Ez(n);return{kind:"response",response:nn(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")}}let P=Date.now();if(n.affinity&&n.affinityStore)if(!u){let U=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,I.id,e??kd(),P,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries);if(u=U,T=U.accountId,e=U.conversationId,E&&(U.accountId!==M.accountId||U.conversationId!==M.conversationId))throw new ln("Session affinity conflicts with signed reasoning replay","reasoning_replay_context_mismatch");if(U.accountId!==I.id)continue}else if(u.accountId===I.id)u=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,I.id,u.conversationId,P,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),e=u.conversationId;else u=n.affinityStore.rebindSessionAffinity(n.affinity.keyHash,I.id,kd(),P,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),e=u.conversationId;else if(!E&&O!==I.id)O=I.id,e=kd();T=I.id,k("info","upstream_affinity_selected",{projection_mode:n.config.protocol_projection_mode,session_affinity_mode:n.config.session_affinity_mode,affinity_source:n.affinity?.source??n.lineage?.source,affinity_bound:u!==void 0||y!==void 0,affinity_kind:u!==void 0?"explicit":y!==void 0?"history-lineage":void 0,account_hash:Rn(I.id),conversation_hash:e===void 0?void 0:Rn(e),reasoning_replay_locked:E});let m=await Yy(I.id,t),a=!0,j=I,G=!1;try{let U=n.accountManager.toAuthDetails(I);j=await wi(n.tokenRefresher.refreshIfNeeded(I,U,t),t);let F=n.accountManager.toAuthDetails(j);if(n.modelCapabilities){let J=await wi(n.modelCapabilities.ensureAccountModel(j,F,n.model,t),t);if(!J.supported){if(k("warn","account_model_unavailable",{account_hash:Rn(j.id),model_hash:Rn(n.model),capability_source:J.source}),E)return W0();L.add(j.id),T=void 0,O=void 0,e=void 0;continue}}let gn=y_.safeParse(n.config.effort),yn=pe(n.body,n.model,F,i,r,{autoEffortMapping:n.config.auto_effort_mapping,conversationId:e,resolvedReasoningReplays:M.replays,...gn.success?{effort:gn.data}:{}}),Xt=(n.makeClient??d4)(F,yn.region,yn.effort,Tz(n,yn.region),hs(n.config),j.id,n.config.sdk_http_keep_alive),ai={conversationState:yn.conversationState,...yn.profileArn?{profileArn:yn.profileArn}:{},...yn.additionalModelRequestFields?{additionalModelRequestFields:yn.additionalModelRequestFields}:{}};if(!Rz(ai))throw TypeError("Transformed request is not a valid SDK command input");let z0=new Jd(ai);G=!0;let Vs=await wi(Xt.send(z0,{abortSignal:t}),t),xs=Oz(n,j.id,yn.conversationId);if(n.stream)return a=!1,{kind:"stream",sdkResponse:Vs,model:n.model,conversationId:yn.conversationId,...xs,releaseAccount:m};let B=await t4(Vs,n.model,yn.conversationId,t,xs);if(t.aborted)throw $t(t);return{kind:"response",response:Response.json(B,{headers:{"Content-Type":Be}})}}catch(U){if(t.aborted)throw $t(t);if(!G){if(U instanceof cn||U instanceof ln)throw U;if(E)return W0();throw U}if(U instanceof $r){if(c<n.config.rate_limit_max_retries){c+=1,await Bo(n.config.rate_limit_retry_delay_ms*2**(c-1),t);continue}return{kind:"response",response:Dr(502,U.message,U.code)}}if(U instanceof Ot)return{kind:"response",response:Dr(502,U.message,U.code)};let F=Vd(U),gn=F.status===500?(f.get(j.id)??0)+1:0;if(F.status===500)f.set(j.id,gn);let yn=i4(F,{accountId:j.id,accountCount:Math.max(1,g.size),retryCount:c,maxRetries:n.config.rate_limit_max_retries,serverErrorCount:gn,retryDelayMs:n.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:s});switch(yn.action){case"refresh-then-retry":await wi(n.tokenRefresher.forceRefresh(j,t),t);continue;case"retry":c+=1,await Bo(yn.retryAfterMs??0,t);continue;case"switch":if(E)return W0();if(h.add(j.id),F.status===401||F.status===403&&Ct(F.message))o=F;if(F.status===402)w=F;if(F.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(j,`InvalidTokenException: Account Suspended: ${F.message}`);else if(F.status===402)u4(n,j);else n.accountManager.markRateLimited(j,Date.now()+(yn.retryAfterMs??n.config.rate_limit_retry_delay_ms));if(T=void 0,O=void 0,!n.affinityStore)e=void 0;continue;case"fail":if(F.status===402)u4(n,j);if(F.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(j,`InvalidTokenException: Account Suspended: ${F.message}`);return{kind:"response",response:Dr(yn.terminalStatus??yn.status??500,F.message,F.code)}}}finally{if(a)m()}}}async function Xs(n){let t=Py(n.deadlineSignal,n.config.request_timeout_ms),i,r,s=!1;try{if(n.affinity)i=await Go(n.affinity.keyHash,t.signal);else if(n.lineage?.lookupKeyHash!==void 0)i=await Go(n.lineage.lookupKeyHash,t.signal);let f=await Lz(n,t.signal);if(f.kind==="response")return f.response;r=f.releaseAccount;let h=r,_=i,o=(n.createStreamResponse??_4)(f,t.signal,n.config.stream_idle_timeout_ms,()=>{h(),_?.(),t.dispose()});return r=void 0,i=void 0,s=!0,o}catch(f){if(f instanceof cn)return nn(400,f.message,"invalid_request_error",f.code,f.param);if(f instanceof ln)return nn(f.retryable?503:400,f.message,f.retryable?"service_unavailable":"invalid_request_error",f.code);if(t.signal.aborted)return nn(504,"Request deadline exceeded","timeout_error","request_timeout");let h=Vd(f);return nn(500,h.message,"internal_error",h.code)}finally{if(!s)r?.(),i?.(),t.dispose()}}function Br(n,t,i){return{id:n.id,object:"chat.completion.chunk",created:n.created,model:n.model,choices:[{index:0,delta:t,finish_reason:i}]}}function Iz(n,t,i){switch(n.type){case"text_delta":return[JSON.stringify(Br(t,{content:n.text},null))];case"reasoning_delta":return[JSON.stringify(Br(t,{reasoning_content:n.text},null))];case"reasoning_signature":return[JSON.stringify(Br(t,{reasoning_signature:n.signature},null))];case"reasoning_redacted":return[JSON.stringify(Br(t,{reasoning_redacted_content:n.data},null))];case"reasoning_encrypted":return[JSON.stringify(Br(t,{reasoning_encrypted_content:n.encryptedContent},null))];case"tool_call_delta":return[JSON.stringify(Br(t,{tool_calls:[{index:n.index,...n.id!==void 0?{id:n.id,type:"function"}:{},function:{...n.name!==void 0?{name:n.name}:{},arguments:n.arguments}}]},null))];case"completed":{let r=JSON.stringify(Br(t,{},n.finishReason));if(!i)return[r];let s={id:t.id,object:"chat.completion.chunk",created:t.created,model:t.model,choices:[],usage:{prompt_tokens:n.usage.inputTokens,completion_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens}};return[r,JSON.stringify(s)]}}}function A4(n){let t=n.reasoning;return Response.json({id:n.conversationId,object:"chat.completion",created:n.createdAt,model:n.model,choices:[{index:0,message:{role:"assistant",content:n.text,...t?.text?{reasoning_content:t.text}:{},...t?.signature?{reasoning_signature:t.signature}:{},...t?.redactedContent?{reasoning_redacted_content:t.redactedContent}:{},...t?.encryptedContent?{reasoning_encrypted_content:t.encryptedContent}:{},...n.toolCalls.length>0?{tool_calls:n.toolCalls.map((i)=>({id:i.id,type:"function",function:{name:i.name,arguments:i.input}}))}:{}},finish_reason:n.finishReason}],usage:{prompt_tokens:n.usage.inputTokens,completion_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens}})}function R4(n,t,i,r){let s=r.includeUsage===!0,h=(n.body??new ReadableStream({start:(g)=>g.close()})).getReader(),_=new TextDecoder,o=new TextEncoder,w=[],c=new Map,d="",u,y=!1,R,M,E=!1,T=(g)=>{w.push(o.encode(`data: ${g}
|
|
358
|
+
`,"legacy-user-prefix"),..._.content]},{messages:i,projectedIndexByOriginal:r}}function $a(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,_]of n.entries()){let o=[..._.toolCalls,..._.content.flatMap((h)=>h.type==="tool_use"?[{id:h.id,name:h.name,input:h.input,path:h.path}]:[])];for(let h of o){if(!i.has(h.name))throw new dn(`Tool call ${h.id} references ${h.name} without an exact declaration`,"missing_tool_declaration");if(r.has(h.id))throw new dn(`Duplicate tool call id ${h.id}`,"invalid_tool_history");r.set(h.id,{name:h.name,index:f})}for(let h of _.content){if(h.type!=="tool_result")continue;let e=r.get(h.toolCallId);if(!e||e.index>=f||s.has(h.toolCallId))throw new dn(`Tool result ${h.toolCallId} has no earlier unique matching call`,"invalid_tool_history");s.add(h.toolCallId)}}}function Da(n){return n.map((t)=>({toolSpecification:{name:t.wireName,description:t.description??"",inputSchema:{json:{...t.inputSchema}}}}))}function yg(n,t,i,r=!1,s=20000,f={}){if(!KT(n))throw new dn("CanonicalRequest is required before Kiro projection","canonical_request_required");let _=n;if(_.model!==t)throw new dn(`CanonicalRequest model ${_.model} does not match pipeline model ${t}`,"canonical_model_mismatch");if(_.messages.length===0)throw new dn("No messages","empty_input");Na(_.messages);let o,h;try{let g=yi(t);o=g.wireId,h=g.effort}catch(g){if(g instanceof Error&&g.message.startsWith("Unsupported model:"))throw new dn(g.message,"unsupported_model","model");throw g}let e=Ua(_);if(e.messages.length===0)throw new dn("No executable messages","empty_input");$a(e.messages,_.tools);let c=(f.resolvedReasoningReplays??[]).map((g)=>{let O=e.projectedIndexByOriginal.get(g.insertBeforeMessage);if(O===void 0)throw new dn("Reasoning replay does not reference an assistant output message","invalid_reasoning_replay");return{...g,insertBeforeMessage:O}}),d=e.messages.at(-1);if(!d)throw new dn("No executable messages","empty_input");let u=d.role==="assistant",w=u?e.messages:e.messages.slice(0,-1),A=c.filter((g)=>g.insertBeforeMessage<w.length),R=hg(w,o,A),M=u?{content:"",modelId:o,origin:On.ORIGIN_AI_EDITOR}:dg(d,o),E=_.toolChoice==="auto"?Da(_.tools):[];if(E.length>0)M.userInputMessageContext??={},M.userInputMessageContext.tools=E;if(eg(R)&&_.toolChoice==="auto"){let g=new Set(E.map((N)=>N.toolSpecification.name)),O=[...cg(R)].filter((N)=>!g.has(N));if(O.length>0)throw new dn(`Tool history is missing exact declarations for: ${O.join(", ")}`,"missing_tool_declaration")}let T=f.conversationId??ug(),l={conversationState:{chatTriggerType:On.CHAT_TRIGGER_TYPE_MANUAL,conversationId:T,agentContinuationId:ug(),agentTaskType:"vibe",currentMessage:{userInputMessage:M},...R.length>0?{history:R}:{}},...i.profileArn?{profileArn:i.profileArn}:{}};return h===void 0?{request:l,resolved:o,convId:T}:{request:l,resolved:o,convId:T,variantEffort:h}}function Ag(n,t,i,r=!1,s=20000,f){let{request:_,resolved:o,convId:h}=yg(n,t,i,r,s,{conversationId:f?.conversationId,resolvedReasoningReplays:f?.resolvedReasoningReplays}),e=pT({model:t,think:r,budget:s,reasoningEffort:n.reasoningEffort,configEffort:f?.effort,autoEffortMapping:f?.autoEffortMapping}),c=n.outputTokenLimit,d=c===void 0?void 0:pi(t,c);if(d?.ok===!1)throw new dn(d.message,d.code);return{conversationState:_.conversationState,..._.profileArn?{profileArn:_.profileArn}:{},...d?.ok===!0?{additionalModelRequestFields:d.additionalModelRequestFields}:{},streaming:!0,effectiveModel:o,conversationId:h,region:Kw(i.profileArn)??i.region,...e?{effort:e}:{}}}function Hh(n){return Math.ceil(n.length/4)}var Ba=new Set(["assistantResponseEvent","contextUsageEvent","messageMetadataEvent","metadataEvent","meteringEvent","reasoningContentEvent","toolUseEvent"]);class Gr extends Error{name="SemanticStreamTruncationError";code="upstream_stream_incomplete";constructor(){super("Kiro event stream ended before an authoritative completion witness")}}class jn extends Error{code;name="SdkStreamProtocolError";constructor(n,t){super(n);this.code=t}}function ru(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 Wh(n){let t=n.metadataEvent?.tokenUsage;return typeof t==="object"&&t!==null}function Fh(n){let t=n.meteringEvent;return typeof t?.usage==="number"&&Number.isFinite(t.usage)&&t.usage>=0&&typeof t.unit==="string"&&t.unit.length>0}function Ch(n){let t=ru(n);if(n.error!==void 0)throw new jn("Kiro returned an embedded stream error","upstream_stream_error");if(n.invalidStateEvent!==void 0)throw new jn("Kiro returned an invalid stream state","upstream_invalid_state");if(n.$unknown!==void 0||t.includes("unknown"))throw new jn("Kiro returned an unknown stream event","unsupported_upstream_event");let i=t.find((r)=>!Ba.has(r));if(i!==void 0)throw new jn(`Kiro returned unsupported stream event type ${i}`,"unsupported_upstream_event")}function Ph(){return{text:"",signature:"",signatureConflict:!1,redactedChunks:[]}}function Yh(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 Ro(n){let t=n.redactedChunks.reduce((_,o)=>_+o.byteLength,0),i;if(t>0){i=new Uint8Array(t);let _=0;for(let o of n.redactedChunks)i.set(o,_),_+=o.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 Xh(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((_)=>{t.removeEventListener("abort",f),r({kind:"event",result:_})},(_)=>{t.removeEventListener("abort",f),s(_)})})}function Jh(n,t){if(!t)return;if(!t.name||!t.toolUseId)throw new jn("Kiro emitted a tool call without both name and toolUseId","invalid_upstream_tool_call");let i=n.get(t.toolUseId);if(i){if(i.name!==t.name)throw new jn("Kiro changed a tool name while streaming one tool call","invalid_upstream_tool_call");if(i.stopped&&(t.input??"").length>0)throw new jn("Kiro emitted tool arguments after the tool call stopped","invalid_upstream_tool_call");i.input+=t.input??"",i.stopped||=t.stop===!0;return}n.set(t.toolUseId,{toolUseId:t.toolUseId,name:t.name,input:t.input??"",stopped:t.stop===!0})}function Qh(n){for(let t of n.values()){if(!t.stopped)throw new jn(`Kiro ended before tool call ${t.toolUseId} emitted its stop marker`,"incomplete_upstream_tool_call");try{JSON.parse(t.input)}catch{throw new jn(`Kiro returned invalid JSON arguments for tool call ${t.toolUseId}`,"invalid_upstream_tool_call")}}}function ah(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 zh(n,t,i){let r=n.outputTokens??Hh(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(uy(i)*n.contextUsagePercentage/100);s=Math.max(0,f-r)}return{inputTokens:s??0,outputTokens:r}}class Rg extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function Mg(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new Rg;let _=f[Symbol.asyncIterator](),o=new Map,h={},e="",c=Ph(),d=!1,u=!1,w=!1;try{while(!0){let g=await Xh(_,r);if(g.kind==="aborted"){if(_.return)await _.return();u=!0;break}if(g.result.done){d=!0;break}let O=g.result.value;if(Ch(O),ah(h,O),Yh(c,O.reasoningContentEvent),Wh(O)){w=!0,u=!0;try{let N=_.return?.();if(N)Promise.resolve(N).catch(()=>{return})}catch{}break}if(Fh(O))w=!0;e+=O.assistantResponseEvent?.content??"",Jh(o,O.toolUseEvent)}}finally{if(!d&&!u&&_.return)await _.return()}if(r?.aborted)throw r.reason;if(!w)throw new Gr;Qh(o);let A=zh(h,e,t),R=Ro(c),M={text:e,toolCalls:Array.from(o.values(),(g)=>({id:g.toolUseId,name:g.name,input:g.input}))},E=(s.fingerprintOutput??Lt)(M),T=s.captureReasoning?.(R,E);s.captureOutput?.(M,E);let l={...R.text?{text:R.text}:{},...s.emitAnthropicReasoningMetadata&&R.signature!==void 0?{signature:R.signature}:{},...s.emitAnthropicReasoningMetadata&&R.redactedContent!==void 0?{redactedContent:Buffer.from(R.redactedContent).toString("base64")}:{},...s.emitEncryptedReasoning&&T!==void 0?{encryptedContent:T}:{}};return{canonicalOutputVersion:At,conversationId:i,model:t,createdAt:Math.floor(Date.now()/1000),text:e,...Object.keys(l).length>0?{reasoning:l}:{},toolCalls:M.toolCalls,finishReason:o.size>0?"tool_calls":"stop",usage:{inputTokens:A.inputTokens,outputTokens:A.outputTokens,totalTokens:A.inputTokens+A.outputTokens}}}var Ga=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],ma=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function xh(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Kh(n,t){let i=n[t];return typeof i==="string"?i:void 0}function Ha(n){let t=n.$metadata;if(!xh(t))return;let i=t.httpStatusCode;return typeof i==="number"?i:void 0}function Wa(n){let t=n.$response;if(!xh(t))return;let i=t.headers;if(!xh(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 su(n){if(!xh(n))return{message:n instanceof Error?n.message:String(n)};let t=Ha(n),i=Kh(n,"message")??String(n),r=Kh(n,"code")??Kh(n,"name"),s=Kh(n,"reason"),f=Wa(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 Fa(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 Ca(n){return Ga.some((t)=>t.test(n))}function Eg(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:Ca(n.message)?413:400};case 401:if(!t.forcedRefreshAccountIds.has(t.accountId))return t.forcedRefreshAccountIds.add(t.accountId),{action:"refresh-then-retry",status:401};return t.accountCount>1?{action:"switch",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return t.accountCount>1?{action:"switch",status:402}:{action:"fail",status:402,terminalStatus:402};case 403:if(Qt(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=Fa(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(ma.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}}}class lg extends Error{name="MissingSdkOutputStreamError";code="missing_upstream_stream";constructor(){super("SDK response has no event stream")}}function Pa(n){try{let t=n.return?.();if(t)Promise.resolve(t).catch(()=>{return})}catch{}}async function*Tg(n,t,i,r,s={}){let f=n.generateAssistantResponseResponse;if(!f)throw new lg;let _=new Map,o={},h=Ph(),e=f[Symbol.asyncIterator](),c="",d=!1,u=!1,w=!1,A=!1,R=!1,M=!1,E;try{yield{canonicalOutputVersion:At,type:"started",conversationId:i,model:t,createdAt:Math.floor(Date.now()/1000)};while(!0){let K=await Xh(e,r);if(K.kind==="aborted"){if(e.return)await e.return();M=!0;return}if(K.result.done){R=!0;break}let S=K.result.value;if(s.onRawEvent?.(ru(S)),Ch(S),ah(o,S),Yh(h,S.reasoningContentEvent),Wh(S)){E="token-usage-metadata",s.onCompletionWitness?.(E),M=!0,Pa(e);break}if(Fh(S))E="metering-clean-eof";if(s.emitAnthropicReasoningMetadata){if(h.signatureConflict)throw new jn("Kiro emitted conflicting reasoning signatures","invalid_upstream_reasoning");if(h.text.length>0&&h.redactedChunks.length>0)throw new jn("Kiro mixed visible and redacted reasoning payloads","invalid_upstream_reasoning");if(u&&d&&S.reasoningContentEvent?.signature!==void 0&&S.reasoningContentEvent.signature.length>0)throw new jn("Kiro emitted a reasoning signature after assistant output began","invalid_upstream_reasoning")}let W=S.reasoningContentEvent?.text;if(W)d=!0,yield{canonicalOutputVersion:At,type:"reasoning_delta",text:W};let C=S.assistantResponseEvent?.content;if(C){if(s.emitAnthropicReasoningMetadata){let I=Ro(h);if(d&&!w&&I.signature!==void 0)w=!0,yield{canonicalOutputVersion:At,type:"reasoning_signature",signature:I.signature};if(!d&&!A&&I.redactedContent!==void 0)A=!0,yield{canonicalOutputVersion:At,type:"reasoning_redacted",data:Buffer.from(I.redactedContent).toString("base64")}}u=!0,c+=C,yield{canonicalOutputVersion:At,type:"text_delta",text:C}}if(S.toolUseEvent)Jh(_,S.toolUseEvent)}}finally{if(!R&&!M&&e.return)await e.return()}if(E===void 0)throw new Gr;if(E==="metering-clean-eof")s.onCompletionWitness?.(E);Qh(_);let T=Ro(h);if(s.emitAnthropicReasoningMetadata){if(d&&!w&&T.signature!==void 0)yield{canonicalOutputVersion:At,type:"reasoning_signature",signature:T.signature};if(!A&&T.redactedContent!==void 0)yield{canonicalOutputVersion:At,type:"reasoning_redacted",data:Buffer.from(T.redactedContent).toString("base64")}}let l=0;for(let K of _.values())yield{canonicalOutputVersion:At,type:"tool_call_delta",index:l,id:K.toolUseId,name:K.name,arguments:K.input},l+=1;let g={text:c,toolCalls:[..._.values()].map((K)=>({id:K.toolUseId,name:K.name,input:K.input}))},O=(s.fingerprintOutput??Lt)(g),N=s.captureReasoning?.(T,O);if(s.captureOutput?.(g,O),s.emitEncryptedReasoning&&N!==void 0)yield{canonicalOutputVersion:At,type:"reasoning_encrypted",encryptedContent:N};let F=zh(o,c,t);yield{canonicalOutputVersion:At,type:"completed",finishReason:_.size>0?"tool_calls":"stop",usage:{inputTokens:F.inputTokens,outputTokens:F.outputTokens,totalTokens:F.inputTokens+F.outputTokens}}}var Lg={request_deadline_exceeded:{disposition:"retryable",message:"Request deadline exceeded"},upstream_stream_error:{disposition:"retryable",message:"Upstream stream error"},upstream_stream_incomplete:{disposition:"retryable",message:"Upstream stream ended before completion"},upstream_stream_idle_timeout:{disposition:"retryable",message:"Upstream stream idle timeout"},incomplete_upstream_tool_call:{disposition:"fatal",message:"Upstream returned an incomplete tool call"},invalid_upstream_reasoning:{disposition:"fatal",message:"Upstream returned invalid reasoning metadata"},invalid_upstream_tool_call:{disposition:"fatal",message:"Upstream returned an invalid tool call"},missing_upstream_stream:{disposition:"fatal",message:"Upstream response did not include a stream"},unsupported_upstream_event:{disposition:"fatal",message:"Upstream returned an unsupported stream event"},upstream_invalid_state:{disposition:"fatal",message:"Upstream returned an invalid stream state"},upstream_protocol_error:{disposition:"fatal",message:"Upstream stream protocol error"}};function fu(n,t){if(typeof n!=="object"||n===null)return;try{return Reflect.get(n,t)}catch{return}}function Vs(n,t){let i=fu(n,t);return typeof i==="string"&&i.length>0?i:void 0}function gg(n){let t=Vs(n,"code");return t!==void 0&&Object.hasOwn(Lg,t)?t:void 0}function Og(n){let t=Vs(n,"code");return t!==void 0&&/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(t)?t:void 0}function It(n,t){let i=Lg[n];return{code:n,disposition:i.disposition,message:t??i.message}}function mr(n,t="upstream_stream_error"){let i=gg(n)??gg(fu(n,"cause"));return It(i??t)}function ou(n){let t=mr(n),i=Vs(n,"message"),r=Og(n),s=fu(n,"cause"),f=Vs(s,"name"),_=Og(s),o=Vs(s,"message");return{error_type:Vs(n,"name")??typeof n,error_code:t.code,error_disposition:t.disposition,...i!==void 0?{error_message_hash:wn(i)}:{},...r!==void 0?{source_error_code:r}:{},...f!==void 0?{error_cause_type:f}:{},..._!==void 0?{error_cause_code:_}:{},...o!==void 0?{error_cause_message_hash:wn(o)}:{}}}class Ig extends Error{timeoutMs;name="StreamIdleTimeoutError";code="upstream_stream_idle_timeout";constructor(n){super(`SDK stream idle timeout after ${n}ms`);this.timeoutMs=n}}function Sg(n,t,i,r){let s=new Map,f=0,_,o=()=>JSON.stringify(Object.fromEntries([...s.entries()].sort())),h=()=>({model:n.model,conversation_hash:wn(n.conversationId),raw_event_count:f,last_event_type:_,event_type_counts:o()}),e=new AbortController,c=AbortSignal.any([t,e.signal]),d=Tg(n.sdkResponse,n.model,n.conversationId,c,{...n.captureReasoning?{captureReasoning:n.captureReasoning}:{},emitEncryptedReasoning:n.emitEncryptedReasoning,emitAnthropicReasoningMetadata:n.emitAnthropicReasoningMetadata,...n.fingerprintOutput?{fingerprintOutput:n.fingerprintOutput}:{},...n.captureOutput?{captureOutput:n.captureOutput}:{},onCompletionWitness:(N)=>{V("info","sdk_stream_completion_witness",{model:n.model,conversation_hash:wn(n.conversationId),witness_kind:N})},onRawEvent:(N)=>{f+=1,_=N.join("+");for(let F of N)s.set(F,(s.get(F)??0)+1)}})[Symbol.asyncIterator](),u=d.next(),w=new TextEncoder,A,R,M,E=()=>{if(R===void 0)return;clearTimeout(R),R=void 0},T=(N)=>{if(A!==void 0)return!1;return A=N,!0},l=()=>{c.removeEventListener("abort",O)},g=(N,F)=>{if(!T(N))return;if(Kn(l,E,()=>{if(N==="normal-complete")M?.close();else if(N!=="consumer-cancel")M?.error(F)},r),N!=="normal-complete"&&N!=="consumer-cancel")Kn(()=>{if(!e.signal.aborted)e.abort(F)});Mn(()=>d.return?.(void 0))},O=()=>{g("external-abort",Gt(c))};return new Response(new ReadableStream({start(N){if(M=N,c.addEventListener("abort",O,{once:!0}),c.aborted)O()},async pull(N){if(A!==void 0)return;R=setTimeout(()=>{R=void 0;let F=new Ig(i);V("warn","sdk_stream_idle_timeout",{...h(),...ou(F),idle_timeout_ms:i}),g("idle-timeout",F)},i);try{let F=u??d.next();u=void 0;let K=await F;if(A!==void 0)return;if(E(),K.done){V("info","sdk_stream_completed",h()),g("normal-complete");return}N.enqueue(w.encode(`${JSON.stringify(K.value)}
|
|
359
|
+
`))}catch(F){if(A!==void 0)return;let K=F instanceof Error?F:TypeError("SDK stream failed with a non-Error reason",{cause:F});V("warn","sdk_stream_upstream_error",{...h(),...ou(K)}),g("upstream-error",K)}},cancel(N){g("consumer-cancel",N)}}),{headers:{"Content-Type":jT}})}import{createHash as Ng}from"crypto";import{Agent as Ya}from"http";import{Agent as Xa}from"https";var eu=k(v_(),1);var _u=new Map,bg=new Map,Ja=3,hu=50;function Hr(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function Qa(n){let t=n.conversationState;if(!Hr(t))return;let i=t.currentMessage;if(!Hr(i))return;let r=i.userInputMessage;if(!Hr(r))return;let s=r.modelId;return typeof s==="string"?s:void 0}function Ug(n,t){let i=Hr(n)?{...n}:{};for(let[r,s]of Object.entries(t)){let f=i[r];i[r]=Hr(f)&&Hr(s)?Ug(f,s):s}return i}function aa(n,t,i,r,s=$g(r,!1)){return{region:t,endpoint:i,token:()=>Promise.resolve({token:n.access}),maxAttempts:Ja,retryMode:"standard",customUserAgent:[[On.USER_AGENT]],requestHandler:s}}function $g(n,t){if(n){let i=new Tf(n,{keepAlive:t,maxSockets:hu});return new eu.NodeHttpHandler({httpAgent:i,httpsAgent:i})}return new eu.NodeHttpHandler({httpAgent:new Ya({keepAlive:t,maxSockets:hu}),httpsAgent:new Xa({keepAlive:t,maxSockets:hu})})}function za(n){return Ng("sha256").update("kiro-provider-sdk-account-v1\x00").update(n.email??n.refresh).digest("hex")}function Ka(n){return Ng("sha256").update("kiro-provider-sdk-access-token-v1\x00").update(n).digest("hex")}function Dg(n,t,i,r,s,f,_=!1){let o=r??`https://q.${t}.amazonaws.com`,h=JSON.stringify([f??za(n),t,o,s??null,_]),e=bg.get(h),c=e!==void 0;if(!e)e={handler:$g(s,_)},bg.set(h,e);let d=JSON.stringify([h,i??null]),u=_u.get(d),w=Ka(n.access),A=u!==void 0&&u.accessTokenHash!==w;if(A)_u.delete(d);let R=A?void 0:u;if(f!==void 0)V("info","sdk_connection_pool_selected",{account_hash:wn(f),region:t,effort:i??null,http_keep_alive:_,transport_pool_hit:c,sdk_client_pool_hit:R!==void 0,sdk_client_rebuilt_for_token_change:A});if(R)return R.client;let M=new vd(aa(n,t,o,s,e.handler));if(M.middlewareStack.add((E)=>async(T)=>{if(T.request instanceof _t.HttpRequest)T.request.headers["x-amzn-kiro-agent-mode"]="vibe";return E(T)},{step:"build",name:"addKiroHeaders"}),i)M.middlewareStack.add((E)=>async(T)=>{if(T.request instanceof _t.HttpRequest&&typeof T.request.body==="string")try{let l=JSON.parse(T.request.body);if(Hr(l)){let g=Qa(l);if(g)l.additionalModelRequestFields=Ug(l.additionalModelRequestFields,vT(g,i)),T.request.body=JSON.stringify(l)}}catch(l){if(!(l instanceof SyntaxError))throw l}return E(T)},{step:"build",name:"addEffortConfig",priority:"high"});return _u.set(d,{client:M,accessTokenHash:w}),M}function jh(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function xa(n){if(!jh(n))return!1;let t=n.conversationState;return jh(t)&&typeof t.conversationId==="string"&&jh(t.currentMessage)&&typeof t.chatTriggerType==="string"}function Va(n,t){return{think:t.endsWith("-thinking")||n.thinking?.enabled===!0,budget:n.thinking?.budgetTokens??20000}}function Wr(n,t,i){return tn(n,t,"upstream_error",i)}function Bg(n,t){let i=Date.now()+n.config.quota_recheck_interval_ms;if(n.accountManager.markQuotaExhausted)n.accountManager.markQuotaExhausted(t,i);else n.accountManager.markRateLimited(t,i);V("warn","quota_exhausted_account_persisted",{account_hash:wn(t.id),recheck_after:i})}function ja(n){let t=n.modelCapabilities?.isKnownModel(n.model)??!1;return{kind:"response",response:tn(t?503:400,t?`Model ${n.model} is not available to any currently usable Kiro account`:`Model ${n.model} is not supported by Kiro`,t?"service_unavailable":"invalid_request_error",t?"model_unavailable_for_accounts":"unsupported_model","model")}}function qa(n,t){if(n.config.test_upstream_endpoint)return n.config.test_upstream_endpoint;return n.config.runtime_endpoint_mode==="kiro-runtime"?On.RUNTIME_ENDPOINT.replace("{{region}}",t):void 0}function Gg(n){let t=new Map(n.tools.map((i)=>[i.wireName,i]));return(i)=>Lt({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 _=JSON.parse(r.input);if(jh(_)&&Object.keys(_).length===1&&typeof _.input==="string")f=_.input}catch{}return{...r,name:s.name,input:f}})})}function Vh(){return{kind:"response",response:tn(503,"The account bound to signed reasoning replay is currently unavailable","service_unavailable","reasoning_replay_account_unavailable")}}function ka(n,t){if(n.body.reasoningReplays.length===0)return{replays:[]};if(!n.tenantId)throw new bn("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 bn("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 _=n.reasoningReplayStore;if(!_)throw new bn("Reasoning replay storage is unavailable","reasoning_replay_store_unavailable",!0);let o={tenantId:n.tenantId,model:n.body.model,outputFingerprint:f.outputFingerprint,...i!==void 0?{accountId:i}:{},...r!==void 0?{conversationId:r}:{}},h=f.lookup.kind==="responses-token"?_.resolveResponses(f.lookup.encryptedContent,o,f.insertBeforeMessage):_.resolveChat(f.lookup.reasoningText,o,f.insertBeforeMessage);if(i!==void 0&&i!==h.accountId||r!==void 0&&r!==h.conversationId)throw new bn("Reasoning replay items resolve to different accounts or conversations","reasoning_replay_context_mismatch");i=h.accountId,r=h.conversationId,s.push(h.replay)}return{...i!==void 0?{accountId:i}:{},...r!==void 0?{conversationId:r}:{},replays:s}}function Za(n,t,i){let r=n.body,s=r.includeEncryptedReasoning===!0,f=r.protocol==="anthropic-messages",_=n.lineage&&n.affinityStore?(o)=>{if(o.text.length===0&&o.toolCalls.length===0)return;let h=tu(r,o),e=n.lineage?.outputKeyHash(h);if(e===void 0)return;n.affinityStore?.recordOutputLineage(e,t,i,Date.now(),n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),V("info","output_lineage_recorded",{protocol:r.protocol,lineage_source:n.lineage?.source,lineage_hash:wn(e),account_hash:wn(t),conversation_hash:wn(i)})}:void 0;if(!n.reasoningReplayStore||!n.tenantId)return{emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,...r?{fingerprintOutput:Gg(r)}:{},..._?{captureOutput:_}:{}};return{captureReasoning:(o,h)=>n.reasoningReplayStore?.store(o,{tenantId:n.tenantId,model:r.model,accountId:t,conversationId:i,outputFingerprint:h}),emitEncryptedReasoning:s,emitAnthropicReasoningMetadata:f,fingerprintOutput:Gg(r),..._?{captureOutput:_}:{}}}async function va(n,t){let{think:i,budget:r}=Va(n.body,n.model),s=new Set,f=new Map,_=new Set,o=new Set,h,e,c=0,d=0,u=n.affinity&&n.affinityStore?n.affinityStore.getSessionAffinity(n.affinity.keyHash):void 0,w=u===void 0&&n.lineage?.lookupKeyHash!==void 0&&n.affinityStore?n.affinityStore.resolveOutputLineage(n.lineage.lookupKeyHash):void 0,A=u??w,R=ka(n,A),M=R.accountId!==void 0,E=R.accountId??A?.accountId,T=R.accountId??A?.accountId,l=R.conversationId??A?.conversationId,g=new Set;if(n.quotaRechecker)await n.quotaRechecker.recheckDueAccounts(n.accountManager.reconcileFromDb(),t,R.accountId??A?.accountId);while(!0){if(t.aborted)throw Gt(t);if(d+=1,d>n.config.max_request_iterations){if(h)return{kind:"response",response:Wr(h.status??403,h.message,h.code??"upstream_authentication_failed")};if(e)return{kind:"response",response:Wr(402,e.message,e.code??"quota_exhausted")};return{kind:"response",response:tn(500,`Exceeded max iterations (${n.config.max_request_iterations})`,"request_error","max_request_iterations")}}let N=n.accountManager.reconcileFromDb().filter((b)=>!g.has(b.id)&&!_.has(b.id)),F=N.filter(yn),K=F.filter((b)=>!o.has(b.id));for(let b of K)o.add(b.id);if(K.length>0)V("info","quota_exhausted_accounts_excluded",{account_count:K.length});let S=N.filter((b)=>!yn(b)).map((b)=>b.id),W=n.modelCapabilities?.eligibleAccountIds(n.model,S),C=new Set([...W??S].filter((b)=>!g.has(b))),I=n.accountManager.selectHealthyAccount(E,C);if(!I||R.accountId!==void 0&&I.id!==R.accountId){if(M)return Vh();if(S.length===0&&h)return{kind:"response",response:Wr(h.status??403,h.message,h.code??"upstream_authentication_failed")};if(S.length===0&&(F.length>0||e))return{kind:"response",response:Wr(402,e?.message??"All eligible Kiro accounts have exhausted their quota",e?.code??"quota_exhausted")};if(g.size>0||W!==void 0&&C.size===0)return ja(n);return{kind:"response",response:tn(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")}}let L=Date.now();if(n.affinity&&n.affinityStore)if(!u){let b=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,I.id,l??cu(),L,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries);if(u=b,E=b.accountId,l=b.conversationId,M&&(b.accountId!==R.accountId||b.conversationId!==R.conversationId))throw new bn("Session affinity conflicts with signed reasoning replay","reasoning_replay_context_mismatch");if(b.accountId!==I.id)continue}else if(u.accountId===I.id)u=n.affinityStore.claimSessionAffinity(n.affinity.keyHash,I.id,u.conversationId,L,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),l=u.conversationId;else u=n.affinityStore.rebindSessionAffinity(n.affinity.keyHash,I.id,cu(),L,n.config.session_affinity_ttl_ms,n.config.session_affinity_max_entries),l=u.conversationId;else if(!M&&T!==I.id)T=I.id,l=cu();E=I.id,V("info","upstream_affinity_selected",{projection_mode:n.config.protocol_projection_mode,session_affinity_mode:n.config.session_affinity_mode,affinity_source:n.affinity?.source??n.lineage?.source,affinity_bound:u!==void 0||w!==void 0,affinity_kind:u!==void 0?"explicit":w!==void 0?"history-lineage":void 0,account_hash:wn(I.id),conversation_hash:l===void 0?void 0:wn(l),reasoning_replay_locked:M});let m=await vw(I.id,t),q=!0,Q=I,Z=!1;try{let b=n.accountManager.toAuthDetails(I);Q=await jt(n.tokenRefresher.refreshIfNeeded(I,b,t),t);let D=n.accountManager.toAuthDetails(Q);if(n.modelCapabilities){let B=await jt(n.modelCapabilities.ensureAccountModel(Q,D,n.model,t),t);if(!B.supported){if(V("warn","account_model_unavailable",{account_hash:wn(Q.id),model_hash:wn(n.model),capability_source:B.source}),M)return Vh();g.add(Q.id),E=void 0,T=void 0,l=void 0;continue}}let Dn=No.safeParse(n.config.effort),cn=Ag(n.body,n.model,D,i,r,{autoEffortMapping:n.config.auto_effort_mapping,conversationId:l,resolvedReasoningReplays:R.replays,...Dn.success?{effort:Dn.data}:{}}),Bn=(n.makeClient??Dg)(D,cn.region,cn.effort,qa(n,cn.region),di(n.config),Q.id,n.config.sdk_http_keep_alive),St={conversationState:cn.conversationState,...cn.profileArn?{profileArn:cn.profileArn}:{},...cn.additionalModelRequestFields?{additionalModelRequestFields:cn.additionalModelRequestFields}:{}};if(!xa(St))throw TypeError("Transformed request is not a valid SDK command input");let Jr=new pd(St);Z=!0;let To=await jt(Bn.send(Jr,{abortSignal:t}),t),nf=Za(n,Q.id,cn.conversationId);if(n.stream)return q=!1,{kind:"stream",sdkResponse:To,model:n.model,conversationId:cn.conversationId,...nf,releaseAccount:m};let go=await Mg(To,n.model,cn.conversationId,t,nf);if(t.aborted)throw Gt(t);return{kind:"response",response:Response.json(go,{headers:{"Content-Type":VT}})}}catch(b){if(t.aborted)throw Gt(t);if(!Z){if(b instanceof dn||b instanceof bn)throw b;if(M)return Vh();throw b}if(b instanceof Gr){if(c<n.config.rate_limit_max_retries){c+=1,await a0(n.config.rate_limit_retry_delay_ms*2**(c-1),t);continue}return{kind:"response",response:Wr(502,b.message,b.code)}}if(b instanceof jn)return{kind:"response",response:Wr(502,b.message,b.code)};let D=su(b),Dn=D.status===500?(f.get(Q.id)??0)+1:0;if(D.status===500)f.set(Q.id,Dn);let cn=Eg(D,{accountId:Q.id,accountCount:Math.max(1,C.size),retryCount:c,maxRetries:n.config.rate_limit_max_retries,serverErrorCount:Dn,retryDelayMs:n.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:s});switch(cn.action){case"refresh-then-retry":await jt(n.tokenRefresher.forceRefresh(Q,t),t);continue;case"retry":c+=1,await a0(cn.retryAfterMs??0,t);continue;case"switch":if(M)return Vh();if(_.add(Q.id),D.status===401||D.status===403&&Qt(D.message))h=D;if(D.status===402)e=D;if(D.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(Q,`InvalidTokenException: Account Suspended: ${D.message}`);else if(D.status===402)Bg(n,Q);else n.accountManager.markRateLimited(Q,Date.now()+(cn.retryAfterMs??n.config.rate_limit_retry_delay_ms));if(E=void 0,T=void 0,!n.affinityStore)l=void 0;continue;case"fail":if(D.status===402)Bg(n,Q);if(D.reason==="TEMPORARILY_SUSPENDED")n.accountManager.markUnhealthy(Q,`InvalidTokenException: Account Suspended: ${D.message}`);return{kind:"response",response:Wr(cn.terminalStatus??cn.status??500,D.message,D.code)}}}finally{if(q)m()}}}async function js(n){let t=pw(n.deadlineSignal,n.config.request_timeout_ms),i,r,s=!1;try{if(n.affinity)i=await z0(n.affinity.keyHash,t.signal);else if(n.lineage?.lookupKeyHash!==void 0)i=await z0(n.lineage.lookupKeyHash,t.signal);let f=await va(n,t.signal);if(f.kind==="response")return f.response;r=f.releaseAccount;let _=r,o=i,h=(n.createStreamResponse??Sg)(f,t.signal,n.config.stream_idle_timeout_ms,()=>{_(),o?.(),t.dispose()});return r=void 0,i=void 0,s=!0,h}catch(f){if(f instanceof dn)return tn(400,f.message,"invalid_request_error",f.code,f.param);if(f instanceof bn)return tn(f.retryable?503:400,f.message,f.retryable?"service_unavailable":"invalid_request_error",f.code);if(t.signal.aborted)return tn(504,"Request deadline exceeded","timeout_error","request_timeout");let _=su(f);return tn(500,_.message,"internal_error",_.code)}finally{if(!s)r?.(),i?.(),t.dispose()}}function Fr(n,t,i){return{id:n.id,object:"chat.completion.chunk",created:n.created,model:n.model,choices:[{index:0,delta:t,finish_reason:i}]}}function pa(n,t,i){switch(n.type){case"text_delta":return[JSON.stringify(Fr(t,{content:n.text},null))];case"reasoning_delta":return[JSON.stringify(Fr(t,{reasoning_content:n.text},null))];case"reasoning_signature":return[JSON.stringify(Fr(t,{reasoning_signature:n.signature},null))];case"reasoning_redacted":return[JSON.stringify(Fr(t,{reasoning_redacted_content:n.data},null))];case"reasoning_encrypted":return[JSON.stringify(Fr(t,{reasoning_encrypted_content:n.encryptedContent},null))];case"tool_call_delta":return[JSON.stringify(Fr(t,{tool_calls:[{index:n.index,...n.id!==void 0?{id:n.id,type:"function"}:{},function:{...n.name!==void 0?{name:n.name}:{},arguments:n.arguments}}]},null))];case"completed":{let r=JSON.stringify(Fr(t,{},n.finishReason));if(!i)return[r];let s={id:t.id,object:"chat.completion.chunk",created:t.created,model:t.model,choices:[],usage:{prompt_tokens:n.usage.inputTokens,completion_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens}};return[r,JSON.stringify(s)]}}}function mg(n){let t=n.reasoning;return Response.json({id:n.conversationId,object:"chat.completion",created:n.createdAt,model:n.model,choices:[{index:0,message:{role:"assistant",content:n.text,...t?.text?{reasoning_content:t.text}:{},...t?.signature?{reasoning_signature:t.signature}:{},...t?.redactedContent?{reasoning_redacted_content:t.redactedContent}:{},...t?.encryptedContent?{reasoning_encrypted_content:t.encryptedContent}:{},...n.toolCalls.length>0?{tool_calls:n.toolCalls.map((i)=>({id:i.id,type:"function",function:{name:i.name,arguments:i.input}}))}:{}},finish_reason:n.finishReason}],usage:{prompt_tokens:n.usage.inputTokens,completion_tokens:n.usage.outputTokens,total_tokens:n.usage.totalTokens}})}function Hg(n,t,i,r){let s=r.includeUsage===!0,_=(n.body??new ReadableStream({start:(L)=>L.close()})).getReader(),o=new TextDecoder,h=new TextEncoder,e=[],c=new Map,d="",u,w=!1,A,R,M=!1,E=(L)=>{e.push(h.encode(`data: ${L}
|
|
360
360
|
|
|
361
|
-
`))},
|
|
362
|
-
`);if(I>=0){let a=d.slice(0,I).trimEnd();if(d=d.slice(I+1),a.length===0)continue;let j=Oi(a);if(!j||!H(j)){Y("upstream-protocol-error");return}if(e(g))return;continue}let P=await h.read();if(R!==void 0)return;if(!P.done){d+=_.decode(P.value,{stream:!0});continue}d+=_.decode();let m=d.trim();if(d="",m.length>0){let a=Oi(m);if(!a||!H(a)){Y("upstream-protocol-error");return}}if(!y){Y("upstream-protocol-error");return}Y("normal-complete");return}}catch(I){if(R!==void 0)return;Y("upstream-error",I)}},cancel(g){Y("consumer-cancel",g)}}),{status:n.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}function X(n,t,i){return i===void 0?{ok:!1,code:n,message:t}:{ok:!1,code:n,message:t,param:i}}var gz=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"]),Nz=["temperature","top_p","response_format","n","stop","seed","presence_penalty","frequency_penalty","logit_bias","logprobs","top_logprobs","modalities","audio","prediction","metadata","service_tier"];function Y0(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function _t(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return X("unsupported_parameter",`Chat field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function P0(n,t){return{type:"text",text:n,path:t}}function bz(n,t){if(typeof n==="string")return{ok:!0,value:[P0(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=_t(s,f,new Set(["type","text"]));if(!h.ok)return h;i.push(P0(s.text,`${f}.text`));break}case"image_url":{let h=_t(s,f,new Set(["type","image_url"]));if(!h.ok)return h;let _=_t(s.image_url,`${f}.image_url`,new Set(["url","detail"]));if(!_.ok)return _;if(s.image_url.detail!==void 0)return X("unsupported_parameter","Chat image detail cannot be represented by the Kiro upstream",`${f}.image_url.detail`);if(!s.image_url.url.startsWith("data:"))return X("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=_t(s,f,new Set(["type","source"]));if(!h.ok)return h;let _=_t(s.source,`${f}.source`,new Set(["type","data","media_type"]));if(!_.ok)return _;if(s.source.type!=="base64")return X("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=_t(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=_t(s,f,new Set(["type","tool_use_id","content","is_error"]));if(!h.ok)return h;let _=Sz(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 X("unsupported_content_part",`Chat content part ${f} uses unsupported type thinking`,f)}}return{ok:!0,value:i}}function Sz(n,t){if(typeof n==="string")return{ok:!0,value:[P0(n,t)]};if(!Array.isArray(n))return X("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(!Y0(s)||s.type!=="text"||typeof s.text!=="string")return X("unsupported_tool_result_content",`Tool result ${t}.${r} must be a text block`,`${t}.${r}`);let f=_t(s,`${t}.${r}`,new Set(["type","text"]));if(!f.ok)return f;i.push(P0(s.text,`${t}.${r}.text`))}return{ok:!0,value:i}}function lz(n,t){let i=_t(n,t,new Set(["id","type","function"]));if(!i.ok)return i;let r=_t(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 X("invalid_tool_history",`Tool call ${t} contains invalid JSON arguments`,`${t}.function.arguments`)}}function $z(n){let t=[],i=new Set;for(let[r,s]of(n??[]).entries()){let f=`tools.${r}`,h=Y0(s.function)?s.function:void 0;if(h!==void 0){let d=_t(s,f,new Set(["type","function"]));if(!d.ok)return d;let u=_t(h,`${f}.function`,new Set(["name","description","parameters","strict"]));if(!u.ok)return u;if(h.strict===!0)return X("unsupported_strict_tools","Chat function strict=true cannot be guaranteed by the Kiro upstream",`${f}.function.strict`)}else{let d=_t(s,f,new Set(["name","description","input_schema"]));if(!d.ok)return d}let _=typeof h?.name==="string"?h.name:s.name;if(typeof _!=="string"||_.length===0)return X("invalid_tool_declaration",`Tool declaration ${f} requires a name`,f);let o=_;if(i.has(o))return X("invalid_tool_declaration",`Duplicate tool declaration ${o}`,f);i.add(o);let w=typeof h?.description==="string"?h.description:typeof s.description==="string"?s.description:void 0,c=h!==void 0?Y0(h.parameters)?h.parameters:{}:Y0(s.input_schema)?s.input_schema:{};t.push({publicType:"function",name:o,wireName:o,...w!==void 0?{description:w}:{},inputSchema:c,...h!==void 0?{strict:!1}:{},path:f})}return{ok:!0,value:t}}function Uz(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 X("missing_tool_declaration",`Tool call ${_.id} references ${_.name} without an exact tool declaration`,_.path);if(r.has(_.id))return X("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 o=r.get(_.toolCallId);if(!o||o.index>=f||s.has(_.toolCallId))return X("invalid_tool_history",`Tool result ${_.toolCallId} has no earlier unique matching call`,_.path);s.add(_.toolCallId)}}return{ok:!0,value:void 0}}function M4(n,t){for(let w of Object.keys(n))if(!gz.has(w))return X("unsupported_parameter",`Chat parameter ${w} is not supported`,w);if(n.stream_options!==void 0){let w=_t(n.stream_options,"stream_options",new Set(["include_usage"]));if(!w.ok)return w;if(!n.stream)return X("unsupported_parameter","Chat stream_options requires stream=true","stream_options")}for(let w of Nz)if(n[w]!==void 0)return X("unsupported_parameter",`Chat parameter ${w} cannot be represented by the Kiro upstream`,w);if(n.store===!0)return X("unsupported_parameter","Chat parameter store=true is not supported","store");if(n.max_tokens!==void 0&&n.max_completion_tokens!==void 0)return X("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 w=qi(n.model,i);if(!w.ok)return X(w.code,w.message,r)}if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return X("unsupported_tool_choice","Required or named tool choice cannot be represented by the Kiro upstream","tool_choice");let s=$z(n.tools);if(!s.ok)return s;let f=[];if(n.parallel_tool_calls===!1&&n.tool_choice!=="none"&&s.value.length>0)return X("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");let h=[];for(let[w,c]of n.messages.entries()){let d=`messages.${w}`,u=c.role==="assistant"?new Set(["role","content","tool_calls","reasoning_content"]):c.role==="tool"?new Set(["role","content","tool_call_id"]):new Set(["role","content"]);for(let T of Object.keys(c))if(!u.has(T))return X("unsupported_message_field",`Chat message field ${d}.${T} is not supported`,`${d}.${T}`);if(t==="safe"&&(c.role==="system"||c.role==="developer"))return X("unsupported_instruction_projection",`${c.role} messages cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,d);let y=bz(c.content,`${d}.content`);if(!y.ok)return y;let R=[];if(c.role==="assistant")for(let[T,O]of(c.tool_calls??[]).entries()){let e=lz(O,`${d}.tool_calls.${T}`);if(!e.ok)return e;R.push(e.value)}let M=y.value;if(c.role==="tool"){let T=M.filter((O)=>O.type==="text");if(T.length!==M.length)return X("unsupported_tool_result_content",`Chat tool message ${d} may contain text only`,`${d}.content`);M=[{type:"tool_result",toolCallId:c.tool_call_id,content:T,isError:!1,path:d}]}let E={role:c.role,content:M,toolCalls:R,path:d};if(c.role==="assistant"&&c.reasoning_content!==void 0)h.push({lookup:{kind:"chat-hash",reasoningText:c.reasoning_content},outputFingerprint:et({text:ii(M),toolCalls:(c.tool_calls??[]).map((T)=>({id:T.id,name:T.function.name,input:T.function.arguments}))}),insertBeforeMessage:f.length,path:`${d}.reasoning_content`});f.push(E)}let _=Uz(f,s.value);if(!_.ok)return _;let o=new Set;for(let w of f){for(let c of w.toolCalls)o.add(c.id);for(let c of w.content)if(c.type==="tool_result")o.delete(c.toolCallId)}if(n.tool_choice==="none"&&o.size>0)return X("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 Gr=A.record(A.unknown()),Dz=A.record(A.string()).superRefine((n,t)=>{let i=Object.entries(n);if(i.length>16)t.addIssue({code:A.ZodIssueCode.custom,message:"metadata must contain at most 16 entries"});for(let[r,s]of i){if(r.length>64)t.addIssue({code:A.ZodIssueCode.custom,message:"metadata keys must contain at most 64 characters",path:[r]});if(s.length>512)t.addIssue({code:A.ZodIssueCode.custom,message:"metadata values must contain at most 512 characters",path:[r]})}}),Bz=A.object({type:A.literal("text"),text:A.string()}).passthrough(),Gz=A.object({type:A.literal("image_url"),image_url:A.object({url:A.string(),detail:A.string().optional()}).passthrough()}).passthrough(),Hz=A.object({type:A.literal("image"),source:A.object({type:A.string(),data:A.string(),media_type:A.string().optional()}).passthrough()}).passthrough(),Wz=A.object({type:A.literal("tool_result"),tool_use_id:A.string().min(1),content:A.unknown()}).passthrough(),Fz=A.object({type:A.literal("tool_use"),id:A.string().min(1),name:A.string().min(1),input:A.unknown()}).passthrough(),Yz=A.object({type:A.literal("thinking"),thinking:A.string().optional(),text:A.string().optional()}).passthrough(),Pz=A.discriminatedUnion("type",[Bz,Gz,Hz,Wz,Fz,Yz]),__=A.union([A.string(),A.array(Pz)]);function E4(n){try{return JSON.parse(n),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function Xz(n){return n.trim().length===0?"{}":n}var Cz=A.object({id:A.string().min(1),type:A.literal("function"),function:A.object({name:A.string().min(1),arguments:A.string().refine(E4,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),Jz=A.object({role:A.literal("system"),content:__}).passthrough(),Qz=A.object({role:A.literal("developer"),content:__}).passthrough(),mz=A.object({role:A.literal("user"),content:__}).passthrough(),zz=A.object({role:A.literal("assistant"),content:__.nullable().optional(),tool_calls:A.array(Cz).min(1).optional(),reasoning_content:A.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"}),Kz=A.object({role:A.literal("tool"),content:__,tool_call_id:A.string().min(1)}).passthrough(),Vz=A.union([Jz,Qz,mz,zz,Kz]),xz=A.object({type:A.literal("function"),function:A.object({name:A.string().min(1),description:A.string().optional(),parameters:Gr.optional()}).passthrough()}).passthrough(),jz=A.object({name:A.string().min(1),description:A.string().optional(),input_schema:Gr.optional()}).passthrough(),qz=A.object({model:A.string().trim().min(1),stream:A.boolean().default(!1),stream_options:A.object({include_usage:A.boolean().optional()}).passthrough().optional(),messages:A.array(Vz).min(1),tools:A.array(A.union([xz,jz])).optional(),user:A.string().optional(),prompt_cache_key:A.string().optional(),reasoning_effort:A.enum(["low","medium","high","xhigh","max"]).optional(),tool_choice:A.union([A.enum(["auto","none","required"]),A.object({type:A.literal("function"),function:A.object({name:A.string().min(1)}).passthrough()}).passthrough()]).optional(),parallel_tool_calls:A.boolean().optional(),max_tokens:A.number().int().positive().optional(),max_completion_tokens:A.number().int().positive().optional(),temperature:A.number().optional(),top_p:A.number().optional(),response_format:A.unknown().optional(),n:A.number().int().positive().optional(),stop:A.unknown().optional(),seed:A.number().int().optional(),presence_penalty:A.number().optional(),frequency_penalty:A.number().optional(),logit_bias:A.unknown().optional(),logprobs:A.boolean().optional(),top_logprobs:A.number().int().optional(),modalities:A.unknown().optional(),audio:A.unknown().optional(),prediction:A.unknown().optional(),store:A.boolean().optional(),metadata:A.unknown().optional(),service_tier:A.unknown().optional()}).passthrough(),kz=A.object({type:A.literal("input_text"),text:A.string()}).passthrough(),az=A.object({type:A.literal("output_text"),text:A.string()}).passthrough(),Zz=A.object({type:A.literal("input_image"),image_url:A.string()}).passthrough(),vz=A.object({type:A.literal("input_file"),file_data:A.string().optional(),file_id:A.string().optional(),filename:A.string().min(1).optional()}).passthrough(),pz=A.object({type:A.literal("encrypted_content"),encrypted_content:A.string()}).passthrough(),nK=new Set(["input_text","output_text","input_image","input_file","encrypted_content"]),tK=A.object({type:A.string()}).passthrough().refine((n)=>!nK.has(n.type),{message:"known content parts must have a valid payload"}),T4=A.union([kz,az,Zz,vz,pz,tK]),iK=A.object({type:A.literal("message").optional(),id:A.string().optional(),status:A.string().optional(),role:A.enum(["system","developer","user","assistant"]),content:A.union([A.string(),A.array(T4)])}).passthrough(),rK=A.object({type:A.literal("agent_message"),author:A.string().min(1),recipient:A.string().min(1),content:A.array(T4)}).passthrough(),sK=A.object({type:A.literal("function_call"),id:A.string().optional(),status:A.string().optional(),call_id:A.string().min(1),namespace:A.string().min(1).optional(),name:A.string().min(1),arguments:A.string().transform(Xz).refine(E4,"function arguments must contain valid JSON")}).passthrough(),fK=A.object({type:A.literal("custom_tool_call"),id:A.string().optional(),status:A.string().optional(),call_id:A.string().min(1),namespace:A.string().min(1).optional(),name:A.string().min(1),input:A.string()}).passthrough(),e4=A.union([A.string(),A.array(A.object({type:A.string(),text:A.string().optional()}).passthrough())]),_K=A.object({type:A.literal("function_call_output"),id:A.string().optional(),status:A.string().optional(),call_id:A.string().min(1),output:e4}).passthrough(),hK=A.object({type:A.literal("custom_tool_call_output"),id:A.string().optional(),status:A.string().optional(),call_id:A.string().min(1),output:e4}).passthrough(),O4=A.object({type:A.literal("function"),name:A.string().min(1),description:A.string().optional(),parameters:Gr.optional(),strict:A.boolean().optional()}).passthrough(),X0=A.object({type:A.literal("custom"),name:A.string().min(1),description:A.string().optional(),format:A.object({type:A.literal("grammar"),syntax:A.string().min(1),definition:A.string()}).passthrough().optional()}).passthrough(),oK=A.union([O4,X0]),wK=A.object({type:A.literal("namespace"),name:A.string().min(1),description:A.string().optional(),tools:A.array(oK)}).passthrough(),cK=A.object({type:A.literal("function"),name:A.string().min(1),description:A.string().optional(),parameters:Gr.optional(),inputSchema:Gr.optional(),strict:A.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),dK=A.object({type:A.literal("function").optional(),name:A.string().min(1),description:A.string().optional(),parameters:Gr.optional(),inputSchema:Gr.optional(),strict:A.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),uK=A.union([dK,X0]),yK=A.object({type:A.literal("namespace"),name:A.string().min(1),description:A.string().optional(),tools:A.array(uK)}).passthrough().transform((n)=>({...n,type:"namespace"})),AK=new Set(["function","custom","namespace"]),L4=A.object({type:A.string()}).passthrough().refine((n)=>!AK.has(n.type),{message:"known tools must have a valid payload"}),RK=A.union([O4,X0,wK]),MK=A.union([RK,L4]),EK=A.union([cK,X0,yK,L4]),TK=A.object({type:A.literal("additional_tools"),role:A.string().optional(),tools:A.array(EK)}).passthrough(),eK=A.object({type:A.literal("summary_text"),text:A.string()}).passthrough(),OK=A.object({type:A.literal("reasoning_text"),reasoning_text:A.string()}).passthrough(),LK=A.object({type:A.literal("reasoning"),id:A.string().optional(),status:A.string().optional(),summary:A.array(eK).nullable().optional(),content:A.array(OK).nullable().optional(),encrypted_content:A.string().nullable().optional()}).passthrough(),IK=new Set(["message","agent_message","function_call","custom_tool_call","function_call_output","custom_tool_call_output","additional_tools","reasoning"]),gK=A.object({type:A.string()}).passthrough().refine((n)=>!IK.has(n.type),{message:"known input items must have a valid payload"}),NK=A.union([iK,rK,sK,fK,_K,hK,TK,LK,gK]),bK=A.object({effort:A.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),summary:A.unknown().optional()}).passthrough(),SK=A.object({model:A.string().trim().min(1),input:A.union([A.string(),A.array(NK)]),instructions:A.string().optional(),stream:A.boolean().default(!1),tools:A.array(MK).optional(),tool_choice:A.union([A.enum(["auto","none","required"]),A.record(A.unknown())]).optional(),parallel_tool_calls:A.boolean().optional(),reasoning:bK.nullable().optional(),include:A.array(A.string()).optional(),store:A.boolean().optional(),text:A.unknown().optional(),service_tier:A.unknown().optional(),max_output_tokens:A.number().int().positive().optional(),temperature:A.number().optional(),top_p:A.number().optional(),truncation:A.unknown().optional(),background:A.boolean().optional(),max_tool_calls:A.number().int().positive().optional(),prompt_cache_key:A.string().optional(),metadata:Dz.optional(),client_metadata:A.unknown().optional(),previous_response_id:A.string().optional(),conversation:A.unknown().optional()}).passthrough();function I4(n){let t=qz.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:nn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}function g4(n){let t=SK.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:nn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}import{createHash as S4}from"crypto";function lK(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ad(n){if(n===null||typeof n!=="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(ad).join(",")}]`;return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${JSON.stringify(i)}:${ad(r)}`).join(",")}}`}function Li(n,t,i,r){return{keyHash:S4("sha256").update("kiro-provider-session-affinity-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(ad(r)).digest("hex"),source:i}}function N4(n,t,i,r){return S4("sha256").update("kiro-provider-output-lineage-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(r).digest("hex")}function Cs(n,t){if(!t)return;let i=n.protocol==="chat-completions"?"chat":n.protocol==="anthropic-messages"?"anthropic":"responses",r=`${i}.history_lineage`,s=De(n);return{...s!==void 0?{lookupKeyHash:N4(t,i,n.model,s)}:{},source:r,outputKeyHash:(f)=>N4(t,i,n.model,f)}}function b4(n,t){if(!lK(n))return;let i=n[t];return typeof i==="string"&&i.length>0?i:void 0}function $K(n){if(typeof n==="string")return{role:"user",content:n};return n.find((i)=>i.type==="message"&&i.role==="user")??n[0]}function UK(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function DK(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function l4(n,t,i="explicit-only"){if(!t)return;for(let s of["zuno_session_id","kiro_provider_session_id"]){let f=b4(n.metadata,s);if(f!==void 0){let h=`responses.metadata.${s}`;return Li(t,"responses",h,f)}}for(let s of["thread_id","session_id","conversation_id"]){let f=b4(n.client_metadata,s);if(f!==void 0){let h=`responses.client_metadata.${s}`;return Li(t,"responses",h,f)}}if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return Li(t,"responses","responses.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=$K(n.input);return r===void 0?void 0:Li(t,"responses","responses.initial_input",r)}function $4(n,t,i="explicit-only"){if(!t)return;if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return Li(t,"chat","chat.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=UK(n);if(r===void 0)return;if(n.user&&n.user.length>0)return Li(t,"chat","chat.user_and_initial_input",{user:n.user,initial:r});return Li(t,"chat","chat.initial_input",r)}function U4(n,t,i="explicit-only"){if(!t)return;if(i!=="legacy-initial-input")return;let r=DK(n);if(r===void 0)return;let s=n.metadata?.user_id;if(s)return Li(t,"anthropic","anthropic.user_and_initial_input",{userId:s,initial:r});return Li(t,"anthropic","anthropic.initial_input",r)}class vd extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function Zd(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function BK(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,h,_=new Promise((w,c)=>{h=c}),o=()=>{let w=Zd(i.combined);h?.(w),Mn(()=>r.cancel(w))};i.combined.addEventListener("abort",o,{once:!0});try{while(!0){if(i.combined.aborted)throw Zd(i.combined);let d=await Promise.race([r.read(),_]);if(i.combined.aborted)throw Zd(i.combined);if(d.done)break;if(f+=d.value.byteLength,f>t)throw new vd(t);s.push(d.value)}let w=new Uint8Array(f),c=0;for(let d of s)w.set(d,c),c+=d.byteLength;return{ok:!0,text:new TextDecoder().decode(w)}}catch(w){if(w instanceof vd)return Mn(()=>r.cancel(w)),{ok:!1,response:nn(413,w.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return Mn(()=>r.cancel(w)),{ok:!1,response:nn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return Mn(()=>r.cancel(w)),{ok:!1,response:nn(499,"Client closed request","request_aborted","client_disconnected")};throw w}finally{i.combined.removeEventListener("abort",o)}}async function D4(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 BK(n,t.max_request_body_bytes,h);if(!_.ok)return clearTimeout(s),_.response;let o;try{o=JSON.parse(_.text)}catch(E){if(clearTimeout(s),!(E instanceof SyntaxError))throw E;return nn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let w=I4(o);if(!w.ok)return clearTimeout(s),w.response;let c=$4(w.value,i.tenantId,t.session_affinity_mode),d=M4(w.value,t.protocol_projection_mode);if(!d.ok)return k("warn","protocol_projection_rejected",{protocol:"chat-completions",projection_mode:t.protocol_projection_mode,code:d.code,param:d.param}),clearTimeout(s),nn(400,d.message,"invalid_request_error",d.code,d.param);let u=Cs(d.value,i.tenantId),y,R=!1,M=()=>{Vn(()=>clearTimeout(s),()=>y?.restore())};try{y=i.createRequestIdleTimeoutLease?.(),y?.disable();let E=await(i.runPipeline??Xs)({body:d.value,model:w.value.model,stream:w.value.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...i.quotaRechecker?{quotaRechecker:i.quotaRechecker}:{},...c?{affinity:c}:{},...u?{lineage:u}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},...i.modelCapabilities?{modelCapabilities:i.modelCapabilities}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return Mn(()=>E.body?.cancel()),nn(499,"Client closed request","request_aborted","client_disconnected");let T=E.headers.get("Content-Type")??"";if(!E.ok)return E;if(!w.value.stream){if(!T.includes(Fs))return Mn(()=>E.body?.cancel()),nn(500,"Pipeline returned an unsupported non-streaming response","internal_error","invalid_pipeline_response");let e=Ps(await E.json());if(!e||e.model!==w.value.model)return nn(500,"Pipeline returned an invalid canonical completion","internal_error","invalid_pipeline_response");return A4(e)}if(!T.includes(Ys))return Mn(()=>E.body?.cancel()),nn(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let O=R4(E,h,M,{expectedModel:w.value.model,includeUsage:w.value.stream_options?.include_usage===!0});return R=!0,O}finally{if(!R)M()}}function B4(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var G4=A.object({type:A.string().min(1)}).passthrough(),GK=A.object({role:A.enum(["user","assistant"]),content:A.union([A.string(),A.array(G4)])}).passthrough(),HK=A.object({name:A.string().min(1),description:A.string().optional(),input_schema:A.record(A.unknown()).optional()}).passthrough(),WK=A.object({type:A.enum(["auto","any","tool","none"]),name:A.string().min(1).optional(),disable_parallel_tool_use:A.boolean().optional()}).passthrough().refine((n)=>n.type!=="tool"||n.name!==void 0,{message:"tool_choice.name is required when tool_choice.type is tool"}),FK=A.object({type:A.enum(["enabled","adaptive","disabled"]),budget_tokens:A.number().int().positive().optional()}).passthrough(),YK=A.object({model:A.string().min(1),max_tokens:A.number().int().positive().optional(),messages:A.array(GK).min(1),system:A.union([A.string(),A.array(G4)]).optional(),stream:A.boolean().default(!1),tools:A.array(HK).optional(),tool_choice:WK.optional(),thinking:FK.optional(),output_config:A.object({effort:A.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough().optional(),metadata:A.object({user_id:A.string().min(1).optional()}).passthrough().optional()}).passthrough(),PK=new Set(["model","max_tokens","messages","system","stream","tools","tool_choice","thinking","output_config","metadata"]);function nu(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function un(n,t,i){return{ok:!1,message:n,...t!==void 0?{code:t}:{},...i!==void 0?{param:i}:{}}}function Yt(n,t,i,r="unsupported_parameter"){for(let s of Object.keys(n)){if(i.has(s))continue;return un(`Invalid request: ${t}.${s} is not supported`,r,`${t}.${s}`)}return}function pd(n){return nu(n)&&n.ok===!1&&typeof n.message==="string"}function XK(n){return n.issues.map((t)=>{return`${t.path.length>0?t.path.join("."):"request"}: ${t.message}`}).join(", ")}function Js(n,t){return{type:"text",text:n,path:t}}function CK(n){if(n===void 0)return[];if(typeof n==="string")return[Js(n,"system")];let t=[];for(let[i,r]of n.entries()){let s=`system.${i}`,f=Yt(r,s,new Set(["type","text"]));if(f)return f;if(r.type!=="text"||typeof r.text!=="string")return un(`Invalid request: system.${i} must be a text block`,"unsupported_instruction_projection",s);t.push(Js(r.text,`system.${i}.text`))}return t}function JK(n,t){if(typeof n==="string")return[Js(n,t)];if(!Array.isArray(n))return un(`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(!nu(s)||s.type!=="text"||typeof s.text!=="string")return un(`Invalid request: ${t}.${r} must be a text block`,"unsupported_tool_result_content",`${t}.${r}`);let f=Yt(s,`${t}.${r}`,new Set(["type","text"]));if(f)return f;i.push(Js(s.text,`${t}.${r}.text`))}return i}function QK(n,t){if(n.type==="thinking"){let i=Yt(n,t,new Set(["type","thinking","signature"]),"invalid_reasoning_replay");if(i)return i;if(typeof n.thinking!=="string"||typeof n.signature!=="string")return un(`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=Yt(n,t,new Set(["type","data"]),"invalid_reasoning_replay");if(i)return i;let r=n.data;if(typeof r!=="string")return un(`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 un(`Invalid request: ${t} contains invalid base64 redacted data`,"invalid_reasoning_replay",t)}}return un(`Invalid request: ${t} is not a reasoning block`,void 0,t)}function mK(n,t){let i=`messages.${t}`;for(let h of Object.keys(n))if(h!=="role"&&h!=="content")return un(`Invalid request: ${i}.${h} is not supported`,"unsupported_message_field",`${i}.${h}`);if(typeof n.content==="string")return{message:{role:n.role,content:[Js(n.content,`${i}.content`)],toolCalls:[],path:i}};let r=[],s=[],f;for(let[h,_]of n.content.entries()){let o=`${i}.content.${h}`;switch(_.type){case"text":{let w=Yt(_,o,new Set(["type","text"]));if(w)return w;if(typeof _.text!=="string")return un(`Invalid request: ${o}.text must be a string`,void 0,`${o}.text`);r.push(Js(_.text,`${o}.text`));break}case"image":{let w=Yt(_,o,new Set(["type","source"]));if(w)return w;if(!nu(_.source)||_.source.type!=="base64"||typeof _.source.data!=="string")return un(`Invalid request: ${o} requires a base64 image source`,"unsupported_image_source",o);let c=Yt(_.source,`${o}.source`,new Set(["type","data","media_type"]));if(c)return c;r.push({type:"image",data:_.source.data,...typeof _.source.media_type==="string"?{mediaType:_.source.media_type}:{},path:o});break}case"tool_use":{let w=Yt(_,o,new Set(["type","id","name","input"]));if(w)return w;if(typeof _.id!=="string"||typeof _.name!=="string")return un(`Invalid request: ${o} requires id and name`,"invalid_tool_history",o);s.push({id:_.id,name:_.name,input:_.input??{},path:o});break}case"tool_result":{let w=Yt(_,o,new Set(["type","tool_use_id","content","is_error"]));if(w)return w;if(typeof _.tool_use_id!=="string")return un(`Invalid request: ${o} requires tool_use_id`,"invalid_tool_history",o);let c=JK(_.content,`${o}.content`);if(pd(c))return c;r.push({type:"tool_result",toolCallId:_.tool_use_id,content:c,isError:_.is_error===!0,path:o});break}case"thinking":case"redacted_thinking":{if(n.role!=="assistant"||f!==void 0)return un(`Invalid request: ${o} is not a valid single assistant reasoning block`,"invalid_reasoning_replay",o);let w=QK(_,o);if("ok"in w)return w;f=w;break}default:return un(`Invalid request: unsupported content block ${_.type} at ${o}`,"unsupported_content_part",o)}}return{message:{role:n.role,content:r,toolCalls:s,path:i},...f!==void 0?{replay:f}:{}}}function zK(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 un(`Invalid request: tools.${r}.${f} is not supported`,"unsupported_tool_field",`tools.${r}.${f}`);if(i.has(s.name))return un(`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 KK(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 un(`Invalid request: tool call ${_.id} has no exact declaration for ${_.name}`,"missing_tool_declaration",_.path);if(r.has(_.id))return un(`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 o=r.get(_.toolCallId);if(o===void 0||o>=f||s.has(_.toolCallId))return un(`Invalid request: tool result ${_.toolCallId} has no earlier unique call`,"invalid_tool_history",_.path);s.add(_.toolCallId)}}return}function tu(n,t={},i="safe"){let r=YK.safeParse(n);if(!r.success){let y=r.error.issues[0]?.path;return un(`Invalid request: ${XK(r.error)}`,void 0,y&&y.length>0?y.join("."):void 0)}let s=r.data;for(let y of Object.keys(s))if(!PK.has(y))return un(`Invalid request: parameter ${y} is not supported`,"unsupported_parameter",y);if(t.requireMaxTokens===!0&&s.max_tokens===void 0)return un("Invalid request: max_tokens is required",void 0,"max_tokens");if(s.max_tokens!==void 0){let y=qi(s.model,s.max_tokens);if(!y.ok)return un(`Invalid request: max_tokens: ${y.message}`,y.code,"max_tokens")}if(s.tool_choice?.type==="any"||s.tool_choice?.type==="tool")return un(`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=Yt(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 un("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 un("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 un(`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 un(`Invalid request: thinking.${y} is not supported`,"unsupported_parameter",`thinking.${y}`)}if(s.metadata){let y=Yt(s.metadata,"metadata",new Set(["user_id"]));if(y)return y}let f=CK(s.system);if(pd(f))return f;if(f.length>0&&i==="safe")return un("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=zK(s.tools);if(pd(h))return h;let _=[],o=[];if(f.length>0)_.push({role:"system",content:f,toolCalls:[],path:"system"});for(let[y,R]of s.messages.entries()){let M=mK(R,y);if("ok"in M)return M;if(M.replay!==void 0)o.push({lookup:{kind:"anthropic-direct",content:M.replay},outputFingerprint:et({text:ii(M.message.content),toolCalls:M.message.toolCalls.map((E)=>({id:E.id,name:E.name,input:JSON.stringify(E.input)}))}),insertBeforeMessage:_.length,path:M.message.path});_.push(M.message)}let w=KK(_,h);if(w)return w;let c=new Set;for(let y of _){for(let R of y.toolCalls)c.add(R.id);for(let R of y.content)if(R.type==="tool_result")c.delete(R.toolCallId)}if(s.tool_choice?.type==="none"&&c.size>0)return un("Invalid request: tool_choice none cannot be used while tool calls await results","unsupported_tool_choice","tool_choice");let d=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:d,...s.thinking.budget_tokens!==void 0?{budgetTokens:s.thinking.budget_tokens}:{}}}:{},...s.max_tokens!==void 0?{outputTokenLimit:s.max_tokens}:{},reasoningReplays:o,includeEncryptedReasoning:!1};return{ok:!0,value:{source:s,body:u}}}import{randomUUID as H4}from"crypto";function VK(n,t){return`event: ${n}
|
|
361
|
+
`))},T=(L)=>{if(M||A===void 0||A==="consumer-cancel"||e.length>0)return;M=!0,L.close()},l=(L)=>{if(M||e.length===0)return T(L),!1;let m=L.desiredSize;if(m===null||m<=0)return!1;let q=e.shift();if(!q)return!1;return L.enqueue(q),T(L),!0},g=(L)=>{if(A!==void 0)return!1;return A=L,!0},O=()=>{t.deadline.removeEventListener("abort",K)},N=()=>{t.client.removeEventListener("abort",S)},F=(L,m,q)=>{if(!g(L))return;if(L==="consumer-cancel")e.length=0;Kn(O,N,()=>{if(L==="normal-complete")E("[DONE]");else if(L==="deadline"||L==="upstream-error"||L==="upstream-protocol-error"){let Q=q??(L==="deadline"?It("request_deadline_exceeded"):L==="upstream-protocol-error"?It("upstream_protocol_error"):mr(m));E(JSON.stringify({error:{message:Q.message,type:Q.disposition==="fatal"?"upstream_protocol_error":"upstream_error",code:Q.code}}))}},i,()=>{if(R)l(R)}),Mn(()=>_.cancel(m))},K=()=>{F("deadline",t.deadline.reason instanceof Error?t.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError"))},S=()=>{F("client-abort",t.client.reason instanceof Error?t.client.reason:new DOMException("Client closed request","AbortError"))},W=()=>{F("upstream-protocol-error",void 0,It("upstream_protocol_error"))},C=()=>{F("upstream-error",void 0,It("upstream_stream_incomplete"))},I=(L)=>{if(L.type==="started"){if(u!==void 0||w||L.model!==r.expectedModel)return!1;return u={id:L.conversationId,model:L.model,created:L.createdAt},!0}if(!u||w)return!1;if(L.type==="tool_call_delta"){let m=c.get(L.index)??{id:"",name:"",arguments:""};if(L.id!==void 0&&m.id.length>0&&L.id!==m.id||L.name!==void 0&&m.name.length>0&&L.name!==m.name)return!1;if(L.id!==void 0)m.id=L.id;if(L.name!==void 0)m.name=L.name;m.arguments+=L.arguments,c.set(L.index,m)}if(L.type==="completed"){let m=[...c.entries()].sort(([Q],[Z])=>Q-Z),q=m.length>0?"tool_calls":"stop";if(L.finishReason!==q||m.some(([Q,Z],b)=>Q!==b||Z.id.length===0||Z.name.length===0)||new Set(m.map(([,Q])=>Q.id)).size!==m.length)return!1}for(let m of pa(L,u,s))E(m);if(L.type==="completed")w=!0;return!0};return new Response(new ReadableStream({start(L){if(R=L,t.deadline.addEventListener("abort",K,{once:!0}),t.client.addEventListener("abort",S,{once:!0}),t.deadline.aborted)K();else if(t.client.aborted)S()},async pull(L){if(l(L))return;if(A!==void 0)return;try{while(A===void 0){let m=d.indexOf(`
|
|
362
|
+
`);if(m>=0){let Z=d.slice(0,m).trimEnd();if(d=d.slice(m+1),Z.length===0)continue;let b=Si(Z);if(!b||!I(b)){W();return}if(l(L))return;continue}let q=await _.read();if(A!==void 0)return;if(!q.done){d+=o.decode(q.value,{stream:!0});continue}d+=o.decode();let Q=d.trim();if(d="",Q.length>0){let Z=Si(Q);if(!Z||!I(Z)){W();return}}if(!w){C();return}F("normal-complete");return}}catch(m){if(A!==void 0)return;F("upstream-error",m)}},cancel(L){F("consumer-cancel",L)}}),{status:n.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}function P(n,t,i){return i===void 0?{ok:!1,code:n,message:t}:{ok:!1,code:n,message:t,param:i}}var nz=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"]),tz=["temperature","top_p","response_format","n","stop","seed","presence_penalty","frequency_penalty","logit_bias","logprobs","top_logprobs","modalities","audio","prediction","metadata","service_tier"];function qh(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ht(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return P("unsupported_parameter",`Chat field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function kh(n,t){return{type:"text",text:n,path:t}}function iz(n,t){if(typeof n==="string")return{ok:!0,value:[kh(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 _=ht(s,f,new Set(["type","text"]));if(!_.ok)return _;i.push(kh(s.text,`${f}.text`));break}case"image_url":{let _=ht(s,f,new Set(["type","image_url"]));if(!_.ok)return _;let o=ht(s.image_url,`${f}.image_url`,new Set(["url","detail"]));if(!o.ok)return o;if(s.image_url.detail!==void 0)return P("unsupported_parameter","Chat image detail cannot be represented by the Kiro upstream",`${f}.image_url.detail`);if(!s.image_url.url.startsWith("data:"))return P("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 _=ht(s,f,new Set(["type","source"]));if(!_.ok)return _;let o=ht(s.source,`${f}.source`,new Set(["type","data","media_type"]));if(!o.ok)return o;if(s.source.type!=="base64")return P("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 _=ht(s,f,new Set(["type","id","name","input"]));if(!_.ok)return _;i.push({type:"tool_use",id:s.id,name:s.name,input:s.input,path:f});break}case"tool_result":{let _=ht(s,f,new Set(["type","tool_use_id","content","is_error"]));if(!_.ok)return _;let o=rz(s.content,`${f}.content`);if(!o.ok)return o;i.push({type:"tool_result",toolCallId:s.tool_use_id,content:o.value,isError:s.is_error===!0,path:f});break}case"thinking":return P("unsupported_content_part",`Chat content part ${f} uses unsupported type thinking`,f)}}return{ok:!0,value:i}}function rz(n,t){if(typeof n==="string")return{ok:!0,value:[kh(n,t)]};if(!Array.isArray(n))return P("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(!qh(s)||s.type!=="text"||typeof s.text!=="string")return P("unsupported_tool_result_content",`Tool result ${t}.${r} must be a text block`,`${t}.${r}`);let f=ht(s,`${t}.${r}`,new Set(["type","text"]));if(!f.ok)return f;i.push(kh(s.text,`${t}.${r}.text`))}return{ok:!0,value:i}}function sz(n,t){let i=ht(n,t,new Set(["id","type","function"]));if(!i.ok)return i;let r=ht(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 P("invalid_tool_history",`Tool call ${t} contains invalid JSON arguments`,`${t}.function.arguments`)}}function fz(n){let t=[],i=new Set;for(let[r,s]of(n??[]).entries()){let f=`tools.${r}`,_=qh(s.function)?s.function:void 0;if(_!==void 0){let d=ht(s,f,new Set(["type","function"]));if(!d.ok)return d;let u=ht(_,`${f}.function`,new Set(["name","description","parameters","strict"]));if(!u.ok)return u;if(_.strict===!0)return P("unsupported_strict_tools","Chat function strict=true cannot be guaranteed by the Kiro upstream",`${f}.function.strict`)}else{let d=ht(s,f,new Set(["name","description","input_schema"]));if(!d.ok)return d}let o=typeof _?.name==="string"?_.name:s.name;if(typeof o!=="string"||o.length===0)return P("invalid_tool_declaration",`Tool declaration ${f} requires a name`,f);let h=o;if(i.has(h))return P("invalid_tool_declaration",`Duplicate tool declaration ${h}`,f);i.add(h);let e=typeof _?.description==="string"?_.description:typeof s.description==="string"?s.description:void 0,c=_!==void 0?qh(_.parameters)?_.parameters:{}:qh(s.input_schema)?s.input_schema:{};t.push({publicType:"function",name:h,wireName:h,...e!==void 0?{description:e}:{},inputSchema:c,..._!==void 0?{strict:!1}:{},path:f})}return{ok:!0,value:t}}function oz(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,_]of n.entries()){for(let o of _.toolCalls){if(!i.has(o.name))return P("missing_tool_declaration",`Tool call ${o.id} references ${o.name} without an exact tool declaration`,o.path);if(r.has(o.id))return P("invalid_tool_history",`Duplicate tool call id ${o.id}`,o.path);r.set(o.id,{name:o.name,index:f})}for(let o of _.content){if(o.type!=="tool_result")continue;let h=r.get(o.toolCallId);if(!h||h.index>=f||s.has(o.toolCallId))return P("invalid_tool_history",`Tool result ${o.toolCallId} has no earlier unique matching call`,o.path);s.add(o.toolCallId)}}return{ok:!0,value:void 0}}function Wg(n,t){for(let e of Object.keys(n))if(!nz.has(e))return P("unsupported_parameter",`Chat parameter ${e} is not supported`,e);if(n.stream_options!==void 0){let e=ht(n.stream_options,"stream_options",new Set(["include_usage"]));if(!e.ok)return e;if(!n.stream)return P("unsupported_parameter","Chat stream_options requires stream=true","stream_options")}for(let e of tz)if(n[e]!==void 0)return P("unsupported_parameter",`Chat parameter ${e} cannot be represented by the Kiro upstream`,e);if(n.store===!0)return P("unsupported_parameter","Chat parameter store=true is not supported","store");if(n.max_tokens!==void 0&&n.max_completion_tokens!==void 0)return P("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 e=pi(n.model,i);if(!e.ok)return P(e.code,e.message,r)}if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return P("unsupported_tool_choice","Required or named tool choice cannot be represented by the Kiro upstream","tool_choice");let s=fz(n.tools);if(!s.ok)return s;let f=[];if(n.parallel_tool_calls===!1&&n.tool_choice!=="none"&&s.value.length>0)return P("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");let _=[];for(let[e,c]of n.messages.entries()){let d=`messages.${e}`,u=c.role==="assistant"?new Set(["role","content","tool_calls","reasoning_content"]):c.role==="tool"?new Set(["role","content","tool_call_id"]):new Set(["role","content"]);for(let E of Object.keys(c))if(!u.has(E))return P("unsupported_message_field",`Chat message field ${d}.${E} is not supported`,`${d}.${E}`);if(t==="safe"&&(c.role==="system"||c.role==="developer"))return P("unsupported_instruction_projection",`${c.role} messages cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,d);let w=iz(c.content,`${d}.content`);if(!w.ok)return w;let A=[];if(c.role==="assistant")for(let[E,T]of(c.tool_calls??[]).entries()){let l=sz(T,`${d}.tool_calls.${E}`);if(!l.ok)return l;A.push(l.value)}let R=w.value;if(c.role==="tool"){let E=R.filter((T)=>T.type==="text");if(E.length!==R.length)return P("unsupported_tool_result_content",`Chat tool message ${d} may contain text only`,`${d}.content`);R=[{type:"tool_result",toolCallId:c.tool_call_id,content:E,isError:!1,path:d}]}let M={role:c.role,content:R,toolCalls:A,path:d};if(c.role==="assistant"&&c.reasoning_content!==void 0)_.push({lookup:{kind:"chat-hash",reasoningText:c.reasoning_content},outputFingerprint:Lt({text:oi(R),toolCalls:(c.tool_calls??[]).map((E)=>({id:E.id,name:E.function.name,input:E.function.arguments}))}),insertBeforeMessage:f.length,path:`${d}.reasoning_content`});f.push(M)}let o=oz(f,s.value);if(!o.ok)return o;let h=new Set;for(let e of f){for(let c of e.toolCalls)h.add(c.id);for(let c of e.content)if(c.type==="tool_result")h.delete(c.toolCallId)}if(n.tool_choice==="none"&&h.size>0)return P("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:_,includeEncryptedReasoning:!1,...n.prompt_cache_key!==void 0?{promptCacheKey:n.prompt_cache_key}:{}}}}var Cr=y.record(y.unknown()),_z=y.record(y.string()).superRefine((n,t)=>{let i=Object.entries(n);if(i.length>16)t.addIssue({code:y.ZodIssueCode.custom,message:"metadata must contain at most 16 entries"});for(let[r,s]of i){if(r.length>64)t.addIssue({code:y.ZodIssueCode.custom,message:"metadata keys must contain at most 64 characters",path:[r]});if(s.length>512)t.addIssue({code:y.ZodIssueCode.custom,message:"metadata values must contain at most 512 characters",path:[r]})}}),hz=y.object({type:y.literal("text"),text:y.string()}).passthrough(),ez=y.object({type:y.literal("image_url"),image_url:y.object({url:y.string(),detail:y.string().optional()}).passthrough()}).passthrough(),cz=y.object({type:y.literal("image"),source:y.object({type:y.string(),data:y.string(),media_type:y.string().optional()}).passthrough()}).passthrough(),dz=y.object({type:y.literal("tool_result"),tool_use_id:y.string().min(1),content:y.unknown()}).passthrough(),uz=y.object({type:y.literal("tool_use"),id:y.string().min(1),name:y.string().min(1),input:y.unknown()}).passthrough(),wz=y.object({type:y.literal("thinking"),thinking:y.string().optional(),text:y.string().optional()}).passthrough(),yz=y.discriminatedUnion("type",[hz,ez,cz,dz,uz,wz]),Mo=y.union([y.string(),y.array(yz)]);function Fg(n){try{return JSON.parse(n),!0}catch(t){if(t instanceof SyntaxError)return!1;throw t}}function Az(n){return n.trim().length===0?"{}":n}var Rz=y.object({id:y.string().min(1),type:y.literal("function"),function:y.object({name:y.string().min(1),arguments:y.string().refine(Fg,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),Mz=y.object({role:y.literal("system"),content:Mo}).passthrough(),Ez=y.object({role:y.literal("developer"),content:Mo}).passthrough(),lz=y.object({role:y.literal("user"),content:Mo}).passthrough(),Tz=y.object({role:y.literal("assistant"),content:Mo.nullable().optional(),tool_calls:y.array(Rz).min(1).optional(),reasoning_content:y.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"}),gz=y.object({role:y.literal("tool"),content:Mo,tool_call_id:y.string().min(1)}).passthrough(),Oz=y.union([Mz,Ez,lz,Tz,gz]),Lz=y.object({type:y.literal("function"),function:y.object({name:y.string().min(1),description:y.string().optional(),parameters:Cr.optional()}).passthrough()}).passthrough(),Iz=y.object({name:y.string().min(1),description:y.string().optional(),input_schema:Cr.optional()}).passthrough(),Sz=y.object({model:y.string().trim().min(1),stream:y.boolean().default(!1),stream_options:y.object({include_usage:y.boolean().optional()}).passthrough().optional(),messages:y.array(Oz).min(1),tools:y.array(y.union([Lz,Iz])).optional(),user:y.string().optional(),prompt_cache_key:y.string().optional(),reasoning_effort:y.enum(["low","medium","high","xhigh","max"]).optional(),tool_choice:y.union([y.enum(["auto","none","required"]),y.object({type:y.literal("function"),function:y.object({name:y.string().min(1)}).passthrough()}).passthrough()]).optional(),parallel_tool_calls:y.boolean().optional(),max_tokens:y.number().int().positive().optional(),max_completion_tokens:y.number().int().positive().optional(),temperature:y.number().optional(),top_p:y.number().optional(),response_format:y.unknown().optional(),n:y.number().int().positive().optional(),stop:y.unknown().optional(),seed:y.number().int().optional(),presence_penalty:y.number().optional(),frequency_penalty:y.number().optional(),logit_bias:y.unknown().optional(),logprobs:y.boolean().optional(),top_logprobs:y.number().int().optional(),modalities:y.unknown().optional(),audio:y.unknown().optional(),prediction:y.unknown().optional(),store:y.boolean().optional(),metadata:y.unknown().optional(),service_tier:y.unknown().optional()}).passthrough(),bz=y.object({type:y.literal("input_text"),text:y.string()}).passthrough(),Nz=y.object({type:y.literal("output_text"),text:y.string()}).passthrough(),Uz=y.object({type:y.literal("input_image"),image_url:y.string()}).passthrough(),$z=y.object({type:y.literal("input_file"),file_data:y.string().optional(),file_id:y.string().optional(),filename:y.string().min(1).optional()}).passthrough(),Dz=y.object({type:y.literal("encrypted_content"),encrypted_content:y.string()}).passthrough(),Bz=new Set(["input_text","output_text","input_image","input_file","encrypted_content"]),Gz=y.object({type:y.string()}).passthrough().refine((n)=>!Bz.has(n.type),{message:"known content parts must have a valid payload"}),Cg=y.union([bz,Nz,Uz,$z,Dz,Gz]),mz=y.object({type:y.literal("message").optional(),id:y.string().optional(),status:y.string().optional(),role:y.enum(["system","developer","user","assistant"]),content:y.union([y.string(),y.array(Cg)])}).passthrough(),Hz=y.object({type:y.literal("agent_message"),author:y.string().min(1),recipient:y.string().min(1),content:y.array(Cg)}).passthrough(),Wz=y.object({type:y.literal("function_call"),id:y.string().optional(),status:y.string().optional(),call_id:y.string().min(1),namespace:y.string().min(1).optional(),name:y.string().min(1),arguments:y.string().transform(Az).refine(Fg,"function arguments must contain valid JSON")}).passthrough(),Fz=y.object({type:y.literal("custom_tool_call"),id:y.string().optional(),status:y.string().optional(),call_id:y.string().min(1),namespace:y.string().min(1).optional(),name:y.string().min(1),input:y.string()}).passthrough(),Pg=y.union([y.string(),y.array(y.object({type:y.string(),text:y.string().optional()}).passthrough())]),Cz=y.object({type:y.literal("function_call_output"),id:y.string().optional(),status:y.string().optional(),call_id:y.string().min(1),output:Pg}).passthrough(),Pz=y.object({type:y.literal("custom_tool_call_output"),id:y.string().optional(),status:y.string().optional(),call_id:y.string().min(1),output:Pg}).passthrough(),Yg=y.object({type:y.literal("function"),name:y.string().min(1),description:y.string().optional(),parameters:Cr.optional(),strict:y.boolean().optional()}).passthrough(),Zh=y.object({type:y.literal("custom"),name:y.string().min(1),description:y.string().optional(),format:y.object({type:y.literal("grammar"),syntax:y.string().min(1),definition:y.string()}).passthrough().optional()}).passthrough(),Yz=y.union([Yg,Zh]),Xz=y.object({type:y.literal("namespace"),name:y.string().min(1),description:y.string().optional(),tools:y.array(Yz)}).passthrough(),Jz=y.object({type:y.literal("function"),name:y.string().min(1),description:y.string().optional(),parameters:Cr.optional(),inputSchema:Cr.optional(),strict:y.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),Qz=y.object({type:y.literal("function").optional(),name:y.string().min(1),description:y.string().optional(),parameters:Cr.optional(),inputSchema:Cr.optional(),strict:y.boolean().optional()}).passthrough().transform((n)=>({...n,type:"function",...n.parameters!==void 0?{parameters:n.parameters}:n.inputSchema!==void 0?{parameters:n.inputSchema}:{}})),az=y.union([Qz,Zh]),zz=y.object({type:y.literal("namespace"),name:y.string().min(1),description:y.string().optional(),tools:y.array(az)}).passthrough().transform((n)=>({...n,type:"namespace"})),Kz=new Set(["function","custom","namespace"]),Xg=y.object({type:y.string()}).passthrough().refine((n)=>!Kz.has(n.type),{message:"known tools must have a valid payload"}),xz=y.union([Yg,Zh,Xz]),Vz=y.union([xz,Xg]),jz=y.union([Jz,Zh,zz,Xg]),qz=y.object({type:y.literal("additional_tools"),role:y.string().optional(),tools:y.array(jz)}).passthrough(),kz=y.object({type:y.literal("summary_text"),text:y.string()}).passthrough(),Zz=y.object({type:y.literal("reasoning_text"),reasoning_text:y.string()}).passthrough(),vz=y.object({type:y.literal("reasoning"),id:y.string().optional(),status:y.string().optional(),summary:y.array(kz).nullable().optional(),content:y.array(Zz).nullable().optional(),encrypted_content:y.string().nullable().optional()}).passthrough(),pz=new Set(["message","agent_message","function_call","custom_tool_call","function_call_output","custom_tool_call_output","additional_tools","reasoning"]),nK=y.object({type:y.string()}).passthrough().refine((n)=>!pz.has(n.type),{message:"known input items must have a valid payload"}),tK=y.union([mz,Hz,Wz,Fz,Cz,Pz,qz,vz,nK]),iK=y.object({effort:y.enum(["none","minimal","low","medium","high","xhigh","max"]).optional(),summary:y.unknown().optional()}).passthrough(),rK=y.object({model:y.string().trim().min(1),input:y.union([y.string(),y.array(tK)]),instructions:y.string().optional(),stream:y.boolean().default(!1),tools:y.array(Vz).optional(),tool_choice:y.union([y.enum(["auto","none","required"]),y.record(y.unknown())]).optional(),parallel_tool_calls:y.boolean().optional(),reasoning:iK.nullable().optional(),include:y.array(y.string()).optional(),store:y.boolean().optional(),text:y.unknown().optional(),service_tier:y.unknown().optional(),max_output_tokens:y.number().int().positive().optional(),temperature:y.number().optional(),top_p:y.number().optional(),truncation:y.unknown().optional(),background:y.boolean().optional(),max_tool_calls:y.number().int().positive().optional(),prompt_cache_key:y.string().optional(),metadata:_z.optional(),client_metadata:y.unknown().optional(),previous_response_id:y.string().optional(),conversation:y.unknown().optional()}).passthrough();function Jg(n){let t=Sz.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:tn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}function Qg(n){let t=rK.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:tn(400,`Invalid request: ${i}`,"invalid_request_error","invalid_request")}}import{createHash as Kg}from"crypto";function sK(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function du(n){if(n===null||typeof n!=="object")return JSON.stringify(n);if(Array.isArray(n))return`[${n.map(du).join(",")}]`;return`{${Object.entries(n).filter(([,i])=>i!==void 0).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${JSON.stringify(i)}:${du(r)}`).join(",")}}`}function bi(n,t,i,r){return{keyHash:Kg("sha256").update("kiro-provider-session-affinity-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(du(r)).digest("hex"),source:i}}function ag(n,t,i,r){return Kg("sha256").update("kiro-provider-output-lineage-v1\x00").update(n).update("\x00").update(t).update("\x00").update(i).update("\x00").update(r).digest("hex")}function qs(n,t){if(!t)return;let i=n.protocol==="chat-completions"?"chat":n.protocol==="anthropic-messages"?"anthropic":"responses",r=`${i}.history_lineage`,s=xT(n);return{...s!==void 0?{lookupKeyHash:ag(t,i,n.model,s)}:{},source:r,outputKeyHash:(f)=>ag(t,i,n.model,f)}}function zg(n,t){if(!sK(n))return;let i=n[t];return typeof i==="string"&&i.length>0?i:void 0}function fK(n){if(typeof n==="string")return{role:"user",content:n};return n.find((i)=>i.type==="message"&&i.role==="user")??n[0]}function oK(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function _K(n){return n.messages.find((t)=>t.role==="user")??n.messages[0]}function xg(n,t,i="explicit-only"){if(!t)return;for(let s of["zuno_session_id","kiro_provider_session_id"]){let f=zg(n.metadata,s);if(f!==void 0){let _=`responses.metadata.${s}`;return bi(t,"responses",_,f)}}for(let s of["thread_id","session_id","conversation_id"]){let f=zg(n.client_metadata,s);if(f!==void 0){let _=`responses.client_metadata.${s}`;return bi(t,"responses",_,f)}}if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return bi(t,"responses","responses.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=fK(n.input);return r===void 0?void 0:bi(t,"responses","responses.initial_input",r)}function Vg(n,t,i="explicit-only"){if(!t)return;if(n.prompt_cache_key&&n.prompt_cache_key.length>0)return bi(t,"chat","chat.prompt_cache_key",n.prompt_cache_key);if(i!=="legacy-initial-input")return;let r=oK(n);if(r===void 0)return;if(n.user&&n.user.length>0)return bi(t,"chat","chat.user_and_initial_input",{user:n.user,initial:r});return bi(t,"chat","chat.initial_input",r)}function jg(n,t,i="explicit-only"){if(!t)return;if(i!=="legacy-initial-input")return;let r=_K(n);if(r===void 0)return;let s=n.metadata?.user_id;if(s)return bi(t,"anthropic","anthropic.user_and_initial_input",{userId:s,initial:r});return bi(t,"anthropic","anthropic.initial_input",r)}class wu extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function uu(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function hK(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,_,o=new Promise((e,c)=>{_=c}),h=()=>{let e=uu(i.combined);_?.(e),Mn(()=>r.cancel(e))};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw uu(i.combined);let d=await Promise.race([r.read(),o]);if(i.combined.aborted)throw uu(i.combined);if(d.done)break;if(f+=d.value.byteLength,f>t)throw new wu(t);s.push(d.value)}let e=new Uint8Array(f),c=0;for(let d of s)e.set(d,c),c+=d.byteLength;return{ok:!0,text:new TextDecoder().decode(e)}}catch(e){if(e instanceof wu)return Mn(()=>r.cancel(e)),{ok:!1,response:tn(413,e.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return Mn(()=>r.cancel(e)),{ok:!1,response:tn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return Mn(()=>r.cancel(e)),{ok:!1,response:tn(499,"Client closed request","request_aborted","client_disconnected")};throw e}finally{i.combined.removeEventListener("abort",h)}}async function qg(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]),_={combined:f,deadline:r.signal,client:n.signal},o=await hK(n,t.max_request_body_bytes,_);if(!o.ok)return clearTimeout(s),o.response;let h;try{h=JSON.parse(o.text)}catch(M){if(clearTimeout(s),!(M instanceof SyntaxError))throw M;return tn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let e=Jg(h);if(!e.ok)return clearTimeout(s),e.response;let c=Vg(e.value,i.tenantId,t.session_affinity_mode),d=Wg(e.value,t.protocol_projection_mode);if(!d.ok)return V("warn","protocol_projection_rejected",{protocol:"chat-completions",projection_mode:t.protocol_projection_mode,code:d.code,param:d.param}),clearTimeout(s),tn(400,d.message,"invalid_request_error",d.code,d.param);let u=qs(d.value,i.tenantId),w,A=!1,R=()=>{Kn(()=>clearTimeout(s),()=>w?.restore())};try{w=i.createRequestIdleTimeoutLease?.(),w?.disable();let M=await(i.runPipeline??js)({body:d.value,model:e.value.model,stream:e.value.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...i.quotaRechecker?{quotaRechecker:i.quotaRechecker}:{},...c?{affinity:c}:{},...u?{lineage:u}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},...i.modelCapabilities?{modelCapabilities:i.modelCapabilities}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return Mn(()=>M.body?.cancel()),tn(499,"Client closed request","request_aborted","client_disconnected");let E=M.headers.get("Content-Type")??"";if(!M.ok)return M;if(!e.value.stream){if(!E.includes(zs))return Mn(()=>M.body?.cancel()),tn(500,"Pipeline returned an unsupported non-streaming response","internal_error","invalid_pipeline_response");let l=xs(await M.json());if(!l||l.model!==e.value.model)return tn(500,"Pipeline returned an invalid canonical completion","internal_error","invalid_pipeline_response");return mg(l)}if(!E.includes(Ks))return Mn(()=>M.body?.cancel()),tn(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let T=Hg(M,_,R,{expectedModel:e.value.model,includeUsage:e.value.stream_options?.include_usage===!0});return A=!0,T}finally{if(!A)R()}}function kg(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var Zg=y.object({type:y.string().min(1)}).passthrough(),eK=y.object({role:y.enum(["user","assistant"]),content:y.union([y.string(),y.array(Zg)])}).passthrough(),cK=y.object({name:y.string().min(1),description:y.string().optional(),input_schema:y.record(y.unknown()).optional()}).passthrough(),dK=y.object({type:y.enum(["auto","any","tool","none"]),name:y.string().min(1).optional(),disable_parallel_tool_use:y.boolean().optional()}).passthrough().refine((n)=>n.type!=="tool"||n.name!==void 0,{message:"tool_choice.name is required when tool_choice.type is tool"}),uK=y.object({type:y.enum(["enabled","adaptive","disabled"]),budget_tokens:y.number().int().positive().optional()}).passthrough(),wK=y.object({model:y.string().min(1),max_tokens:y.number().int().positive().optional(),messages:y.array(eK).min(1),system:y.union([y.string(),y.array(Zg)]).optional(),stream:y.boolean().default(!1),tools:y.array(cK).optional(),tool_choice:dK.optional(),thinking:uK.optional(),output_config:y.object({effort:y.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough().optional(),metadata:y.object({user_id:y.string().min(1).optional()}).passthrough().optional()}).passthrough(),yK=new Set(["model","max_tokens","messages","system","stream","tools","tool_choice","thinking","output_config","metadata"]);function Au(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function An(n,t,i){return{ok:!1,message:n,...t!==void 0?{code:t}:{},...i!==void 0?{param:i}:{}}}function Xt(n,t,i,r="unsupported_parameter"){for(let s of Object.keys(n)){if(i.has(s))continue;return An(`Invalid request: ${t}.${s} is not supported`,r,`${t}.${s}`)}return}function yu(n){return Au(n)&&n.ok===!1&&typeof n.message==="string"}function AK(n){return n.issues.map((t)=>{return`${t.path.length>0?t.path.join("."):"request"}: ${t.message}`}).join(", ")}function ks(n,t){return{type:"text",text:n,path:t}}function RK(n){if(n===void 0)return[];if(typeof n==="string")return[ks(n,"system")];let t=[];for(let[i,r]of n.entries()){let s=`system.${i}`,f=Xt(r,s,new Set(["type","text"]));if(f)return f;if(r.type!=="text"||typeof r.text!=="string")return An(`Invalid request: system.${i} must be a text block`,"unsupported_instruction_projection",s);t.push(ks(r.text,`system.${i}.text`))}return t}function MK(n,t){if(typeof n==="string")return[ks(n,t)];if(!Array.isArray(n))return An(`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(!Au(s)||s.type!=="text"||typeof s.text!=="string")return An(`Invalid request: ${t}.${r} must be a text block`,"unsupported_tool_result_content",`${t}.${r}`);let f=Xt(s,`${t}.${r}`,new Set(["type","text"]));if(f)return f;i.push(ks(s.text,`${t}.${r}.text`))}return i}function EK(n,t){if(n.type==="thinking"){let i=Xt(n,t,new Set(["type","thinking","signature"]),"invalid_reasoning_replay");if(i)return i;if(typeof n.thinking!=="string"||typeof n.signature!=="string")return An(`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=Xt(n,t,new Set(["type","data"]),"invalid_reasoning_replay");if(i)return i;let r=n.data;if(typeof r!=="string")return An(`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 An(`Invalid request: ${t} contains invalid base64 redacted data`,"invalid_reasoning_replay",t)}}return An(`Invalid request: ${t} is not a reasoning block`,void 0,t)}function lK(n,t){let i=`messages.${t}`;for(let _ of Object.keys(n))if(_!=="role"&&_!=="content")return An(`Invalid request: ${i}.${_} is not supported`,"unsupported_message_field",`${i}.${_}`);if(typeof n.content==="string")return{message:{role:n.role,content:[ks(n.content,`${i}.content`)],toolCalls:[],path:i}};let r=[],s=[],f;for(let[_,o]of n.content.entries()){let h=`${i}.content.${_}`;switch(o.type){case"text":{let e=Xt(o,h,new Set(["type","text"]));if(e)return e;if(typeof o.text!=="string")return An(`Invalid request: ${h}.text must be a string`,void 0,`${h}.text`);r.push(ks(o.text,`${h}.text`));break}case"image":{let e=Xt(o,h,new Set(["type","source"]));if(e)return e;if(!Au(o.source)||o.source.type!=="base64"||typeof o.source.data!=="string")return An(`Invalid request: ${h} requires a base64 image source`,"unsupported_image_source",h);let c=Xt(o.source,`${h}.source`,new Set(["type","data","media_type"]));if(c)return c;r.push({type:"image",data:o.source.data,...typeof o.source.media_type==="string"?{mediaType:o.source.media_type}:{},path:h});break}case"tool_use":{let e=Xt(o,h,new Set(["type","id","name","input"]));if(e)return e;if(typeof o.id!=="string"||typeof o.name!=="string")return An(`Invalid request: ${h} requires id and name`,"invalid_tool_history",h);s.push({id:o.id,name:o.name,input:o.input??{},path:h});break}case"tool_result":{let e=Xt(o,h,new Set(["type","tool_use_id","content","is_error"]));if(e)return e;if(typeof o.tool_use_id!=="string")return An(`Invalid request: ${h} requires tool_use_id`,"invalid_tool_history",h);let c=MK(o.content,`${h}.content`);if(yu(c))return c;r.push({type:"tool_result",toolCallId:o.tool_use_id,content:c,isError:o.is_error===!0,path:h});break}case"thinking":case"redacted_thinking":{if(n.role!=="assistant"||f!==void 0)return An(`Invalid request: ${h} is not a valid single assistant reasoning block`,"invalid_reasoning_replay",h);let e=EK(o,h);if("ok"in e)return e;f=e;break}default:return An(`Invalid request: unsupported content block ${o.type} at ${h}`,"unsupported_content_part",h)}}return{message:{role:n.role,content:r,toolCalls:s,path:i},...f!==void 0?{replay:f}:{}}}function TK(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 An(`Invalid request: tools.${r}.${f} is not supported`,"unsupported_tool_field",`tools.${r}.${f}`);if(i.has(s.name))return An(`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 gK(n,t){let i=new Set(t.map((f)=>f.wireName)),r=new Map,s=new Set;for(let[f,_]of n.entries()){for(let o of _.toolCalls){if(!i.has(o.name))return An(`Invalid request: tool call ${o.id} has no exact declaration for ${o.name}`,"missing_tool_declaration",o.path);if(r.has(o.id))return An(`Invalid request: duplicate tool call id ${o.id}`,"invalid_tool_history",o.path);r.set(o.id,f)}for(let o of _.content){if(o.type!=="tool_result")continue;let h=r.get(o.toolCallId);if(h===void 0||h>=f||s.has(o.toolCallId))return An(`Invalid request: tool result ${o.toolCallId} has no earlier unique call`,"invalid_tool_history",o.path);s.add(o.toolCallId)}}return}function Ru(n,t={},i="safe"){let r=wK.safeParse(n);if(!r.success){let w=r.error.issues[0]?.path;return An(`Invalid request: ${AK(r.error)}`,void 0,w&&w.length>0?w.join("."):void 0)}let s=r.data;for(let w of Object.keys(s))if(!yK.has(w))return An(`Invalid request: parameter ${w} is not supported`,"unsupported_parameter",w);if(t.requireMaxTokens===!0&&s.max_tokens===void 0)return An("Invalid request: max_tokens is required",void 0,"max_tokens");if(s.max_tokens!==void 0){let w=pi(s.model,s.max_tokens);if(!w.ok)return An(`Invalid request: max_tokens: ${w.message}`,w.code,"max_tokens")}if(s.tool_choice?.type==="any"||s.tool_choice?.type==="tool")return An(`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 w=Xt(s.tool_choice,"tool_choice",new Set(["type","name","disable_parallel_tool_use"]));if(w)return w;if(s.tool_choice.name!==void 0)return An("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 An("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 w of Object.keys(s.output_config))if(w!=="effort")return An(`Invalid request: output_config.${w} is not supported`,"unsupported_parameter",`output_config.${w}`)}if(s.thinking){for(let w of Object.keys(s.thinking))if(w!=="type"&&w!=="budget_tokens")return An(`Invalid request: thinking.${w} is not supported`,"unsupported_parameter",`thinking.${w}`)}if(s.metadata){let w=Xt(s.metadata,"metadata",new Set(["user_id"]));if(w)return w}let f=RK(s.system);if(yu(f))return f;if(f.length>0&&i==="safe")return An("Invalid request: system cannot be projected losslessly to Kiro in safe mode; enable legacy-user-prefix explicitly to migrate","unsupported_instruction_projection","system");let _=TK(s.tools);if(yu(_))return _;let o=[],h=[];if(f.length>0)o.push({role:"system",content:f,toolCalls:[],path:"system"});for(let[w,A]of s.messages.entries()){let R=lK(A,w);if("ok"in R)return R;if(R.replay!==void 0)h.push({lookup:{kind:"anthropic-direct",content:R.replay},outputFingerprint:Lt({text:oi(R.message.content),toolCalls:R.message.toolCalls.map((M)=>({id:M.id,name:M.name,input:JSON.stringify(M.input)}))}),insertBeforeMessage:o.length,path:R.message.path});o.push(R.message)}let e=gK(o,_);if(e)return e;let c=new Set;for(let w of o){for(let A of w.toolCalls)c.add(A.id);for(let A of w.content)if(A.type==="tool_result")c.delete(A.toolCallId)}if(s.tool_choice?.type==="none"&&c.size>0)return An("Invalid request: tool_choice none cannot be used while tool calls await results","unsupported_tool_choice","tool_choice");let d=s.thinking?.type==="enabled"||s.thinking?.type==="adaptive",u={canonicalVersion:1,protocol:"anthropic-messages",projectionMode:i,model:s.model,stream:s.stream,messages:o,tools:_,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:d,...s.thinking.budget_tokens!==void 0?{budgetTokens:s.thinking.budget_tokens}:{}}}:{},...s.max_tokens!==void 0?{outputTokenLimit:s.max_tokens}:{},reasoningReplays:h,includeEncryptedReasoning:!1};return{ok:!0,value:{source:s,body:u}}}import{randomUUID as vg}from"crypto";function vh(n,t=n.message){return{message:t,type:n.disposition==="retryable"?"overloaded_error":"api_error"}}function OK(n,t){return`event: ${n}
|
|
363
363
|
data: ${JSON.stringify(t)}
|
|
364
364
|
|
|
365
|
-
`}function
|
|
366
|
-
`);if(
|
|
365
|
+
`}function LK(n){return{input_tokens:n.inputTokens,output_tokens:n.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}}function Mu(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 pg(n,t){let i=[],r=n.reasoning;if(r?.redactedContent!==void 0&&(r.text!==void 0||r.signature!==void 0))return Wn(502,"Upstream mixed visible and redacted reasoning payloads","api_error");if(r?.redactedContent!==void 0)i.push({type:"redacted_thinking",data:r.redactedContent});else if(r?.text!==void 0||r?.signature!==void 0){if(!r.text||!r.signature)return Wn(502,"Upstream returned incomplete signed reasoning metadata","api_error");i.push({type:"thinking",thinking:r.text,signature:r.signature})}if(n.text.length>0)i.push({type:"text",text:n.text});for(let s of n.toolCalls){let f=Mu(s.input);if(!f)return Wn(502,`Upstream returned invalid JSON arguments for tool ${s.name}`,"api_error");i.push({type:"tool_use",id:s.id,name:s.name,input:f})}return Response.json({id:`msg_${vg()}`,type:"message",role:"assistant",model:t,content:i,stop_reason:n.finishReason==="tool_calls"?"tool_use":"end_turn",stop_sequence:null,usage:LK(n.usage)})}function n2(n,t){let r=(n.body??new ReadableStream({start:(b)=>b.close()})).getReader(),s=new TextEncoder,f=new TextDecoder,_=`msg_${vg()}`,o=new Map,h="",e=0,c,d,u=!1,w=!1,A,R=!1,M=!1,E=!1,T=!1,l,g,O=(b,D)=>{g?.enqueue(s.encode(OK(b,D)))},N=(b)=>{if(l!==void 0)return!1;return l=b,!0},F=()=>{t.signals.deadline.removeEventListener("abort",I)},K=()=>{t.signals.client.removeEventListener("abort",L)},S=(b,D,Dn)=>{if(!N(b))return;Kn(F,K,()=>{if(!Dn||!g)return;g.enqueue(s.encode(by(Dn.message,Dn.type??"api_error")))},()=>{if(b!=="consumer-cancel")g?.close()},t.finalize),Mn(()=>r.cancel(D))},W=(b)=>{S("upstream-protocol-error",void 0,vh(It("upstream_protocol_error"),b))},C=()=>{S("upstream-error",void 0,vh(It("upstream_stream_incomplete")))},I=()=>{let b=t.signals.deadline.reason instanceof Error?t.signals.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");S("deadline",b,vh(It("request_deadline_exceeded")))},L=()=>{let b=t.signals.client.reason instanceof Error?t.signals.client.reason:new DOMException("Client closed request","AbortError");S("client-abort",b)},m=()=>{if(!R||T||c===void 0)return;T=!0,O("content_block_stop",{type:"content_block_stop",index:c})},q=()=>{if(!u||w||d===void 0)return;if(A!==void 0)O("content_block_delta",{type:"content_block_delta",index:d,delta:{type:"signature_delta",signature:A}}),A=void 0;w=!0,O("content_block_stop",{type:"content_block_stop",index:d})},Q=(b)=>{switch(b.type){case"started":case"completed":return!1;case"reasoning_delta":{if(!u)d=e,e+=1,u=!0,O("content_block_start",{type:"content_block_start",index:d,content_block:{type:"thinking",thinking:"",signature:""}});return O("content_block_delta",{type:"content_block_delta",index:d,delta:{type:"thinking_delta",thinking:b.text}}),!0}case"reasoning_signature":if(u&&!w&&d!==void 0)O("content_block_delta",{type:"content_block_delta",index:d,delta:{type:"signature_delta",signature:b.signature}});else A=b.signature;return!1;case"reasoning_redacted":{if(u||A!==void 0)return W("Upstream mixed visible and redacted reasoning payloads"),!1;let D=e;return e+=1,O("content_block_start",{type:"content_block_start",index:D,content_block:{type:"redacted_thinking",data:b.data}}),O("content_block_stop",{type:"content_block_stop",index:D}),!0}case"reasoning_encrypted":return!1;case"text_delta":{if(q(),!R)c=e,e+=1,R=!0,O("content_block_start",{type:"content_block_start",index:c,content_block:{type:"text",text:""}});return O("content_block_delta",{type:"content_block_delta",index:c,delta:{type:"text_delta",text:b.text}}),!0}case"tool_call_delta":{q();let D=o.get(b.index)??{id:"",name:"",arguments:""};if(D.id.length===0&&b.id!==void 0)D.id=b.id;if(D.name.length===0&&b.name!==void 0)D.name=b.name;return D.arguments+=b.arguments,o.set(b.index,D),!1}}},Z=(b,D)=>{let Dn=[...o.entries()].sort(([Bn],[St])=>Bn-St),cn=Dn.length>0?"tool_calls":"stop";if(D!==cn){W("Upstream finish reason does not match its output");return}if(Dn.some(([,Bn])=>{return Bn.id.length===0||Bn.name.length===0||!Mu(Bn.arguments)})){W("Malformed upstream tool call");return}m(),q();for(let[,Bn]of Dn){let St=e;if(e+=1,!Mu(Bn.arguments)||Bn.id.length===0||Bn.name.length===0){W("Malformed upstream tool call");return}if(O("content_block_start",{type:"content_block_start",index:St,content_block:{type:"tool_use",id:Bn.id,name:Bn.name,input:{}}}),Bn.arguments.length>0)O("content_block_delta",{type:"content_block_delta",index:St,delta:{type:"input_json_delta",partial_json:Bn.arguments}});O("content_block_stop",{type:"content_block_stop",index:St})}O("message_delta",{type:"message_delta",delta:{stop_reason:Dn.length>0?"tool_use":"end_turn",stop_sequence:null},usage:{output_tokens:b.outputTokens}}),O("message_stop",{type:"message_stop"}),S("normal-complete")};return new Response(new ReadableStream({start(b){if(g=b,O("message_start",{type:"message_start",message:{id:_,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",I,{once:!0}),t.signals.client.addEventListener("abort",L,{once:!0}),t.signals.deadline.aborted)I();else if(t.signals.client.aborted)L()},async pull(){if(l!==void 0)return;try{while(l===void 0){let b=h.indexOf(`
|
|
366
|
+
`);if(b>=0){let cn=h.slice(0,b).trimEnd();if(h=h.slice(b+1),cn.length===0)continue;let dt=Si(cn);if(!dt){W("Malformed upstream stream");return}if(dt.type==="started"){if(M||E||dt.model!==t.model){W("Malformed upstream stream start");return}M=!0;continue}if(!M||E){W("Malformed upstream event ordering");return}if(dt.type==="completed"){E=!0,Z(dt.usage,dt.finishReason);return}let Bn=Q(dt);if(l!==void 0)return;if(Bn)return;continue}let D=await r.read();if(l!==void 0)return;if(!D.done){h+=f.decode(D.value,{stream:!0});continue}h+=f.decode();let Dn=h.trim();if(h="",Dn.length>0){let cn=Si(Dn);if(!cn){W("Malformed upstream stream");return}if(cn.type==="started"){if(M||E||cn.model!==t.model){W("Malformed upstream stream start");return}M=!0}else if(!M||E){W("Malformed upstream event ordering");return}else if(cn.type==="completed"){E=!0,Z(cn.usage,cn.finishReason);return}else if(Q(cn),l!==void 0)return}C();return}}catch(b){if(l!==void 0)return;let D=mr(b);S(D.disposition==="fatal"?"upstream-protocol-error":"upstream-error",b,vh(D))}},cancel(b){S("consumer-cancel",b)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8","x-kiro-token-count-mode":"estimate"}})}class lu extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function Eu(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,_,o=new Promise((e,c)=>{_=c}),h=()=>{let e=Eu(i.combined);_?.(e),Mn(()=>r.cancel(e))};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw Eu(i.combined);let d=await Promise.race([r.read(),o]);if(i.combined.aborted)throw Eu(i.combined);if(d.done)break;if(f+=d.value.byteLength,f>t)throw new lu(t);s.push(d.value)}let e=new Uint8Array(f),c=0;for(let d of s)e.set(d,c),c+=d.byteLength;return{ok:!0,text:new TextDecoder().decode(e)}}catch(e){if(e instanceof lu)return Mn(()=>r.cancel(e)),{ok:!1,response:Wn(413,e.message,"request_too_large")};if(i.deadline.aborted)return Mn(()=>r.cancel(e)),{ok:!1,response:Wn(504,"Request deadline exceeded","api_error")};if(i.client.aborted)return Mn(()=>r.cancel(e)),{ok:!1,response:Wn(499,"Client closed request","api_error")};throw e}finally{i.combined.removeEventListener("abort",h)}}async function t2(n,t,i){let r=await IK(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:Wn(400,"Request body must contain valid JSON","invalid_request_error")}}}function SK(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 bK(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 Wn(n.status,t,SK(n.status))}function i2(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 r2(n){return Math.max(1,Hh(JSON.stringify(n)))}async function s2(n,t,i){let r=i2(n,t),s=await t2(n,t,r.signals);if(!s.ok)return r.finalize(),s.response;let f=Ru(s.value,{requireMaxTokens:!0},t.protocol_projection_mode);if(!f.ok)return V("warn","protocol_projection_rejected",{protocol:"anthropic-messages",projection_mode:t.protocol_projection_mode,code:f.code,param:f.param}),r.finalize(),Wn(400,f.message,"invalid_request_error");let _=jg(f.value.source,i.tenantId,t.session_affinity_mode),o=qs(f.value.body,i.tenantId),h,e=!1,c=()=>{Kn(r.finalize,()=>h?.restore())};try{h=i.createRequestIdleTimeoutLease?.(),h?.disable();let d=await(i.runPipeline??js)({body:f.value.body,model:f.value.body.model,stream:f.value.source.stream,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...i.quotaRechecker?{quotaRechecker:i.quotaRechecker}:{},..._?{affinity:_}:{},...o?{lineage:o}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},...i.modelCapabilities?{modelCapabilities:i.modelCapabilities}:{},deadlineSignal:r.signals.combined,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signals.deadline.aborted)return Mn(()=>d.body?.cancel()),Wn(499,"Client closed request","api_error");let u=d.headers.get("Content-Type")??"";if(!d.ok)return await bK(d);if(f.value.source.stream){if(!u.includes(Ks))return Mn(()=>d.body?.cancel()),Wn(502,"Pipeline returned an unsupported streaming response","api_error");let w=n2(d,{model:f.value.body.model,inputTokens:r2(f.value.body),signals:r.signals,finalize:c});return e=!0,w}if(u.includes(zs)){let w=xs(await d.json());if(w&&w.model===f.value.body.model)return pg(w,f.value.body.model);return Wn(502,"Pipeline returned an invalid non-streaming response","api_error")}return Mn(()=>d.body?.cancel()),Wn(502,"Pipeline returned an unsupported response","api_error")}finally{if(!e)c()}}async function f2(n,t){let i=i2(n,t);try{let r=await t2(n,t,i.signals);if(!r.ok)return r.response;let s=Ru(r.value,{},t.protocol_projection_mode);if(!s.ok)return Wn(400,s.message,"invalid_request_error");let f=r2(s.value.body);return Response.json({input_tokens:f},{headers:{"x-kiro-token-count-mode":"estimate"}})}finally{i.finalize()}}var NK=1700000000,UK=/-(low|medium|high|xhigh|max)$/;function $K(n){if(!Br(n))return[];return(iu(n)?["low","medium","high","xhigh","max"]:["low","medium","high","max"]).map((i)=>({effort:i,description:`${i} reasoning effort`}))}function DK(n){if(!Br(n.wireId))return null;let t=UK.exec(n.id)?.[1];if(t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max")return t;return"medium"}function BK(n){return n.modalities.input.includes("image")?["text","image"]:["text"]}function GK(n,t,i){return{slug:n.id,display_name:n.name,description:n.description??null,default_reasoning_level:DK(n),supported_reasoning_levels:$K(n.wireId),shell_type:"unified_exec",visibility:"list",supported_in_api:!0,priority:i-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:BK(n),supports_search_tool:!1,use_responses_lite:!1,node_repl_auto_review_required:!1,node_repl_disabled:!1}}async function o2(n,t,i,r,s){if(n&&t&&i){let h=r??new AbortController().signal,e=t.reconcileFromDb();if(s)await s.recheckDueAccounts(e,h),e=t.reconcileFromDb();e=e.filter((u)=>!yn(u));let d=(await Promise.allSettled(e.map(async(u)=>{return await i.refreshIfNeeded(u,t.toAuthDetails(u),h)}))).flatMap((u)=>u.status==="fulfilled"?[u.value]:[]);await n.refreshAccounts(d,(u)=>t.toAuthDetails(u),h)}let f=n?.catalog()??Sf,_=f.map((h)=>({id:h.id,object:"model",created:NK,owned_by:"kiro",name:h.name,context_limit:h.contextLimit,output_limit:h.outputLimit,modalities:h.modalities,...h.description!==void 0?{description:h.description}:{},...h.rateMultiplier!==void 0?{rate_multiplier:h.rateMultiplier}:{}})),o=f.map((h,e)=>GK(h,e,f.length));return new Response(JSON.stringify({object:"list",data:_,models:o}),{status:200,headers:{"Content-Type":"application/json"}})}function _2(n,t,i){try{if(n.reconcileFromDb(),n.getAccountCount()===0)return Response.json({status:"not_ready",reason:"no_active_accounts"},{status:503});if(t){let s=t.readiness();if(!s.writable)return Response.json({status:"not_ready",reason:"reasoning_replay_database_not_writable"},{status:503});if(!s.keyringAvailable)return Response.json({status:"not_ready",reason:"reasoning_replay_keyring_unavailable"},{status:503});if(s.missingKeyIds.length>0)return Response.json({status:"not_ready",reason:"reasoning_replay_key_coverage_incomplete",missing_key_ids:s.missingKeyIds},{status:503})}return Response.json({status:"ready",...i?{model_catalog:i.readiness()}:{}})}catch{return Response.json({status:"not_ready",reason:"authentication_store_unavailable"},{status:503})}}import{randomUUID as n0}from"crypto";var h2=/^gpt-5\.6-sol(?:-|$)/;function e2(n){return n.trim()}function ph(n,t){if(!h2.test(n))return!1;let i=e2(t);return i==="..."||i==="\u2026"}function c2(n,t){if(!h2.test(n))return!1;let i=e2(t);return i===""||i==="."||i===".."||i==="..."||i==="\u2026"}var mK="kiro_custom_",HK="kiro_ns_";function Eo(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 d2(...n){let t=n.filter((i)=>i!==void 0&&i.length>0);return t.length>0?t.join(`
|
|
367
367
|
|
|
368
|
-
`):void 0}function j4(){return{type:"object",properties:{input:{type:"string"}},required:["input"],additionalProperties:!1}}function sV(n){return{type:"function",function:{name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:{}}}}function a4(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 fu(n){return n.kind==="custom"||n.kind==="namespace"&&n.toolType==="custom"}function q4(n){return n.type==="function_call"||n.type==="custom_tool_call"}function fV(n){return n.type==="additional_tools"}function k4(n){return n.type==="function"||n.type==="custom"||n.type==="namespace"}function _V(n){return n.type==="function_call_output"||n.type==="custom_tool_call_output"}function hV(n){return n.trim().length===0?"{}":n}function oV(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 Z4{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=a4(n),i=this.#n.get(h_(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(fu(r)){let s=oV(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:hV(i.arguments)})}return{ok:!0,items:t}}}function wV(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 v4(n){let t=new Map,i=new Map,r=new Set,s=[],f=typeof n.input==="string"?[]:n.input;for(let e of f)if(q4(e)&&e.type==="function_call"&&e.namespace===void 0)r.add(e.name);let h=(e)=>{let L=h_(e.identity),N=t.get(L);if(N!==void 0){if(N.fingerprint===e.fingerprint)return;return{ok:!1,code:"invalid_tool_declaration",message:`Tool ${e.path} conflicts with ${N.path}`}}t.set(L,e);return},_=(e,L,N,l)=>{if(e.type==="namespace"){if(wV(e))return{ok:!1,code:"invalid_tool_declaration",message:`Namespace ${e.name} contains duplicate child names`};for(let[H,g]of e.tools.entries()){let I={kind:"namespace",namespace:e.name,name:g.name,toolType:g.type},P=`${L}.tools.${H}`,m={type:"function",function:{name:"",...x4(e.description,g.description)!==void 0?{description:x4(e.description,g.description)}:{},parameters:g.type==="custom"?j4():g.parameters??{type:"object"}}},a=h({identity:I,tool:m,path:P,origin:N,...l!==void 0?{sourceMetadata:{role:l}}:{},...g.type==="function"?{strict:!1}:{},fingerprint:i_({identity:I,tool:m,origin:N,sourceRole:l})});if(a)return a}return}let Y=i.get(e.name);if(Y!==void 0&&Y!==e.type)return{ok:!1,code:"invalid_tool_declaration",message:`Tool name ${e.name} is declared as both function and custom`};if(i.set(e.name,e.type),e.type==="function")r.add(e.name);let V={kind:e.type,name:e.name},b=e.type==="function"?sV(e):{type:"function",function:{name:"",...e.description!==void 0?{description:e.description}:{},parameters:j4()}};return h({identity:V,tool:b,path:L,origin:N,...l!==void 0?{sourceMetadata:{role:l}}:{},...e.type==="function"?{strict:!1}:{},fingerprint:i_({identity:V,tool:b,origin:N,sourceRole:l})})};for(let[e,L]of(n.tools??[]).entries()){if(!k4(L))continue;let N=_(L,`tools.${e}`,"request");if(N)return N}for(let[e,L]of f.entries()){if(!fV(L))continue;for(let[N,l]of L.tools.entries()){if(!k4(l))continue;let Y=_(l,`input.${e}.tools.${N}`,"input",L.role);if(Y)return Y}}let o=new Map;for(let[e,L]of f.entries()){if(!q4(L))continue;if(o.has(L.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool call id ${L.call_id}`};let N={index:e,identity:a4(L)};o.set(L.call_id,N),s.push(N)}let w=new Set;for(let[e,L]of f.entries()){if(!_V(L))continue;if(w.has(L.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool output id ${L.call_id}`};w.add(L.call_id);let N=o.get(L.call_id);if(!N)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${L.call_id} has no matching call`};let l=fu(N.identity),Y=L.type==="custom_tool_call_output"&&l||L.type==="function_call_output"&&!l;if(N.index>=e||!Y)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${L.call_id} is out of order or has the wrong type`}}let c=[...t.values()];for(let e of s){let L=h_(e.identity);if(t.has(L))continue;return{ok:!1,code:"missing_tool_declaration",message:`Historical ${e.identity.kind} tool call has no exact declaration; resend the original tool declaration`}}let d=new Set(r),u=new Map,y=new Map,R=0,M=0,E=(e)=>{for(;;){let L=e==="custom"?`${iV}${R++}`:`${rV}${M++}`;if(d.has(L))continue;return d.add(L),L}},T=[],O=[];for(let e of c){let L=h_(e.identity),N=e.identity.kind==="function"?e.identity.name:E(e.identity.kind);u.set(L,N),y.set(N,e.identity),T.push({type:"function",function:{...e.tool.function,name:N}}),O.push({publicType:fu(e.identity)?"custom":"function",publicName:e.identity.kind==="namespace"?`${e.identity.namespace}.${e.identity.name}`:e.identity.name,wireName:N,...e.tool.function.description!==void 0?{description:e.tool.function.description}:{},parameters:e.tool.function.parameters??{},path:e.path,origin:e.origin,...e.strict!==void 0?{strict:e.strict}:{},...e.sourceMetadata!==void 0?{sourceMetadata:e.sourceMetadata}:{}})}for(let e of r){let L={kind:"function",name:e};u.set(h_(L),e),y.set(e,L)}return{ok:!0,bridge:new Z4({internalTools:T,declarations:O,wireNameByIdentity:u,identityByWireName:y})}}var cV=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"]),dV=["temperature","top_p","truncation","background","max_tool_calls","service_tier"],uV=new Set(["type","id","status","role","content"]),yV=new Set(["type","id","status","call_id","namespace","name","arguments"]),AV=new Set(["type","id","status","call_id","namespace","name","input"]),RV=new Set(["type","id","status","call_id","output"]),MV=new Set(["type","role","tools"]),EV=new Set(["type","id","status","summary","content","encrypted_content"]);function p4(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function ht(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return X("unsupported_parameter",`Responses field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function ki(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 _u(n){return n.type==="message"||n.type===void 0&&"role"in n}function TV(n){return n.type==="agent_message"}function hu(n){return n.type==="function_call"}function ou(n){return n.type==="custom_tool_call"}function nO(n){return n.type==="function_call_output"}function tO(n){return n.type==="custom_tool_call_output"}function wu(n){return n.type==="additional_tools"}function cu(n){return n.type==="reasoning"}function Hr(n,t){return{type:"text",text:n,path:t}}function eV(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"]),_=ht(s,f,h);if(!_.ok)return _;i.push({...Hr(s.text,`${f}.text`),...ki(s,`${f}.text`,["annotations","logprobs"])});continue}if(s.type==="input_image"&&"image_url"in s&&typeof s.image_url==="string"){let h=ht(s,f,new Set(["type","image_url"]));if(!h.ok)return h;if(!s.image_url.startsWith("data:"))return X("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}if(s.type==="input_file"){let h=ht(s,f,new Set(["type","file_data","file_id","filename"]));if(!h.ok)return h;if("file_id"in s&&s.file_id!==void 0)return X("unsupported_file_reference","Responses file_id references cannot be resolved by this stateless provider; send file_data and filename",`${f}.file_id`);if(!("file_data"in s)||typeof s.file_data!=="string"||!("filename"in s)||typeof s.filename!=="string")return X("invalid_file_data","Responses input_file requires inline file_data and filename",f);try{let _=me(s.filename,s.file_data,`${f}.file_data`,`${f}.filename`);i.push({type:"document",name:_.name,format:_.format,data:_.data,path:f})}catch(_){if(!(_ instanceof cn))throw _;return X(_.code,_.message,_.param??`${f}.file_data`)}continue}return X("unsupported_content_part",`Responses content part ${f} of type ${s.type} is not supported`,f)}return{ok:!0,value:i}}function iO(n,t){return typeof n==="string"?{ok:!0,value:[Hr(n,t)]}:eV(n,t)}function OV(n,t){if(typeof n==="string")return{ok:!0,value:[Hr(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 X("unsupported_tool_result_content",`Tool output ${f} must be a text block`,f);let h=ht(s,f,s.type==="output_text"?new Set(["type","text","annotations","logprobs"]):new Set(["type","text"]));if(!h.ok)return h;i.push({...Hr(s.text,`${f}.text`),...ki(s,`${f}.text`,["annotations","logprobs"])})}return{ok:!0,value:i}}function LV(n,t){if(_u(n))return ht(n,t,uV);if(hu(n))return ht(n,t,yV);if(ou(n))return ht(n,t,AV);if(nO(n)||tO(n))return ht(n,t,RV);if(wu(n)){let i=ht(n,t,MV);if(!i.ok)return i;if(n.role!==void 0&&n.role!=="developer")return X("unsupported_additional_tools_role","additional_tools.role must be developer when provided",`${t}.role`);return{ok:!0,value:void 0}}if(cu(n)){let i=ht(n,t,EV);if(!i.ok)return i;for(let[r,s]of(n.summary??[]).entries()){let f=`${t}.summary.${r}`,h=ht(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=ht(s,f,new Set(["type","reasoning_text"]));if(!h.ok)return h}}return{ok:!0,value:void 0}}function IV(n){if(n==="minimal")return"low";if(n==="low"||n==="medium"||n==="high"||n==="xhigh"||n==="max")return n;return}function gV(n){if(n===void 0)return{ok:!0,value:void 0};if(!p4(n))return X("unsupported_parameter","Responses text must request the default text format","text");for(let i of Object.keys(n))if(i!=="format"&&i!=="verbosity")return X("unsupported_parameter",`Responses text.${i} is not supported`,`text.${i}`);if(n.verbosity!==void 0)return X("unsupported_parameter","Responses text.verbosity cannot be represented by the Kiro upstream","text.verbosity");if(n.format===void 0)return{ok:!0,value:void 0};let t=n.format;if(p4(t)&&t.type==="text"&&Object.keys(t).length===1)return{ok:!0,value:void 0};return X("unsupported_structured_output","Structured Responses text output cannot be represented by the Kiro upstream","text.format")}function NV(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 X("unsupported_parameter",`Responses reasoning.${i} is not supported`,`reasoning.${i}`);if(t.summary!==void 0)return X("unsupported_reasoning_summary","reasoning.summary cannot be guaranteed by the Kiro upstream","reasoning.summary");return{ok:!0,value:void 0}}function bV(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(_u(h)){if(h.role!=="assistant")break;let _=iO(h.content,`input.${f}.content`);if(!_.ok)return _;i+=ii(_.value),s=!0;continue}if(hu(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(ou(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(cu(h))continue;break}if(!s)return X("invalid_reasoning_replay",`Reasoning item input.${t} has no associated assistant output`,`input.${t}`);return{ok:!0,value:et({text:i,toolCalls:r})}}function SV(n){let t=(i,r,s)=>{if(i.type==="namespace")return X("unsupported_tool_type","Responses namespace tools cannot be represented without changing tool identity",r);if(i.type!=="function"&&i.type!=="custom")return X(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 _=ht(i,r,h);if(!_.ok)return _;if(s&&i.parameters!==void 0&&i.inputSchema!==void 0)return X("invalid_tool_declaration",`Responses tool ${r} cannot specify both parameters and inputSchema`,r);if(i.strict===!0)return X("unsupported_strict_tools","strict=true cannot be guaranteed by the Kiro upstream",`${r}.strict`);return{ok:!0,value:void 0}}let f=ht(i,r,new Set(["type","name","description","format"]));if(!f.ok)return f;if(i.format!==void 0)return X("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(!wu(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 rO(n,t="safe"){for(let E of Object.keys(n))if(!cV.has(E))return X("unsupported_parameter",`Responses parameter ${E} is not supported`,E);for(let E of dV)if(n[E]!==void 0)return X("unsupported_parameter",`Responses parameter ${E} cannot be represented by the Kiro upstream`,E);if(n.previous_response_id!==void 0||n.conversation!==void 0)return X("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 X("unsupported_parameter","Responses store=true is not supported","store");if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return X("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((E)=>E!=="reasoning.encrypted_content");if(r!==void 0)return X("unsupported_parameter",`Responses include value ${r} is not supported`,"include");let s=gV(n.text);if(!s.ok)return s;let f=NV(n);if(!f.ok)return f;if(n.max_output_tokens!==void 0){let E=qi(n.model,n.max_output_tokens);if(!E.ok)return X(E.code,E.message,"max_output_tokens")}let h=SV(n);if(!h.ok)return h;let _=v4(n);if(!_.ok)return _;let o=_.bridge,w=o.declarations.map((E)=>({publicType:E.publicType,name:E.publicName,wireName:E.wireName,...E.description!==void 0?{description:E.description}:{},inputSchema:E.parameters,path:E.path,origin:E.origin,...E.strict!==void 0?{strict:E.strict}:{},...E.sourceMetadata!==void 0?{sourceMetadata:E.sourceMetadata}:{}})),c=[],d=[];if(n.parallel_tool_calls===!1&&n.tool_choice!=="none"&&w.length>0)return X("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");let u=n.instructions!==void 0?Hr(n.instructions,"instructions"):void 0;if(n.instructions!==void 0&&n.instructions.length>0){if(t==="safe")return X("unsupported_instruction_projection","Responses instructions cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate","instructions");c.push({role:"developer",content:[Hr(n.instructions,"instructions")],toolCalls:[],path:"instructions"})}let y=!1;if(typeof n.input==="string")c.push({role:"user",content:[Hr(n.input,"input")],toolCalls:[],path:"input"}),y=!0;else for(let[E,T]of n.input.entries()){let O=`input.${E}`,e=LV(T,O);if(!e.ok)return e;if(cu(T)){let L=T.summary!==void 0&&T.summary!==null&&T.summary.length>0,N=T.content!==void 0&&T.content!==null&&T.content.length>0;if(T.encrypted_content===void 0||T.encrypted_content===null){if(L||N)return X("unsupported_reasoning_plaintext_replay","Reasoning replay requires encrypted_content; summary/content are output metadata only",O);return X("invalid_reasoning_replay","Reasoning replay requires a kiro-provider kr1_ encrypted_content token",`${O}.encrypted_content`)}if(typeof T.encrypted_content!=="string"||!T.encrypted_content.startsWith("kr1_"))return X("invalid_reasoning_replay","Reasoning replay requires a kiro-provider kr1_ encrypted_content token",`${O}.encrypted_content`);let l=bV(n.input,E);if(!l.ok)return l;d.push({lookup:{kind:"responses-token",encryptedContent:T.encrypted_content},outputFingerprint:l.value,insertBeforeMessage:c.length,...ki(T,O)});continue}if(hu(T)||ou(T)){if(T.namespace!==void 0)return X("unsupported_tool_namespace","Namespaced tool calls cannot be represented without changing tool identity",`${O}.namespace`);let L=o.lowerCall(T),N;try{N=JSON.parse(L.function.arguments)}catch(l){if(!(l instanceof SyntaxError))throw l;return X("invalid_tool_history",`Tool call ${T.call_id} contains invalid JSON arguments`,O)}c.push({role:"assistant",content:[],toolCalls:[{id:T.call_id,name:L.function.name,input:N,...ki(T,O)}],...ki(T,O)}),y=!0;continue}if(_u(T)){if(t==="safe"&&(T.role==="system"||T.role==="developer"))return X("unsupported_instruction_projection",`${T.role} input cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,O);let L=iO(T.content,`${O}.content`);if(!L.ok)return L;c.push({role:T.role,content:L.value,toolCalls:[],...ki(T,O)}),y=!0;continue}if(TV(T))return X("unsupported_input_item","agent_message author/recipient semantics cannot be represented by the Kiro upstream",O);if(nO(T)||tO(T)){let L=OV(T.output,`${O}.output`);if(!L.ok)return L;c.push({role:"tool",content:[{type:"tool_result",toolCallId:T.call_id,content:L.value,isError:!1,...ki(T,O)}],toolCalls:[],...ki(T,O)}),y=!0;continue}if(wu(T))continue;return X("unsupported_input_item",`Responses input item ${O} of type ${T.type} is not supported`,O)}if(!y)return X("empty_input","input produced no executable messages","input");let R=new Set;for(let E of c){for(let T of E.toolCalls)R.add(T.id);for(let T of E.content)if(T.type==="tool_result")R.delete(T.toolCallId)}if(n.tool_choice==="none"&&R.size>0)return X("unsupported_tool_choice","tool_choice=none cannot be used while tool calls are awaiting results","tool_choice");let M=IV(n.reasoning?.effort);return{ok:!0,body:{canonicalVersion:1,protocol:"responses",projectionMode:t,model:n.model,stream:n.stream,messages:c,tools:w,toolChoice:n.tool_choice==="none"?"none":"auto",...M!==void 0?{reasoningEffort:M}:{},...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:d,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:o}}import{randomUUID as zs}from"crypto";function lV(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 sO(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(lV)}}var $V={instructions:null,maxOutputTokens:null,metadata:{},reasoningEffort:null,toolChoice:"auto",tools:[]};function Wr(n){let t=n.configuration??$V;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 fO(n){return{type:"response.created",sequence_number:n.sequenceNumber,response:Wr({id:n.responseId,model:n.model,status:"in_progress",...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function _O(n){return{type:"response.in_progress",sequence_number:n.sequenceNumber,response:Wr({id:n.responseId,model:n.model,status:"in_progress",...n.createdAt!==void 0?{createdAt:n.createdAt}:{},...n.configuration!==void 0?{configuration:n.configuration}:{}})}}function Qs(n){return{type:"response.output_item.added",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function hO(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 oO(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 wO(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 cO(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 du(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 dO(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 ms(n){return{type:"response.output_item.done",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function uO(n){return{type:"response.completed",sequence_number:n.sequenceNumber,response:Wr({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 yO(n){return{type:"response.failed",sequence_number:n.sequenceNumber,response:Wr({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 AO(n){return{type:"response.function_call_arguments.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function RO(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 MO(n){return{type:"response.function_call_arguments.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,arguments:n.arguments}}function EO(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 TO(n){return`event: ${n.type}
|
|
368
|
+
`):void 0}function u2(){return{type:"object",properties:{input:{type:"string"}},required:["input"],additionalProperties:!1}}function WK(n){return{type:"function",function:{name:n.name,...n.description!==void 0?{description:n.description}:{},...n.parameters!==void 0?{parameters:n.parameters}:{}}}}function A2(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 Tu(n){return n.kind==="custom"||n.kind==="namespace"&&n.toolType==="custom"}function w2(n){return n.type==="function_call"||n.type==="custom_tool_call"}function FK(n){return n.type==="additional_tools"}function y2(n){return n.type==="function"||n.type==="custom"||n.type==="namespace"}function CK(n){return n.type==="function_call_output"||n.type==="custom_tool_call_output"}function PK(n){return n.trim().length===0?"{}":n}function YK(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 R2{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=A2(n),i=this.#n.get(Eo(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(Tu(r)){let s=YK(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:PK(i.arguments)})}return{ok:!0,items:t}}}function XK(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 M2(n){let t=new Map,i=new Map,r=new Set,s=[],f=typeof n.input==="string"?[]:n.input;for(let l of f)if(w2(l)&&l.type==="function_call"&&l.namespace===void 0)r.add(l.name);let _=(l)=>{let g=Eo(l.identity),O=t.get(g);if(O!==void 0){if(O.fingerprint===l.fingerprint)return;return{ok:!1,code:"invalid_tool_declaration",message:`Tool ${l.path} conflicts with ${O.path}`}}t.set(g,l);return},o=(l,g,O,N)=>{if(l.type==="namespace"){if(XK(l))return{ok:!1,code:"invalid_tool_declaration",message:`Namespace ${l.name} contains duplicate child names`};for(let[W,C]of l.tools.entries()){let I={kind:"namespace",namespace:l.name,name:C.name,toolType:C.type},L=`${g}.tools.${W}`,m={type:"function",function:{name:"",...d2(l.description,C.description)!==void 0?{description:d2(l.description,C.description)}:{},parameters:C.type==="custom"?u2():C.parameters??{type:"object"}}},q=_({identity:I,tool:m,path:L,origin:O,...N!==void 0?{sourceMetadata:{role:N}}:{},...C.type==="function"?{strict:!1}:{},fingerprint:wo({identity:I,tool:m,origin:O,sourceRole:N})});if(q)return q}return}let F=i.get(l.name);if(F!==void 0&&F!==l.type)return{ok:!1,code:"invalid_tool_declaration",message:`Tool name ${l.name} is declared as both function and custom`};if(i.set(l.name,l.type),l.type==="function")r.add(l.name);let K={kind:l.type,name:l.name},S=l.type==="function"?WK(l):{type:"function",function:{name:"",...l.description!==void 0?{description:l.description}:{},parameters:u2()}};return _({identity:K,tool:S,path:g,origin:O,...N!==void 0?{sourceMetadata:{role:N}}:{},...l.type==="function"?{strict:!1}:{},fingerprint:wo({identity:K,tool:S,origin:O,sourceRole:N})})};for(let[l,g]of(n.tools??[]).entries()){if(!y2(g))continue;let O=o(g,`tools.${l}`,"request");if(O)return O}for(let[l,g]of f.entries()){if(!FK(g))continue;for(let[O,N]of g.tools.entries()){if(!y2(N))continue;let F=o(N,`input.${l}.tools.${O}`,"input",g.role);if(F)return F}}let h=new Map;for(let[l,g]of f.entries()){if(!w2(g))continue;if(h.has(g.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool call id ${g.call_id}`};let O={index:l,identity:A2(g)};h.set(g.call_id,O),s.push(O)}let e=new Set;for(let[l,g]of f.entries()){if(!CK(g))continue;if(e.has(g.call_id))return{ok:!1,code:"invalid_tool_history",message:`Duplicate tool output id ${g.call_id}`};e.add(g.call_id);let O=h.get(g.call_id);if(!O)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${g.call_id} has no matching call`};let N=Tu(O.identity),F=g.type==="custom_tool_call_output"&&N||g.type==="function_call_output"&&!N;if(O.index>=l||!F)return{ok:!1,code:"invalid_tool_history",message:`Tool output ${g.call_id} is out of order or has the wrong type`}}let c=[...t.values()];for(let l of s){let g=Eo(l.identity);if(t.has(g))continue;return{ok:!1,code:"missing_tool_declaration",message:`Historical ${l.identity.kind} tool call has no exact declaration; resend the original tool declaration`}}let d=new Set(r),u=new Map,w=new Map,A=0,R=0,M=(l)=>{for(;;){let g=l==="custom"?`${mK}${A++}`:`${HK}${R++}`;if(d.has(g))continue;return d.add(g),g}},E=[],T=[];for(let l of c){let g=Eo(l.identity),O=l.identity.kind==="function"?l.identity.name:M(l.identity.kind);u.set(g,O),w.set(O,l.identity),E.push({type:"function",function:{...l.tool.function,name:O}}),T.push({publicType:Tu(l.identity)?"custom":"function",publicName:l.identity.kind==="namespace"?`${l.identity.namespace}.${l.identity.name}`:l.identity.name,wireName:O,...l.tool.function.description!==void 0?{description:l.tool.function.description}:{},parameters:l.tool.function.parameters??{},path:l.path,origin:l.origin,...l.strict!==void 0?{strict:l.strict}:{},...l.sourceMetadata!==void 0?{sourceMetadata:l.sourceMetadata}:{}})}for(let l of r){let g={kind:"function",name:l};u.set(Eo(g),l),w.set(l,g)}return{ok:!0,bridge:new R2({internalTools:E,declarations:T,wireNameByIdentity:u,identityByWireName:w})}}var JK=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"]),QK=["temperature","top_p","truncation","background","max_tool_calls","service_tier"],aK=new Set(["type","id","status","role","content"]),zK=new Set(["type","id","status","call_id","namespace","name","arguments"]),KK=new Set(["type","id","status","call_id","namespace","name","input"]),xK=new Set(["type","id","status","call_id","output"]),VK=new Set(["type","role","tools"]),jK=new Set(["type","id","status","summary","content","encrypted_content"]);function E2(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function et(n,t,i){for(let r of Object.keys(n)){if(i.has(r))continue;return P("unsupported_parameter",`Responses field ${t}.${r} is not supported`,`${t}.${r}`)}return{ok:!0,value:void 0}}function nr(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 gu(n){return n.type==="message"||n.type===void 0&&"role"in n}function qK(n){return n.type==="agent_message"}function Ou(n){return n.type==="function_call"}function Lu(n){return n.type==="custom_tool_call"}function l2(n){return n.type==="function_call_output"}function T2(n){return n.type==="custom_tool_call_output"}function Iu(n){return n.type==="additional_tools"}function Su(n){return n.type==="reasoning"}function Pr(n,t){return{type:"text",text:n,path:t}}function kK(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 _=s.type==="input_text"?new Set(["type","text"]):new Set(["type","text","annotations","logprobs"]),o=et(s,f,_);if(!o.ok)return o;i.push({...Pr(s.text,`${f}.text`),...nr(s,`${f}.text`,["annotations","logprobs"])});continue}if(s.type==="input_image"&&"image_url"in s&&typeof s.image_url==="string"){let _=et(s,f,new Set(["type","image_url"]));if(!_.ok)return _;if(!s.image_url.startsWith("data:"))return P("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}if(s.type==="input_file"){let _=et(s,f,new Set(["type","file_data","file_id","filename"]));if(!_.ok)return _;if("file_id"in s&&s.file_id!==void 0)return P("unsupported_file_reference","Responses file_id references cannot be resolved by this stateless provider; send file_data and filename",`${f}.file_id`);if(!("file_data"in s)||typeof s.file_data!=="string"||!("filename"in s)||typeof s.filename!=="string")return P("invalid_file_data","Responses input_file requires inline file_data and filename",f);try{let o=sg(s.filename,s.file_data,`${f}.file_data`,`${f}.filename`);i.push({type:"document",name:o.name,format:o.format,data:o.data,path:f})}catch(o){if(!(o instanceof dn))throw o;return P(o.code,o.message,o.param??`${f}.file_data`)}continue}return P("unsupported_content_part",`Responses content part ${f} of type ${s.type} is not supported`,f)}return{ok:!0,value:i}}function g2(n,t){return typeof n==="string"?{ok:!0,value:[Pr(n,t)]}:kK(n,t)}function ZK(n,t){if(typeof n==="string")return{ok:!0,value:[Pr(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 P("unsupported_tool_result_content",`Tool output ${f} must be a text block`,f);let _=et(s,f,s.type==="output_text"?new Set(["type","text","annotations","logprobs"]):new Set(["type","text"]));if(!_.ok)return _;i.push({...Pr(s.text,`${f}.text`),...nr(s,`${f}.text`,["annotations","logprobs"])})}return{ok:!0,value:i}}function vK(n,t){if(gu(n))return et(n,t,aK);if(Ou(n))return et(n,t,zK);if(Lu(n))return et(n,t,KK);if(l2(n)||T2(n))return et(n,t,xK);if(Iu(n)){let i=et(n,t,VK);if(!i.ok)return i;if(n.role!==void 0&&n.role!=="developer")return P("unsupported_additional_tools_role","additional_tools.role must be developer when provided",`${t}.role`);return{ok:!0,value:void 0}}if(Su(n)){let i=et(n,t,jK);if(!i.ok)return i;for(let[r,s]of(n.summary??[]).entries()){let f=`${t}.summary.${r}`,_=et(s,f,new Set(["type","text"]));if(!_.ok)return _}for(let[r,s]of(n.content??[]).entries()){let f=`${t}.content.${r}`,_=et(s,f,new Set(["type","reasoning_text"]));if(!_.ok)return _}}return{ok:!0,value:void 0}}function pK(n){if(n==="minimal")return"low";if(n==="low"||n==="medium"||n==="high"||n==="xhigh"||n==="max")return n;return}function nx(n){if(n===void 0)return{ok:!0,value:void 0};if(!E2(n))return P("unsupported_parameter","Responses text must request the default text format","text");for(let i of Object.keys(n))if(i!=="format"&&i!=="verbosity")return P("unsupported_parameter",`Responses text.${i} is not supported`,`text.${i}`);if(n.verbosity!==void 0)return P("unsupported_parameter","Responses text.verbosity cannot be represented by the Kiro upstream","text.verbosity");if(n.format===void 0)return{ok:!0,value:void 0};let t=n.format;if(E2(t)&&t.type==="text"&&Object.keys(t).length===1)return{ok:!0,value:void 0};return P("unsupported_structured_output","Structured Responses text output cannot be represented by the Kiro upstream","text.format")}function tx(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 P("unsupported_parameter",`Responses reasoning.${i} is not supported`,`reasoning.${i}`);if(t.summary!==void 0)return P("unsupported_reasoning_summary","reasoning.summary cannot be guaranteed by the Kiro upstream","reasoning.summary");return{ok:!0,value:void 0}}function ix(n,t){let i="",r=[],s=!1;for(let f=t+1;f<n.length;f+=1){let _=n[f];if(!_)continue;if(gu(_)){if(_.role!=="assistant")break;let o=g2(_.content,`input.${f}.content`);if(!o.ok)return o;i+=oi(o.value),s=!0;continue}if(Ou(_)){r.push({id:_.call_id,name:_.namespace===void 0?_.name:`${_.namespace}.${_.name}`,input:_.arguments}),s=!0;continue}if(Lu(_)){r.push({id:_.call_id,name:_.namespace===void 0?_.name:`${_.namespace}.${_.name}`,input:_.input}),s=!0;continue}if(Su(_))continue;break}if(!s)return P("invalid_reasoning_replay",`Reasoning item input.${t} has no associated assistant output`,`input.${t}`);return{ok:!0,value:Lt({text:i,toolCalls:r})}}function rx(n){let t=(i,r,s)=>{if(i.type==="namespace")return P("unsupported_tool_type","Responses namespace tools cannot be represented without changing tool identity",r);if(i.type!=="function"&&i.type!=="custom")return P(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 _=new Set(["type","name","description","parameters","strict"]);if(s)_.add("inputSchema");let o=et(i,r,_);if(!o.ok)return o;if(s&&i.parameters!==void 0&&i.inputSchema!==void 0)return P("invalid_tool_declaration",`Responses tool ${r} cannot specify both parameters and inputSchema`,r);if(i.strict===!0)return P("unsupported_strict_tools","strict=true cannot be guaranteed by the Kiro upstream",`${r}.strict`);return{ok:!0,value:void 0}}let f=et(i,r,new Set(["type","name","description","format"]));if(!f.ok)return f;if(i.format!==void 0)return P("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(!Iu(r))continue;for(let[s,f]of r.tools.entries()){let _=t(f,`input.${i}.tools.${s}`,!0);if(!_.ok)return _}}return{ok:!0,value:void 0}}function O2(n,t="safe"){for(let M of Object.keys(n))if(!JK.has(M))return P("unsupported_parameter",`Responses parameter ${M} is not supported`,M);for(let M of QK)if(n[M]!==void 0)return P("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 P("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 P("unsupported_parameter","Responses store=true is not supported","store");if(n.tool_choice==="required"||typeof n.tool_choice==="object"&&n.tool_choice!==null)return P("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 P("unsupported_parameter",`Responses include value ${r} is not supported`,"include");let s=nx(n.text);if(!s.ok)return s;let f=tx(n);if(!f.ok)return f;if(n.max_output_tokens!==void 0){let M=pi(n.model,n.max_output_tokens);if(!M.ok)return P(M.code,M.message,"max_output_tokens")}let _=rx(n);if(!_.ok)return _;let o=M2(n);if(!o.ok)return o;let h=o.bridge,e=h.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}:{}})),c=[],d=[];if(n.parallel_tool_calls===!1&&n.tool_choice!=="none"&&e.length>0)return P("unsupported_parallel_tool_calls","parallel_tool_calls=false cannot be guaranteed by the Kiro upstream","parallel_tool_calls");let u=n.instructions!==void 0?Pr(n.instructions,"instructions"):void 0;if(n.instructions!==void 0&&n.instructions.length>0){if(t==="safe")return P("unsupported_instruction_projection","Responses instructions cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate","instructions");c.push({role:"developer",content:[Pr(n.instructions,"instructions")],toolCalls:[],path:"instructions"})}let w=!1;if(typeof n.input==="string")c.push({role:"user",content:[Pr(n.input,"input")],toolCalls:[],path:"input"}),w=!0;else for(let[M,E]of n.input.entries()){let T=`input.${M}`,l=vK(E,T);if(!l.ok)return l;if(Su(E)){let g=E.summary!==void 0&&E.summary!==null&&E.summary.length>0,O=E.content!==void 0&&E.content!==null&&E.content.length>0;if(E.encrypted_content===void 0||E.encrypted_content===null){if(g||O)return P("unsupported_reasoning_plaintext_replay","Reasoning replay requires encrypted_content; summary/content are output metadata only",T);return P("invalid_reasoning_replay","Reasoning replay requires a kiro-provider kr1_ encrypted_content token",`${T}.encrypted_content`)}if(typeof E.encrypted_content!=="string"||!E.encrypted_content.startsWith("kr1_"))return P("invalid_reasoning_replay","Reasoning replay requires a kiro-provider kr1_ encrypted_content token",`${T}.encrypted_content`);let N=ix(n.input,M);if(!N.ok)return N;d.push({lookup:{kind:"responses-token",encryptedContent:E.encrypted_content},outputFingerprint:N.value,insertBeforeMessage:c.length,...nr(E,T)});continue}if(Ou(E)||Lu(E)){if(E.namespace!==void 0)return P("unsupported_tool_namespace","Namespaced tool calls cannot be represented without changing tool identity",`${T}.namespace`);let g=h.lowerCall(E),O;try{O=JSON.parse(g.function.arguments)}catch(N){if(!(N instanceof SyntaxError))throw N;return P("invalid_tool_history",`Tool call ${E.call_id} contains invalid JSON arguments`,T)}c.push({role:"assistant",content:[],toolCalls:[{id:E.call_id,name:g.function.name,input:O,...nr(E,T)}],...nr(E,T)}),w=!0;continue}if(gu(E)){if(t==="safe"&&(E.role==="system"||E.role==="developer"))return P("unsupported_instruction_projection",`${E.role} input cannot be projected losslessly to Kiro; use legacy-user-prefix explicitly to migrate`,T);let g=g2(E.content,`${T}.content`);if(!g.ok)return g;c.push({role:E.role,content:g.value,toolCalls:[],...nr(E,T)}),w=!0;continue}if(qK(E))return P("unsupported_input_item","agent_message author/recipient semantics cannot be represented by the Kiro upstream",T);if(l2(E)||T2(E)){let g=ZK(E.output,`${T}.output`);if(!g.ok)return g;c.push({role:"tool",content:[{type:"tool_result",toolCallId:E.call_id,content:g.value,isError:!1,...nr(E,T)}],toolCalls:[],...nr(E,T)}),w=!0;continue}if(Iu(E))continue;return P("unsupported_input_item",`Responses input item ${T} of type ${E.type} is not supported`,T)}if(!w)return P("empty_input","input produced no executable messages","input");let A=new Set;for(let M of c){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 P("unsupported_tool_choice","tool_choice=none cannot be used while tool calls are awaiting results","tool_choice");let R=pK(n.reasoning?.effort);return{ok:!0,body:{canonicalVersion:1,protocol:"responses",projectionMode:t,model:n.model,stream:n.stream,messages:c,tools:e,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:d,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:h}}import{randomUUID as ps}from"crypto";function sx(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 L2(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(sx)}}var fx={instructions:null,maxOutputTokens:null,metadata:{},reasoningEffort:null,toolChoice:"auto",tools:[]};function Yr(n){let t=n.configuration??fx;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 I2(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 S2(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 Zs(n){return{type:"response.output_item.added",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function b2(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 N2(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 U2(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 bu(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 D2(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 vs(n){return{type:"response.output_item.done",sequence_number:n.sequenceNumber,output_index:n.outputIndex,item:n.item}}function B2(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 G2(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 m2(n){return{type:"response.function_call_arguments.delta",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,delta:n.delta}}function H2(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 W2(n){return{type:"response.function_call_arguments.done",sequence_number:n.sequenceNumber,item_id:n.itemId,output_index:n.outputIndex,arguments:n.arguments}}function F2(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 C2(n){return`event: ${n.type}
|
|
369
369
|
data: ${JSON.stringify(n)}
|
|
370
370
|
|
|
371
|
-
`}function
|
|
372
|
-
`);if(J>=0){let Tn=y.slice(0,J).trimEnd();if(y=y.slice(J+1),Tn.length===0)continue;let kn=Oi(Tn);if(!kn){F("Malformed upstream stream");return}if(kn.type==="started"){if(H||g||kn.model!==t.model){F("Malformed upstream stream start");return}H=!0;continue}if(!H||g){F("Malformed upstream event ordering");return}if(kn.type==="completed"){g=!0,xs(B,kn.usage,kn.finishReason);return}if(Vs(B,kn),m(B))return;continue}let _n=await s.read();if(N!==void 0)return;if(!_n.done){y+=f.decode(_n.value,{stream:!0});continue}y+=f.decode();let zn=y.trim();if(y="",zn.length>0){let Tn=Oi(zn);if(!Tn){F("Malformed upstream stream");return}if(Tn.type==="started"){if(H||g||Tn.model!==t.model){F("Malformed upstream stream start");return}H=!0}else if(!H||g){F("Malformed upstream event ordering");return}else if(Tn.type==="completed"){g=!0,xs(B,Tn.usage,Tn.finishReason);return}else Vs(B,Tn)}F("Upstream stream ended before completion");return}}catch(J){if(N!==void 0)return;U("upstream-error",J,{code:"upstream_error",message:"Upstream stream error"})}},cancel(B){U("consumer-cancel",B)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class yu extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function uu(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function UV(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,h,_=new Promise((w,c)=>{h=c}),o=()=>{let w=uu(i.combined);h?.(w),r.cancel(w)};i.combined.addEventListener("abort",o,{once:!0});try{while(!0){if(i.combined.aborted)throw uu(i.combined);let d=await Promise.race([r.read(),_]);if(i.combined.aborted)throw uu(i.combined);if(d.done)break;if(f+=d.value.byteLength,f>t)throw new yu(t);s.push(d.value)}let w=new Uint8Array(f),c=0;for(let d of s)w.set(d,c),c+=d.byteLength;return{ok:!0,text:new TextDecoder().decode(w)}}catch(w){if(w instanceof yu)return r.cancel(w).catch(()=>{return}),{ok:!1,response:nn(413,w.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return r.cancel(w).catch(()=>{return}),{ok:!1,response:nn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return r.cancel(w).catch(()=>{return}),{ok:!1,response:nn(499,"Client closed request","request_aborted","client_disconnected")};throw w}finally{i.combined.removeEventListener("abort",o)}}function DV(n,t,i,r){let s=i.restoreCalls(n.toolCalls.map((o)=>({itemId:`fc_${J0()}`,id:o.id,name:o.name,arguments:o.input})));if(!s.ok)return nn(502,s.message,"upstream_error","upstream_protocol_error");let f=[],h=n.reasoning?.text,_=h!==void 0&&!C0(t,h)?[{type:"summary_text",text:h}]:[];if(_.length>0||n.reasoning?.encryptedContent){let o={id:`rs_${J0()}`,type:"reasoning",summary:_,...n.reasoning?.encryptedContent?{encrypted_content:n.reasoning.encryptedContent}:{}};f.push(o)}if(n.text.length>0){let o={id:`msg_${J0()}`,type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:n.text,annotations:[]}]};f.push(o)}return f.push(...s.items),Response.json(Wr({id:`resp_${J0()}`,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 OO(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 UV(n,t.max_request_body_bytes,h);if(!_.ok)return clearTimeout(s),_.response;let o;try{o=JSON.parse(_.text)}catch(O){if(clearTimeout(s),!(O instanceof SyntaxError))throw O;return nn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let w=g4(o);if(!w.ok)return clearTimeout(s),w.response;let c=l4(w.value,i.tenantId,t.session_affinity_mode),d=rO(w.value,t.protocol_projection_mode);if(!d.ok)return k("warn","protocol_projection_rejected",{protocol:"responses",projection_mode:t.protocol_projection_mode,code:d.code,param:d.param}),clearTimeout(s),nn(400,d.message??"input produced no messages","invalid_request_error",d.code,d.param);let u=sO(d.body),y=Cs(d.body,i.tenantId),R=w.value.stream,M,E=!1,T=()=>{Vn(()=>clearTimeout(s),()=>M?.restore())};try{M=i.createRequestIdleTimeoutLease?.(),M?.disable();let O=await(i.runPipeline??Xs)({body:d.body,model:d.body.model,stream:R,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...i.quotaRechecker?{quotaRechecker:i.quotaRechecker}:{},...c?{affinity:c}:{},...y?{lineage:y}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},...i.modelCapabilities?{modelCapabilities:i.modelCapabilities}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return Mn(()=>O.body?.cancel()),nn(499,"Client closed request","request_aborted","client_disconnected");let e=O.headers.get("Content-Type")??"";if(!O.ok)return O;if(R){if(!e.includes(Ys))return Mn(()=>O.body?.cancel()),nn(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let L=eO(O,{model:d.body.model,signals:h,finalize:T,bridge:d.bridge,configuration:u,includeEncryptedReasoning:d.body.includeEncryptedReasoning});return E=!0,L}if(e.includes(Fs)){let L=Ps(await O.json());if(L&&L.model===d.body.model)return DV(L,d.body.model,d.bridge,u);return nn(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return Mn(()=>O.body?.cancel()),nn(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}finally{if(!E)T()}}var IO=Z(To(),1);import{chmodSync as BV,closeSync as GV,existsSync as HV,mkdirSync as WV,openSync as FV}from"fs";import{homedir as YV}from"os";import{dirname as PV,join as Au}from"path";var XV={stale:30000,update:1e4,retries:0,realpath:!1};class Q0 extends Error{name="ServiceInstanceLockError";code="service_instance_already_running"}function LO(n){if(typeof n!=="object"||n===null||!("code"in n))return;return typeof n.code==="string"?n.code:void 0}function CV(n={}){let t=n.env??process.env,i=n.platform??process.platform,r=n.homeDirectory??YV(),s=i==="win32"?t.APPDATA??Au(r,"AppData","Roaming"):t.XDG_CONFIG_HOME??Au(r,".config");return Au(s,"kiro-provider","service.instance")}function JV(n){if(WV(PV(n),{recursive:!0}),!HV(n)){let t=FV(n,"a",384);GV(t)}if(process.platform!=="win32")BV(n,384)}function gO(n,t={}){if(!n.enforce_single_instance){k("warn","single_instance_protection_disabled",{});return}let i=n.instance_lock_path??CV(t);JV(i);let r;try{r=IO.default.lockSync(i,XV)}catch(f){if(LO(f)==="ELOCKED")throw new Q0(`Another kiro-provider instance already holds the service lock at ${i}`,{cause:f});throw new Q0(`Unable to acquire the kiro-provider service lock at ${i}`,{cause:f})}k("info","single_instance_lock_acquired",{lock_path_hash:Rn(i)});let s=!1;return{path:i,release(){if(s)return;s=!0;try{r?.()}catch(f){if(LO(f)!=="ERELEASED")throw f}}}}function NO(n,t){if(!t)return n;let i=n.stop.bind(n),r=(s)=>{try{i(s)}finally{t.release()}};try{Object.defineProperty(n,"stop",{configurable:!0,value:r})}catch(s){try{i(!0)}finally{t.release()}throw new Q0("Unable to bind the service lock lifecycle to the server",{cause:s})}return n}var QV=10;function mV(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,QV)}}}function zV(n,t){return async(i,r)=>{let s=new URL(i.url);if(i.method==="GET"&&s.pathname==="/health")return B4();let f=s.pathname==="/v1/messages"||s.pathname==="/v1/messages/count_tokens",h=f?xo(i,n.api_keys,(c,d)=>Fn(c,d,"authentication_error")):xo(i,n.api_keys);if(!h.ok)return h.response;let _=t.createRequestIdleTimeoutLease??mV,o=r?()=>_(i,r):void 0,w={accountManager:t.accountManager,tokenRefresher:t.tokenRefresher,...t.quotaRechecker?{quotaRechecker:t.quotaRechecker}:{},tenantId:h.tenantId,...t.affinityStore?{affinityStore:t.affinityStore}:{},...t.reasoningReplayStore?{reasoningReplayStore:t.reasoningReplayStore}:{},...t.modelCapabilities?{modelCapabilities:t.modelCapabilities}:{},...t.makeClient?{makeClient:t.makeClient}:{},...o?{createRequestIdleTimeoutLease:o}:{}};try{if(i.method==="POST"&&s.pathname==="/v1/chat/completions"){if(!n.enable_legacy_chat_completions)return nn(404,"Legacy Chat Completions is disabled; set enable_legacy_chat_completions to true","invalid_request_error","legacy_chat_completions_disabled");return await D4(i,n,w)}if(i.method==="POST"&&s.pathname==="/v1/responses")return await OO(i,n,w);if(i.method==="POST"&&s.pathname==="/v1/messages")return await C4(i,n,w);if(i.method==="POST"&&s.pathname==="/v1/messages/count_tokens")return await J4(i,n);if(i.method==="GET"&&s.pathname==="/v1/models")return await Q4(t.modelCapabilities,t.accountManager,t.tokenRefresher,i.signal,t.quotaRechecker);if(i.method==="GET"&&s.pathname==="/ready")return m4(t.accountManager,t.reasoningReplayStore,t.modelCapabilities);return nn(404,"Route not found","invalid_request_error","not_found")}catch(c){let d=c instanceof Error?c.message:"Internal server error";if(f)return Fn(500,d,"api_error");return nn(500,d,"internal_error","internal_error")}}}function KV(n,t={}){if(n.protocol_projection_mode==="legacy-user-prefix")k("warn","legacy_protocol_projection_enabled",{projection_mode:n.protocol_projection_mode,planned_removal:"v0.7.0"});if(n.session_affinity_mode==="legacy-initial-input")k("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 ur,r=t.createReasoningReplayStore?.(i,n)??new Jo(i,n),s=t.createModelCapabilityService?.(n)??new Wo(n),f=hs(n);if(n.auth_source==="opencode-shared"){let c=n.opencode_auth_db_path??qs(),d=t.createOpenCodeAuthStore?.(c)??new x0(c),u=new Uo(d,n.account_selection_strategy),y=t.createOpenCodeTokenRefresher?t.createOpenCodeTokenRefresher(u,d,n.token_expiry_buffer_ms,f):new Do(u,d,n.token_expiry_buffer_ms,f),R=t.createQuotaRechecker?.(u,y,n,f)??new Y_({accountManager:u,tokenRefresher:y,intervalMs:n.quota_recheck_interval_ms,usageRefreshIntervalMs:n.usage_refresh_interval_ms,timeoutMs:n.quota_recheck_timeout_ms,concurrency:n.quota_recheck_concurrency,proxyUrl:f}),M=t.createAccountMaintenance?.(u,y,R,n)??new R_({enabled:n.account_maintenance_enabled,intervalMs:n.account_maintenance_interval_ms,timeoutMs:n.account_maintenance_timeout_ms,concurrency:n.account_maintenance_concurrency,tokenExpiryBufferMs:n.token_expiry_buffer_ms,accountManager:u,tokenRefresher:y,usageRefresher:R});return{accountManager:u,tokenRefresher:y,quotaRechecker:R,accountMaintenance:M,affinityStore:i,reasoningReplayStore:r,modelCapabilities:s}}let h=new to(i.getAccounts(),n.account_selection_strategy,i),_=t.createTokenRefresher?t.createTokenRefresher(h,n.token_expiry_buffer_ms,f):new $o(h,n.token_expiry_buffer_ms,f),o=t.createQuotaRechecker?.(h,_,n,f)??new Y_({accountManager:h,tokenRefresher:_,intervalMs:n.quota_recheck_interval_ms,usageRefreshIntervalMs:n.usage_refresh_interval_ms,timeoutMs:n.quota_recheck_timeout_ms,concurrency:n.quota_recheck_concurrency,proxyUrl:f}),w=t.createAccountMaintenance?.(h,_,o,n)??new R_({enabled:n.account_maintenance_enabled,intervalMs:n.account_maintenance_interval_ms,timeoutMs:n.account_maintenance_timeout_ms,concurrency:n.account_maintenance_concurrency,tokenExpiryBufferMs:n.token_expiry_buffer_ms,accountManager:h,tokenRefresher:_,usageRefresher:o});return{accountManager:h,tokenRefresher:_,quotaRechecker:o,accountMaintenance:w,affinityStore:i,reasoningReplayStore:r,modelCapabilities:s}}function VV(n,t){return{hostname:n.host,port:n.port,fetch:zV(n,t)}}function bO(n){let t=gO(n);try{let i=KV(n),r=Bun.serve(VV(n,i)),s=NO(r,t);return Pu(s,i.accountMaintenance)}catch(i){throw t?.release(),i}}import{parseArgs as Ru}from"util";var m0=`Usage: kiro-provider <command> [options]
|
|
371
|
+
`}function P2(n){return{code:n.code,message:n.message}}function Y2(n,t){let i=t.signals,s=(n.body??new ReadableStream({start:(B)=>B.close()})).getReader(),f=new TextDecoder,_=new TextEncoder,o=`resp_${ps()}`,h=`msg_${ps()}`,e=Math.floor(Date.now()/1000),c=new Map,d=new Map,u=[],w="",A="",R,M,E="",T,l=0,g=0,O,N,F,K,S=!1,W=!1,C=!1,I=(B,J)=>{u.push(_.encode(C2(J(g)))),g+=1},L=(B)=>{if(S||O===void 0||O==="consumer-cancel"||u.length>0)return;S=!0,B.close()},m=(B)=>{if(S)return!1;let J=B.desiredSize;if(u.length>0&&J!==null&&J>0){let nn=u.shift();if(!nn)return!1;return B.enqueue(nn),L(B),!0}return L(B),!1},q=(B)=>{if(O!==void 0)return!1;return O=B,!0},Q=()=>{i.deadline.removeEventListener("abort",cn)},Z=()=>{i.client.removeEventListener("abort",dt)},b=(B,J,nn)=>{if(!q(B))return;if(F=nn,B==="consumer-cancel")u.length=0;Kn(Q,Z,()=>{if(!K)return;if(B==="normal-complete"){if(!N)throw TypeError("Responses stream completed without terminal data");I(K,(an)=>B2({responseId:o,model:t.model,output:N?.output??[],usage:N?.usage??{input_tokens:0,output_tokens:0,total_tokens:0},sequenceNumber:an,createdAt:e,completedAt:Math.floor(Date.now()/1000),configuration:t.configuration}))}else if(B==="deadline"||B==="upstream-error"||B==="upstream-protocol-error"){let an=F??{code:"upstream_stream_error",message:"Upstream stream error"};I(K,(ln)=>G2({responseId:o,model:t.model,error:an,sequenceNumber:ln,createdAt:e,configuration:t.configuration}))}},t.finalize,()=>{if(K)m(K)}),Mn(()=>s.cancel(J))},D=(B,J="upstream_protocol_error")=>{b("upstream-protocol-error",void 0,{code:J,message:B})},Dn=()=>{b("upstream-error",void 0,P2(It("upstream_stream_incomplete")))},cn=()=>{let B=i.deadline.reason instanceof Error?i.deadline.reason:new DOMException("Request deadline exceeded","TimeoutError");b("deadline",B,{code:"request_deadline_exceeded",message:"Request deadline exceeded"})},dt=()=>{let B=i.client.reason instanceof Error?i.client.reason:new DOMException("Client closed request","AbortError");b("client-abort",B)},Bn=(B,J)=>{if(J.emitted)return;let nn=l;l+=1,J.outputIndex=nn,J.emitted=!0,I(B,(an)=>Zs({item:{id:J.id,type:"reasoning",summary:[]},outputIndex:nn,sequenceNumber:an})),I(B,(an)=>bu({itemId:J.id,outputIndex:nn,summaryIndex:0,delta:J.text,sequenceNumber:an}))},St=(B,J)=>{if(ph(t.model,J.text)){if(!t.includeEncryptedReasoning)return;let ln=l;l+=1;let kn={id:J.id,type:"reasoning",summary:[],...T!==void 0?{encrypted_content:T}:{}};I(B,(Qr)=>Zs({item:{id:J.id,type:"reasoning",summary:[]},outputIndex:ln,sequenceNumber:Qr})),I(B,(Qr)=>vs({item:kn,outputIndex:ln,sequenceNumber:Qr})),d.set(ln,kn);return}Bn(B,J);let nn=J.outputIndex;if(nn===void 0)throw TypeError("Reasoning output index was not allocated");I(B,(ln)=>D2({itemId:J.id,outputIndex:nn,summaryIndex:0,text:J.text,sequenceNumber:ln}));let an={id:J.id,type:"reasoning",summary:[{type:"summary_text",text:J.text}],...T!==void 0?{encrypted_content:T}:{}};I(B,(ln)=>vs({item:an,outputIndex:nn,sequenceNumber:ln})),d.set(nn,an)},Jr=(B)=>{if(!M)return;let J=M;M=void 0,St(B,J)},To=(B)=>{if(E.length===0)return;let J={id:`rs_${ps()}`,text:E,emitted:!1};E="",St(B,J)},nf=(B,J)=>{switch(J.type){case"started":case"completed":return;case"reasoning_delta":{if(R!==void 0){E+=J.text;return}if(!M)M={id:`rs_${ps()}`,text:"",emitted:!1};let nn=M,an=nn.emitted;if(nn.text+=J.text,an){let ln=nn.outputIndex;if(ln===void 0)throw TypeError("Reasoning output index was not allocated");I(B,(kn)=>bu({itemId:nn.id,outputIndex:ln,summaryIndex:0,delta:J.text,sequenceNumber:kn}))}else if(!c2(t.model,nn.text))Bn(B,nn);return}case"reasoning_encrypted":if(t.includeEncryptedReasoning)T=J.encryptedContent;return;case"reasoning_signature":case"reasoning_redacted":return;case"text_delta":{if(Jr(B),R===void 0)R=l,l+=1,I(B,(nn)=>Zs({item:{id:h,type:"message",role:"assistant",status:"in_progress",content:[]},outputIndex:R??0,sequenceNumber:nn})),I(B,(nn)=>N2({itemId:h,outputIndex:R??0,contentIndex:0,part:{type:"output_text",text:"",annotations:[]},sequenceNumber:nn}));A+=J.text,I(B,(nn)=>b2({itemId:h,outputIndex:R??0,contentIndex:0,delta:J.text,sequenceNumber:nn}));return}case"tool_call_delta":{Jr(B);let nn=c.get(J.index)??{itemId:`fc_${ps()}`,id:"",name:"",arguments:""};if(nn.id.length===0&&J.id!==void 0)nn.id=J.id;if(nn.name.length===0&&J.name!==void 0)nn.name=J.name;nn.arguments+=J.arguments,c.set(J.index,nn);return}}},go=(B,J,nn)=>{if([...c.values()].some((rn)=>rn.id.length===0||rn.name.length===0)){D("Malformed upstream tool call");return}let ln=[...c.entries()].sort(([rn],[Ln])=>rn-Ln),kn=ln.length>0?"tool_calls":"stop";if(nn!==kn){D("Upstream finish reason does not match its output");return}let Qr=ln.map(([,rn])=>({itemId:rn.itemId,id:rn.id,name:rn.name,arguments:rn.arguments.trim().length===0?"{}":rn.arguments})),f0=t.bridge?.restoreCalls(Qr)??{ok:!0,items:Qr.map((rn)=>({id:rn.itemId,type:"function_call",call_id:rn.id,name:rn.name,arguments:rn.arguments}))};if(!f0.ok){D(f0.message,"upstream_protocol_error");return}if(Jr(B),R!==void 0){let rn={id:h,type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:A,annotations:[]}]};I(B,(Ln)=>U2({itemId:h,outputIndex:R??0,contentIndex:0,text:A,sequenceNumber:Ln})),I(B,(Ln)=>$2({itemId:h,outputIndex:R??0,contentIndex:0,part:{type:"output_text",text:A,annotations:[]},sequenceNumber:Ln})),I(B,(Ln)=>vs({item:rn,outputIndex:R??0,sequenceNumber:Ln})),d.set(R,rn)}if(To(B),T!==void 0){let rn=!1;for(let[Ln,Ui]of d){if(Ui.type!=="reasoning")continue;d.set(Ln,{...Ui,encrypted_content:T}),rn=!0}if(!rn){let Ln=l;l+=1;let Ui={id:`rs_${ps()}`,type:"reasoning",summary:[],encrypted_content:T};I(B,(ar)=>Zs({item:{id:Ui.id,type:"reasoning",summary:[]},outputIndex:Ln,sequenceNumber:ar})),I(B,(ar)=>vs({item:Ui,outputIndex:Ln,sequenceNumber:ar})),d.set(Ln,Ui)}}for(let rn of f0.items){let Ln=l;l+=1;let Ui=rn.type==="function_call"?{...rn,arguments:""}:{...rn,input:""};if(I(B,(bt)=>Zs({item:Ui,outputIndex:Ln,sequenceNumber:bt})),rn.type==="function_call")I(B,(bt)=>m2({itemId:rn.id,outputIndex:Ln,delta:rn.arguments,sequenceNumber:bt})),I(B,(bt)=>W2({itemId:rn.id,outputIndex:Ln,arguments:rn.arguments,sequenceNumber:bt}));else I(B,(bt)=>H2({itemId:rn.id,outputIndex:Ln,delta:rn.input,sequenceNumber:bt})),I(B,(bt)=>F2({itemId:rn.id,outputIndex:Ln,input:rn.input,sequenceNumber:bt}));let ar={...rn,status:"completed"};I(B,(bt)=>vs({item:ar,outputIndex:Ln,sequenceNumber:bt})),d.set(Ln,ar)}N={output:[...d.entries()].sort(([rn],[Ln])=>rn-Ln).map(([,rn])=>rn),usage:{input_tokens:J.inputTokens,output_tokens:J.outputTokens,total_tokens:J.totalTokens}},b("normal-complete")};return new Response(new ReadableStream({start(B){if(K=B,I(B,(J)=>I2({responseId:o,model:t.model,sequenceNumber:J,createdAt:e,configuration:t.configuration})),I(B,(J)=>S2({responseId:o,model:t.model,sequenceNumber:J,createdAt:e,configuration:t.configuration})),i.deadline.addEventListener("abort",cn,{once:!0}),i.client.addEventListener("abort",dt,{once:!0}),i.deadline.aborted)cn();else if(i.client.aborted)dt();m(B)},async pull(B){if(m(B))return;if(O!==void 0)return;try{while(O===void 0){let J=w.indexOf(`
|
|
372
|
+
`);if(J>=0){let ln=w.slice(0,J).trimEnd();if(w=w.slice(J+1),ln.length===0)continue;let kn=Si(ln);if(!kn){D("Malformed upstream stream");return}if(kn.type==="started"){if(W||C||kn.model!==t.model){D("Malformed upstream stream start");return}W=!0;continue}if(!W||C){D("Malformed upstream event ordering");return}if(kn.type==="completed"){C=!0,go(B,kn.usage,kn.finishReason);return}if(nf(B,kn),m(B))return;continue}let nn=await s.read();if(O!==void 0)return;if(!nn.done){w+=f.decode(nn.value,{stream:!0});continue}w+=f.decode();let an=w.trim();if(w="",an.length>0){let ln=Si(an);if(!ln){D("Malformed upstream stream");return}if(ln.type==="started"){if(W||C||ln.model!==t.model){D("Malformed upstream stream start");return}W=!0}else if(!W||C){D("Malformed upstream event ordering");return}else if(ln.type==="completed"){C=!0,go(B,ln.usage,ln.finishReason);return}else nf(B,ln)}Dn();return}}catch(J){if(O!==void 0)return;let nn=mr(J);b(nn.disposition==="fatal"?"upstream-protocol-error":"upstream-error",J,P2(nn))}},cancel(B){b("consumer-cancel",B)}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class Uu extends Error{limit;name="RequestBodyTooLargeError";constructor(n){super(`Request body exceeds the ${n} byte limit`);this.limit=n}}function Nu(n){return n.reason instanceof Error?n.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function ox(n,t,i){let r=n.body?.getReader();if(!r)return{ok:!0,text:""};let s=[],f=0,_,o=new Promise((e,c)=>{_=c}),h=()=>{let e=Nu(i.combined);_?.(e),r.cancel(e)};i.combined.addEventListener("abort",h,{once:!0});try{while(!0){if(i.combined.aborted)throw Nu(i.combined);let d=await Promise.race([r.read(),o]);if(i.combined.aborted)throw Nu(i.combined);if(d.done)break;if(f+=d.value.byteLength,f>t)throw new Uu(t);s.push(d.value)}let e=new Uint8Array(f),c=0;for(let d of s)e.set(d,c),c+=d.byteLength;return{ok:!0,text:new TextDecoder().decode(e)}}catch(e){if(e instanceof Uu)return r.cancel(e).catch(()=>{return}),{ok:!1,response:tn(413,e.message,"invalid_request_error","request_too_large")};if(i.deadline.aborted)return r.cancel(e).catch(()=>{return}),{ok:!1,response:tn(504,"Request deadline exceeded","timeout_error","request_timeout")};if(i.client.aborted)return r.cancel(e).catch(()=>{return}),{ok:!1,response:tn(499,"Client closed request","request_aborted","client_disconnected")};throw e}finally{i.combined.removeEventListener("abort",h)}}function _x(n,t,i,r){let s=i.restoreCalls(n.toolCalls.map((h)=>({itemId:`fc_${n0()}`,id:h.id,name:h.name,arguments:h.input})));if(!s.ok)return tn(502,s.message,"upstream_error","upstream_protocol_error");let f=[],_=n.reasoning?.text,o=_!==void 0&&!ph(t,_)?[{type:"summary_text",text:_}]:[];if(o.length>0||n.reasoning?.encryptedContent){let h={id:`rs_${n0()}`,type:"reasoning",summary:o,...n.reasoning?.encryptedContent?{encrypted_content:n.reasoning.encryptedContent}:{}};f.push(h)}if(n.text.length>0){let h={id:`msg_${n0()}`,type:"message",role:"assistant",status:"completed",content:[{type:"output_text",text:n.text,annotations:[]}]};f.push(h)}return f.push(...s.items),Response.json(Yr({id:`resp_${n0()}`,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 X2(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]),_={combined:f,deadline:r.signal,client:n.signal},o=await ox(n,t.max_request_body_bytes,_);if(!o.ok)return clearTimeout(s),o.response;let h;try{h=JSON.parse(o.text)}catch(T){if(clearTimeout(s),!(T instanceof SyntaxError))throw T;return tn(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let e=Qg(h);if(!e.ok)return clearTimeout(s),e.response;let c=xg(e.value,i.tenantId,t.session_affinity_mode),d=O2(e.value,t.protocol_projection_mode);if(!d.ok)return V("warn","protocol_projection_rejected",{protocol:"responses",projection_mode:t.protocol_projection_mode,code:d.code,param:d.param}),clearTimeout(s),tn(400,d.message??"input produced no messages","invalid_request_error",d.code,d.param);let u=L2(d.body),w=qs(d.body,i.tenantId),A=e.value.stream,R,M=!1,E=()=>{Kn(()=>clearTimeout(s),()=>R?.restore())};try{R=i.createRequestIdleTimeoutLease?.(),R?.disable();let T=await(i.runPipeline??js)({body:d.body,model:d.body.model,stream:A,config:t,accountManager:i.accountManager,tokenRefresher:i.tokenRefresher,...i.quotaRechecker?{quotaRechecker:i.quotaRechecker}:{},...c?{affinity:c}:{},...w?{lineage:w}:{},...i.affinityStore?{affinityStore:i.affinityStore}:{},tenantId:i.tenantId,...i.reasoningReplayStore?{reasoningReplayStore:i.reasoningReplayStore}:{},...i.modelCapabilities?{modelCapabilities:i.modelCapabilities}:{},deadlineSignal:f,...i.makeClient?{makeClient:i.makeClient}:{}});if(n.signal.aborted&&!r.signal.aborted)return Mn(()=>T.body?.cancel()),tn(499,"Client closed request","request_aborted","client_disconnected");let l=T.headers.get("Content-Type")??"";if(!T.ok)return T;if(A){if(!l.includes(Ks))return Mn(()=>T.body?.cancel()),tn(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");let g=Y2(T,{model:d.body.model,signals:_,finalize:E,bridge:d.bridge,configuration:u,includeEncryptedReasoning:d.body.includeEncryptedReasoning});return M=!0,g}if(l.includes(zs)){let g=xs(await T.json());if(g&&g.model===d.body.model)return _x(g,d.body.model,d.bridge,u);return tn(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return Mn(()=>T.body?.cancel()),tn(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}finally{if(!M)E()}}var Q2=k(B0(),1);import{chmodSync as hx,closeSync as ex,existsSync as cx,mkdirSync as dx,openSync as ux}from"fs";import{homedir as wx}from"os";import{dirname as yx,join as $u}from"path";var Ax={stale:30000,update:1e4,retries:0,realpath:!1};class t0 extends Error{name="ServiceInstanceLockError";code="service_instance_already_running"}function J2(n){if(typeof n!=="object"||n===null||!("code"in n))return;return typeof n.code==="string"?n.code:void 0}function Rx(n={}){let t=n.env??process.env,i=n.platform??process.platform,r=n.homeDirectory??wx(),s=i==="win32"?t.APPDATA??$u(r,"AppData","Roaming"):t.XDG_CONFIG_HOME??$u(r,".config");return $u(s,"kiro-provider","service.instance")}function Mx(n){if(dx(yx(n),{recursive:!0}),!cx(n)){let t=ux(n,"a",384);ex(t)}if(process.platform!=="win32")hx(n,384)}function a2(n,t={}){if(!n.enforce_single_instance){V("warn","single_instance_protection_disabled",{});return}let i=n.instance_lock_path??Rx(t);Mx(i);let r;try{r=Q2.default.lockSync(i,Ax)}catch(f){if(J2(f)==="ELOCKED")throw new t0(`Another kiro-provider instance already holds the service lock at ${i}`,{cause:f});throw new t0(`Unable to acquire the kiro-provider service lock at ${i}`,{cause:f})}V("info","single_instance_lock_acquired",{lock_path_hash:wn(i)});let s=!1;return{path:i,release(){if(s)return;s=!0;try{r?.()}catch(f){if(J2(f)!=="ERELEASED")throw f}}}}function z2(n,t){if(!t)return n;let i=n.stop.bind(n),r=(s)=>{try{i(s)}finally{t.release()}};try{Object.defineProperty(n,"stop",{configurable:!0,value:r})}catch(s){try{i(!0)}finally{t.release()}throw new t0("Unable to bind the service lock lifecycle to the server",{cause:s})}return n}var Ex=10;function lx(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,Ex)}}}function Tx(n,t){return async(i,r)=>{let s=new URL(i.url);if(i.method==="GET"&&s.pathname==="/health")return kg();let f=s.pathname==="/v1/messages"||s.pathname==="/v1/messages/count_tokens",_=f?fe(i,n.api_keys,(c,d)=>Wn(c,d,"authentication_error")):fe(i,n.api_keys);if(!_.ok)return _.response;let o=t.createRequestIdleTimeoutLease??lx,h=r?()=>o(i,r):void 0,e={accountManager:t.accountManager,tokenRefresher:t.tokenRefresher,...t.quotaRechecker?{quotaRechecker:t.quotaRechecker}:{},tenantId:_.tenantId,...t.affinityStore?{affinityStore:t.affinityStore}:{},...t.reasoningReplayStore?{reasoningReplayStore:t.reasoningReplayStore}:{},...t.modelCapabilities?{modelCapabilities:t.modelCapabilities}:{},...t.makeClient?{makeClient:t.makeClient}:{},...h?{createRequestIdleTimeoutLease:h}:{}};try{if(i.method==="POST"&&s.pathname==="/v1/chat/completions"){if(!n.enable_legacy_chat_completions)return tn(404,"Legacy Chat Completions is disabled; set enable_legacy_chat_completions to true","invalid_request_error","legacy_chat_completions_disabled");return await qg(i,n,e)}if(i.method==="POST"&&s.pathname==="/v1/responses")return await X2(i,n,e);if(i.method==="POST"&&s.pathname==="/v1/messages")return await s2(i,n,e);if(i.method==="POST"&&s.pathname==="/v1/messages/count_tokens")return await f2(i,n);if(i.method==="GET"&&s.pathname==="/v1/models")return await o2(t.modelCapabilities,t.accountManager,t.tokenRefresher,i.signal,t.quotaRechecker);if(i.method==="GET"&&s.pathname==="/ready")return _2(t.accountManager,t.reasoningReplayStore,t.modelCapabilities);return tn(404,"Route not found","invalid_request_error","not_found")}catch(c){let d=c instanceof Error?c.message:"Internal server error";if(f)return Wn(500,d,"api_error");return tn(500,d,"internal_error","internal_error")}}}function gx(n,t={}){if(n.protocol_projection_mode==="legacy-user-prefix")V("warn","legacy_protocol_projection_enabled",{projection_mode:n.protocol_projection_mode,planned_removal:"v0.7.0"});if(n.session_affinity_mode==="legacy-initial-input")V("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 Ai,r=t.createReasoningReplayStore?.(i,n)??new p0(i,n),s=t.createModelCapabilityService?.(n)??new V0(n),f=di(n);if(n.auth_source==="opencode-shared"){let c=n.opencode_auth_db_path??rf(),d=t.createOpenCodeAuthStore?.(c)??new _0(c),u=new J0(d,n.account_selection_strategy),w=t.createOpenCodeTokenRefresher?t.createOpenCodeTokenRefresher(u,d,n.token_expiry_buffer_ms,f):new Q0(u,d,n.token_expiry_buffer_ms,f),A=t.createQuotaRechecker?.(u,w,n,f)??new Ms({accountManager:u,tokenRefresher:w,intervalMs:n.quota_recheck_interval_ms,usageRefreshIntervalMs:n.usage_refresh_interval_ms,timeoutMs:n.quota_recheck_timeout_ms,concurrency:n.quota_recheck_concurrency,proxyUrl:f}),R=t.createAccountMaintenance?.(u,w,A,n)??new Uo({enabled:n.account_maintenance_enabled,intervalMs:n.account_maintenance_interval_ms,timeoutMs:n.account_maintenance_timeout_ms,concurrency:n.account_maintenance_concurrency,tokenExpiryBufferMs:n.token_expiry_buffer_ms,accountManager:u,tokenRefresher:w,usageRefresher:A});return{accountManager:u,tokenRefresher:w,quotaRechecker:A,accountMaintenance:R,affinityStore:i,reasoningReplayStore:r,modelCapabilities:s}}let _=new uf(i.getAccounts(),n.account_selection_strategy,i),o=t.createTokenRefresher?t.createTokenRefresher(_,n.token_expiry_buffer_ms,f):new Lf(_,n.token_expiry_buffer_ms,f),h=t.createQuotaRechecker?.(_,o,n,f)??new Ms({accountManager:_,tokenRefresher:o,intervalMs:n.quota_recheck_interval_ms,usageRefreshIntervalMs:n.usage_refresh_interval_ms,timeoutMs:n.quota_recheck_timeout_ms,concurrency:n.quota_recheck_concurrency,proxyUrl:f}),e=t.createAccountMaintenance?.(_,o,h,n)??new Uo({enabled:n.account_maintenance_enabled,intervalMs:n.account_maintenance_interval_ms,timeoutMs:n.account_maintenance_timeout_ms,concurrency:n.account_maintenance_concurrency,tokenExpiryBufferMs:n.token_expiry_buffer_ms,accountManager:_,tokenRefresher:o,usageRefresher:h});return{accountManager:_,tokenRefresher:o,quotaRechecker:h,accountMaintenance:e,affinityStore:i,reasoningReplayStore:r,modelCapabilities:s}}function Ox(n,t){return{hostname:n.host,port:n.port,fetch:Tx(n,t)}}function K2(n){let t=a2(n);try{let i=gx(n),r=Bun.serve(Ox(n,i)),s=z2(r,t);return nw(s,i.accountMaintenance)}catch(i){throw t?.release(),i}}class q2 extends Error{identifier;constructor(n){super(`Account not found: ${n}`);this.identifier=n;this.name="AccountNotFoundError"}}class k2 extends Error{identifier;accountIds;constructor(n,t){super(`Account identifier is ambiguous: ${n}. Matching account IDs: ${t.join(", ")}`);this.identifier=n;this.accountIds=t;this.name="AmbiguousAccountError"}}function x2(n){return n.trim().toLowerCase()}function lo(n,t){let i=n.find((f)=>f.id===t);if(i)return i;let r=x2(t),s=n.filter((f)=>x2(f.email)===r);if(s.length===0)throw new q2(t);if(s.length>1)throw new k2(t,s.map(({id:f})=>f).sort());return s[0]}function Bu(n,t=Date.now()){if(Zn(n.unhealthyReason))return"needs-relogin";if(yn(n))return"quota-exhausted";if(n.rateLimitResetTime>t)return"rate-limited";if(!n.isHealthy)return"unhealthy";return"available"}function V2(n){let t=n.usedCount??0,i=n.limitCount??0;return i>0?`${t}/${i}`:`${t}/unknown`}function Du(n){if(!n||n<=0)return"-";return new Date(n).toISOString()}function i0(n){if(!n||n<=0)return null;return new Date(n).toISOString()}function j2(n,t){let i=n.map((s,f)=>Math.max(s.length,...t.map((_)=>(_[f]??"").length))),r=(s)=>s.map((f,_)=>_===s.length-1?f:f.padEnd(i[_]??f.length)).join(" ").trimEnd();return[r(n),r(i.map((s)=>"-".repeat(s))),...t.map(r)]}function Lx(n){let t=n.usedCount??0,i=n.limitCount??0;return{id:n.id,email:n.email,auth_method:n.authMethod,region:n.region,oidc_region:n.oidcRegion??null,start_url:n.startUrl??null,health:n.isHealthy?"healthy":"unhealthy",availability:Bu(n),unhealthy_reason:n.unhealthyReason??null,used_count:t,limit_count:i,overage_count:n.overageCount??0,usage_ratio:i>0?t/i:null,last_sync:i0(n.lastSync),last_used:i0(n.lastUsed),token_expires_at:i0(n.expiresAt),rate_limit_reset_at:i0(n.rateLimitResetTime),generation:n.generation}}function Z2(n,t){let i=[...n].sort((r,s)=>r.email.localeCompare(s.email)||r.id.localeCompare(s.id));if(t==="json")return[JSON.stringify(i.map(Lx),null,2)];if(t==="details")return j2(["ID","EMAIL","AUTH","REGION","HEALTH","AVAILABILITY","USAGE","OVERAGE","LAST_SYNC","TOKEN_EXPIRES","RECHECK_AT","GENERATION"],i.map((r)=>[r.id,r.email,r.authMethod,r.region,r.isHealthy?"healthy":"unhealthy",Bu(r),V2(r),String(r.overageCount??0),Du(r.lastSync),Du(r.expiresAt),Du(r.rateLimitResetTime),String(r.generation)]));return j2(["EMAIL","REGION","HEALTH","AVAILABILITY","USAGE"],i.map((r)=>[r.email,r.region,r.isHealthy?"healthy":"unhealthy",Bu(r),V2(r)]))}function v2(n,t){if(t)return[JSON.stringify(n,null,2)];let i=[`Refreshed ${n.totalAccounts} accounts \xB7 ${n.tokenRenewed} token renewed \xB7 ${n.usageUpdated} usage updated \xB7 ${n.failed} failed`];for(let r of n.accounts){let s=r.error?` \xB7 ${r.error}`:"";i.push(`- ${r.email} [${r.accountId}] \u2014 ${r.before.usedCount}/${r.before.limitCount} \u2192 ${r.after.usedCount}/${r.after.limitCount} \xB7 token ${r.tokenStatus} \xB7 usage ${r.usageStatus}${s}`)}return i}import{parseArgs as Xr}from"util";var r0=`Usage: kiro-provider <command> [options]
|
|
373
373
|
|
|
374
374
|
Commands:
|
|
375
375
|
serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
|
|
376
376
|
Start the Responses, Messages, and optional legacy Chat gateway.
|
|
377
377
|
login [--config <path>] [--start-url <url>] [--region <region>]
|
|
378
378
|
Sign in directly to the provider-owned local auth store.
|
|
379
|
-
accounts list
|
|
380
|
-
List accounts
|
|
379
|
+
accounts list [--details | --json]
|
|
380
|
+
List accounts without exposing credentials.
|
|
381
|
+
accounts refresh (--all | <id|email>) [--config <path>] [--json]
|
|
382
|
+
Refresh authoritative usage now and renew access tokens when needed.
|
|
383
|
+
accounts relogin <id|email> [--config <path>] [--start-url <url>] [--region <region>]
|
|
384
|
+
Re-authenticate one account while preserving its internal account ID.
|
|
381
385
|
accounts import [--from <path>] [--config <path>]
|
|
382
386
|
Copy OpenCode Kiro accounts once into the provider-owned local store.
|
|
383
|
-
accounts remove <id|email>
|
|
387
|
+
accounts remove <id|email> [--yes]
|
|
384
388
|
Remove an account from the provider-owned local store and write a tombstone.
|
|
385
389
|
|
|
386
390
|
Options:
|
|
387
|
-
-h, --help Show this help.`;class
|
|
391
|
+
-h, --help Show this help.`;class Ni extends Error{constructor(n){super(n);this.name="CliUsageError"}}function Ix(n){let t=Xr({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 Ni(`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 Sx(n){let t=Xr({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 bx(n){let t=Xr({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 Nx(n){let t=Xr({args:[...n],options:{details:{type:"boolean"},json:{type:"boolean"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(t.values.help)return{kind:"help"};if(t.values.details&&t.values.json)throw new Ni("accounts list accepts only one of --details or --json");return{kind:"accounts-list",mode:t.values.json?"json":t.values.details?"details":"table"}}function Ux(n){let t=Xr({args:[...n],options:{all:{type:"boolean"},config:{type:"string"},json:{type:"boolean"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!0});if(t.values.help)return{kind:"help"};if(t.positionals.length>1)throw new Ni("accounts refresh accepts exactly one <id|email> or --all");let i=t.positionals[0];if((t.values.all??!1)===(i!==void 0))throw new Ni("accounts refresh requires exactly one <id|email> or --all");return{kind:"accounts-refresh",...i?{identifier:i}:{},...t.values.config?{configPath:t.values.config}:{},json:t.values.json??!1}}function $x(n){let t=Xr({args:[...n],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!0});if(t.values.help)return{kind:"help"};let i=t.positionals[0];if(!i||t.positionals.length!==1)throw new Ni("accounts relogin requires exactly one <id|email>");return{kind:"accounts-relogin",identifier:i,...t.values.config?{configPath:t.values.config}:{},...t.values["start-url"]?{startUrl:t.values["start-url"]}:{},...t.values.region?{region:t.values.region}:{}}}function Dx(n){let t=Xr({args:[...n],options:{yes:{type:"boolean",short:"y"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!0});if(t.values.help)return{kind:"help"};let i=t.positionals[0];if(!i||t.positionals.length!==1)throw new Ni("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:i,yes:t.values.yes??!1}}function Bx(n){let t=n[0];switch(t){case"list":return Nx(n.slice(1));case"refresh":return Ux(n.slice(1));case"relogin":return $x(n.slice(1));case"import":return bx(n.slice(1));case"remove":return Dx(n.slice(1));default:throw new Ni(t===void 0?"accounts requires list, refresh, relogin, import, or remove":`Unknown accounts command: ${t}`)}}function Gu(n){let t=n[0];switch(t){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return Ix(n.slice(1));case"login":return Sx(n.slice(1));case"accounts":return Bx(n.slice(1));default:throw new Ni(`Unknown command: ${t}`)}}import{Database as Gx}from"bun:sqlite";import{homedir as mx}from"os";import{join as p2}from"path";var Hx=y.object({id:y.string().min(1),email:y.string().min(1),auth_method:y.string(),region:y.string(),oidc_region:y.string().nullable(),client_id:y.string().nullable(),client_secret:y.string().nullable(),profile_arn:y.string().nullable(),start_url:y.string().nullable(),refresh_token:y.string(),access_token:y.string(),expires_at:y.number(),rate_limit_reset:y.number().nullable(),is_healthy:y.number().nullable(),unhealthy_reason:y.string().nullable(),recovery_time:y.number().nullable(),fail_count:y.number().nullable(),last_used:y.number().nullable(),used_count:y.number().nullable(),limit_count:y.number().nullable(),last_sync:y.number().nullable(),overage_count:y.number().nullable()});function Wx(n=process.env){let t=n.XDG_CONFIG_HOME??p2(mx(),".config");return p2(t,"opencode","kiro.db")}function Jt(n){return n===null||n===""?void 0:n}function Fx(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=or.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=Jt(n.oidc_region),r=i===void 0?void 0:or.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}:{},...Jt(n.client_id)?{clientId:Jt(n.client_id)}:{},...Jt(n.client_secret)?{clientSecret:Jt(n.client_secret)}:{},...Jt(n.profile_arn)?{profileArn:Jt(n.profile_arn)}:{},...Jt(n.start_url)?{startUrl:Jt(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,...Jt(n.unhealthy_reason)?{unhealthyReason:Jt(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 nO(n,t){let i=n.from??Wx(),r=new Gx(i,{readonly:!0,strict:!0}),s=0,f=0;try{let o=r.query(`SELECT
|
|
388
392
|
id, email, auth_method, region, oidc_region, client_id, client_secret,
|
|
389
393
|
profile_arn, start_url, refresh_token, access_token, expires_at,
|
|
390
394
|
rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
|
|
391
395
|
last_used, used_count, limit_count, last_sync, overage_count
|
|
392
|
-
FROM accounts`).all();for(let
|
|
393
|
-
${
|
|
396
|
+
FROM accounts`).all();for(let h of o){let e=Hx.safeParse(h);if(!e.success){f+=1,t.stdout("Skipped malformed source account row");continue}let c=Fx(e.data);if(c.kind==="skipped"){f+=1,t.stdout(`Skipped ${e.data.email}: ${c.reason}`);continue}t.database.insertAccount(c.account),s+=1,t.stdout(`Imported ${c.account.email} ${c.account.authMethod} ${c.account.region}`)}}finally{r.close()}let _=t.database.getAccounts().length;return t.stdout(`Imported ${s}, skipped ${f}, total in DB now ${_}`),{imported:s,skipped:f,total:_}}import{createHash as Xx}from"crypto";var Cx=y.object({clientId:y.string().min(1),clientSecret:y.string().min(1)}),Px=y.object({verificationUri:y.string().min(1),verificationUriComplete:y.string().min(1),userCode:y.string().min(1),deviceCode:y.string().min(1),interval:y.number().positive().default(5),expiresIn:y.number().positive().default(600)}),Yx=y.object({error:y.string().optional(),error_description:y.string().optional(),access_token:y.string().optional(),accessToken:y.string().optional(),refresh_token:y.string().optional(),refreshToken:y.string().optional(),expires_in:y.number().optional(),expiresIn:y.number().optional()}).passthrough();class ct extends Error{constructor(n,t){super(n,t);this.name="KiroIDCError"}}async function mu(n){try{return await n.text()}catch(t){if(t instanceof Error)return"";throw t}}async function tO(n,t,i){let r=Y0(n),s=gf(Of.SSO_OIDC_ENDPOINT,r),f=t??Of.BUILDER_ID_START_URL,_=await fetch(`${s}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":On.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Of.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...i?{proxy:i}:{}});if(!_.ok)throw new ct(`Client registration failed: ${_.status} ${await mu(_)}`);let o=Cx.safeParse(await _.json());if(!o.success)throw new ct("Client registration response missing clientId or clientSecret",{cause:o.error});let h=await fetch(`${s}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":On.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:f}),...i?{proxy:i}:{}});if(!h.ok)throw new ct(`Device authorization failed: ${h.status} ${await mu(h)}`);let e=Px.safeParse(await h.json());if(!e.success)throw new ct("Device authorization response missing required fields",{cause:e.error});return{verificationUrl:e.data.verificationUri,verificationUriComplete:e.data.verificationUriComplete,userCode:e.data.userCode,deviceCode:e.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:e.data.interval,expiresIn:e.data.expiresIn,region:r,startUrl:f}}async function iO(n,t,i,r,s,f,_=(h)=>new Promise((e)=>setTimeout(e,h)),o){if(!n||!t||!i)throw new ct("Missing required parameters for token polling");let h=Y0(f),e=gf(Of.SSO_OIDC_ENDPOINT,h),c=Math.floor(s/r),d=r*1000;for(let u=1;u<=c;u+=1){await _(d);let w=await fetch(`${e}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":On.USER_AGENT},body:JSON.stringify({clientId:n,clientSecret:t,deviceCode:i,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await mu(w),R={};if(A)try{R=JSON.parse(A)}catch(g){throw new ct(`Token polling failed: invalid JSON response (HTTP ${w.status})`,{cause:g})}let M=Yx.safeParse(R);if(!M.success)throw new ct(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:M.error});let E=M.data;switch(E.error){case void 0:break;case"authorization_pending":continue;case"slow_down":d+=5000;continue;case"expired_token":throw new ct("Device code has expired. Please restart the authorization process.");case"access_denied":throw new ct("Authorization was denied by the user.");default:throw new ct(`Token polling failed: ${E.error} - ${E.error_description??""}`)}let T=E.access_token??E.accessToken,l=E.refresh_token??E.refreshToken;if(T&&l)return{refreshToken:l,accessToken:T,expiresAt:Date.now()+(E.expires_in??E.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:n,clientSecret:t,region:h,authMethod:"idc"};if(!w.ok)throw new ct(`Token request failed with status: ${w.status}`);throw new ct("Token polling failed: response did not contain tokens")}throw new ct("Token polling timed out. Authorization may have expired.")}class sO extends Error{expectedEmail;actualEmail;constructor(n,t){super(`Re-login authenticated ${t}, but the selected account is ${n}. No credentials were changed.`);this.expectedEmail=n;this.actualEmail=t;this.name="ReloginIdentityMismatchError"}}function fO(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 Jx(n,t){return Xx("sha256").update(`${n}:idc:${t}:`).digest("hex")}function s0(n){return n.trim().toLowerCase()}function rO(n){try{return fO(n)??""}catch{return n?.trim()??""}}function Qx(n,t){return s0(n.email)===s0(t.email)&&n.authMethod===t.authMethod&&rO(n.startUrl)===rO(t.startUrl)&&(n.profileArn??"")===(t.profileArn??"")}function ax(n,t,i){return{refresh:_s({refreshToken:n.refreshToken,clientId:n.clientId,clientSecret:n.clientSecret,authMethod:"idc"}),access:n.accessToken,expires:n.expiresAt,authMethod:"idc",region:t,oidcRegion:t,clientId:n.clientId,clientSecret:n.clientSecret,email:n.email,...i?{profileArn:i}:{}}}async function oO(n,t={},i={}){let r=i.authorize??tO,s=i.poll??iO,f=i.fetchUsage??qo,_=i.stdout??console.log,o=t.replaceAccount,h=fO(t.startUrl??o?.startUrl),e=or.parse(t.region??o?.oidcRegion??o?.region??n.default_region),c=di(n),d=await r(e,h,c);_(`Open this URL to sign in:
|
|
397
|
+
${d.verificationUriComplete}`);let u=await s(d.clientId,d.clientSecret,d.deviceCode,d.interval,d.expiresIn,e,void 0,c),w,A=u.email,R=Date.now();if(o){if(w=await f(ax(u,e,o.profileArn),{proxyUrl:c,timeoutMs:n.quota_recheck_timeout_ms}),!w.email)throw Error("Kiro usage verification did not return an account email. No credentials were changed.");A=w.email;let g=s0(o.email);if(g!=="builder-id@aws.amazon.com"&&g!==s0(A))throw new sO(o.email,A)}let M={id:o?.id??Jx(A,u.clientId),email:A,authMethod:"idc",region:e,oidcRegion:e,clientId:u.clientId,clientSecret:u.clientSecret,...h?{startUrl:h}:{},...o?.profileArn?{profileArn:o.profileArn}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:w&&yn(w)?R+n.quota_recheck_interval_ms:0,isHealthy:!0,failCount:0,lastUsed:o?.lastUsed??0,usedCount:w?.usedCount??o?.usedCount??0,limitCount:w?.limitCount??o?.limitCount??0,overageCount:w?.overageCount??o?.overageCount??0,lastSync:w?R:o?.lastSync??0},E=i.openDb?.(Et)??new Ai(Et),T=[],l;try{let g=E.getAccounts();if(o&&!g.some(({id:N})=>N===o.id))throw Error(`Account ${o.id} was removed while re-login was in progress. No credentials were changed.`);let O=o?g.filter((N)=>N.id!==o.id&&Qx(N,o)):[];l=E.insertAccount(M);for(let N of O)E.removeAccount(N.id),T.push(N.id)}finally{E.close()}if(o){if(_(`Re-login successful: ${l.email} [${l.id}]`),T.length>0)_(`Removed ${T.length} duplicate account record(s).`)}else _(`Login successful: ${l.email}`);return{account:l,removedDuplicateIds:T}}async function _O(n,t={},i={}){let r=i.openDb?.(Et)??new Ai(Et);try{let s=new uf(r.getAccounts(),n.account_selection_strategy,r),f=new Lf(s,n.token_expiry_buffer_ms,di(n)),_=new Ms({accountManager:s,tokenRefresher:f,intervalMs:n.quota_recheck_interval_ms,usageRefreshIntervalMs:n.usage_refresh_interval_ms,timeoutMs:n.quota_recheck_timeout_ms,concurrency:n.account_maintenance_concurrency,proxyUrl:di(n),...i.fetchUsage?{fetchUsage:i.fetchUsage}:{},...i.now?{now:i.now}:{}}),o=s.getAccounts(),h=t.identifier?[lo(o,t.identifier)]:o,e=AbortSignal.timeout(n.account_maintenance_timeout_ms),c=t.signal?AbortSignal.any([t.signal,e]):e;return await _.refreshAccounts(h,c)}finally{r.close()}}async function Kx(n){if(!process.stdin.isTTY||!process.stdout.isTTY)return!1;let t=zx({input:process.stdin,output:process.stdout});try{let i=await t.question(`${n} [y/N] `);return i.trim().toLowerCase()==="y"||i.trim().toLowerCase()==="yes"}finally{t.close()}}function Hu(n){if(n.auth_source!=="opencode-shared")return;return`auth_source=opencode-shared uses ${n.opencode_auth_db_path??rf()} as the authentication authority. Run "opencode auth login" and select Kiro, or set auth_source to "local" before using provider-owned account commands.`}var xx={loadConfig:Zu,startServer:K2,runLogin:oO,runAccountRefresh:_O,runImportAccounts:nO,openDb:(n)=>new Ai(n),confirm:Kx,stdout:console.log,stderr:console.error};async function Vx(n,t){switch(n.kind){case"help":return t.stdout(r0),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}:{}}),r=Hu(i);if(r)return t.stderr(r),1;return await t.runLogin(i,{...n.startUrl?{startUrl:n.startUrl}:{},...n.region?{region:n.region}:{}}),0}case"accounts-list":{let i=t.openDb(Et);try{for(let r of Z2(i.getAccounts(),n.mode))t.stdout(r)}finally{i.close()}return 0}case"accounts-refresh":{let i=t.loadConfig({...n.configPath?{configPath:n.configPath}:{}}),r=Hu(i);if(r)return t.stderr(r),1;let s=await t.runAccountRefresh(i,{...n.identifier?{identifier:n.identifier}:{}});for(let f of v2(s,n.json))t.stdout(f);return s.failed===0?0:1}case"accounts-relogin":{let i=t.loadConfig({...n.configPath?{configPath:n.configPath}:{}}),r=Hu(i);if(r)return t.stderr(r),1;let s=t.openDb(Et),f;try{f=lo(s.getAccounts(),n.identifier)}finally{s.close()}return await t.runLogin(i,{replaceAccount:f,...n.startUrl?{startUrl:n.startUrl}:{},...n.region?{region:n.region}:{}}),0}case"accounts-import":{let i=t.openDb(Et);try{t.runImportAccounts({...n.from?{from:n.from}:{}},{database:i,stdout:t.stdout}),t.stderr("Accounts imported into the provider-owned local database. kiro-provider will now refresh access tokens, usage, and account health independently.")}finally{i.close()}return 0}case"accounts-remove":{let i=t.openDb(Et);try{let r=lo(i.getAccounts(),n.identifier);if(!n.yes){if(!await t.confirm(`Remove ${r.email} [${r.id}]? This also deletes its session affinity, output lineage, and reasoning replay state.`))return t.stderr("Account removal cancelled. Use --yes for non-interactive confirmation."),1}i.removeAccount(r.id),t.stdout(`Removed account ${r.email} [${r.id}]`)}finally{i.close()}return 0}}}async function hO(n=process.argv.slice(2),t=xx){let i;try{i=Gu(n)}catch(r){return t.stderr(r instanceof Error?r.message:String(r)),t.stderr(r0),1}try{return await Vx(i,t)}catch(r){return t.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await hO();
|