@sunerpy/kiro-provider 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +68 -67
  2. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -1,62 +1,62 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var NE=Object.create;var{getPrototypeOf:WE,defineProperty:Qo,getOwnPropertyNames:DE}=Object;var YE=Object.prototype.hasOwnProperty;function mE(t){return this[t]}var QE,JE,Y=(t,n,s)=>{var r=t!=null&&typeof t==="object";if(r){var i=n?QE??=new WeakMap:JE??=new WeakMap,e=i.get(t);if(e)return e}s=t!=null?NE(WE(t)):{};let f=n||!t||!t.__esModule?Qo(s,"default",{value:t,enumerable:!0}):s;for(let o of DE(t))if(!YE.call(f,o))Qo(f,o,{get:mE.bind(t,o),enumerable:!0});if(r)i.set(t,f);return f};var Z=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var kE=(t)=>t;function XE(t,n){this[t]=kE.bind(null,n)}var zE=(t,n)=>{for(var s in n)Qo(t,s,{get:n[s],enumerable:!0,configurable:!0,set:XE.bind(n,s)})};var nt=import.meta.require;var D0=Z((Gm,W0)=>{var Ds=1000,Ys=Ds*60,ms=Ys*60,ts=ms*24,wR=ts*7,AR=ts*365.25;W0.exports=function(t,n){n=n||{};var s=typeof t;if(s==="string"&&t.length>0)return MR(t);else if(s==="number"&&isFinite(t))return n.long?ER(t):gR(t);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function MR(t){if(t=String(t),t.length>100)return;var n=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!n)return;var s=parseFloat(n[1]),r=(n[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return s*AR;case"weeks":case"week":case"w":return s*wR;case"days":case"day":case"d":return s*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return s*ms;case"minutes":case"minute":case"mins":case"min":case"m":return s*Ys;case"seconds":case"second":case"secs":case"sec":case"s":return s*Ds;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}function gR(t){var n=Math.abs(t);if(n>=ts)return Math.round(t/ts)+"d";if(n>=ms)return Math.round(t/ms)+"h";if(n>=Ys)return Math.round(t/Ys)+"m";if(n>=Ds)return Math.round(t/Ds)+"s";return t+"ms"}function ER(t){var n=Math.abs(t);if(n>=ts)return Gi(t,n,ts,"day");if(n>=ms)return Gi(t,n,ms,"hour");if(n>=Ys)return Gi(t,n,Ys,"minute");if(n>=Ds)return Gi(t,n,Ds,"second");return t+" ms"}function Gi(t,n,s,r){var i=n>=s*1.5;return Math.round(t/s)+" "+r+(i?"s":"")}});var Co=Z((Bm,Y0)=>{function dR(t){s.debug=s,s.default=s,s.coerce=c,s.disable=f,s.enable=i,s.enabled=o,s.humanize=D0(),s.destroy=h,Object.keys(t).forEach((u)=>{s[u]=t[u]}),s.names=[],s.skips=[],s.formatters={};function n(u){let _=0;for(let l=0;l<u.length;l++)_=(_<<5)-_+u.charCodeAt(l),_|=0;return s.colors[Math.abs(_)%s.colors.length]}s.selectColor=n;function s(u){let _,l=null,w,A;function M(...E){if(!M.enabled)return;let d=M,T=Number(new Date),U=T-(_||T);if(d.diff=U,d.prev=_,d.curr=T,_=T,E[0]=s.coerce(E[0]),typeof E[0]!=="string")E.unshift("%O");let S=0;E[0]=E[0].replace(/%([a-zA-Z%])/g,(D,q)=>{if(D==="%%")return"%";S++;let tt=s.formatters[q];if(typeof tt==="function"){let J=E[S];D=tt.call(d,J),E.splice(S,1),S--}return D}),s.formatArgs.call(d,E),(d.log||s.log).apply(d,E)}if(M.namespace=u,M.useColors=s.useColors(),M.color=s.selectColor(u),M.extend=r,M.destroy=s.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(l!==null)return l;if(w!==s.namespaces)w=s.namespaces,A=s.enabled(u);return A},set:(E)=>{l=E}}),typeof s.init==="function")s.init(M);return M}function r(u,_){let l=s(this.namespace+(typeof _>"u"?":":_)+u);return l.log=this.log,l}function i(u){s.save(u),s.namespaces=u,s.names=[],s.skips=[];let _=(typeof u==="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let l of _)if(l[0]==="-")s.skips.push(l.slice(1));else s.names.push(l)}function e(u,_){let l=0,w=0,A=-1,M=0;while(l<u.length)if(w<_.length&&(_[w]===u[l]||_[w]==="*"))if(_[w]==="*")A=w,M=l,w++;else l++,w++;else if(A!==-1)w=A+1,M++,l=M;else return!1;while(w<_.length&&_[w]==="*")w++;return w===_.length}function f(){let u=[...s.names,...s.skips.map((_)=>"-"+_)].join(",");return s.enable(""),u}function o(u){for(let _ of s.skips)if(e(u,_))return!1;for(let _ of s.names)if(e(u,_))return!0;return!1}function c(u){if(u instanceof Error)return u.stack||u.message;return u}function h(){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 s.enable(s.load()),s}Y0.exports=dR});var Q0=Z((m0,Bi)=>{m0.formatArgs=bR;m0.save=TR;m0.load=SR;m0.useColors=RR;m0.storage=$R();m0.destroy=(()=>{let t=!1;return()=>{if(!t)t=!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`.")}})();m0.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 RR(){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 t;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&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function bR(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Bi.exports.humanize(this.diff),!this.useColors)return;let n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,r=0;t[0].replace(/%[a-zA-Z%]/g,(i)=>{if(i==="%%")return;if(s++,i==="%c")r=s}),t.splice(r,0,n)}m0.log=console.debug||console.log||(()=>{});function TR(t){try{if(t)m0.storage.setItem("debug",t);else m0.storage.removeItem("debug")}catch(n){}}function SR(){let t;try{t=m0.storage.getItem("debug")||m0.storage.getItem("DEBUG")}catch(n){}if(!t&&typeof process<"u"&&"env"in process)t=process.env.DEBUG;return t}function $R(){try{return localStorage}catch(t){}}Bi.exports=Co()(m0);var{formatters:UR}=Bi.exports;UR.j=function(t){try{return JSON.stringify(t)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}});var z0=Z((k0,Hi)=>{var HR=nt("tty"),Fi=nt("util");k0.init=QR;k0.log=DR;k0.formatArgs=NR;k0.save=YR;k0.load=mR;k0.useColors=PR;k0.destroy=Fi.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");k0.colors=[6,2,3,4,5,1];try{let t=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(t&&(t.stderr||t).level>=2)k0.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(t){}k0.inspectOpts=Object.keys(process.env).filter((t)=>{return/^debug_/i.test(t)}).reduce((t,n)=>{let s=n.substring(6).toLowerCase().replace(/_([a-z])/g,(i,e)=>{return e.toUpperCase()}),r=process.env[n];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 t[s]=r,t},{});function PR(){return"colors"in k0.inspectOpts?Boolean(k0.inspectOpts.colors):HR.isatty(process.stderr.fd)}function NR(t){let{namespace:n,useColors:s}=this;if(s){let r=this.color,i="\x1B[3"+(r<8?r:"8;5;"+r),e=` ${i};1m${n} \x1B[0m`;t[0]=e+t[0].split(`
3
+ var Nd=Object.create;var{getPrototypeOf:Wd,defineProperty:Qo,getOwnPropertyNames:Dd}=Object;var md=Object.prototype.hasOwnProperty;function Yd(t){return this[t]}var Qd,Jd,m=(t,n,s)=>{var i=t!=null&&typeof t==="object";if(i){var r=n?Qd??=new WeakMap:Jd??=new WeakMap,e=r.get(t);if(e)return e}s=t!=null?Nd(Wd(t)):{};let f=n||!t||!t.__esModule?Qo(s,"default",{value:t,enumerable:!0}):s;for(let o of Dd(t))if(!md.call(f,o))Qo(f,o,{get:Yd.bind(t,o),enumerable:!0});if(i)r.set(t,f);return f};var Z=(t,n)=>()=>(n||t((n={exports:{}}).exports,n),n.exports);var kd=(t)=>t;function zd(t,n){this[t]=kd.bind(null,n)}var Xd=(t,n)=>{for(var s in n)Qo(t,s,{get:n[s],enumerable:!0,configurable:!0,set:zd.bind(n,s)})};var nt=import.meta.require;var D0=Z((PY,W0)=>{var Ds=1000,ms=Ds*60,Ys=ms*60,ts=Ys*24,wR=ts*7,AR=ts*365.25;W0.exports=function(t,n){n=n||{};var s=typeof t;if(s==="string"&&t.length>0)return MR(t);else if(s==="number"&&isFinite(t))return n.long?dR(t):gR(t);throw Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function MR(t){if(t=String(t),t.length>100)return;var n=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(!n)return;var s=parseFloat(n[1]),i=(n[2]||"ms").toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return s*AR;case"weeks":case"week":case"w":return s*wR;case"days":case"day":case"d":return s*ts;case"hours":case"hour":case"hrs":case"hr":case"h":return s*Ys;case"minutes":case"minute":case"mins":case"min":case"m":return s*ms;case"seconds":case"second":case"secs":case"sec":case"s":return s*Ds;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:return}}function gR(t){var n=Math.abs(t);if(n>=ts)return Math.round(t/ts)+"d";if(n>=Ys)return Math.round(t/Ys)+"h";if(n>=ms)return Math.round(t/ms)+"m";if(n>=Ds)return Math.round(t/Ds)+"s";return t+"ms"}function dR(t){var n=Math.abs(t);if(n>=ts)return Gr(t,n,ts,"day");if(n>=Ys)return Gr(t,n,Ys,"hour");if(n>=ms)return Gr(t,n,ms,"minute");if(n>=Ds)return Gr(t,n,Ds,"second");return t+" ms"}function Gr(t,n,s,i){var r=n>=s*1.5;return Math.round(t/s)+" "+i+(r?"s":"")}});var Co=Z((NY,m0)=>{function ER(t){s.debug=s,s.default=s,s.coerce=c,s.disable=f,s.enable=r,s.enabled=o,s.humanize=D0(),s.destroy=h,Object.keys(t).forEach((u)=>{s[u]=t[u]}),s.names=[],s.skips=[],s.formatters={};function n(u){let l=0;for(let _=0;_<u.length;_++)l=(l<<5)-l+u.charCodeAt(_),l|=0;return s.colors[Math.abs(l)%s.colors.length]}s.selectColor=n;function s(u){let l,_=null,w,A;function M(...d){if(!M.enabled)return;let E=M,T=Number(new Date),U=T-(l||T);if(E.diff=U,E.prev=l,E.curr=T,l=T,d[0]=s.coerce(d[0]),typeof d[0]!=="string")d.unshift("%O");let S=0;d[0]=d[0].replace(/%([a-zA-Z%])/g,(D,q)=>{if(D==="%%")return"%";S++;let tt=s.formatters[q];if(typeof tt==="function"){let J=d[S];D=tt.call(E,J),d.splice(S,1),S--}return D}),s.formatArgs.call(E,d),(E.log||s.log).apply(E,d)}if(M.namespace=u,M.useColors=s.useColors(),M.color=s.selectColor(u),M.extend=i,M.destroy=s.destroy,Object.defineProperty(M,"enabled",{enumerable:!0,configurable:!1,get:()=>{if(_!==null)return _;if(w!==s.namespaces)w=s.namespaces,A=s.enabled(u);return A},set:(d)=>{_=d}}),typeof s.init==="function")s.init(M);return M}function i(u,l){let _=s(this.namespace+(typeof l>"u"?":":l)+u);return _.log=this.log,_}function r(u){s.save(u),s.namespaces=u,s.names=[],s.skips=[];let l=(typeof u==="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let _ of l)if(_[0]==="-")s.skips.push(_.slice(1));else s.names.push(_)}function e(u,l){let _=0,w=0,A=-1,M=0;while(_<u.length)if(w<l.length&&(l[w]===u[_]||l[w]==="*"))if(l[w]==="*")A=w,M=_,w++;else _++,w++;else if(A!==-1)w=A+1,M++,_=M;else return!1;while(w<l.length&&l[w]==="*")w++;return w===l.length}function f(){let u=[...s.names,...s.skips.map((l)=>"-"+l)].join(",");return s.enable(""),u}function o(u){for(let l of s.skips)if(e(u,l))return!1;for(let l of s.names)if(e(u,l))return!0;return!1}function c(u){if(u instanceof Error)return u.stack||u.message;return u}function h(){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 s.enable(s.load()),s}m0.exports=ER});var Q0=Z((Y0,Br)=>{Y0.formatArgs=bR;Y0.save=TR;Y0.load=SR;Y0.useColors=RR;Y0.storage=$R();Y0.destroy=(()=>{let t=!1;return()=>{if(!t)t=!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`.")}})();Y0.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 RR(){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 t;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&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function bR(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Br.exports.humanize(this.diff),!this.useColors)return;let n="color: "+this.color;t.splice(1,0,n,"color: inherit");let s=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(r)=>{if(r==="%%")return;if(s++,r==="%c")i=s}),t.splice(i,0,n)}Y0.log=console.debug||console.log||(()=>{});function TR(t){try{if(t)Y0.storage.setItem("debug",t);else Y0.storage.removeItem("debug")}catch(n){}}function SR(){let t;try{t=Y0.storage.getItem("debug")||Y0.storage.getItem("DEBUG")}catch(n){}if(!t&&typeof process<"u"&&"env"in process)t=process.env.DEBUG;return t}function $R(){try{return localStorage}catch(t){}}Br.exports=Co()(Y0);var{formatters:UR}=Br.exports;UR.j=function(t){try{return JSON.stringify(t)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}});var X0=Z((k0,Hr)=>{var HR=nt("tty"),Fr=nt("util");k0.init=QR;k0.log=DR;k0.formatArgs=NR;k0.save=mR;k0.load=YR;k0.useColors=PR;k0.destroy=Fr.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");k0.colors=[6,2,3,4,5,1];try{let t=(()=>{throw new Error("Cannot require module "+"supports-color");})();if(t&&(t.stderr||t).level>=2)k0.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(t){}k0.inspectOpts=Object.keys(process.env).filter((t)=>{return/^debug_/i.test(t)}).reduce((t,n)=>{let s=n.substring(6).toLowerCase().replace(/_([a-z])/g,(r,e)=>{return e.toUpperCase()}),i=process.env[n];if(/^(yes|on|true|enabled)$/i.test(i))i=!0;else if(/^(no|off|false|disabled)$/i.test(i))i=!1;else if(i==="null")i=null;else i=Number(i);return t[s]=i,t},{});function PR(){return"colors"in k0.inspectOpts?Boolean(k0.inspectOpts.colors):HR.isatty(process.stderr.fd)}function NR(t){let{namespace:n,useColors:s}=this;if(s){let i=this.color,r="\x1B[3"+(i<8?i:"8;5;"+i),e=` ${r};1m${n} \x1B[0m`;t[0]=e+t[0].split(`
4
4
  `).join(`
5
- `+e),t.push(i+"m+"+Hi.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=WR()+n+" "+t[0]}function WR(){if(k0.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function DR(...t){return process.stderr.write(Fi.formatWithOptions(k0.inspectOpts,...t)+`
6
- `)}function YR(t){if(t)process.env.DEBUG=t;else delete process.env.DEBUG}function mR(){return process.env.DEBUG}function QR(t){t.inspectOpts={};let n=Object.keys(k0.inspectOpts);for(let s=0;s<n.length;s++)t.inspectOpts[n[s]]=k0.inspectOpts[n[s]]}Hi.exports=Co()(k0);var{formatters:J0}=Hi.exports;J0.o=function(t){return this.inspectOpts.colors=this.useColors,Fi.inspect(t,this.inspectOpts).split(`
7
- `).map((n)=>n.trim()).join(" ")};J0.O=function(t){return this.inspectOpts.colors=this.useColors,Fi.inspect(t,this.inspectOpts)}});var Vo=Z((Pm,Ko)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Ko.exports=Q0();else Ko.exports=z0()});var is=Z((lb)=>{var ef;(function(t){t.HEADER="header",t.QUERY="query"})(ef||(ef={}));var of;(function(t){t.HEADER="header",t.QUERY="query"})(of||(of={}));var ff;(function(t){t.HTTP="http",t.HTTPS="https"})(ff||(ff={}));var Br;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(Br||(Br={}));var fb=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>Br.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>Br.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){n.push(s)},checksumAlgorithms(){return n}}},cb=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{n[s.algorithmId()]=s.checksumConstructor()}),n},hb=(t)=>{return fb(t)},ub=(t)=>{return cb(t)},cf;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(cf||(cf={}));var _b="__smithy_context",hf;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(hf||(hf={}));var uf;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(uf||(uf={}));lb.AlgorithmId=Br;lb.EndpointURLScheme=ff;lb.FieldPosition=cf;lb.HttpApiKeyAuthLocation=of;lb.HttpAuthLocation=ef;lb.IniSectionType=hf;lb.RequestHandlerProtocol=uf;lb.SMITHY_CONTEXT_KEY=_b;lb.getDefaultClientConfiguration=hb;lb.resolveDefaultRuntimeConfig=ub});var nn=Z((Gb)=>{var{SMITHY_CONTEXT_KEY:fu}=is(),$b=(t)=>t[fu]||(t[fu]={});class Qi{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new Qi({...t,headers:{...t.headers}});if(n.query)n.query=Ub(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return Qi.clone(this)}}function Ub(t){return Object.keys(t).reduce((n,s)=>{let r=t[s];return{...n,[s]:Array.isArray(r)?[...r]:r}},{})}class cu{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}var Lb=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),hu=(t,n=!1)=>{if(!n)return Lb.test(t);let s=t.split(".");for(let r of s)if(!hu(r))return!1;return!0};function Ib(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var Ob=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};function uu(t){let n={};if(t=t.replace(/^\?/,""),t)for(let s of t.split("&")){let[r,i=null]=s.split("=");if(r=decodeURIComponent(r),i)i=decodeURIComponent(i);if(!(r in n))n[r]=i;else if(Array.isArray(n[r]))n[r].push(i);else n[r]=[n[r],i]}return n}var Ji=(t)=>{if(typeof t==="string")return Ji(new URL(t));let{hostname:n,pathname:s,port:r,protocol:i,search:e}=t,f;if(e)f=uu(e);return{hostname:n,port:r?parseInt(r):void 0,protocol:i,path:s,query:f}},yb=(t)=>{if(typeof t==="object"){if("url"in t){let n=Ji(t.url);if(t.headers){n.headers={};for(let s in t.headers)n.headers[s.toLowerCase()]=t.headers[s].join(", ")}return n}return t}return Ji(t)};Gb.HttpRequest=Qi;Gb.HttpResponse=cu;Gb.getSmithyContext=$b;Gb.isValidHostLabel=hu;Gb.isValidHostname=Ib;Gb.normalizeProvider=Ob;Gb.parseQueryString=uu;Gb.parseUrl=Ji;Gb.toEndpointV1=yb});var Nn=Z((Zb)=>{var{getSmithyContext:_u,HttpResponse:Qb,toEndpointV1:Jb}=nn(),ki=(t)=>{if(typeof t==="function")return t();return t},wf=(t,n,s,r,i)=>({name:n,namespace:t,traits:s,input:r,output:i}),kb=(t)=>(n,s)=>async(r)=>{let{response:i}=await n(r),{operationSchema:e}=_u(s),[,f,o,c,h,u]=e??[];try{let _=await t.protocol.deserializeResponse(wf(f,o,c,h,u),{...t,...s},i);return{response:i,output:_}}catch(_){if(Object.defineProperty(_,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in _)){try{_.message+=`
8
- Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof _.$responseBodyText<"u"){if(_.$response)_.$response.body=_.$responseBodyText}try{if(Qb.isInstance(i)){let{headers:w={},statusCode:A}=i,M=Object.entries(w);_.$metadata={httpStatusCode:A,requestId:_f(/^x-[\w-]+-request-?id$/,M),extendedRequestId:_f(/^x-[\w-]+-id-2$/,M),cfId:_f(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw _}},_f=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},Xb=(t)=>(n,s)=>async(r)=>{let{operationSchema:i}=_u(s),[,e,f,o,c,h]=i??[],u=s.endpointV2?async()=>Jb(s.endpointV2):t.endpoint,_=await t.protocol.serializeRequest(wf(e,f,o,c,h),r.input,{...t,...s,endpoint:u});return n({...r,request:_})},lu={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},wu={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function zb(t){return{applyToStack:(n)=>{n.add(Xb(t),wu),n.add(kb(t),lu),t.protocol.setSerdeContext(t)}}}class Tt{name;namespace;traits;static assign(t,n){return Object.assign(t,n)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}getName(){return this.namespace+"#"+this.name}}class qi extends Tt{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=qi.symbol}var xb=(t,n,s,r)=>Tt.assign(new qi,{name:n,namespace:t,traits:s,valueSchema:r});class Ci extends Tt{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=Ci.symbol}var qb=(t,n,s,r,i)=>Tt.assign(new Ci,{name:n,namespace:t,traits:s,keySchema:r,valueSchema:i});class Ki extends Tt{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Ki.symbol}var Cb=(t,n,s,r,i)=>Tt.assign(new Ki,{name:n,namespace:t,traits:s,input:r,output:i});class Nr extends Tt{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Nr.symbol}var Kb=(t,n,s,r,i)=>Tt.assign(new Nr,{name:n,namespace:t,traits:s,memberNames:r,memberList:i});class Vi extends Nr{static symbol=Symbol.for("@smithy/err");ctor;symbol=Vi.symbol}var Vb=(t,n,s,r,i,e)=>Tt.assign(new Vi,{name:n,namespace:t,traits:s,memberNames:r,memberList:i,ctor:null}),Xi=[];function Pr(t){if(typeof t==="object")return t;if(t=t|0,Xi[t])return Xi[t];let n={},s=0;for(let r of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((t>>s++&1)===1)n[r]=1;return Xi[t]=n}var Fr={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},zi=[],xi={};class dn{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=dn.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],r=t,i=t;this._isMemberSchema=!1;while(lf(r))s.push(r[1]),r=r[0],i=ki(r),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let e=s.length-1;e>=0;--e){let f=s[e];Object.assign(this.memberTraits,Pr(f))}}else this.memberTraits=0;if(i instanceof dn){let e=this.memberTraits;Object.assign(this,i),this.memberTraits=Object.assign({},e,i.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??i.memberName;return}if(this.schema=ki(i),Au(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(i),this.traits=0;if(this._isMemberSchema&&!n)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}static of(t){let n=typeof t==="function"||typeof t==="object"&&t!==null;if(typeof t==="number"){if(zi[t])return zi[t]}else if(typeof t==="string"){if(xi[t])return xi[t]}else if(n){if(t[Fr.ns])return t[Fr.ns]}let s=ki(t);if(s instanceof dn)return s;if(lf(s)){let[i,e]=s;if(i instanceof dn)return Object.assign(i.getMergedTraits(),Pr(e)),i;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let r=new dn(s);if(n)return t[Fr.ns]=r;if(typeof s==="string")return xi[s]=r;if(typeof s==="number")return zi[s]=r;return r}getSchema(){let t=this.schema;if(Array.isArray(t)&&t[0]===0)return t[4];return t}getName(t=!1){let{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let t=this.getSchema();return typeof t==="number"?t>=64&&t<128:t[0]===1}isMapSchema(){let t=this.getSchema();return typeof t==="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;let n=t[0];return n===3||n===-3||n===4}isUnionSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;return t[0]===4}isBlobSchema(){let t=this.getSchema();return t===21||t===42}isTimestampSchema(){let t=this.getSchema();return typeof t==="number"&&t>=4&&t<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Pr(this.memberTraits)}getOwnTraits(){return Pr(this.traits)}getKeySchema(){let[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let s=this.getSchema(),r=t?15:s[4]??0;return Hr([r,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,r]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],i=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||r)?t[3+t[0]]:n?15:void 0;if(i!=null)return Hr([i,0],s?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){let n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){let s=n[4].indexOf(t),r=n[5][s];return Hr(lf(r)?r:[r,0],t)}if(this.isDocumentSchema())return Hr([15,0],t);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${t}.`)}getMemberSchemas(){let t={};try{for(let[n,s]of this.structIterator())t[n]=s}catch(n){}return t}getEventStreamMember(){if(this.isStructSchema()){for(let[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let t=this.getSchema(),n=t[4].length,s=t[Fr.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let r=0;r<n;++r){let i=t[4][r],e=Hr([t[5][r],0],i);yield s[r]=[i,e]}t[Fr.it]=s}}function Hr(t,n){if(t instanceof dn)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new dn(t,n)}var lf=(t)=>Array.isArray(t)&&t.length===2,Au=(t)=>Array.isArray(t)&&t.length>=5;class Wr extends Tt{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Wr.symbol}var jb=(t,n,s,r)=>Tt.assign(new Wr,{name:n,namespace:t,traits:r,schemaRef:s}),ab=(t,n,s,r)=>Tt.assign(new Wr,{name:n,namespace:t,traits:s,schemaRef:r}),pb={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class En{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,s=new Map){this.namespace=t,this.schemas=n,this.exceptions=s}static for(t){if(!En.registries.has(t))En.registries.set(t,new En(t));return En.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[r,i]of t.schemas)if(!n.has(r))n.set(r,i);for(let[r,i]of t.exceptions)if(!s.has(r))s.set(r,i)}register(t,n){let s=this.normalizeShapeId(t);for(let r of[this,En.for(s.split("#")[0])])r.schemas.set(s,n)}getSchema(t){let n=this.normalizeShapeId(t);if(!this.schemas.has(n)){if(!t.includes("#")){let s="#"+t,r=[];for(let[i,e]of this.schemas.entries())if(i.endsWith(s))r.push(e);if(r.length===1)return r[0]}throw Error(`@smithy/core/schema - schema not found for ${n}`)}return this.schemas.get(n)}registerError(t,n){let s=t,r=s[1];for(let i of[this,En.for(r)])i.schemas.set(r+"#"+s[2],s),i.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return En.for(n[1]).exceptions.get(n)}getBaseException(){for(let t of this.exceptions.keys())if(Array.isArray(t)){let[,n,s]=t,r=n+"#"+s;if(r.startsWith("smithy.ts.sdk.synthetic.")&&r.endsWith("ServiceException"))return t}return}find(t){for(let n of this.schemas.values())if(t(n))return n;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){if(t.includes("#"))return t;return this.namespace+"#"+t}}Zb.ErrorSchema=Vi;Zb.ListSchema=qi;Zb.MapSchema=Ci;Zb.NormalizedSchema=dn;Zb.OperationSchema=Ki;Zb.SCHEMA=pb;Zb.Schema=Tt;Zb.SimpleSchema=Wr;Zb.StructureSchema=Nr;Zb.TypeRegistry=En;Zb.deref=ki;Zb.deserializerMiddlewareOption=lu;Zb.error=Vb;Zb.getSchemaSerdePlugin=zb;Zb.isStaticSchema=Au;Zb.list=xb;Zb.map=qb;Zb.op=Cb;Zb.operation=wf;Zb.serializerMiddlewareOption=wu;Zb.sim=jb;Zb.simAdapter=ab;Zb.simpleSchemaCacheN=zi;Zb.simpleSchemaCacheS=xi;Zb.struct=Kb;Zb.traitsCache=Xi;Zb.translateTraits=Pr});var Rn=Z((e2)=>{var{getSmithyContext:I4,normalizeProvider:O4}=nn();e2.getSmithyContext=I4;e2.normalizeProvider=O4;var{SMITHY_CONTEXT_KEY:y4,AlgorithmId:ai}=is();e2.AlgorithmId=ai;var{NormalizedSchema:G4}=Nn(),es=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let r of n)s.push(r);return s},Wn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Dr=()=>{let t=[],n=[],s=!1,r=new Set,i=(_)=>_.sort((l,w)=>Mu[w.step]-Mu[l.step]||gu[w.priority||"normal"]-gu[l.priority||"normal"]),e=(_)=>{let l=!1,w=(A)=>{let M=es(A.name,A.aliases);if(M.includes(_)){l=!0;for(let E of M)r.delete(E);return!1}return!0};return t=t.filter(w),n=n.filter(w),l},f=(_)=>{let l=!1,w=(A)=>{if(A.middleware===_){l=!0;for(let M of es(A.name,A.aliases))r.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),l},o=(_)=>{return t.forEach((l)=>{_.add(l.middleware,{...l})}),n.forEach((l)=>{_.addRelativeTo(l.middleware,{...l})}),_.identifyOnResolve?.(u.identifyOnResolve()),_},c=(_)=>{let l=[];return _.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)l.push(w);else l.push(...c(w))}),l.push(_),_.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)l.push(w);else l.push(...c(w))}),l},h=(_=!1)=>{let l=[],w=[],A={};return t.forEach((E)=>{let d={...E,before:[],after:[]};for(let T of es(d.name,d.aliases))A[T]=d;l.push(d)}),n.forEach((E)=>{let d={...E,before:[],after:[]};for(let T of es(d.name,d.aliases))A[T]=d;w.push(d)}),w.forEach((E)=>{if(E.toMiddleware){let d=A[E.toMiddleware];if(d===void 0){if(_)return;throw Error(`${E.toMiddleware} is not found when adding ${Wn(E.name,E.aliases)} middleware ${E.relation} ${E.toMiddleware}`)}if(E.relation==="after")d.after.push(E);if(E.relation==="before")d.before.push(E)}}),i(l).map(c).reduce((E,d)=>{return E.push(...d),E},[])},u={add:(_,l={})=>{let{name:w,override:A,aliases:M}=l,E={step:"initialize",priority:"normal",middleware:_,...l},d=es(w,M);if(d.length>0){if(d.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of d){let U=t.findIndex((O)=>O.name===T||O.aliases?.some((D)=>D===T));if(U===-1)continue;let S=t[U];if(S.step!==E.step||E.priority!==S.priority)throw Error(`"${Wn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Wn(w,M)}" middleware with ${E.priority} priority in ${E.step} step.`);t.splice(U,1)}}for(let T of d)r.add(T)}t.push(E)},addRelativeTo:(_,l)=>{let{name:w,override:A,aliases:M}=l,E={middleware:_,...l},d=es(w,M);if(d.length>0){if(d.some((T)=>r.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of d){let U=n.findIndex((O)=>O.name===T||O.aliases?.some((D)=>D===T));if(U===-1)continue;let S=n[U];if(S.toMiddleware!==E.toMiddleware||S.relation!==E.relation)throw Error(`"${Wn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Wn(w,M)}" middleware ${E.relation} "${E.toMiddleware}" middleware.`);n.splice(U,1)}}for(let T of d)r.add(T)}n.push(E)},clone:()=>o(Dr()),use:(_)=>{_.applyToStack(u)},remove:(_)=>{if(typeof _==="string")return e(_);else return f(_)},removeByTag:(_)=>{let l=!1,w=(A)=>{let{tags:M,name:E,aliases:d}=A;if(M&&M.includes(_)){let T=es(E,d);for(let U of T)r.delete(U);return l=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),l},concat:(_)=>{let l=o(Dr());return l.use(_),l.identifyOnResolve(s||l.identifyOnResolve()||(_.identifyOnResolve?.()??!1)),l},applyToStack:o,identify:()=>{return h(!0).map((_)=>{let l=_.step??_.relation+" "+_.toMiddleware;return Wn(_.name,_.aliases)+" - "+l})},identifyOnResolve(_){if(typeof _==="boolean")s=_;return s},resolve:(_,l)=>{for(let w of h().map((A)=>A.middleware).reverse())_=w(_,l);if(s)console.log(u.identify());return _}};return u},Mu={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gu={high:3,normal:2,low:1},B4=(t)=>()=>{throw Error(t)},F4=(t)=>()=>Promise.reject(t),ji=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},H4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},Ru={minDelay:2,maxDelay:120},sn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(sn||(sn={}));var P4=(t)=>{if(t.state===sn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},ji())}`);throw n.name="AbortError",n}else if(t.state===sn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},ji())}`);throw n.name="TimeoutError",n}else if(t.state!==sn.SUCCESS)throw Error(`${JSON.stringify(t,ji())}`);return t},N4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:r,client:i,abortSignal:e},f,o)=>{let c={},[h,u]=[t*1000,n*1000],_=0,l=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(_>0){let d=Y4(h,u,_,l);if(r?.signal?.aborted||e?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:sn.ABORTED,observedResponses:c};if(Date.now()+d>l)return{state:sn.TIMEOUT,observedResponses:c};await H4(d/1000)}let{state:M,reason:E}=await o(i,f);if(E){let d=D4(E);c[d]|=0,c[d]+=1}if(M!==sn.RETRY)return{state:M,reason:E,final:E,observedResponses:c};if(_+=1,!A&&Date.now()>=w)W4(c,i),A=!0}},W4=(t={},n)=>{let s=Object.keys(t),r=0;for(let f of s){let o=t[f]|0;if(f.startsWith("403:"))r+=o}let i=n?.config?.logger,e=typeof i?.warn==="function"&&!i.constructor?.name?.includes?.("NoOpLogger")?i:console;if(r>=3||s[s.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},D4=(t)=>{let n=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;if(t?.$responseBodyText)return`${n?n+": ":""}Deserialization error for body: ${t.$responseBodyText}`;if(n){if(t?.$response||t?.message)return`${n??"Unknown"}: ${t?.message}`;return`${n}: OK`}return String(t?.message??JSON.stringify(t,ji())??"Unknown")},Y4=(t,n,s,r)=>{let i=Math.log(n/t)/Math.log(2)+1;if(s>i)return n;let e=t*2**(s-1),f=Math.min(e,n),o=m4(t,f);if(Date.now()+o>r){let c=r-Date.now();return Math.max(0,c-500)}return o},m4=(t,n)=>t+Math.random()*(n-t),Q4=(t)=>{if(t.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(t.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(t.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(t.maxWaitTime<=t.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);else if(t.maxDelay<t.minDelay)throw Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)},Eu=(t)=>{let n,s=new Promise((r)=>{if(n=()=>r({state:sn.ABORTED}),typeof t.addEventListener==="function")t.addEventListener("abort",n);else t.onabort=n});return{clearListener(){if(typeof t.removeEventListener==="function")t.removeEventListener("abort",n)},aborted:s}},J4=async(t,n,s)=>{let r={...Ru,...t};Q4(r);let i=[N4(r,n,s)],e=[];if(t.abortSignal){let{aborted:f,clearListener:o}=Eu(t.abortSignal);e.push(o),i.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=Eu(t.abortController.signal);e.push(o),i.push(f)}return Promise.race(i).then((f)=>{for(let o of e)o();return f})};class bu{config;middlewareStack=Dr();initConfig;handlers;constructor(t){this.config=t;let{protocol:n,protocolSettings:s}=t;if(s){if(typeof n==="function")t.protocol=new n(s)}}send(t,n,s){let r=typeof n!=="function"?n:void 0,i=typeof n==="function"?n:s,e=r===void 0&&this.config.cacheMiddleware===!0,f;if(e){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(t.constructor))f=o.get(t.constructor);else f=t.resolveMiddleware(this.middlewareStack,this.config,r),o.set(t.constructor,f)}else delete this.handlers,f=t.resolveMiddleware(this.middlewareStack,this.config,r);if(i)f(t).then((o)=>i(null,o.output),(o)=>i(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Af="***SensitiveInformation***";function pi(t,n){if(n==null)return n;let s=G4.of(t);if(s.getMergedTraits().sensitive)return Af;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isStructSchema()&&typeof n==="object"){let r=n,i={};for(let[e,f]of s.structIterator())if(r[e]!=null)i[e]=pi(f,r[e]);return i}return n}class Zi{middlewareStack=Dr();schema;static classBuilder(){return new Tu}resolveMiddlewareWithContext(t,n,s,{middlewareFn:r,clientName:i,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let E of r.bind(this)(u,t,n,s))this.middlewareStack.use(E);let _=t.concat(this.middlewareStack),{logger:l}=n,w={logger:l,clientName:i,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[y4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return _.resolve((E)=>A.handle(E.request,M),w)}}class Tu{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,s={}){return this._smithyContext={service:t,operation:n,...s},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=(s)=>s,n=(s)=>s){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){let t=this,n;return n=class extends Zi{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,r,i){let e=t._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(s,r,i,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(e?pi.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(e?pi.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var k4="***SensitiveInformation***",X4=(t,n,s)=>{for(let[e,f]of Object.entries(t)){let o=async function(h,u,_){let l=new f(h);if(typeof u==="function")this.send(l,u);else if(typeof _==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(l,u||{},_)}else return this.send(l,u)},c=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:r={},waiters:i={}}=s??{};for(let[e,f]of Object.entries(r))if(n.prototype[e]===void 0)n.prototype[e]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[e,f]of Object.entries(i))if(n.prototype[e]===void 0)n.prototype[e]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Js extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;let n=t;return Js.prototype.isPrototypeOf(n)||Boolean(n.$fault)&&Boolean(n.$metadata)&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;let n=t;if(this===Js)return Js.isInstance(t);if(Js.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var Su=(t,n={})=>{Object.entries(n).filter(([,r])=>r!==void 0).forEach(([r,i])=>{if(t[r]==null||t[r]==="")t[r]=i});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},$u=({output:t,parsedBody:n,exceptionCtor:s,errorCode:r})=>{let i=x4(t),e=i.httpStatusCode?i.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||r||e||"UnknownError",$fault:"client",$metadata:i});throw Su(f,n)},z4=(t)=>{return({output:n,parsedBody:s,errorCode:r})=>{$u({output:n,parsedBody:s,exceptionCtor:t,errorCode:r})}},x4=(t)=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}),q4=(t)=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}},du=!1,C4=(t)=>{if(t&&!du&&parseInt(t.substring(1,t.indexOf(".")))<16)du=!0},Uu=Object.values(ai),Lu=(t)=>{let n=[];for(let s in ai){let r=ai[s];if(t[r]===void 0)continue;n.push({algorithmId:()=>r,checksumConstructor:()=>t[r]})}for(let[s,r]of Object.entries(t.checksumAlgorithms??{}))n.push({algorithmId:()=>s,checksumConstructor:()=>r});return{addChecksumAlgorithm(s){t.checksumAlgorithms=t.checksumAlgorithms??{};let r=s.algorithmId(),i=s.checksumConstructor();if(Uu.includes(r))t.checksumAlgorithms[r.toUpperCase()]=i;else t.checksumAlgorithms[r]=i;n.push(s)},checksumAlgorithms(){return n}}},Iu=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let r=s.algorithmId();if(Uu.includes(r))n[r]=s.checksumConstructor()}),n},Ou=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},yu=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},Gu=(t)=>{return Object.assign(Lu(t),Ou(t))},K4=Gu,V4=(t)=>{return Object.assign(Iu(t),yu(t))},j4=(t)=>Array.isArray(t)?t:[t],Bu=(t)=>{for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]["#text"]!==void 0)t[s]=t[s]["#text"];else if(typeof t[s]==="object"&&t[s]!==null)t[s]=Bu(t[s]);return t},a4=(t)=>{return t!=null};class Fu{trace(){}debug(){}info(){}warn(){}error(){}}function Hu(t,n,s){let r,i,e;if(typeof n>"u"&&typeof s>"u")r={},e=t;else if(r=t,typeof n==="function")return i=n,e=s,v4(r,i,e);else e=n;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){r[f]=e[f];continue}Pu(r,null,e,f)}return r}var p4=(t)=>{let n={};for(let[s,r]of Object.entries(t||{}))n[s]=[,r];return n},Z4=(t,n)=>{let s={};for(let r in n)Pu(s,t,n,r);return s},v4=(t,n,s)=>{return Hu(t,Object.entries(s).reduce((r,[i,e])=>{if(Array.isArray(e))r[i]=e;else if(typeof e==="function")r[i]=[n,e()];else r[i]=[n,e];return r},{}))},Pu=(t,n,s,r)=>{if(n!==null){let f=s[r];if(typeof f==="function")f=[,f];let[o=t2,c=n2,h=r]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[r]=c(n[h]);return}let[i,e]=s[r];if(typeof e==="function"){let f,o=i===void 0&&(f=e())!=null,c=typeof i==="function"&&!!i(void 0)||typeof i!=="function"&&!!i;if(o)t[r]=f;else if(c)t[r]=e()}else{let f=i===void 0&&e!=null,o=typeof i==="function"&&!!i(e)||typeof i!=="function"&&!!i;if(f||o)t[r]=e}},t2=(t)=>t!=null,n2=(t)=>t,s2=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},r2=(t)=>t.toISOString().replace(".000Z","Z"),Mf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(Mf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=Mf(t[s])}return n}return t};function i2(t,n,s,r){return function(e,f,o,c,h={}){let u=Object.assign({},t,e);return Zi.classBuilder().ep(u).m(function(_,l,w,A){let M=f.call(this,_,l,w,A);return M.unshift(r(w,_.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}e2.Client=bu;e2.Command=Zi;e2.NoOpLogger=Fu;e2.SENSITIVE_STRING=k4;e2.ServiceException=Js;e2.WaiterState=sn;e2._json=Mf;e2.checkExceptions=P4;e2.constructStack=Dr;e2.convertMap=p4;e2.createAggregatedClient=X4;e2.createWaiter=J4;e2.decorateServiceException=Su;e2.emitWarningIfUnsupportedVersion=C4;e2.getArrayIfSingleItem=j4;e2.getChecksumConfiguration=Lu;e2.getDefaultClientConfiguration=K4;e2.getDefaultExtensionConfiguration=Gu;e2.getRetryConfiguration=Ou;e2.getValueFromTextNode=Bu;e2.invalidFunction=B4;e2.invalidProvider=F4;e2.isSerializableHeaderValue=a4;e2.loadConfigsForDefaultMode=q4;e2.makeBuilder=i2;e2.map=Hu;e2.resolveChecksumRuntimeConfig=Iu;e2.resolveDefaultRuntimeConfig=V4;e2.resolveRetryRuntimeConfig=yu;e2.schemaLogFilter=pi;e2.serializeDateTime=r2;e2.serializeFloat=s2;e2.take=Z4;e2.throwDefaultError=$u;e2.waiterServiceDefaults=Ru;e2.withBaseException=z4});var St=Z((qT)=>{var{homedir:q2}=nt("os"),{sep:C2,join:Yr}=nt("path"),{createHash:K2}=nt("crypto"),{readFile:Xu}=nt("fs/promises"),{IniSectionType:vi}=is(),{normalizeProvider:te}=Rn(),{isValidHostLabel:V2}=nn();class ks extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let s,r=!0;if(typeof n==="boolean")s=void 0,r=n;else if(n!=null&&typeof n==="object")s=n.logger,r=n.tryNextLink??!0;super(t);this.tryNextLink=r,Object.setPrototypeOf(this,ks.prototype),s?.debug?.(`@smithy/property-provider ${r?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class mr extends ks{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,mr.prototype)}}class bf extends ks{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,bf.prototype)}}var zu=(...t)=>async()=>{if(t.length===0)throw new ks("No providers in chain");let n;for(let s of t)try{return await s()}catch(r){if(n=r,r?.tryNextLink)continue;throw r}throw n},xu=(t)=>()=>Promise.resolve(t),Tf=(t,n,s)=>{let r,i,e,f=!1,o=async()=>{if(!i)i=t();try{r=await i,e=!0,f=!1}finally{i=void 0}return r};if(n===void 0)return async(c)=>{if(!e||c?.forceRefresh)r=await o();return r};return async(c)=>{if(!e||c?.forceRefresh)r=await o();if(f)return r;if(s&&!s(r))return f=!0,r;if(n(r))return await o(),r;return r}},bn=(t,n,s)=>{if(!(n in t))return;if(t[n]==="true")return!0;if(t[n]==="false")return!1;throw Error(`Cannot load ${s} "${n}". Expected "true" or "false", got ${t[n]}.`)},j2=(t,n,s)=>{if(!(n in t))return;let r=parseInt(t[n],10);if(Number.isNaN(r))throw TypeError(`Cannot load ${s} '${n}'. Expected number, got '${t[n]}'.`);return r},zt;(function(t){t.ENV="env",t.CONFIG="shared config entry"})(zt||(zt={}));var gf={},a2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Qr=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:r=`C:${C2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${r}${s}`;let i=a2();if(!gf[i])gf[i]=q2();return gf[i]},qu="AWS_PROFILE",Cu="default",Ku=(t)=>t.profile||process.env[qu]||Cu,Vu=(t)=>{let s=K2("sha1").update(t).digest("hex");return Yr(Qr(),".aws","sso","cache",`${s}.json`)},ne={},p2=async(t)=>{if(ne[t])return ne[t];let n=Vu(t),s=await Xu(n,"utf8");return JSON.parse(s)},os=".",Z2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(vi).includes(n.substring(0,s))}).reduce((n,[s,r])=>{let i=s.indexOf(os),e=s.substring(0,i)===vi.PROFILE?s.substring(i+1):s;return n[e]=r,n},{...t.default&&{default:t.default}}),v2="AWS_CONFIG_FILE",ju=()=>process.env[v2]||Yr(Qr(),".aws","config"),tT="AWS_SHARED_CREDENTIALS_FILE",nT=()=>process.env[tT]||Yr(Qr(),".aws","credentials"),sT=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,rT=["__proto__","profile __proto__"],df=(t)=>{let n={},s,r;for(let i of t.split(/\r?\n/)){let e=i.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){s=void 0,r=void 0;let o=e.substring(1,e.length-1),c=sT.exec(o);if(c){let[,h,,u]=c;if(Object.values(vi).includes(h))s=[h,u].join(os)}else s=o;if(rT.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=e.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(h==="")r=c;else{if(r&&i.trimStart()===i)r=void 0;n[s]=n[s]||{};let u=r?[r,c].join(os):c;n[s][u]=h}}}}return n},Ef={},se={},re=(t,n)=>{if(se[t]!==void 0)return se[t];if(!Ef[t]||n?.ignoreCache)Ef[t]=Xu(t,"utf8");return Ef[t]},Nu=()=>({}),Sf=async(t={})=>{let{filepath:n=nT(),configFilepath:s=ju()}=t,r=Qr(),i="~/",e=n;if(n.startsWith("~/"))e=Yr(r,n.slice(2));let f=s;if(s.startsWith("~/"))f=Yr(r,s.slice(2));let o=await Promise.all([re(f,{ignoreCache:t.ignoreCache}).then(df).then(Z2).catch(Nu),re(e,{ignoreCache:t.ignoreCache}).then(df).catch(Nu)]);return{configFile:o[0],credentialsFile:o[1]}},iT=(t)=>Object.entries(t).filter(([n])=>n.startsWith(vi.SSO_SESSION+os)).reduce((n,[s,r])=>({...n,[s.substring(s.indexOf(os)+1)]:r}),{}),eT=()=>({}),oT=async(t={})=>re(t.configFilepath??ju()).then(df).then(iT).catch(eT),fT=(...t)=>{let n={};for(let s of t)for(let[r,i]of Object.entries(s))if(n[r]!==void 0)Object.assign(n[r],i);else n[r]=i;return n},cT=async(t)=>{let n=await Sf(t);return fT(n.configFile,n.credentialsFile)},hT={getFileRecord(){return se},interceptFile(t,n){se[t]=Promise.resolve(n)},getTokenRecord(){return ne},interceptToken(t,n){ne[t]=n}};function au(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var uT=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new mr(s.message||`Not found in ENV: ${au(t.toString())}`,{logger:n?.logger})}},_T=(t,{preferredFile:n="config",...s}={})=>async()=>{let r=Ku(s),{configFile:i,credentialsFile:e}=await Sf(s),f=e[r]||{},o=i[r]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?i:e);if(u===void 0)throw Error();return u}catch(h){throw new mr(h.message||`Not found in config files w/ profile [${r}]: ${au(t.toString())}`,{logger:s.logger})}},lT=(t)=>typeof t==="function",pu=(t)=>lT(t)?async()=>await t():xu(t),Rf=({environmentVariableSelector:t,configFileSelector:n,default:s},r={})=>{let{signingName:i,logger:e}=r;return Tf(zu(uT(t,{signingName:i,logger:e}),_T(n,r),pu(s)))},$f="AWS_USE_DUALSTACK_ENDPOINT",Uf="use_dualstack_endpoint",wT=!1,AT={environmentVariableSelector:(t)=>bn(t,$f,zt.ENV),configFileSelector:(t)=>bn(t,Uf,zt.CONFIG),default:!1},MT={environmentVariableSelector:(t)=>bn(t,$f,zt.ENV),configFileSelector:(t)=>bn(t,Uf,zt.CONFIG),default:void 0},Lf="AWS_USE_FIPS_ENDPOINT",If="use_fips_endpoint",gT=!1,ET={environmentVariableSelector:(t)=>bn(t,Lf,zt.ENV),configFileSelector:(t)=>bn(t,If,zt.CONFIG),default:!1},dT={environmentVariableSelector:(t)=>bn(t,Lf,zt.ENV),configFileSelector:(t)=>bn(t,If,zt.CONFIG),default:void 0},RT=(t)=>{let{tls:n,endpoint:s,urlParser:r,useDualstackEndpoint:i}=t;return Object.assign(t,{tls:n??!0,endpoint:te(typeof s==="string"?r(s):s),isCustomEndpoint:!0,useDualstackEndpoint:te(i??!1)})},bT=async(t)=>{let{tls:n=!0}=t,s=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(s))throw Error("Invalid region in client config");let i=await t.useDualstackEndpoint(),e=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:i,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},TT=(t)=>{let n=te(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:r,urlParser:i,tls:e}=t;return Object.assign(t,{tls:e??!0,endpoint:s?te(typeof s==="string"?i(s):s):()=>bT({...t,useDualstackEndpoint:n,useFipsEndpoint:r}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},ST="AWS_EXECUTION_ENV",Wu="AWS_REGION",Du="AWS_DEFAULT_REGION",$T="AWS_EC2_METADATA_DISABLED",UT=["in-region","cross-region","mobile","standard","legacy"],LT="/latest/meta-data/placement/region",IT="/latest/api/token",OT="x-aws-ec2-metadata-token",yT="x-aws-ec2-metadata-token-ttl-seconds",Yu=1000,GT=60000,Zu=0,vu=async()=>{if(process.env[$T])return;if(Date.now()<Zu)return;try{let t=BT(),n=(await Qu({...t,path:IT,method:"PUT",headers:{[yT]:"21600"}})).toString();return(await Qu({...t,path:LT,method:"GET",headers:{[OT]:n}})).toString().trim()||mu()}catch{return mu()}},mu=()=>{Zu=Date.now()+GT;return},BT=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let n=new URL(t);return{hostname:n.hostname.replace(/^\[(.+)]$/,"$1"),port:n.port?Number(n.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Qu=async(t)=>{let{request:n}=nt("http");return new Promise((s,r)=>{let i=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:Yu,signal:AbortSignal.timeout(Yu)});i.on("error",(e)=>{r(e),i.destroy()}),i.on("timeout",()=>{r(Error("TimeoutError from instance metadata service")),i.destroy()}),i.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){r(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),i.destroy();return}let o=[];e.on("data",(c)=>o.push(c)),e.on("end",()=>{s(Buffer.concat(o)),i.destroy()})}),i.end()})},t_="AWS_REGION",n_="region",s_={environmentVariableSelector:(t)=>t[t_],configFileSelector:(t)=>t[n_],default:async()=>{let t=await vu();if(t)return t;throw Error("Region is missing")}},FT={preferredFile:"credentials"},Ju=new Set,HT=(t,n=V2)=>{if(!Ju.has(t)&&!n(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else Ju.add(t)},r_=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),PT=(t)=>r_(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,NT=(t)=>{let{region:n,useFipsEndpoint:s}=t;if(!n)throw Error("Region is missing");return Object.assign(t,{region:async()=>{let r=typeof n==="function"?await n():n,i=PT(r);return HT(i),i},useFipsEndpoint:async()=>{let r=typeof n==="string"?n:await n();if(r_(r))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},ku=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:r})=>n===r.includes("fips")&&s===r.includes("dualstack"))?.hostname,WT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,DT=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",YT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:r})=>{if(n)return n;else if(r){let i=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=t.match(i);if(e)return e[0].slice(1,-1)}},mT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:r,regionHash:i,partitionHash:e})=>{let f=DT(t,{partitionHash:e}),o=t in i?t:e[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=ku(i[o]?.variants,c),u=ku(e[f]?.variants,c),_=WT(o,{regionHostname:h,partitionHostname:u});if(_===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let l=YT(_,{signingRegion:i[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:r,hostname:_,...l&&{signingRegion:l},...i[o]?.signingService&&{signingService:i[o].signingService}}},QT="AWS_DEFAULTS_MODE",JT="defaults_mode",kT={environmentVariableSelector:(t)=>{return t[QT]},configFileSelector:(t)=>{return t[JT]},default:"legacy"},XT=({region:t=Rf(s_),defaultsMode:n=Rf(kT)}={})=>Tf(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return zT(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(s?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${UT.join(", ")}, got ${s}`)}}),zT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await xT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},xT=async()=>{if(process.env[ST]&&(process.env[Wu]||process.env[Du]))return process.env[Wu]??process.env[Du];return vu()};qT.CONFIG_PREFIX_SEPARATOR=os;qT.CONFIG_USE_DUALSTACK_ENDPOINT=Uf;qT.CONFIG_USE_FIPS_ENDPOINT=If;qT.CredentialsProviderError=mr;qT.DEFAULT_PROFILE=Cu;qT.DEFAULT_USE_DUALSTACK_ENDPOINT=wT;qT.DEFAULT_USE_FIPS_ENDPOINT=gT;qT.ENV_PROFILE=qu;qT.ENV_USE_DUALSTACK_ENDPOINT=$f;qT.ENV_USE_FIPS_ENDPOINT=Lf;qT.NODE_REGION_CONFIG_FILE_OPTIONS=FT;qT.NODE_REGION_CONFIG_OPTIONS=s_;qT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=AT;qT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=ET;qT.ProviderError=ks;qT.REGION_ENV_NAME=t_;qT.REGION_INI_NAME=n_;qT.SelectorType=zt;qT.TokenProviderError=bf;qT.booleanSelector=bn;qT.chain=zu;qT.externalDataInterceptor=hT;qT.fromStatic=pu;qT.fromValue=xu;qT.getHomeDir=Qr;qT.getProfileName=Ku;qT.getRegionInfo=mT;qT.getSSOTokenFilepath=Vu;qT.getSSOTokenFromFile=p2;qT.loadConfig=Rf;qT.loadSharedConfigFiles=Sf;qT.loadSsoSessionData=oT;qT.memoize=Tf;qT.nodeDualstackConfigSelectors=MT;qT.nodeFipsConfigSelectors=dT;qT.numberSelector=j2;qT.parseKnownFiles=cT;qT.readFile=re;qT.resolveCustomEndpointsConfig=RT;qT.resolveDefaultsModeConfig=XT;qT.resolveEndpointsConfig=TT;qT.resolveRegionConfig=NT});var fs=Z((d5)=>{var{CONFIG_PREFIX_SEPARATOR:i_,loadConfig:N6}=St(),{toEndpointV1:ie,getSmithyContext:W6,normalizeProvider:Of,isValidHostLabel:f_}=nn();d5.isValidHostLabel=f_;d5.middlewareEndpointToEndpointV1=ie;d5.toEndpointV1=ie;var{EndpointURLScheme:Bf}=is(),e_="AWS_ENDPOINT_URL",o_="endpoint_url",D6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((e)=>e.toUpperCase()),r=n[[e_,...s].join("_")];if(r)return r;let i=n[e_];if(i)return i;return},configFileSelector:(n,s)=>{if(s&&n.services){let i=s[["services",n.services].join(i_)];if(i){let e=t.split(" ").map((o)=>o.toLowerCase()),f=i[[e.join("_"),o_].join(i_)];if(f)return f}}let r=n[o_];if(r)return r;return},default:void 0}),ee=async(t)=>N6(D6(t??""))(),Y6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(X6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!k6(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},m6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,Q6=/(\d+\.){3}\d+/,J6=/\.\./,k6=(t)=>m6.test(t)&&!Q6.test(t)&&!J6.test(t),X6=(t)=>{let[n,s,r,,,i]=t.split(":"),e=n==="arn"&&t.split(":").length>=6,f=Boolean(e&&s&&r&&i);if(e&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},z6=(t,n,s,r=!1)=>{let i=async()=>{let e;if(r)e=s.clientContextParams?.[t]??s[t]??s[n];else e=s[t]??s[n];if(typeof e==="function")return e();return e};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.credentialScope??e?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.accountId??e?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.isCustomEndpoint===!1)return;let e=await i();if(e&&typeof e==="object"){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:f,hostname:o,port:c,path:h}=e;return`${f}//${o}${c?":"+c:""}${h}`}}return e};return i};function c_(t){return async(n,s,r,i)=>{if(!r.isCustomEndpoint){let o;if(r.serviceConfiguredEndpoint)o=await r.serviceConfiguredEndpoint();else o=await t(r.serviceId);if(o)r.endpoint=()=>Promise.resolve(ie(o)),r.isCustomEndpoint=!0}let e=await h_(n,s,r);if(typeof r.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=r.endpointProvider(e,i);if(r.isCustomEndpoint&&r.endpoint){let o=await r.endpoint();if(o?.headers){f.headers??={};for(let[c,h]of Object.entries(o.headers))f.headers[c]=Array.isArray(h)?h:[h]}}return f}}var h_=async(t,n,s)=>{let r={},i=n?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(i))switch(f.type){case"staticContextParams":r[e]=f.value;break;case"contextParams":r[e]=t[f.name];break;case"clientContextParams":case"builtInParams":r[e]=await z6(f.name,e,s,f.type!=="builtInParams")();break;case"operationContextParams":r[e]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(i).length===0)Object.assign(r,s);if(String(s.serviceId).toLowerCase()==="s3")await Y6(r);return r};function x6(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}function u_(t){let n=c_(t);return({config:s,instructions:r})=>{return(i,e)=>async(f)=>{if(s.isCustomEndpoint)x6(e,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return r}},{...s},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let c=e.authSchemes?.[0];if(c){e.signing_region=c.signingRegion,e.signing_service=c.signingName;let u=W6(e)?.selectedHttpAuthScheme?.httpAuthOption;if(u)u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return i({...f})}}}var q6={name:"serializerMiddleware"},__={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:q6.name};function C6(t){let n=u_(t);return(s,r)=>({applyToStack:(i)=>{i.addRelativeTo(n({config:s,instructions:r}),__)}})}function K6(t){return(n)=>{let s=n.tls??!0,{endpoint:r,useDualstackEndpoint:i,useFipsEndpoint:e}=n,f=r!=null?async()=>ie(await Of(r)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!r,useDualstackEndpoint:Of(i??!1),useFipsEndpoint:Of(e??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Ff{nodes;root;conditions;results;constructor(t,n,s,r){this.nodes=t,this.root=n,this.conditions=s,this.results=r}static from(t,n,s,r){return new Ff(t,n,s,r)}}class l_{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){if(this.capacity=t??50,n)this.parameters=n}get(t,n){let s=this.hash(t);if(s===!1)return n();if(!this.data.has(s)){if(this.data.size>this.capacity+10){let r=this.data.keys(),i=0;while(!0){let{value:e,done:f}=r.next();if(this.data.delete(e),f||++i>10)break}}this.data.set(s,n())}return this.data.get(s)}size(){return this.data.size}hash(t){let n="",{parameters:s}=this;if(s.length===0)return!1;for(let r of s){let i=String(t[r]??"");if(i.includes("|;"))return!1;n+=i+"|;"}return n}}class wt extends Error{constructor(t){super(t);this.name="EndpointError"}}var Jr="endpoints";function Dn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Dn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Dn).join(", ")})`;return JSON.stringify(t,null,2)}var w_={},V6=(t,n)=>t===n;function j6(...t){for(let n of t)if(n!=null)return n;return}var a6=(t)=>{let n=t.split("."),s=[];for(let r of n){let i=r.indexOf("[");if(i!==-1){if(r.indexOf("]")!==r.length-1)throw new wt(`Path: '${t}' does not end with ']'`);let e=r.slice(i+1,-1);if(Number.isNaN(parseInt(e)))throw new wt(`Invalid array index: '${e}' in path: '${t}'`);if(i!==0)s.push(r.slice(0,i));s.push(e)}else s.push(r)}return s},A_=(t,n)=>a6(n).reduce((s,r)=>{if(typeof s!=="object")throw new wt(`Index '${r}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let i=parseInt(r);return s[i<0?s.length+i:i]}return s[r]},t),p6=(t)=>t!=null;function Z6(t,n,s){return t?n:s}var v6=(t)=>!t,t5=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),M_=(t)=>t5.test(t)||t.startsWith("[")&&t.endsWith("]"),yf={[Bf.HTTP]:80,[Bf.HTTPS]:443},n5=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:l,port:w,protocol:A="",path:M="",query:E={}}=t,d=new URL(`${A}//${l}${w?`:${w}`:""}${M}`);return d.search=Object.entries(E).map(([T,U])=>`${T}=${U}`).join("&"),d}return new URL(t)}catch(l){return null}})();if(!n)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let s=n.href,{host:r,hostname:i,pathname:e,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values(Bf).includes(c))return null;let h=M_(i),u=s.includes(`${r}:${yf[c]}`)||typeof t==="string"&&t.includes(`${r}:${yf[c]}`),_=`${r}${u?`:${yf[c]}`:""}`;return{scheme:c,authority:_,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:h}};function s5(t,n,s){if(s===1)return[t];if(t==="")return[""];let r=t.split(n);if(s===0)return r;return r.slice(0,s-1).concat(r.slice(1).join(n))}var r5=(t,n)=>t===n,i5=(t,n,s,r)=>{if(t==null||n>=s||t.length<s||/[^\u0000-\u007f]/.test(t))return null;if(!r)return t.substring(n,s);return t.substring(t.length-s,t.length-n)},e5=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),o5={booleanEquals:V6,coalesce:j6,getAttr:A_,isSet:p6,isValidHostLabel:f_,ite:Z6,not:v6,parseURL:n5,split:s5,stringEquals:r5,substring:i5,uriEncode:e5},g_=(t,n)=>{let s=[],{referenceRecord:r,endpointParams:i}=n,e=0;while(e<t.length){let f=t.indexOf("{",e);if(f===-1){s.push(t.slice(e));break}s.push(t.slice(e,f));let o=t.indexOf("}",f);if(o===-1){s.push(t.slice(f));break}if(t[f+1]==="{"&&t[o+1]==="}")s.push(t.slice(f+1,o)),e=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(A_(r[h]??i[h],u))}else s.push(r[c]??i[c]);e=o+1}return s.join("")},f5=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},kr=(t,n,s)=>{if(typeof t==="string")return g_(t,s);else if(t.fn)return d_.callFunction(t,s);else if(t.ref)return f5(t,s);throw new wt(`'${n}': ${String(t)} is not a string, function or reference.`)},E_=({fn:t,argv:n},s)=>{let r=Array(n.length);for(let f=0;f<r.length;++f){let o=n[f];if(typeof o==="boolean"||typeof o==="number")r[f]=o;else r[f]=d_.evaluateExpression(o,"arg",s)}let i=t.indexOf(".");if(i!==-1){let o=w_[t.slice(0,i)]?.[t.slice(i+1)];if(typeof o==="function")return o(...r)}let e=o5[t];if(typeof e==="function")return e(...r);throw Error(`function ${t} not loaded in endpointFunctions.`)},d_={evaluateExpression:kr,callFunction:E_},R_=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new wt(`'${s}' is already defined in Reference Record.`);let r=E_(t,n);n.logger?.debug?.(`${Jr} evaluateCondition: ${Dn(t)} = ${Dn(r)}`);let i=r===""?!0:!!r;if(s!=null)return{result:i,toAssign:{name:s,value:r}};return{result:i}},b_=(t,n)=>Object.entries(t??{}).reduce((s,[r,i])=>{return s[r]=i.map((e)=>{let f=kr(e,"Header value entry",n);if(typeof f!=="string")throw new wt(`Header '${r}' value '${f}' is not a string`);return f}),s},{}),Hf=(t,n)=>Object.entries(t).reduce((s,[r,i])=>{return s[r]=S_.getEndpointProperty(i,n),s},{}),T_=(t,n)=>{if(Array.isArray(t))return t.map((s)=>T_(s,n));switch(typeof t){case"string":return g_(t,n);case"object":if(t===null)throw new wt(`Unexpected endpoint property: ${t}`);return S_.getEndpointProperties(t,n);case"boolean":return t;default:throw new wt(`Unexpected endpoint property type: ${typeof t}`)}},S_={getEndpointProperty:T_,getEndpointProperties:Hf},$_=(t,n)=>{let s=kr(t,"Endpoint URL",n);if(typeof s==="string")try{return new URL(s)}catch(r){throw console.error(`Failed to construct URL with ${s}`,r),r}throw new wt(`Endpoint URL must be a string, got ${typeof s}`)},Gf=1e8,c5=(t,n)=>{let{nodes:s,root:r,results:i,conditions:e}=t,f=r,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Gf){let h=3*(Math.abs(f)-1),[u,_,l]=[s[h],s[h+1],s[h+2]],[w,A,M]=e[u],E=R_({fn:w,assign:M,argv:A},c);if(E.toAssign){let{name:d,value:T}=E.toAssign;o[d]=T}f=f>=0===E.result?_:l}if(f>=Gf){let h=i[f-Gf];if(h[0]===-1){let[,w]=h;throw new wt(kr(w,"Error",c))}let[u,_,l]=h;return{url:$_(u,c),properties:Hf(_,c),headers:b_(l??{},c)}}throw new wt("No matching endpoint.")},Pf=(t=[],n)=>{let s={},r={...n,referenceRecord:{...n.referenceRecord}},i=!1;for(let e of t){let{result:f,toAssign:o}=R_(e,r);if(!f)return{result:f};if(o)i=!0,s[o.name]=o.value,r.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Jr} assign: ${o.name} := ${Dn(o.value)}`)}if(i)return{result:!0,referenceRecord:s};return{result:!0}},h5=(t,n)=>{let{conditions:s,endpoint:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n,{url:o,properties:c,headers:h}=r;n.logger?.debug?.(`${Jr} Resolving endpoint from template: ${Dn(r)}`);let u={url:$_(o,f)};if(h!=null)u.headers=b_(h,f);if(c!=null)u.properties=Hf(c,f);return u},u5=(t,n)=>{let{conditions:s,error:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;throw new wt(kr(r,"Error",f))},U_=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let r=h5(s,n);if(r)return r}else if(s.type==="error")u5(s,n);else if(s.type==="tree"){let r=L_.evaluateTreeRule(s,n);if(r)return r}else throw new wt(`Unknown endpoint rule: ${s}`);throw new wt("Rules evaluation failed")},_5=(t,n)=>{let{conditions:s,rules:r}=t,{result:i,referenceRecord:e}=Pf(s,n);if(!i)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;return L_.evaluateRules(r,f)},L_={evaluateRules:U_,evaluateTreeRule:_5},l5=(t,n)=>{let{endpointParams:s,logger:r}=n,{parameters:i,rules:e}=t;n.logger?.debug?.(`${Jr} Initial EndpointParams: ${Dn(s)}`);for(let o in i){let c=i[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new wt(`Missing required parameter: '${o}'`)}let f=U_(e,{endpointParams:s,logger:r,referenceRecord:{}});return n.logger?.debug?.(`${Jr} Resolved endpoint: ${Dn(f)}`),f},w5=(t)=>{let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return t},A5=c_(ee),M5=K6(ee),g5=u_(ee),E5=C6(ee);d5.BinaryDecisionDiagram=Ff;d5.EndpointCache=l_;d5.EndpointError=wt;d5.customEndpointFunctions=w_;d5.decideEndpoint=c5;d5.endpointMiddleware=g5;d5.endpointMiddlewareOptions=__;d5.getEndpointFromInstructions=A5;d5.getEndpointPlugin=E5;d5.isIpAddress=M_;d5.resolveEndpoint=l5;d5.resolveEndpointConfig=M5;d5.resolveEndpointRequiredConfig=w5;d5.resolveParams=h_});var $t=Z((uS)=>{var{createHmac:D5,createHash:Y5,getRandomValues:m5}=nt("crypto"),{ReadStream:Q5,lstatSync:J5,fstatSync:k5}=nt("fs"),{HttpResponse:X5}=nn(),{toEndpointV1:z5}=fs(),{Readable:Xs,Writable:P_,PassThrough:I_}=nt("stream"),N_=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",xs=(t,n=0,s=t.byteLength-n)=>{if(!N_(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},he=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?Buffer.from(t,n):Buffer.from(t)},x5=/^[A-Za-z0-9+/]*={0,2}$/,W_=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!x5.exec(t))throw TypeError("Invalid base64 string.");let n=he(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},ue=(t)=>{let n=he(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},kf=(t)=>{let n;if(typeof t==="string")n=ue(t);else n=t;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return xs(n.buffer,n.byteOffset,n.byteLength).toString("base64")};function q5(t,n,s,r){return class i extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return i.mutate(r(e));return i.mutate(n(e))}throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,i.prototype),e}transformToString(e="utf-8"){if(e==="base64")return s(this);return t(this)}}}var D_=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return xs(t.buffer,t.byteOffset,t.byteLength).toString("utf8")},Et=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function C5(t){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let n=new Uint8Array(16);return t(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,Et[n[0]]+Et[n[1]]+Et[n[2]]+Et[n[3]]+"-"+Et[n[4]]+Et[n[5]]+"-"+Et[n[6]]+Et[n[7]]+"-"+Et[n[8]]+Et[n[9]]+"-"+Et[n[10]]+Et[n[11]]+Et[n[12]]+Et[n[13]]+Et[n[14]]+Et[n[15]]}}var K5=(t,n,s=(r)=>r)=>t,V5=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},j5=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)qr.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(t===0)return!1;if(t===1)return!0}if(typeof t==="string"){let n=t.toLowerCase();if(n==="false"||n==="true")qr.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(n==="false")return!1;if(n==="true")return!0}if(typeof t==="boolean")return t;throw TypeError(`Expected boolean, got ${typeof t}: ${t}`)},zr=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string"){let n=parseFloat(t);if(!Number.isNaN(n)){if(String(n)!==String(t))qr.warn(fe(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},a5=Math.ceil(340282346638528860000000000000000000000),oe=(t)=>{let n=zr(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>a5)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},xr=(t)=>{if(t===null||t===void 0)return;if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw TypeError(`Expected integer, got ${typeof t}: ${t}`)},p5=xr,Yf=(t)=>Xf(t,32),mf=(t)=>Xf(t,16),Qf=(t)=>Xf(t,8),Xf=(t,n)=>{let s=xr(t);if(s!==void 0&&Z5(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},Z5=(t,n)=>{switch(n){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},v5=(t,n)=>{if(t===null||t===void 0){if(n)throw TypeError(`Expected a non-null value for ${n}`);throw TypeError("Expected a non-null value")}return t},Y_=(t)=>{if(t===null||t===void 0)return;if(typeof t==="object"&&!Array.isArray(t))return t;let n=Array.isArray(t)?"array":typeof t;throw TypeError(`Expected object, got ${n}: ${t}`)},t8=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return qr.warn(fe(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},n8=(t)=>{if(t===null||t===void 0)return;let n=Y_(t),s=[];for(let r in n)if(n[r]!=null)s.push(r);if(s.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(s.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${s} were not null.`);return n},zf=(t)=>{if(typeof t=="string")return zr(Ks(t));return zr(t)},s8=zf,m_=(t)=>{if(typeof t=="string")return oe(Ks(t));return oe(t)},r8=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ks=(t)=>{let n=t.match(r8);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},xf=(t)=>{if(typeof t=="string")return Q_(t);return zr(t)},i8=xf,e8=xf,o8=(t)=>{if(typeof t=="string")return Q_(t);return oe(t)},Q_=(t)=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${t}`)}},J_=(t)=>{if(typeof t==="string")return xr(Ks(t));return xr(t)},f8=J_,c8=(t)=>{if(typeof t==="string")return Yf(Ks(t));return Yf(t)},qs=(t)=>{if(typeof t==="string")return mf(Ks(t));return mf(t)},k_=(t)=>{if(typeof t==="string")return Qf(Ks(t));return Qf(t)},fe=(t)=>{return String(TypeError(t).stack||t).split(`
5
+ `+e),t.push(r+"m+"+Hr.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=WR()+n+" "+t[0]}function WR(){if(k0.inspectOpts.hideDate)return"";return new Date().toISOString()+" "}function DR(...t){return process.stderr.write(Fr.formatWithOptions(k0.inspectOpts,...t)+`
6
+ `)}function mR(t){if(t)process.env.DEBUG=t;else delete process.env.DEBUG}function YR(){return process.env.DEBUG}function QR(t){t.inspectOpts={};let n=Object.keys(k0.inspectOpts);for(let s=0;s<n.length;s++)t.inspectOpts[n[s]]=k0.inspectOpts[n[s]]}Hr.exports=Co()(k0);var{formatters:J0}=Hr.exports;J0.o=function(t){return this.inspectOpts.colors=this.useColors,Fr.inspect(t,this.inspectOpts).split(`
7
+ `).map((n)=>n.trim()).join(" ")};J0.O=function(t){return this.inspectOpts.colors=this.useColors,Fr.inspect(t,this.inspectOpts)}});var Vo=Z((mY,Ko)=>{if(typeof process>"u"||process.type==="renderer"||!1||process.__nwjs)Ko.exports=Q0();else Ko.exports=X0()});var rs=Z((_b)=>{var ef;(function(t){t.HEADER="header",t.QUERY="query"})(ef||(ef={}));var of;(function(t){t.HEADER="header",t.QUERY="query"})(of||(of={}));var ff;(function(t){t.HTTP="http",t.HTTPS="https"})(ff||(ff={}));var Bi;(function(t){t.MD5="md5",t.CRC32="crc32",t.CRC32C="crc32c",t.SHA1="sha1",t.SHA256="sha256"})(Bi||(Bi={}));var fb=(t)=>{let n=[];if(t.sha256!==void 0)n.push({algorithmId:()=>Bi.SHA256,checksumConstructor:()=>t.sha256});if(t.md5!=null)n.push({algorithmId:()=>Bi.MD5,checksumConstructor:()=>t.md5});return{addChecksumAlgorithm(s){n.push(s)},checksumAlgorithms(){return n}}},cb=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{n[s.algorithmId()]=s.checksumConstructor()}),n},hb=(t)=>{return fb(t)},ub=(t)=>{return cb(t)},cf;(function(t){t[t.HEADER=0]="HEADER",t[t.TRAILER=1]="TRAILER"})(cf||(cf={}));var lb="__smithy_context",hf;(function(t){t.PROFILE="profile",t.SSO_SESSION="sso-session",t.SERVICES="services"})(hf||(hf={}));var uf;(function(t){t.HTTP_0_9="http/0.9",t.HTTP_1_0="http/1.0",t.TDS_8_0="tds/8.0"})(uf||(uf={}));_b.AlgorithmId=Bi;_b.EndpointURLScheme=ff;_b.FieldPosition=cf;_b.HttpApiKeyAuthLocation=of;_b.HttpAuthLocation=ef;_b.IniSectionType=hf;_b.RequestHandlerProtocol=uf;_b.SMITHY_CONTEXT_KEY=lb;_b.getDefaultClientConfiguration=hb;_b.resolveDefaultRuntimeConfig=ub});var nn=Z((Gb)=>{var{SMITHY_CONTEXT_KEY:fu}=rs(),$b=(t)=>t[fu]||(t[fu]={});class Qr{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(t){this.method=t.method||"GET",this.hostname=t.hostname||"localhost",this.port=t.port,this.query=t.query||{},this.headers=t.headers||{},this.body=t.body,this.protocol=t.protocol?t.protocol.slice(-1)!==":"?`${t.protocol}:`:t.protocol:"https:",this.path=t.path?t.path.charAt(0)!=="/"?`/${t.path}`:t.path:"/",this.username=t.username,this.password=t.password,this.fragment=t.fragment}static clone(t){let n=new Qr({...t,headers:{...t.headers}});if(n.query)n.query=Ub(n.query);return n}static isInstance(t){if(!t)return!1;let n=t;return"method"in n&&"protocol"in n&&"hostname"in n&&"path"in n&&typeof n.query==="object"&&typeof n.headers==="object"}clone(){return Qr.clone(this)}}function Ub(t){return Object.keys(t).reduce((n,s)=>{let i=t[s];return{...n,[s]:Array.isArray(i)?[...i]:i}},{})}class cu{statusCode;reason;headers;body;constructor(t){this.statusCode=t.statusCode,this.reason=t.reason,this.headers=t.headers||{},this.body=t.body}static isInstance(t){if(!t)return!1;let n=t;return typeof n.statusCode==="number"&&typeof n.headers==="object"}}var Lb=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),hu=(t,n=!1)=>{if(!n)return Lb.test(t);let s=t.split(".");for(let i of s)if(!hu(i))return!1;return!0};function Ib(t){return/^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(t)}var yb=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n};function uu(t){let n={};if(t=t.replace(/^\?/,""),t)for(let s of t.split("&")){let[i,r=null]=s.split("=");if(i=decodeURIComponent(i),r)r=decodeURIComponent(r);if(!(i in n))n[i]=r;else if(Array.isArray(n[i]))n[i].push(r);else n[i]=[n[i],r]}return n}var Jr=(t)=>{if(typeof t==="string")return Jr(new URL(t));let{hostname:n,pathname:s,port:i,protocol:r,search:e}=t,f;if(e)f=uu(e);return{hostname:n,port:i?parseInt(i):void 0,protocol:r,path:s,query:f}},Ob=(t)=>{if(typeof t==="object"){if("url"in t){let n=Jr(t.url);if(t.headers){n.headers={};for(let s in t.headers)n.headers[s.toLowerCase()]=t.headers[s].join(", ")}return n}return t}return Jr(t)};Gb.HttpRequest=Qr;Gb.HttpResponse=cu;Gb.getSmithyContext=$b;Gb.isValidHostLabel=hu;Gb.isValidHostname=Ib;Gb.normalizeProvider=yb;Gb.parseQueryString=uu;Gb.parseUrl=Jr;Gb.toEndpointV1=Ob});var Nn=Z((Zb)=>{var{getSmithyContext:lu,HttpResponse:Qb,toEndpointV1:Jb}=nn(),kr=(t)=>{if(typeof t==="function")return t();return t},wf=(t,n,s,i,r)=>({name:n,namespace:t,traits:s,input:i,output:r}),kb=(t)=>(n,s)=>async(i)=>{let{response:r}=await n(i),{operationSchema:e}=lu(s),[,f,o,c,h,u]=e??[];try{let l=await t.protocol.deserializeResponse(wf(f,o,c,h,u),{...t,...s},r);return{response:r,output:l}}catch(l){if(Object.defineProperty(l,"$response",{value:r,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in l)){try{l.message+=`
8
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(w){if(!s.logger||s.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else s.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof l.$responseBodyText<"u"){if(l.$response)l.$response.body=l.$responseBodyText}try{if(Qb.isInstance(r)){let{headers:w={},statusCode:A}=r,M=Object.entries(w);l.$metadata={httpStatusCode:A,requestId:lf(/^x-[\w-]+-request-?id$/,M),extendedRequestId:lf(/^x-[\w-]+-id-2$/,M),cfId:lf(/^x-[\w-]+-cf-id$/,M)}}}catch(w){}}throw l}},lf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},zb=(t)=>(n,s)=>async(i)=>{let{operationSchema:r}=lu(s),[,e,f,o,c,h]=r??[],u=s.endpointV2?async()=>Jb(s.endpointV2):t.endpoint,l=await t.protocol.serializeRequest(wf(e,f,o,c,h),i.input,{...t,...s,endpoint:u});return n({...i,request:l})},_u={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},wu={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function Xb(t){return{applyToStack:(n)=>{n.add(zb(t),wu),n.add(kb(t),_u),t.protocol.setSerdeContext(t)}}}class Tt{name;namespace;traits;static assign(t,n){return Object.assign(t,n)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}getName(){return this.namespace+"#"+this.name}}class qr extends Tt{static symbol=Symbol.for("@smithy/lis");name;traits;valueSchema;symbol=qr.symbol}var xb=(t,n,s,i)=>Tt.assign(new qr,{name:n,namespace:t,traits:s,valueSchema:i});class Cr extends Tt{static symbol=Symbol.for("@smithy/map");name;traits;keySchema;valueSchema;symbol=Cr.symbol}var qb=(t,n,s,i,r)=>Tt.assign(new Cr,{name:n,namespace:t,traits:s,keySchema:i,valueSchema:r});class Kr extends Tt{static symbol=Symbol.for("@smithy/ope");name;traits;input;output;symbol=Kr.symbol}var Cb=(t,n,s,i,r)=>Tt.assign(new Kr,{name:n,namespace:t,traits:s,input:i,output:r});class Ni extends Tt{static symbol=Symbol.for("@smithy/str");name;traits;memberNames;memberList;symbol=Ni.symbol}var Kb=(t,n,s,i,r)=>Tt.assign(new Ni,{name:n,namespace:t,traits:s,memberNames:i,memberList:r});class Vr extends Ni{static symbol=Symbol.for("@smithy/err");ctor;symbol=Vr.symbol}var Vb=(t,n,s,i,r,e)=>Tt.assign(new Vr,{name:n,namespace:t,traits:s,memberNames:i,memberList:r,ctor:null}),zr=[];function Pi(t){if(typeof t==="object")return t;if(t=t|0,zr[t])return zr[t];let n={},s=0;for(let i of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])if((t>>s++&1)===1)n[i]=1;return zr[t]=n}var Fi={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Xr=[],xr={};class En{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=En.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(t,n){this.ref=t,this.memberName=n;let s=[],i=t,r=t;this._isMemberSchema=!1;while(_f(i))s.push(i[1]),i=i[0],r=kr(i),this._isMemberSchema=!0;if(s.length>0){this.memberTraits={};for(let e=s.length-1;e>=0;--e){let f=s[e];Object.assign(this.memberTraits,Pi(f))}}else this.memberTraits=0;if(r instanceof En){let e=this.memberTraits;Object.assign(this,r),this.memberTraits=Object.assign({},e,r.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=n??r.memberName;return}if(this.schema=kr(r),Au(this.schema))this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3];else this.name=this.memberName??String(r),this.traits=0;if(this._isMemberSchema&&!n)throw Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](t){let n=this.prototype.isPrototypeOf(t);if(!n&&typeof t==="object"&&t!==null)return t.symbol===this.symbol;return n}static of(t){let n=typeof t==="function"||typeof t==="object"&&t!==null;if(typeof t==="number"){if(Xr[t])return Xr[t]}else if(typeof t==="string"){if(xr[t])return xr[t]}else if(n){if(t[Fi.ns])return t[Fi.ns]}let s=kr(t);if(s instanceof En)return s;if(_f(s)){let[r,e]=s;if(r instanceof En)return Object.assign(r.getMergedTraits(),Pi(e)),r;throw Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(t,null,2)}.`)}let i=new En(s);if(n)return t[Fi.ns]=i;if(typeof s==="string")return xr[s]=i;if(typeof s==="number")return Xr[s]=i;return i}getSchema(){let t=this.schema;if(Array.isArray(t)&&t[0]===0)return t[4];return t}getName(t=!1){let{name:n}=this;return!t&&n&&n.includes("#")?n.split("#")[1]:n||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let t=this.getSchema();return typeof t==="number"?t>=64&&t<128:t[0]===1}isMapSchema(){let t=this.getSchema();return typeof t==="number"?t>=128&&t<=255:t[0]===2}isStructSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;let n=t[0];return n===3||n===-3||n===4}isUnionSchema(){let t=this.getSchema();if(typeof t!=="object")return!1;return t[0]===4}isBlobSchema(){let t=this.getSchema();return t===21||t===42}isTimestampSchema(){let t=this.getSchema();return typeof t==="number"&&t>=4&&t<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:t}=this.getMergedTraits();return!!t||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return Pi(this.memberTraits)}getOwnTraits(){return Pi(this.traits)}getKeySchema(){let[t,n]=[this.isDocumentSchema(),this.isMapSchema()];if(!t&&!n)throw Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);let s=this.getSchema(),i=t?15:s[4]??0;return Hi([i,0],"key")}getValueSchema(){let t=this.getSchema(),[n,s,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],r=typeof t==="number"?63&t:t&&typeof t==="object"&&(s||i)?t[3+t[0]]:n?15:void 0;if(r!=null)return Hi([r,0],s?"value":"member");throw Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(t){let n=this.getSchema();if(this.isStructSchema()&&n[4].includes(t)){let s=n[4].indexOf(t),i=n[5][s];return Hi(_f(i)?i:[i,0],t)}if(this.isDocumentSchema())return Hi([15,0],t);throw Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${t}.`)}getMemberSchemas(){let t={};try{for(let[n,s]of this.structIterator())t[n]=s}catch(n){}return t}getEventStreamMember(){if(this.isStructSchema()){for(let[t,n]of this.structIterator())if(n.isStreaming()&&n.isStructSchema())return t}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw Error("@smithy/core/schema - cannot iterate non-struct schema.");let t=this.getSchema(),n=t[4].length,s=t[Fi.it];if(s&&n===s.length){yield*s;return}s=Array(n);for(let i=0;i<n;++i){let r=t[4][i],e=Hi([t[5][i],0],r);yield s[i]=[r,e]}t[Fi.it]=s}}function Hi(t,n){if(t instanceof En)return Object.assign(t,{memberName:n,_isMemberSchema:!0});return new En(t,n)}var _f=(t)=>Array.isArray(t)&&t.length===2,Au=(t)=>Array.isArray(t)&&t.length>=5;class Wi extends Tt{static symbol=Symbol.for("@smithy/sim");name;schemaRef;traits;symbol=Wi.symbol}var jb=(t,n,s,i)=>Tt.assign(new Wi,{name:n,namespace:t,traits:i,schemaRef:s}),ab=(t,n,s,i)=>Tt.assign(new Wi,{name:n,namespace:t,traits:s,schemaRef:i}),pb={BLOB:21,STREAMING_BLOB:42,BOOLEAN:2,STRING:0,NUMERIC:1,BIG_INTEGER:17,BIG_DECIMAL:19,DOCUMENT:15,TIMESTAMP_DEFAULT:4,TIMESTAMP_DATE_TIME:5,TIMESTAMP_HTTP_DATE:6,TIMESTAMP_EPOCH_SECONDS:7,LIST_MODIFIER:64,MAP_MODIFIER:128};class dn{namespace;schemas;exceptions;static registries=new Map;constructor(t,n=new Map,s=new Map){this.namespace=t,this.schemas=n,this.exceptions=s}static for(t){if(!dn.registries.has(t))dn.registries.set(t,new dn(t));return dn.registries.get(t)}copyFrom(t){let{schemas:n,exceptions:s}=this;for(let[i,r]of t.schemas)if(!n.has(i))n.set(i,r);for(let[i,r]of t.exceptions)if(!s.has(i))s.set(i,r)}register(t,n){let s=this.normalizeShapeId(t);for(let i of[this,dn.for(s.split("#")[0])])i.schemas.set(s,n)}getSchema(t){let n=this.normalizeShapeId(t);if(!this.schemas.has(n)){if(!t.includes("#")){let s="#"+t,i=[];for(let[r,e]of this.schemas.entries())if(r.endsWith(s))i.push(e);if(i.length===1)return i[0]}throw Error(`@smithy/core/schema - schema not found for ${n}`)}return this.schemas.get(n)}registerError(t,n){let s=t,i=s[1];for(let r of[this,dn.for(i)])r.schemas.set(i+"#"+s[2],s),r.exceptions.set(s,n)}getErrorCtor(t){let n=t;if(this.exceptions.has(n))return this.exceptions.get(n);return dn.for(n[1]).exceptions.get(n)}getBaseException(){for(let t of this.exceptions.keys())if(Array.isArray(t)){let[,n,s]=t,i=n+"#"+s;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return t}return}find(t){for(let n of this.schemas.values())if(t(n))return n;return}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(t){if(t.includes("#"))return t;return this.namespace+"#"+t}}Zb.ErrorSchema=Vr;Zb.ListSchema=qr;Zb.MapSchema=Cr;Zb.NormalizedSchema=En;Zb.OperationSchema=Kr;Zb.SCHEMA=pb;Zb.Schema=Tt;Zb.SimpleSchema=Wi;Zb.StructureSchema=Ni;Zb.TypeRegistry=dn;Zb.deref=kr;Zb.deserializerMiddlewareOption=_u;Zb.error=Vb;Zb.getSchemaSerdePlugin=Xb;Zb.isStaticSchema=Au;Zb.list=xb;Zb.map=qb;Zb.op=Cb;Zb.operation=wf;Zb.serializerMiddlewareOption=wu;Zb.sim=jb;Zb.simAdapter=ab;Zb.simpleSchemaCacheN=Xr;Zb.simpleSchemaCacheS=xr;Zb.struct=Kb;Zb.traitsCache=zr;Zb.translateTraits=Pi});var Rn=Z((e2)=>{var{getSmithyContext:I4,normalizeProvider:y4}=nn();e2.getSmithyContext=I4;e2.normalizeProvider=y4;var{SMITHY_CONTEXT_KEY:O4,AlgorithmId:ar}=rs();e2.AlgorithmId=ar;var{NormalizedSchema:G4}=Nn(),es=(t,n)=>{let s=[];if(t)s.push(t);if(n)for(let i of n)s.push(i);return s},Wn=(t,n)=>{return`${t||"anonymous"}${n&&n.length>0?` (a.k.a. ${n.join(",")})`:""}`},Di=()=>{let t=[],n=[],s=!1,i=new Set,r=(l)=>l.sort((_,w)=>Mu[w.step]-Mu[_.step]||gu[w.priority||"normal"]-gu[_.priority||"normal"]),e=(l)=>{let _=!1,w=(A)=>{let M=es(A.name,A.aliases);if(M.includes(l)){_=!0;for(let d of M)i.delete(d);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},f=(l)=>{let _=!1,w=(A)=>{if(A.middleware===l){_=!0;for(let M of es(A.name,A.aliases))i.delete(M);return!1}return!0};return t=t.filter(w),n=n.filter(w),_},o=(l)=>{return t.forEach((_)=>{l.add(_.middleware,{..._})}),n.forEach((_)=>{l.addRelativeTo(_.middleware,{..._})}),l.identifyOnResolve?.(u.identifyOnResolve()),l},c=(l)=>{let _=[];return l.before.forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_.push(l),l.after.reverse().forEach((w)=>{if(w.before.length===0&&w.after.length===0)_.push(w);else _.push(...c(w))}),_},h=(l=!1)=>{let _=[],w=[],A={};return t.forEach((d)=>{let E={...d,before:[],after:[]};for(let T of es(E.name,E.aliases))A[T]=E;_.push(E)}),n.forEach((d)=>{let E={...d,before:[],after:[]};for(let T of es(E.name,E.aliases))A[T]=E;w.push(E)}),w.forEach((d)=>{if(d.toMiddleware){let E=A[d.toMiddleware];if(E===void 0){if(l)return;throw Error(`${d.toMiddleware} is not found when adding ${Wn(d.name,d.aliases)} middleware ${d.relation} ${d.toMiddleware}`)}if(d.relation==="after")E.after.push(d);if(d.relation==="before")E.before.push(d)}}),r(_).map(c).reduce((d,E)=>{return d.push(...E),d},[])},u={add:(l,_={})=>{let{name:w,override:A,aliases:M}=_,d={step:"initialize",priority:"normal",middleware:l,..._},E=es(w,M);if(E.length>0){if(E.some((T)=>i.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of E){let U=t.findIndex((y)=>y.name===T||y.aliases?.some((D)=>D===T));if(U===-1)continue;let S=t[U];if(S.step!==d.step||d.priority!==S.priority)throw Error(`"${Wn(S.name,S.aliases)}" middleware with ${S.priority} priority in ${S.step} step cannot be overridden by "${Wn(w,M)}" middleware with ${d.priority} priority in ${d.step} step.`);t.splice(U,1)}}for(let T of E)i.add(T)}t.push(d)},addRelativeTo:(l,_)=>{let{name:w,override:A,aliases:M}=_,d={middleware:l,..._},E=es(w,M);if(E.length>0){if(E.some((T)=>i.has(T))){if(!A)throw Error(`Duplicate middleware name '${Wn(w,M)}'`);for(let T of E){let U=n.findIndex((y)=>y.name===T||y.aliases?.some((D)=>D===T));if(U===-1)continue;let S=n[U];if(S.toMiddleware!==d.toMiddleware||S.relation!==d.relation)throw Error(`"${Wn(S.name,S.aliases)}" middleware ${S.relation} "${S.toMiddleware}" middleware cannot be overridden by "${Wn(w,M)}" middleware ${d.relation} "${d.toMiddleware}" middleware.`);n.splice(U,1)}}for(let T of E)i.add(T)}n.push(d)},clone:()=>o(Di()),use:(l)=>{l.applyToStack(u)},remove:(l)=>{if(typeof l==="string")return e(l);else return f(l)},removeByTag:(l)=>{let _=!1,w=(A)=>{let{tags:M,name:d,aliases:E}=A;if(M&&M.includes(l)){let T=es(d,E);for(let U of T)i.delete(U);return _=!0,!1}return!0};return t=t.filter(w),n=n.filter(w),_},concat:(l)=>{let _=o(Di());return _.use(l),_.identifyOnResolve(s||_.identifyOnResolve()||(l.identifyOnResolve?.()??!1)),_},applyToStack:o,identify:()=>{return h(!0).map((l)=>{let _=l.step??l.relation+" "+l.toMiddleware;return Wn(l.name,l.aliases)+" - "+_})},identifyOnResolve(l){if(typeof l==="boolean")s=l;return s},resolve:(l,_)=>{for(let w of h().map((A)=>A.middleware).reverse())l=w(l,_);if(s)console.log(u.identify());return l}};return u},Mu={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},gu={high:3,normal:2,low:1},B4=(t)=>()=>{throw Error(t)},F4=(t)=>()=>Promise.reject(t),jr=()=>{let t=new WeakSet;return(n,s)=>{if(typeof s==="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s}},H4=(t)=>{return new Promise((n)=>setTimeout(n,t*1000))},Ru={minDelay:2,maxDelay:120},sn;(function(t){t.ABORTED="ABORTED",t.FAILURE="FAILURE",t.SUCCESS="SUCCESS",t.RETRY="RETRY",t.TIMEOUT="TIMEOUT"})(sn||(sn={}));var P4=(t)=>{if(t.state===sn.ABORTED){let n=Error(`${JSON.stringify({...t,reason:"Request was aborted"},jr())}`);throw n.name="AbortError",n}else if(t.state===sn.TIMEOUT){let n=Error(`${JSON.stringify({...t,reason:"Waiter has timed out"},jr())}`);throw n.name="TimeoutError",n}else if(t.state!==sn.SUCCESS)throw Error(`${JSON.stringify(t,jr())}`);return t},N4=async({minDelay:t,maxDelay:n,maxWaitTime:s,abortController:i,client:r,abortSignal:e},f,o)=>{let c={},[h,u]=[t*1000,n*1000],l=0,_=Date.now()+s*1000,w=Date.now()+60000,A=!1;while(!0){if(l>0){let E=m4(h,u,l,_);if(i?.signal?.aborted||e?.aborted)return c["AbortController signal aborted."]|=0,c["AbortController signal aborted."]+=1,{state:sn.ABORTED,observedResponses:c};if(Date.now()+E>_)return{state:sn.TIMEOUT,observedResponses:c};await H4(E/1000)}let{state:M,reason:d}=await o(r,f);if(d){let E=D4(d);c[E]|=0,c[E]+=1}if(M!==sn.RETRY)return{state:M,reason:d,final:d,observedResponses:c};if(l+=1,!A&&Date.now()>=w)W4(c,r),A=!0}},W4=(t={},n)=>{let s=Object.keys(t),i=0;for(let f of s){let o=t[f]|0;if(f.startsWith("403:"))i+=o}let r=n?.config?.logger,e=typeof r?.warn==="function"&&!r.constructor?.name?.includes?.("NoOpLogger")?r:console;if(i>=3||s[s.length-1]?.startsWith("403:"))e.warn("@smithy/util-waiter WARN - 403 status code encountered during waiter polling.")},D4=(t)=>{let n=t?.$response?.statusCode??t?.$metadata?.httpStatusCode;if(t?.$responseBodyText)return`${n?n+": ":""}Deserialization error for body: ${t.$responseBodyText}`;if(n){if(t?.$response||t?.message)return`${n??"Unknown"}: ${t?.message}`;return`${n}: OK`}return String(t?.message??JSON.stringify(t,jr())??"Unknown")},m4=(t,n,s,i)=>{let r=Math.log(n/t)/Math.log(2)+1;if(s>r)return n;let e=t*2**(s-1),f=Math.min(e,n),o=Y4(t,f);if(Date.now()+o>i){let c=i-Date.now();return Math.max(0,c-500)}return o},Y4=(t,n)=>t+Math.random()*(n-t),Q4=(t)=>{if(t.maxWaitTime<=0)throw Error("WaiterConfiguration.maxWaitTime must be greater than 0");else if(t.minDelay<=0)throw Error("WaiterConfiguration.minDelay must be greater than 0");else if(t.maxDelay<=0)throw Error("WaiterConfiguration.maxDelay must be greater than 0");else if(t.maxWaitTime<=t.minDelay)throw Error(`WaiterConfiguration.maxWaitTime [${t.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`);else if(t.maxDelay<t.minDelay)throw Error(`WaiterConfiguration.maxDelay [${t.maxDelay}] must be greater than WaiterConfiguration.minDelay [${t.minDelay}] for this waiter`)},du=(t)=>{let n,s=new Promise((i)=>{if(n=()=>i({state:sn.ABORTED}),typeof t.addEventListener==="function")t.addEventListener("abort",n);else t.onabort=n});return{clearListener(){if(typeof t.removeEventListener==="function")t.removeEventListener("abort",n)},aborted:s}},J4=async(t,n,s)=>{let i={...Ru,...t};Q4(i);let r=[N4(i,n,s)],e=[];if(t.abortSignal){let{aborted:f,clearListener:o}=du(t.abortSignal);e.push(o),r.push(f)}if(t.abortController?.signal){let{aborted:f,clearListener:o}=du(t.abortController.signal);e.push(o),r.push(f)}return Promise.race(r).then((f)=>{for(let o of e)o();return f})};class bu{config;middlewareStack=Di();initConfig;handlers;constructor(t){this.config=t;let{protocol:n,protocolSettings:s}=t;if(s){if(typeof n==="function")t.protocol=new n(s)}}send(t,n,s){let i=typeof n!=="function"?n:void 0,r=typeof n==="function"?n:s,e=i===void 0&&this.config.cacheMiddleware===!0,f;if(e){if(!this.handlers)this.handlers=new WeakMap;let o=this.handlers;if(o.has(t.constructor))f=o.get(t.constructor);else f=t.resolveMiddleware(this.middlewareStack,this.config,i),o.set(t.constructor,f)}else delete this.handlers,f=t.resolveMiddleware(this.middlewareStack,this.config,i);if(r)f(t).then((o)=>r(null,o.output),(o)=>r(o)).catch(()=>{});else return f(t).then((o)=>o.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}var Af="***SensitiveInformation***";function pr(t,n){if(n==null)return n;let s=G4.of(t);if(s.getMergedTraits().sensitive)return Af;if(s.isListSchema()){if(!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isMapSchema()){if(!!s.getKeySchema().getMergedTraits().sensitive||!!s.getValueSchema().getMergedTraits().sensitive)return Af}else if(s.isStructSchema()&&typeof n==="object"){let i=n,r={};for(let[e,f]of s.structIterator())if(i[e]!=null)r[e]=pr(f,i[e]);return r}return n}class Zr{middlewareStack=Di();schema;static classBuilder(){return new Tu}resolveMiddlewareWithContext(t,n,s,{middlewareFn:i,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,smithyContext:c,additionalContext:h,CommandCtor:u}){for(let d of i.bind(this)(u,t,n,s))this.middlewareStack.use(d);let l=t.concat(this.middlewareStack),{logger:_}=n,w={logger:_,clientName:r,commandName:e,inputFilterSensitiveLog:f,outputFilterSensitiveLog:o,[O4]:{commandInstance:this,...c},...h},{requestHandler:A}=n,M=s??{};if(c.eventStream)M={isEventStream:!0,...M};return l.resolve((d)=>A.handle(d.request,M),w)}}class Tu{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(t){this._init=t}ep(t){return this._ep=t,this}m(t){return this._middlewareFn=t,this}s(t,n,s={}){return this._smithyContext={service:t,operation:n,...s},this}c(t={}){return this._additionalContext=t,this}n(t,n){return this._clientName=t,this._commandName=n,this}f(t=(s)=>s,n=(s)=>s){return this._inputFilterSensitiveLog=t,this._outputFilterSensitiveLog=n,this}ser(t){return this._serializer=t,this}de(t){return this._deserializer=t,this}sc(t){return this._operationSchema=t,this._smithyContext.operationSchema=t,this}build(){let t=this,n;return n=class extends Zr{input;static getEndpointParameterInstructions(){return t._ep}constructor(...[s]){super();this.input=s??{},t._init(this),this.schema=t._operationSchema}resolveMiddleware(s,i,r){let e=t._operationSchema,f=e?.[4]??e?.input,o=e?.[5]??e?.output;return this.resolveMiddlewareWithContext(s,i,r,{CommandCtor:n,middlewareFn:t._middlewareFn,clientName:t._clientName,commandName:t._commandName,inputFilterSensitiveLog:t._inputFilterSensitiveLog??(e?pr.bind(null,f):(c)=>c),outputFilterSensitiveLog:t._outputFilterSensitiveLog??(e?pr.bind(null,o):(c)=>c),smithyContext:t._smithyContext,additionalContext:t._additionalContext})}serialize=t._serializer;deserialize=t._deserializer}}}var k4="***SensitiveInformation***",z4=(t,n,s)=>{for(let[e,f]of Object.entries(t)){let o=async function(h,u,l){let _=new f(h);if(typeof u==="function")this.send(_,u);else if(typeof l==="function"){if(typeof u!=="object")throw Error(`Expected http options but got ${typeof u}`);this.send(_,u||{},l)}else return this.send(_,u)},c=(e[0].toLowerCase()+e.slice(1)).replace(/Command$/,"");n.prototype[c]=o}let{paginators:i={},waiters:r={}}=s??{};for(let[e,f]of Object.entries(i))if(n.prototype[e]===void 0)n.prototype[e]=function(o={},c,...h){return f({...c,client:this},o,...h)};for(let[e,f]of Object.entries(r))if(n.prototype[e]===void 0)n.prototype[e]=async function(o={},c,...h){let u=c;if(typeof c==="number")u={maxWaitTime:c};return f({...u,client:this},o,...h)}};class Js extends Error{$fault;$response;$retryable;$metadata;constructor(t){super(t.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=t.name,this.$fault=t.$fault,this.$metadata=t.$metadata}static isInstance(t){if(!t)return!1;let n=t;return Js.prototype.isPrototypeOf(n)||Boolean(n.$fault)&&Boolean(n.$metadata)&&(n.$fault==="client"||n.$fault==="server")}static[Symbol.hasInstance](t){if(!t)return!1;let n=t;if(this===Js)return Js.isInstance(t);if(Js.isInstance(t)){if(n.name&&this.name)return this.prototype.isPrototypeOf(t)||n.name===this.name;return this.prototype.isPrototypeOf(t)}return!1}}var Su=(t,n={})=>{Object.entries(n).filter(([,i])=>i!==void 0).forEach(([i,r])=>{if(t[i]==null||t[i]==="")t[i]=r});let s=t.message||t.Message||"UnknownError";return t.message=s,delete t.Message,t},$u=({output:t,parsedBody:n,exceptionCtor:s,errorCode:i})=>{let r=x4(t),e=r.httpStatusCode?r.httpStatusCode+"":void 0,f=new s({name:n?.code||n?.Code||i||e||"UnknownError",$fault:"client",$metadata:r});throw Su(f,n)},X4=(t)=>{return({output:n,parsedBody:s,errorCode:i})=>{$u({output:n,parsedBody:s,exceptionCtor:t,errorCode:i})}},x4=(t)=>({httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}),q4=(t)=>{switch(t){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:30000};default:return{}}},Eu=!1,C4=(t)=>{if(t&&!Eu&&parseInt(t.substring(1,t.indexOf(".")))<16)Eu=!0},Uu=Object.values(ar),Lu=(t)=>{let n=[];for(let s in ar){let i=ar[s];if(t[i]===void 0)continue;n.push({algorithmId:()=>i,checksumConstructor:()=>t[i]})}for(let[s,i]of Object.entries(t.checksumAlgorithms??{}))n.push({algorithmId:()=>s,checksumConstructor:()=>i});return{addChecksumAlgorithm(s){t.checksumAlgorithms=t.checksumAlgorithms??{};let i=s.algorithmId(),r=s.checksumConstructor();if(Uu.includes(i))t.checksumAlgorithms[i.toUpperCase()]=r;else t.checksumAlgorithms[i]=r;n.push(s)},checksumAlgorithms(){return n}}},Iu=(t)=>{let n={};return t.checksumAlgorithms().forEach((s)=>{let i=s.algorithmId();if(Uu.includes(i))n[i]=s.checksumConstructor()}),n},yu=(t)=>{return{setRetryStrategy(n){t.retryStrategy=n},retryStrategy(){return t.retryStrategy}}},Ou=(t)=>{let n={};return n.retryStrategy=t.retryStrategy(),n},Gu=(t)=>{return Object.assign(Lu(t),yu(t))},K4=Gu,V4=(t)=>{return Object.assign(Iu(t),Ou(t))},j4=(t)=>Array.isArray(t)?t:[t],Bu=(t)=>{for(let s in t)if(Object.prototype.hasOwnProperty.call(t,s)&&t[s]["#text"]!==void 0)t[s]=t[s]["#text"];else if(typeof t[s]==="object"&&t[s]!==null)t[s]=Bu(t[s]);return t},a4=(t)=>{return t!=null};class Fu{trace(){}debug(){}info(){}warn(){}error(){}}function Hu(t,n,s){let i,r,e;if(typeof n>"u"&&typeof s>"u")i={},e=t;else if(i=t,typeof n==="function")return r=n,e=s,v4(i,r,e);else e=n;for(let f of Object.keys(e)){if(!Array.isArray(e[f])){i[f]=e[f];continue}Pu(i,null,e,f)}return i}var p4=(t)=>{let n={};for(let[s,i]of Object.entries(t||{}))n[s]=[,i];return n},Z4=(t,n)=>{let s={};for(let i in n)Pu(s,t,n,i);return s},v4=(t,n,s)=>{return Hu(t,Object.entries(s).reduce((i,[r,e])=>{if(Array.isArray(e))i[r]=e;else if(typeof e==="function")i[r]=[n,e()];else i[r]=[n,e];return i},{}))},Pu=(t,n,s,i)=>{if(n!==null){let f=s[i];if(typeof f==="function")f=[,f];let[o=t2,c=n2,h=i]=f;if(typeof o==="function"&&o(n[h])||typeof o!=="function"&&!!o)t[i]=c(n[h]);return}let[r,e]=s[i];if(typeof e==="function"){let f,o=r===void 0&&(f=e())!=null,c=typeof r==="function"&&!!r(void 0)||typeof r!=="function"&&!!r;if(o)t[i]=f;else if(c)t[i]=e()}else{let f=r===void 0&&e!=null,o=typeof r==="function"&&!!r(e)||typeof r!=="function"&&!!r;if(f||o)t[i]=e}},t2=(t)=>t!=null,n2=(t)=>t,s2=(t)=>{if(t!==t)return"NaN";switch(t){case 1/0:return"Infinity";case-1/0:return"-Infinity";default:return t}},i2=(t)=>t.toISOString().replace(".000Z","Z"),Mf=(t)=>{if(t==null)return{};if(Array.isArray(t))return t.filter((n)=>n!=null).map(Mf);if(typeof t==="object"){let n={};for(let s of Object.keys(t)){if(t[s]==null)continue;n[s]=Mf(t[s])}return n}return t};function r2(t,n,s,i){return function(e,f,o,c,h={}){let u=Object.assign({},t,e);return Zr.classBuilder().ep(u).m(function(l,_,w,A){let M=f.call(this,l,_,w,A);return M.unshift(i(w,l.getEndpointParameterInstructions())),M}).s(n,o,h).n(s,o.charAt(0).toUpperCase()+o.slice(1)+"Command").sc(c).build()}}e2.Client=bu;e2.Command=Zr;e2.NoOpLogger=Fu;e2.SENSITIVE_STRING=k4;e2.ServiceException=Js;e2.WaiterState=sn;e2._json=Mf;e2.checkExceptions=P4;e2.constructStack=Di;e2.convertMap=p4;e2.createAggregatedClient=z4;e2.createWaiter=J4;e2.decorateServiceException=Su;e2.emitWarningIfUnsupportedVersion=C4;e2.getArrayIfSingleItem=j4;e2.getChecksumConfiguration=Lu;e2.getDefaultClientConfiguration=K4;e2.getDefaultExtensionConfiguration=Gu;e2.getRetryConfiguration=yu;e2.getValueFromTextNode=Bu;e2.invalidFunction=B4;e2.invalidProvider=F4;e2.isSerializableHeaderValue=a4;e2.loadConfigsForDefaultMode=q4;e2.makeBuilder=r2;e2.map=Hu;e2.resolveChecksumRuntimeConfig=Iu;e2.resolveDefaultRuntimeConfig=V4;e2.resolveRetryRuntimeConfig=Ou;e2.schemaLogFilter=pr;e2.serializeDateTime=i2;e2.serializeFloat=s2;e2.take=Z4;e2.throwDefaultError=$u;e2.waiterServiceDefaults=Ru;e2.withBaseException=X4});var St=Z((qT)=>{var{homedir:q2}=nt("os"),{sep:C2,join:mi}=nt("path"),{createHash:K2}=nt("crypto"),{readFile:zu}=nt("fs/promises"),{IniSectionType:vr}=rs(),{normalizeProvider:te}=Rn(),{isValidHostLabel:V2}=nn();class ks extends Error{name="ProviderError";tryNextLink;constructor(t,n=!0){let s,i=!0;if(typeof n==="boolean")s=void 0,i=n;else if(n!=null&&typeof n==="object")s=n.logger,i=n.tryNextLink??!0;super(t);this.tryNextLink=i,Object.setPrototypeOf(this,ks.prototype),s?.debug?.(`@smithy/property-provider ${i?"->":"(!)"} ${t}`)}static from(t,n=!0){return Object.assign(new this(t.message,n),t)}}class Yi extends ks{name="CredentialsProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,Yi.prototype)}}class bf extends ks{name="TokenProviderError";constructor(t,n=!0){super(t,n);Object.setPrototypeOf(this,bf.prototype)}}var Xu=(...t)=>async()=>{if(t.length===0)throw new ks("No providers in chain");let n;for(let s of t)try{return await s()}catch(i){if(n=i,i?.tryNextLink)continue;throw i}throw n},xu=(t)=>()=>Promise.resolve(t),Tf=(t,n,s)=>{let i,r,e,f=!1,o=async()=>{if(!r)r=t();try{i=await r,e=!0,f=!1}finally{r=void 0}return i};if(n===void 0)return async(c)=>{if(!e||c?.forceRefresh)i=await o();return i};return async(c)=>{if(!e||c?.forceRefresh)i=await o();if(f)return i;if(s&&!s(i))return f=!0,i;if(n(i))return await o(),i;return i}},bn=(t,n,s)=>{if(!(n in t))return;if(t[n]==="true")return!0;if(t[n]==="false")return!1;throw Error(`Cannot load ${s} "${n}". Expected "true" or "false", got ${t[n]}.`)},j2=(t,n,s)=>{if(!(n in t))return;let i=parseInt(t[n],10);if(Number.isNaN(i))throw TypeError(`Cannot load ${s} '${n}'. Expected number, got '${t[n]}'.`);return i},Xt;(function(t){t.ENV="env",t.CONFIG="shared config entry"})(Xt||(Xt={}));var gf={},a2=()=>{if(process&&process.geteuid)return`${process.geteuid()}`;return"DEFAULT"},Qi=()=>{let{HOME:t,USERPROFILE:n,HOMEPATH:s,HOMEDRIVE:i=`C:${C2}`}=process.env;if(t)return t;if(n)return n;if(s)return`${i}${s}`;let r=a2();if(!gf[r])gf[r]=q2();return gf[r]},qu="AWS_PROFILE",Cu="default",Ku=(t)=>t.profile||process.env[qu]||Cu,Vu=(t)=>{let s=K2("sha1").update(t).digest("hex");return mi(Qi(),".aws","sso","cache",`${s}.json`)},ne={},p2=async(t)=>{if(ne[t])return ne[t];let n=Vu(t),s=await zu(n,"utf8");return JSON.parse(s)},os=".",Z2=(t)=>Object.entries(t).filter(([n])=>{let s=n.indexOf(os);if(s===-1)return!1;return Object.values(vr).includes(n.substring(0,s))}).reduce((n,[s,i])=>{let r=s.indexOf(os),e=s.substring(0,r)===vr.PROFILE?s.substring(r+1):s;return n[e]=i,n},{...t.default&&{default:t.default}}),v2="AWS_CONFIG_FILE",ju=()=>process.env[v2]||mi(Qi(),".aws","config"),tT="AWS_SHARED_CREDENTIALS_FILE",nT=()=>process.env[tT]||mi(Qi(),".aws","credentials"),sT=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,iT=["__proto__","profile __proto__"],Ef=(t)=>{let n={},s,i;for(let r of t.split(/\r?\n/)){let e=r.split(/(^|\s)[;#]/)[0].trim();if(e[0]==="["&&e[e.length-1]==="]"){s=void 0,i=void 0;let o=e.substring(1,e.length-1),c=sT.exec(o);if(c){let[,h,,u]=c;if(Object.values(vr).includes(h))s=[h,u].join(os)}else s=o;if(iT.includes(o))throw Error(`Found invalid profile name "${o}"`)}else if(s){let o=e.indexOf("=");if(![0,-1].includes(o)){let[c,h]=[e.substring(0,o).trim(),e.substring(o+1).trim()];if(h==="")i=c;else{if(i&&r.trimStart()===r)i=void 0;n[s]=n[s]||{};let u=i?[i,c].join(os):c;n[s][u]=h}}}}return n},df={},se={},ie=(t,n)=>{if(se[t]!==void 0)return se[t];if(!df[t]||n?.ignoreCache)df[t]=zu(t,"utf8");return df[t]},Nu=()=>({}),Sf=async(t={})=>{let{filepath:n=nT(),configFilepath:s=ju()}=t,i=Qi(),r="~/",e=n;if(n.startsWith("~/"))e=mi(i,n.slice(2));let f=s;if(s.startsWith("~/"))f=mi(i,s.slice(2));let o=await Promise.all([ie(f,{ignoreCache:t.ignoreCache}).then(Ef).then(Z2).catch(Nu),ie(e,{ignoreCache:t.ignoreCache}).then(Ef).catch(Nu)]);return{configFile:o[0],credentialsFile:o[1]}},rT=(t)=>Object.entries(t).filter(([n])=>n.startsWith(vr.SSO_SESSION+os)).reduce((n,[s,i])=>({...n,[s.substring(s.indexOf(os)+1)]:i}),{}),eT=()=>({}),oT=async(t={})=>ie(t.configFilepath??ju()).then(Ef).then(rT).catch(eT),fT=(...t)=>{let n={};for(let s of t)for(let[i,r]of Object.entries(s))if(n[i]!==void 0)Object.assign(n[i],r);else n[i]=r;return n},cT=async(t)=>{let n=await Sf(t);return fT(n.configFile,n.credentialsFile)},hT={getFileRecord(){return se},interceptFile(t,n){se[t]=Promise.resolve(n)},getTokenRecord(){return ne},interceptToken(t,n){ne[t]=n}};function au(t){try{let n=new Set(Array.from(t.match(/([A-Z_]){3,}/g)??[]));return n.delete("CONFIG"),n.delete("CONFIG_PREFIX_SEPARATOR"),n.delete("ENV"),[...n].join(", ")}catch(n){return t}}var uT=(t,n)=>async()=>{try{let s=t(process.env,n);if(s===void 0)throw Error();return s}catch(s){throw new Yi(s.message||`Not found in ENV: ${au(t.toString())}`,{logger:n?.logger})}},lT=(t,{preferredFile:n="config",...s}={})=>async()=>{let i=Ku(s),{configFile:r,credentialsFile:e}=await Sf(s),f=e[i]||{},o=r[i]||{},c=n==="config"?{...f,...o}:{...o,...f};try{let u=t(c,n==="config"?r:e);if(u===void 0)throw Error();return u}catch(h){throw new Yi(h.message||`Not found in config files w/ profile [${i}]: ${au(t.toString())}`,{logger:s.logger})}},_T=(t)=>typeof t==="function",pu=(t)=>_T(t)?async()=>await t():xu(t),Rf=({environmentVariableSelector:t,configFileSelector:n,default:s},i={})=>{let{signingName:r,logger:e}=i;return Tf(Xu(uT(t,{signingName:r,logger:e}),lT(n,i),pu(s)))},$f="AWS_USE_DUALSTACK_ENDPOINT",Uf="use_dualstack_endpoint",wT=!1,AT={environmentVariableSelector:(t)=>bn(t,$f,Xt.ENV),configFileSelector:(t)=>bn(t,Uf,Xt.CONFIG),default:!1},MT={environmentVariableSelector:(t)=>bn(t,$f,Xt.ENV),configFileSelector:(t)=>bn(t,Uf,Xt.CONFIG),default:void 0},Lf="AWS_USE_FIPS_ENDPOINT",If="use_fips_endpoint",gT=!1,dT={environmentVariableSelector:(t)=>bn(t,Lf,Xt.ENV),configFileSelector:(t)=>bn(t,If,Xt.CONFIG),default:!1},ET={environmentVariableSelector:(t)=>bn(t,Lf,Xt.ENV),configFileSelector:(t)=>bn(t,If,Xt.CONFIG),default:void 0},RT=(t)=>{let{tls:n,endpoint:s,urlParser:i,useDualstackEndpoint:r}=t;return Object.assign(t,{tls:n??!0,endpoint:te(typeof s==="string"?i(s):s),isCustomEndpoint:!0,useDualstackEndpoint:te(r??!1)})},bT=async(t)=>{let{tls:n=!0}=t,s=await t.region();if(!new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/).test(s))throw Error("Invalid region in client config");let r=await t.useDualstackEndpoint(),e=await t.useFipsEndpoint(),{hostname:f}=await t.regionInfoProvider(s,{useDualstackEndpoint:r,useFipsEndpoint:e})??{};if(!f)throw Error("Cannot resolve hostname from client config");return t.urlParser(`${n?"https:":"http:"}//${f}`)},TT=(t)=>{let n=te(t.useDualstackEndpoint??!1),{endpoint:s,useFipsEndpoint:i,urlParser:r,tls:e}=t;return Object.assign(t,{tls:e??!0,endpoint:s?te(typeof s==="string"?r(s):s):()=>bT({...t,useDualstackEndpoint:n,useFipsEndpoint:i}),isCustomEndpoint:!!s,useDualstackEndpoint:n})},ST="AWS_EXECUTION_ENV",Wu="AWS_REGION",Du="AWS_DEFAULT_REGION",$T="AWS_EC2_METADATA_DISABLED",UT=["in-region","cross-region","mobile","standard","legacy"],LT="/latest/meta-data/placement/region",IT="/latest/api/token",yT="x-aws-ec2-metadata-token",OT="x-aws-ec2-metadata-token-ttl-seconds",mu=1000,GT=60000,Zu=0,vu=async()=>{if(process.env[$T])return;if(Date.now()<Zu)return;try{let t=BT(),n=(await Qu({...t,path:IT,method:"PUT",headers:{[OT]:"21600"}})).toString();return(await Qu({...t,path:LT,method:"GET",headers:{[yT]:n}})).toString().trim()||Yu()}catch{return Yu()}},Yu=()=>{Zu=Date.now()+GT;return},BT=()=>{let t=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(t){let n=new URL(t);return{hostname:n.hostname.replace(/^\[(.+)]$/,"$1"),port:n.port?Number(n.port):void 0}}if(process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6")return{hostname:"fd00:ec2::254"};return{hostname:"169.254.169.254"}},Qu=async(t)=>{let{request:n}=nt("http");return new Promise((s,i)=>{let r=n({hostname:t.hostname,port:t.port,path:t.path,method:t.method,headers:t.headers,timeout:mu,signal:AbortSignal.timeout(mu)});r.on("error",(e)=>{i(e),r.destroy()}),r.on("timeout",()=>{i(Error("TimeoutError from instance metadata service")),r.destroy()}),r.on("response",(e)=>{let{statusCode:f=400}=e;if(f<200||f>=300){i(Object.assign(Error("Error response received from instance metadata service"),{statusCode:f})),r.destroy();return}let o=[];e.on("data",(c)=>o.push(c)),e.on("end",()=>{s(Buffer.concat(o)),r.destroy()})}),r.end()})},tl="AWS_REGION",nl="region",sl={environmentVariableSelector:(t)=>t[tl],configFileSelector:(t)=>t[nl],default:async()=>{let t=await vu();if(t)return t;throw Error("Region is missing")}},FT={preferredFile:"credentials"},Ju=new Set,HT=(t,n=V2)=>{if(!Ju.has(t)&&!n(t))if(t==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw Error(`Region not accepted: region="${t}" is not a valid hostname component.`);else Ju.add(t)},il=(t)=>typeof t==="string"&&(t.startsWith("fips-")||t.endsWith("-fips")),PT=(t)=>il(t)?["fips-aws-global","aws-fips"].includes(t)?"us-east-1":t.replace(/fips-(dkr-|prod-)?|-fips/,""):t,NT=(t)=>{let{region:n,useFipsEndpoint:s}=t;if(!n)throw Error("Region is missing");return Object.assign(t,{region:async()=>{let i=typeof n==="function"?await n():n,r=PT(i);return HT(r),r},useFipsEndpoint:async()=>{let i=typeof n==="string"?n:await n();if(il(i))return!0;return typeof s!=="function"?Promise.resolve(!!s):s()}})},ku=(t=[],{useFipsEndpoint:n,useDualstackEndpoint:s})=>t.find(({tags:i})=>n===i.includes("fips")&&s===i.includes("dualstack"))?.hostname,WT=(t,{regionHostname:n,partitionHostname:s})=>n?n:s?s.replace("{region}",t):void 0,DT=(t,{partitionHash:n})=>Object.keys(n||{}).find((s)=>n[s].regions.includes(t))??"aws",mT=(t,{signingRegion:n,regionRegex:s,useFipsEndpoint:i})=>{if(n)return n;else if(i){let r=s.replace("\\\\","\\").replace(/^\^/g,"\\.").replace(/\$$/g,"\\."),e=t.match(r);if(e)return e[0].slice(1,-1)}},YT=(t,{useFipsEndpoint:n=!1,useDualstackEndpoint:s=!1,signingService:i,regionHash:r,partitionHash:e})=>{let f=DT(t,{partitionHash:e}),o=t in r?t:e[f]?.endpoint??t,c={useFipsEndpoint:n,useDualstackEndpoint:s},h=ku(r[o]?.variants,c),u=ku(e[f]?.variants,c),l=WT(o,{regionHostname:h,partitionHostname:u});if(l===void 0)throw Error(`Endpoint resolution failed for: ${{resolvedRegion:o,useFipsEndpoint:n,useDualstackEndpoint:s}}`);let _=mT(l,{signingRegion:r[o]?.signingRegion,regionRegex:e[f].regionRegex,useFipsEndpoint:n});return{partition:f,signingService:i,hostname:l,..._&&{signingRegion:_},...r[o]?.signingService&&{signingService:r[o].signingService}}},QT="AWS_DEFAULTS_MODE",JT="defaults_mode",kT={environmentVariableSelector:(t)=>{return t[QT]},configFileSelector:(t)=>{return t[JT]},default:"legacy"},zT=({region:t=Rf(sl),defaultsMode:n=Rf(kT)}={})=>Tf(async()=>{let s=typeof n==="function"?await n():n;switch(s?.toLowerCase()){case"auto":return XT(t);case"in-region":case"cross-region":case"mobile":case"standard":case"legacy":return Promise.resolve(s?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw Error(`Invalid parameter for "defaultsMode", expect ${UT.join(", ")}, got ${s}`)}}),XT=async(t)=>{if(t){let n=typeof t==="function"?await t():t,s=await xT();if(!s)return"standard";if(n===s)return"in-region";else return"cross-region"}return"standard"},xT=async()=>{if(process.env[ST]&&(process.env[Wu]||process.env[Du]))return process.env[Wu]??process.env[Du];return vu()};qT.CONFIG_PREFIX_SEPARATOR=os;qT.CONFIG_USE_DUALSTACK_ENDPOINT=Uf;qT.CONFIG_USE_FIPS_ENDPOINT=If;qT.CredentialsProviderError=Yi;qT.DEFAULT_PROFILE=Cu;qT.DEFAULT_USE_DUALSTACK_ENDPOINT=wT;qT.DEFAULT_USE_FIPS_ENDPOINT=gT;qT.ENV_PROFILE=qu;qT.ENV_USE_DUALSTACK_ENDPOINT=$f;qT.ENV_USE_FIPS_ENDPOINT=Lf;qT.NODE_REGION_CONFIG_FILE_OPTIONS=FT;qT.NODE_REGION_CONFIG_OPTIONS=sl;qT.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS=AT;qT.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS=dT;qT.ProviderError=ks;qT.REGION_ENV_NAME=tl;qT.REGION_INI_NAME=nl;qT.SelectorType=Xt;qT.TokenProviderError=bf;qT.booleanSelector=bn;qT.chain=Xu;qT.externalDataInterceptor=hT;qT.fromStatic=pu;qT.fromValue=xu;qT.getHomeDir=Qi;qT.getProfileName=Ku;qT.getRegionInfo=YT;qT.getSSOTokenFilepath=Vu;qT.getSSOTokenFromFile=p2;qT.loadConfig=Rf;qT.loadSharedConfigFiles=Sf;qT.loadSsoSessionData=oT;qT.memoize=Tf;qT.nodeDualstackConfigSelectors=MT;qT.nodeFipsConfigSelectors=ET;qT.numberSelector=j2;qT.parseKnownFiles=cT;qT.readFile=ie;qT.resolveCustomEndpointsConfig=RT;qT.resolveDefaultsModeConfig=zT;qT.resolveEndpointsConfig=TT;qT.resolveRegionConfig=NT});var fs=Z((E5)=>{var{CONFIG_PREFIX_SEPARATOR:rl,loadConfig:N6}=St(),{toEndpointV1:re,getSmithyContext:W6,normalizeProvider:yf,isValidHostLabel:fl}=nn();E5.isValidHostLabel=fl;E5.middlewareEndpointToEndpointV1=re;E5.toEndpointV1=re;var{EndpointURLScheme:Bf}=rs(),el="AWS_ENDPOINT_URL",ol="endpoint_url",D6=(t)=>({environmentVariableSelector:(n)=>{let s=t.split(" ").map((e)=>e.toUpperCase()),i=n[[el,...s].join("_")];if(i)return i;let r=n[el];if(r)return r;return},configFileSelector:(n,s)=>{if(s&&n.services){let r=s[["services",n.services].join(rl)];if(r){let e=t.split(" ").map((o)=>o.toLowerCase()),f=r[[e.join("_"),ol].join(rl)];if(f)return f}}let i=n[ol];if(i)return i;return},default:void 0}),ee=async(t)=>N6(D6(t??""))(),m6=async(t)=>{let n=t?.Bucket||"";if(typeof t.Bucket==="string")t.Bucket=n.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"));if(z6(n)){if(t.ForcePathStyle===!0)throw Error("Path-style addressing cannot be used with ARN buckets")}else if(!k6(n)||n.indexOf(".")!==-1&&!String(t.Endpoint).startsWith("http:")||n.toLowerCase()!==n||n.length<3)t.ForcePathStyle=!0;if(t.DisableMultiRegionAccessPoints)t.disableMultiRegionAccessPoints=!0,t.DisableMRAP=!0;return t},Y6=/^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$/,Q6=/(\d+\.){3}\d+/,J6=/\.\./,k6=(t)=>Y6.test(t)&&!Q6.test(t)&&!J6.test(t),z6=(t)=>{let[n,s,i,,,r]=t.split(":"),e=n==="arn"&&t.split(":").length>=6,f=Boolean(e&&s&&i&&r);if(e&&!f)throw Error(`Invalid ARN: ${t} was an invalid ARN.`);return f},X6=(t,n,s,i=!1)=>{let r=async()=>{let e;if(i)e=s.clientContextParams?.[t]??s[t]??s[n];else e=s[t]??s[n];if(typeof e==="function")return e();return e};if(t==="credentialScope"||n==="CredentialScope")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.credentialScope??e?.CredentialScope};if(t==="accountId"||n==="AccountId")return async()=>{let e=typeof s.credentials==="function"?await s.credentials():s.credentials;return e?.accountId??e?.AccountId};if(t==="endpoint"||n==="endpoint")return async()=>{if(s.isCustomEndpoint===!1)return;let e=await r();if(e&&typeof e==="object"){if("url"in e)return e.url.href;if("hostname"in e){let{protocol:f,hostname:o,port:c,path:h}=e;return`${f}//${o}${c?":"+c:""}${h}`}}return e};return r};function cl(t){return async(n,s,i,r)=>{if(!i.isCustomEndpoint){let o;if(i.serviceConfiguredEndpoint)o=await i.serviceConfiguredEndpoint();else o=await t(i.serviceId);if(o)i.endpoint=()=>Promise.resolve(re(o)),i.isCustomEndpoint=!0}let e=await hl(n,s,i);if(typeof i.endpointProvider!=="function")throw Error("config.endpointProvider is not set.");let f=i.endpointProvider(e,r);if(i.isCustomEndpoint&&i.endpoint){let o=await i.endpoint();if(o?.headers){f.headers??={};for(let[c,h]of Object.entries(o.headers))f.headers[c]=Array.isArray(h)?h:[h]}}return f}}var hl=async(t,n,s)=>{let i={},r=n?.getEndpointParameterInstructions?.()||{};for(let[e,f]of Object.entries(r))switch(f.type){case"staticContextParams":i[e]=f.value;break;case"contextParams":i[e]=t[f.name];break;case"clientContextParams":case"builtInParams":i[e]=await X6(f.name,e,s,f.type!=="builtInParams")();break;case"operationContextParams":i[e]=f.get(t);break;default:throw Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(f))}if(Object.keys(r).length===0)Object.assign(i,s);if(String(s.serviceId).toLowerCase()==="s3")await m6(i);return i};function x6(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}function ul(t){let n=cl(t);return({config:s,instructions:i})=>{return(r,e)=>async(f)=>{if(s.isCustomEndpoint)x6(e,"ENDPOINT_OVERRIDE","N");let o=await n(f.input,{getEndpointParameterInstructions(){return i}},{...s},e);e.endpointV2=o,e.authSchemes=o.properties?.authSchemes;let c=e.authSchemes?.[0];if(c){e.signing_region=c.signingRegion,e.signing_service=c.signingName;let u=W6(e)?.selectedHttpAuthScheme?.httpAuthOption;if(u)u.signingProperties=Object.assign(u.signingProperties||{},{signing_region:c.signingRegion,signingRegion:c.signingRegion,signing_service:c.signingName,signingName:c.signingName,signingRegionSet:c.signingRegionSet},c.properties)}return r({...f})}}}var q6={name:"serializerMiddleware"},ll={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:q6.name};function C6(t){let n=ul(t);return(s,i)=>({applyToStack:(r)=>{r.addRelativeTo(n({config:s,instructions:i}),ll)}})}function K6(t){return(n)=>{let s=n.tls??!0,{endpoint:i,useDualstackEndpoint:r,useFipsEndpoint:e}=n,f=i!=null?async()=>re(await yf(i)()):void 0,c=Object.assign(n,{endpoint:f,tls:s,isCustomEndpoint:!!i,useDualstackEndpoint:yf(r??!1),useFipsEndpoint:yf(e??!1)}),h=void 0;return c.serviceConfiguredEndpoint=async()=>{if(n.serviceId&&!h)h=t(n.serviceId);return h},c}}class Ff{nodes;root;conditions;results;constructor(t,n,s,i){this.nodes=t,this.root=n,this.conditions=s,this.results=i}static from(t,n,s,i){return new Ff(t,n,s,i)}}class _l{capacity;data=new Map;parameters=[];constructor({size:t,params:n}){if(this.capacity=t??50,n)this.parameters=n}get(t,n){let s=this.hash(t);if(s===!1)return n();if(!this.data.has(s)){if(this.data.size>this.capacity+10){let i=this.data.keys(),r=0;while(!0){let{value:e,done:f}=i.next();if(this.data.delete(e),f||++r>10)break}}this.data.set(s,n())}return this.data.get(s)}size(){return this.data.size}hash(t){let n="",{parameters:s}=this;if(s.length===0)return!1;for(let i of s){let r=String(t[i]??"");if(r.includes("|;"))return!1;n+=r+"|;"}return n}}class wt extends Error{constructor(t){super(t);this.name="EndpointError"}}var Ji="endpoints";function Dn(t){if(typeof t!=="object"||t==null)return t;if("ref"in t)return`$${Dn(t.ref)}`;if("fn"in t)return`${t.fn}(${(t.argv||[]).map(Dn).join(", ")})`;return JSON.stringify(t,null,2)}var wl={},V6=(t,n)=>t===n;function j6(...t){for(let n of t)if(n!=null)return n;return}var a6=(t)=>{let n=t.split("."),s=[];for(let i of n){let r=i.indexOf("[");if(r!==-1){if(i.indexOf("]")!==i.length-1)throw new wt(`Path: '${t}' does not end with ']'`);let e=i.slice(r+1,-1);if(Number.isNaN(parseInt(e)))throw new wt(`Invalid array index: '${e}' in path: '${t}'`);if(r!==0)s.push(i.slice(0,r));s.push(e)}else s.push(i)}return s},Al=(t,n)=>a6(n).reduce((s,i)=>{if(typeof s!=="object")throw new wt(`Index '${i}' in '${n}' not found in '${JSON.stringify(t)}'`);else if(Array.isArray(s)){let r=parseInt(i);return s[r<0?s.length+r:r]}return s[i]},t),p6=(t)=>t!=null;function Z6(t,n,s){return t?n:s}var v6=(t)=>!t,t5=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),Ml=(t)=>t5.test(t)||t.startsWith("[")&&t.endsWith("]"),Of={[Bf.HTTP]:80,[Bf.HTTPS]:443},n5=(t)=>{let n=(()=>{try{if(t instanceof URL)return t;if(typeof t==="object"&&"hostname"in t){let{hostname:_,port:w,protocol:A="",path:M="",query:d={}}=t,E=new URL(`${A}//${_}${w?`:${w}`:""}${M}`);return E.search=Object.entries(d).map(([T,U])=>`${T}=${U}`).join("&"),E}return new URL(t)}catch(_){return null}})();if(!n)return console.error(`Unable to parse ${JSON.stringify(t)} as a whatwg URL.`),null;let s=n.href,{host:i,hostname:r,pathname:e,protocol:f,search:o}=n;if(o)return null;let c=f.slice(0,-1);if(!Object.values(Bf).includes(c))return null;let h=Ml(r),u=s.includes(`${i}:${Of[c]}`)||typeof t==="string"&&t.includes(`${i}:${Of[c]}`),l=`${i}${u?`:${Of[c]}`:""}`;return{scheme:c,authority:l,path:e,normalizedPath:e.endsWith("/")?e:`${e}/`,isIp:h}};function s5(t,n,s){if(s===1)return[t];if(t==="")return[""];let i=t.split(n);if(s===0)return i;return i.slice(0,s-1).concat(i.slice(1).join(n))}var i5=(t,n)=>t===n,r5=(t,n,s,i)=>{if(t==null||n>=s||t.length<s||/[^\u0000-\u007f]/.test(t))return null;if(!i)return t.substring(n,s);return t.substring(t.length-s,t.length-n)},e5=(t)=>encodeURIComponent(t).replace(/[!*'()]/g,(n)=>`%${n.charCodeAt(0).toString(16).toUpperCase()}`),o5={booleanEquals:V6,coalesce:j6,getAttr:Al,isSet:p6,isValidHostLabel:fl,ite:Z6,not:v6,parseURL:n5,split:s5,stringEquals:i5,substring:r5,uriEncode:e5},gl=(t,n)=>{let s=[],{referenceRecord:i,endpointParams:r}=n,e=0;while(e<t.length){let f=t.indexOf("{",e);if(f===-1){s.push(t.slice(e));break}s.push(t.slice(e,f));let o=t.indexOf("}",f);if(o===-1){s.push(t.slice(f));break}if(t[f+1]==="{"&&t[o+1]==="}")s.push(t.slice(f+1,o)),e=o+2;let c=t.substring(f+1,o);if(c.includes("#")){let[h,u]=c.split("#");s.push(Al(i[h]??r[h],u))}else s.push(i[c]??r[c]);e=o+1}return s.join("")},f5=({ref:t},n)=>{return n.referenceRecord[t]??n.endpointParams[t]},ki=(t,n,s)=>{if(typeof t==="string")return gl(t,s);else if(t.fn)return El.callFunction(t,s);else if(t.ref)return f5(t,s);throw new wt(`'${n}': ${String(t)} is not a string, function or reference.`)},dl=({fn:t,argv:n},s)=>{let i=Array(n.length);for(let f=0;f<i.length;++f){let o=n[f];if(typeof o==="boolean"||typeof o==="number")i[f]=o;else i[f]=El.evaluateExpression(o,"arg",s)}let r=t.indexOf(".");if(r!==-1){let o=wl[t.slice(0,r)]?.[t.slice(r+1)];if(typeof o==="function")return o(...i)}let e=o5[t];if(typeof e==="function")return e(...i);throw Error(`function ${t} not loaded in endpointFunctions.`)},El={evaluateExpression:ki,callFunction:dl},Rl=(t,n)=>{let{assign:s}=t;if(s&&s in n.referenceRecord)throw new wt(`'${s}' is already defined in Reference Record.`);let i=dl(t,n);n.logger?.debug?.(`${Ji} evaluateCondition: ${Dn(t)} = ${Dn(i)}`);let r=i===""?!0:!!i;if(s!=null)return{result:r,toAssign:{name:s,value:i}};return{result:r}},bl=(t,n)=>Object.entries(t??{}).reduce((s,[i,r])=>{return s[i]=r.map((e)=>{let f=ki(e,"Header value entry",n);if(typeof f!=="string")throw new wt(`Header '${i}' value '${f}' is not a string`);return f}),s},{}),Hf=(t,n)=>Object.entries(t).reduce((s,[i,r])=>{return s[i]=Sl.getEndpointProperty(r,n),s},{}),Tl=(t,n)=>{if(Array.isArray(t))return t.map((s)=>Tl(s,n));switch(typeof t){case"string":return gl(t,n);case"object":if(t===null)throw new wt(`Unexpected endpoint property: ${t}`);return Sl.getEndpointProperties(t,n);case"boolean":return t;default:throw new wt(`Unexpected endpoint property type: ${typeof t}`)}},Sl={getEndpointProperty:Tl,getEndpointProperties:Hf},$l=(t,n)=>{let s=ki(t,"Endpoint URL",n);if(typeof s==="string")try{return new URL(s)}catch(i){throw console.error(`Failed to construct URL with ${s}`,i),i}throw new wt(`Endpoint URL must be a string, got ${typeof s}`)},Gf=1e8,c5=(t,n)=>{let{nodes:s,root:i,results:r,conditions:e}=t,f=i,o={},c={referenceRecord:o,endpointParams:n.endpointParams,logger:n.logger};while(f!==1&&f!==-1&&f<Gf){let h=3*(Math.abs(f)-1),[u,l,_]=[s[h],s[h+1],s[h+2]],[w,A,M]=e[u],d=Rl({fn:w,assign:M,argv:A},c);if(d.toAssign){let{name:E,value:T}=d.toAssign;o[E]=T}f=f>=0===d.result?l:_}if(f>=Gf){let h=r[f-Gf];if(h[0]===-1){let[,w]=h;throw new wt(ki(w,"Error",c))}let[u,l,_]=h;return{url:$l(u,c),properties:Hf(l,c),headers:bl(_??{},c)}}throw new wt("No matching endpoint.")},Pf=(t=[],n)=>{let s={},i={...n,referenceRecord:{...n.referenceRecord}},r=!1;for(let e of t){let{result:f,toAssign:o}=Rl(e,i);if(!f)return{result:f};if(o)r=!0,s[o.name]=o.value,i.referenceRecord[o.name]=o.value,n.logger?.debug?.(`${Ji} assign: ${o.name} := ${Dn(o.value)}`)}if(r)return{result:!0,referenceRecord:s};return{result:!0}},h5=(t,n)=>{let{conditions:s,endpoint:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n,{url:o,properties:c,headers:h}=i;n.logger?.debug?.(`${Ji} Resolving endpoint from template: ${Dn(i)}`);let u={url:$l(o,f)};if(h!=null)u.headers=bl(h,f);if(c!=null)u.properties=Hf(c,f);return u},u5=(t,n)=>{let{conditions:s,error:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;throw new wt(ki(i,"Error",f))},Ul=(t,n)=>{for(let s of t)if(s.type==="endpoint"){let i=h5(s,n);if(i)return i}else if(s.type==="error")u5(s,n);else if(s.type==="tree"){let i=Ll.evaluateTreeRule(s,n);if(i)return i}else throw new wt(`Unknown endpoint rule: ${s}`);throw new wt("Rules evaluation failed")},l5=(t,n)=>{let{conditions:s,rules:i}=t,{result:r,referenceRecord:e}=Pf(s,n);if(!r)return;let f=e?{...n,referenceRecord:{...n.referenceRecord,...e}}:n;return Ll.evaluateRules(i,f)},Ll={evaluateRules:Ul,evaluateTreeRule:l5},_5=(t,n)=>{let{endpointParams:s,logger:i}=n,{parameters:r,rules:e}=t;n.logger?.debug?.(`${Ji} Initial EndpointParams: ${Dn(s)}`);for(let o in r){let c=r[o],h=s[o];if(h==null&&c.default!=null){s[o]=c.default;continue}if(c.required&&h==null)throw new wt(`Missing required parameter: '${o}'`)}let f=Ul(e,{endpointParams:s,logger:i,referenceRecord:{}});return n.logger?.debug?.(`${Ji} Resolved endpoint: ${Dn(f)}`),f},w5=(t)=>{let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{throw Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint.")};return t},A5=cl(ee),M5=K6(ee),g5=ul(ee),d5=C6(ee);E5.BinaryDecisionDiagram=Ff;E5.EndpointCache=_l;E5.EndpointError=wt;E5.customEndpointFunctions=wl;E5.decideEndpoint=c5;E5.endpointMiddleware=g5;E5.endpointMiddlewareOptions=ll;E5.getEndpointFromInstructions=A5;E5.getEndpointPlugin=d5;E5.isIpAddress=Ml;E5.resolveEndpoint=_5;E5.resolveEndpointConfig=M5;E5.resolveEndpointRequiredConfig=w5;E5.resolveParams=hl});var $t=Z((uS)=>{var{createHmac:D5,createHash:m5,getRandomValues:Y5}=nt("crypto"),{ReadStream:Q5,lstatSync:J5,fstatSync:k5}=nt("fs"),{HttpResponse:z5}=nn(),{toEndpointV1:X5}=fs(),{Readable:zs,Writable:Pl,PassThrough:Il}=nt("stream"),Nl=(t)=>typeof ArrayBuffer==="function"&&t instanceof ArrayBuffer||Object.prototype.toString.call(t)==="[object ArrayBuffer]",xs=(t,n=0,s=t.byteLength-n)=>{if(!Nl(t))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof t} (${t})`);return Buffer.from(t,n,s)},he=(t,n)=>{if(typeof t!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof t} (${t})`);return n?Buffer.from(t,n):Buffer.from(t)},x5=/^[A-Za-z0-9+/]*={0,2}$/,Wl=(t)=>{if(t.length*3%4!==0)throw TypeError("Incorrect padding on base64 string.");if(!x5.exec(t))throw TypeError("Invalid base64 string.");let n=he(t,"base64");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)},ue=(t)=>{let n=he(t,"utf8");return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)},kf=(t)=>{let n;if(typeof t==="string")n=ue(t);else n=t;if(typeof n!=="object"||typeof n.byteOffset!=="number"||typeof n.byteLength!=="number")throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return xs(n.buffer,n.byteOffset,n.byteLength).toString("base64")};function q5(t,n,s,i){return class r extends Uint8Array{static fromString(e,f="utf-8"){if(typeof e==="string"){if(f==="base64")return r.mutate(i(e));return r.mutate(n(e))}throw Error(`Unsupported conversion from ${typeof e} to Uint8ArrayBlobAdapter.`)}static mutate(e){return Object.setPrototypeOf(e,r.prototype),e}transformToString(e="utf-8"){if(e==="base64")return s(this);return t(this)}}}var Dl=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return xs(t.buffer,t.byteOffset,t.byteLength).toString("utf8")},dt=Array.from({length:256},(t,n)=>n.toString(16).padStart(2,"0"));function C5(t){if(typeof crypto<"u"&&typeof crypto.randomUUID==="function")return()=>crypto.randomUUID();return()=>{let n=new Uint8Array(16);return t(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,dt[n[0]]+dt[n[1]]+dt[n[2]]+dt[n[3]]+"-"+dt[n[4]]+dt[n[5]]+"-"+dt[n[6]]+dt[n[7]]+"-"+dt[n[8]]+dt[n[9]]+"-"+dt[n[10]]+dt[n[11]]+dt[n[12]]+dt[n[13]]+dt[n[14]]+dt[n[15]]}}var K5=(t,n,s=(i)=>i)=>t,V5=(t)=>{switch(t){case"true":return!0;case"false":return!1;default:throw Error(`Unable to parse boolean value "${t}"`)}},j5=(t)=>{if(t===null||t===void 0)return;if(typeof t==="number"){if(t===0||t===1)qi.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(t===0)return!1;if(t===1)return!0}if(typeof t==="string"){let n=t.toLowerCase();if(n==="false"||n==="true")qi.warn(fe(`Expected boolean, got ${typeof t}: ${t}`));if(n==="false")return!1;if(n==="true")return!0}if(typeof t==="boolean")return t;throw TypeError(`Expected boolean, got ${typeof t}: ${t}`)},Xi=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string"){let n=parseFloat(t);if(!Number.isNaN(n)){if(String(n)!==String(t))qi.warn(fe(`Expected number but observed string: ${t}`));return n}}if(typeof t==="number")return t;throw TypeError(`Expected number, got ${typeof t}: ${t}`)},a5=Math.ceil(340282346638528860000000000000000000000),oe=(t)=>{let n=Xi(t);if(n!==void 0&&!Number.isNaN(n)&&n!==1/0&&n!==-1/0){if(Math.abs(n)>a5)throw TypeError(`Expected 32-bit float, got ${t}`)}return n},xi=(t)=>{if(t===null||t===void 0)return;if(Number.isInteger(t)&&!Number.isNaN(t))return t;throw TypeError(`Expected integer, got ${typeof t}: ${t}`)},p5=xi,mf=(t)=>zf(t,32),Yf=(t)=>zf(t,16),Qf=(t)=>zf(t,8),zf=(t,n)=>{let s=xi(t);if(s!==void 0&&Z5(s,n)!==s)throw TypeError(`Expected ${n}-bit integer, got ${t}`);return s},Z5=(t,n)=>{switch(n){case 32:return Int32Array.of(t)[0];case 16:return Int16Array.of(t)[0];case 8:return Int8Array.of(t)[0]}},v5=(t,n)=>{if(t===null||t===void 0){if(n)throw TypeError(`Expected a non-null value for ${n}`);throw TypeError("Expected a non-null value")}return t},ml=(t)=>{if(t===null||t===void 0)return;if(typeof t==="object"&&!Array.isArray(t))return t;let n=Array.isArray(t)?"array":typeof t;throw TypeError(`Expected object, got ${n}: ${t}`)},t8=(t)=>{if(t===null||t===void 0)return;if(typeof t==="string")return t;if(["boolean","number","bigint"].includes(typeof t))return qi.warn(fe(`Expected string, got ${typeof t}: ${t}`)),String(t);throw TypeError(`Expected string, got ${typeof t}: ${t}`)},n8=(t)=>{if(t===null||t===void 0)return;let n=ml(t),s=[];for(let i in n)if(n[i]!=null)s.push(i);if(s.length===0)throw TypeError("Unions must have exactly one non-null member. None were found.");if(s.length>1)throw TypeError(`Unions must have exactly one non-null member. Keys ${s} were not null.`);return n},Xf=(t)=>{if(typeof t=="string")return Xi(Ks(t));return Xi(t)},s8=Xf,Yl=(t)=>{if(typeof t=="string")return oe(Ks(t));return oe(t)},i8=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,Ks=(t)=>{let n=t.match(i8);if(n===null||n[0].length!==t.length)throw TypeError("Expected real number, got implicit NaN");return parseFloat(t)},xf=(t)=>{if(typeof t=="string")return Ql(t);return Xi(t)},r8=xf,e8=xf,o8=(t)=>{if(typeof t=="string")return Ql(t);return oe(t)},Ql=(t)=>{switch(t){case"NaN":return NaN;case"Infinity":return 1/0;case"-Infinity":return-1/0;default:throw Error(`Unable to parse float value: ${t}`)}},Jl=(t)=>{if(typeof t==="string")return xi(Ks(t));return xi(t)},f8=Jl,c8=(t)=>{if(typeof t==="string")return mf(Ks(t));return mf(t)},qs=(t)=>{if(typeof t==="string")return Yf(Ks(t));return Yf(t)},kl=(t)=>{if(typeof t==="string")return Qf(Ks(t));return Qf(t)},fe=(t)=>{return String(TypeError(t).stack||t).split(`
9
9
  `).slice(0,5).filter((n)=>!n.includes("stackTraceWarning")).join(`
10
- `)},qr={warn:console.warn},h8=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],qf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function u8(t){let n=t.getUTCFullYear(),s=t.getUTCMonth(),r=t.getUTCDay(),i=t.getUTCDate(),e=t.getUTCHours(),f=t.getUTCMinutes(),o=t.getUTCSeconds(),c=i<10?`0${i}`:`${i}`,h=e<10?`0${e}`:`${e}`,u=f<10?`0${f}`:`${f}`,_=o<10?`0${o}`:`${o}`;return`${h8[r]}, ${c} ${qf[s]} ${n} ${h}:${u}:${_} GMT`}var _8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),l8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=_8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,i,e,f,o,c,h]=n,u=qs(Cs(r)),_=rn(i,"month",1,12),l=rn(e,"day",1,31);return Xr(u,_,l,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})},w8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),A8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=w8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,r,i,e,f,o,c,h,u]=n,_=qs(Cs(r)),l=rn(i,"month",1,12),w=rn(e,"day",1,31),A=Xr(_,l,w,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h});if(u.toUpperCase()!="Z")A.setTime(A.getTime()-O8(u));return A},M8=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$/),g8=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$/),E8=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})$/),d8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let n=M8.exec(t);if(n){let[s,r,i,e,f,o,c,h]=n;return Xr(qs(Cs(e)),Nf(i),rn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})}if(n=g8.exec(t),n){let[s,r,i,e,f,o,c,h]=n;return S8(Xr(b8(e),Nf(i),rn(r,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h}))}if(n=E8.exec(t),n){let[s,r,i,e,f,o,c,h]=n;return Xr(qs(Cs(h)),Nf(r),rn(i.trimLeft(),"day",1,31),{hours:e,minutes:f,seconds:o,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},R8=(t)=>{if(t===null||t===void 0)return;let n;if(typeof t==="number")n=t;else if(typeof t==="string")n=zf(t);else if(typeof t==="object"&&t.tag===1)n=t.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(n)||n===1/0||n===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(n*1000))},Xr=(t,n,s,r)=>{let i=n-1;return U8(t,i,s),new Date(Date.UTC(t,i,s,rn(r.hours,"hour",0,23),rn(r.minutes,"minute",0,59),rn(r.seconds,"seconds",0,60),I8(r.fractionalMilliseconds)))},b8=(t)=>{let n=new Date().getUTCFullYear(),s=Math.floor(n/100)*100+qs(Cs(t));if(s<n)return s+100;return s},T8=1576800000000,S8=(t)=>{if(t.getTime()-new Date().getTime()>T8)return new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()));return t},Nf=(t)=>{let n=qf.indexOf(t);if(n<0)throw TypeError(`Invalid month: ${t}`);return n+1},$8=[31,28,31,30,31,30,31,31,30,31,30,31],U8=(t,n,s)=>{let r=$8[n];if(n===1&&L8(t))r=29;if(s>r)throw TypeError(`Invalid day for ${qf[n]} in ${t}: ${s}`)},L8=(t)=>{return t%4===0&&(t%100!==0||t%400===0)},rn=(t,n,s,r)=>{let i=k_(Cs(t));if(i<s||i>r)throw TypeError(`${n} must be between ${s} and ${r}, inclusive`);return i},I8=(t)=>{if(t===null||t===void 0)return 0;return m_("0."+t)*1000},O8=(t)=>{let n=t[0],s=1;if(n=="+")s=1;else if(n=="-")s=-1;else throw TypeError(`Offset direction, ${n}, must be "+" or "-"`);let r=Number(t.substring(1,3)),i=Number(t.substring(4,6));return s*(r*60+i)*60*1000},Cs=(t)=>{let n=0;while(n<t.length-1&&t.charAt(n)==="0")n++;if(n===0)return t;return t.slice(n)},cs=function(n){return Object.assign(new String(n),{deserializeJSON(){return JSON.parse(String(n))},toString(){return String(n)},toJSON(){return String(n)}})};cs.from=(t)=>{if(t&&typeof t==="object"&&(t instanceof cs||("deserializeJSON"in t)))return t;else if(typeof t==="string"||Object.getPrototypeOf(t)===String.prototype)return cs(String(t));return cs(JSON.stringify(t))};cs.fromObject=cs.from;function y8(t){if(t.includes(",")||t.includes('"'))t=`"${t.replace(/"/g,"\\\"")}"`;return t}var Cf="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Kf="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Vf="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",X_="(\\d?\\d)",z_="(\\d{4})",G8=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),B8=new RegExp(`^${Cf}, ${X_} ${Kf} ${z_} ${Vf} GMT$`),F8=new RegExp(`^${Cf}, ${X_}-${Kf}-(\\d\\d) ${Vf} GMT$`),H8=new RegExp(`^${Cf} ${Kf} ( [1-9]|\\d\\d) ${Vf} ${z_}$`),P8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],N8=(t)=>{if(t==null)return;let n=NaN;if(typeof t==="number")n=t;else if(typeof t==="string"){if(!/^-?\d*\.?\d+$/.test(t))throw TypeError("parseEpochTimestamp - numeric string invalid.");n=Number.parseFloat(t)}else if(typeof t==="object"&&t.tag===1)n=t.value;if(isNaN(n)||Math.abs(n)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(n*1000))},W8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC3339 timestamps must be strings");let n=G8.exec(t);if(!n)throw TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,s,r,i,e,f,o,,c,h]=n;Tn(r,1,12),Tn(i,1,31),Tn(e,0,23),Tn(f,0,59),Tn(o,0,60);let u=new Date(Date.UTC(Number(s),Number(r)-1,Number(i),Number(e),Number(f),Number(o),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(u.setUTCFullYear(Number(s)),h.toUpperCase()!="Z"){let[,_,l,w]=/([+-])(\d\d):(\d\d)/.exec(h)||[void 0,"+",0,0],A=_==="-"?1:-1;u.setTime(u.getTime()+A*(Number(l)*60*60*1000+Number(w)*60*1000))}return u},D8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC7231 timestamps must be strings.");let n,s,r,i,e,f,o,c;if(c=B8.exec(t))[,n,s,r,i,e,f,o]=c;else if(c=F8.exec(t))[,n,s,r,i,e,f,o]=c,r=(Number(r)+1900).toString();else if(c=H8.exec(t))[,s,n,i,e,f,o,r]=c;if(r&&f){let h=Date.UTC(Number(r),P8.indexOf(s),Number(n),Number(i),Number(e),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);Tn(n,1,31),Tn(i,0,23),Tn(e,0,59),Tn(f,0,60);let u=new Date(h);return u.setUTCFullYear(Number(r)),u}throw TypeError(`Invalid RFC7231 date-time value ${t}.`)};function Tn(t,n,s){let r=Number(t);if(r<n||r>s)throw Error(`Value ${r} out of range [${n}, ${s}]`)}function Y8(t,n,s){if(s<=0||!Number.isInteger(s))throw Error("Invalid number of delimiters ("+s+") for splitEvery.");let r=t.split(n);if(s===1)return r;let i=[],e="";for(let f=0;f<r.length;f++){if(e==="")e=r[f];else e+=n+r[f];if((f+1)%s===0)i.push(e),e=""}if(e!=="")i.push(e);return i}var m8=(t)=>{let n=t.length,s=[],r=!1,i=void 0,e=0;for(let f=0;f<n;++f){let o=t[f];switch(o){case'"':if(i!=="\\")r=!r;break;case",":if(!r)s.push(t.slice(e,f)),e=f+1;break}i=o}return s.push(t.slice(e)),s.map((f)=>{f=f.trim();let o=f.length;if(o<2)return f;if(f[0]==='"'&&f[o-1]==='"')f=f.slice(1,o-1);return f.replace(/\\"/g,'"')})},O_=/^-?\d*(\.\d+)?$/;class _e{string;type;constructor(t,n){if(this.string=t,this.type=n,!O_.test(t))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](t){if(!t||typeof t!=="object")return!1;let n=t;return _e.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&O_.test(n.string)}}function Q8(t){return new _e(String(t),"bigDecimal")}var x_={},Jf={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;x_[t]=n,Jf[n]=t}function J8(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2){let r=t.slice(s,s+2).toLowerCase();if(r in Jf)n[s/2]=Jf[r];else throw Error(`Cannot decode unrecognized sequence ${r} as hexadecimal`)}return n}function q_(t){let n="";for(let s=0;s<t.byteLength;s++)n+=x_[t[s]];return n}var k8=(t)=>{if(!t)return 0;if(typeof t==="string")return Buffer.byteLength(t);else if(typeof t.byteLength==="number")return t.byteLength;else if(typeof t.size==="number")return t.size;else if(typeof t.start==="number"&&typeof t.end==="number")return t.end+1-t.start;else if(t instanceof Q5){if(t.path!=null)return J5(t.path).size;else if(typeof t.fd==="number")return k5(t.fd).size}throw Error(`Body Length computation failed for ${t}`)},C_=(t)=>{if(t instanceof Uint8Array)return t;if(typeof t==="string")return ue(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)};function le(t,n){if(n===void 0){n=0;for(let i of t)n+=i.byteLength}let s=new Uint8Array(n),r=0;for(let i of t)s.set(i,r),r+=i.byteLength;return s}var K_=(t,n)=>(s,r)=>async(i)=>{let{response:e}=await s(i);try{let f=await n(e,t);return{response:e,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:e,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
11
- Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){if(!r.logger||r.logger?.constructor?.name==="NoOpLogger")console.warn("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.");else r.logger?.warn?.("Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.")}if(typeof f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(X5.isInstance(e)){let{headers:c={}}=e,h=Object.entries(c);f.$metadata={httpStatusCode:e.statusCode,requestId:Wf(/^x-[\w-]+-request-?id$/,h),extendedRequestId:Wf(/^x-[\w-]+-id-2$/,h),cfId:Wf(/^x-[\w-]+-cf-id$/,h)}}}catch(c){}}throw f}},Wf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},V_=(t,n)=>(s,r)=>async(i)=>{let e=t,f=r.endpointV2?async()=>z5(r.endpointV2):e.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await n(i.input,{...t,endpoint:f});return s({...i,request:o})},j_={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},a_={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function X8(t,n,s){return{applyToStack:(r)=>{r.add(K_(t,s),j_),r.add(V_(t,n),a_)}}}class p_{algorithmIdentifier;secret;hash;constructor(t,n){this.algorithmIdentifier=t,this.secret=n,this.reset()}update(t,n){this.hash.update(C_(y_(t,n)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?D5(this.algorithmIdentifier,y_(this.secret)):Y5(this.algorithmIdentifier)}}function y_(t,n){if(Buffer.isBuffer(t))return t;if(typeof t==="string")return he(t,n);if(ArrayBuffer.isView(t))return xs(t.buffer,t.byteOffset,t.byteLength);return xs(t)}var Z_=class extends Xs{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:n,checksum:s,source:r,checksumSourceLocation:i,base64Encoder:e}){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=e??kf,this.expectedChecksum=n,this.checksum=s,this.checksumSourceLocation=i,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=(n)=>{if(this.destroyed)return;try{this.checksum.update(n)}catch(s){this.destroy(s);return}if(!this.push(n))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let n=await this.checksum.digest(),s=this.base64Encoder(n);if(this.expectedChecksum!==s){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${s}" in response header "${this.checksumSourceLocation}".`));return}}catch(n){this.destroy(n);return}this.push(null)};onSourceError=(n)=>{this.destroy(n)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(n){this.source.resume()}_destroy(n,s){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(),s(n)}},en=(t)=>typeof ReadableStream==="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),we=(t)=>{return typeof Blob==="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)},z8=(t)=>new TextEncoder().encode(t),v_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(v_).reduce((t,[n,s])=>{return t[s]=Number(n),t},{});var x8=v_.split(""),Df=6,G_=8,q8=63;function tl(t){let n;if(typeof t==="string")n=z8(t);else n=t;let s=typeof n==="object"&&typeof n.length==="number",r=typeof n==="object"&&typeof n.byteOffset==="number"&&typeof n.byteLength==="number";if(!s&&!r)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let e=0;e<n.length;e+=3){let f=0,o=0;for(let h=e,u=Math.min(e+3,n.length);h<u;h++)f|=n[h]<<(u-h-1)*G_,o+=G_;let c=Math.ceil(o/Df);f<<=c*Df-o;for(let h=1;h<=c;h++){let u=(c-h)*Df;i+=x8[(f&q8<<u)>>u]}i+="==".slice(0,4-c)}return i}var C8=typeof ReadableStream==="function"?ReadableStream:function(){};class nl extends C8{}var K8=({expectedChecksum:t,checksum:n,source:s,checksumSourceLocation:r,base64Encoder:i})=>{if(!en(s))throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);let e=i??tl;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let f=new TransformStream({start(){},async transform(c,h){n.update(c),h.enqueue(c)},async flush(c){let h=await n.digest(),u=e(h);if(t!==u){let _=Error(`Checksum mismatch: expected "${t}" but received "${u}" in response header "${r}".`);c.error(_)}else c.terminate()}});s.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,nl.prototype),o};function V8(t){if(typeof ReadableStream==="function"&&en(t.source))return K8(t);return new Z_(t)}class ce{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength}flush(){if(this.byteArrays.length===1){let s=this.byteArrays[0];return this.reset(),s}let t=this.allocByteArray(this.byteLength),n=0;for(let s=0;s<this.byteArrays.length;++s){let r=this.byteArrays[s];t.set(r,n),n+=r.byteLength}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0}}function j8(t,n,s){let r=t.getReader(),i=!1,e=0,f=["",new ce((h)=>new Uint8Array(h))],o=-1,c=async(h)=>{let{value:u,done:_}=await r.read(),l=u;if(_){if(o!==-1){let w=zs(f,o);if(Yn(w)>0)h.enqueue(w)}h.close()}else{let w=rl(l,!1);if(o!==w){if(o>=0)h.enqueue(zs(f,o));o=w}if(o===-1){h.enqueue(l);return}let A=Yn(l);e+=A;let M=Yn(f[o]);if(A>=n&&M===0)h.enqueue(l);else{let E=sl(f,o,l);if(!i&&e>n*2)i=!0,s?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${n}, automatically buffering.`);if(E>=n)h.enqueue(zs(f,o));else await c(h)}}};return new ReadableStream({pull:c})}function sl(t,n,s){switch(n){case 0:return t[0]+=s,Yn(t[0]);case 1:case 2:return t[n].push(s),Yn(t[n])}}function zs(t,n){switch(n){case 0:let s=t[0];return t[0]="",s;case 1:case 2:return t[n].flush()}throw Error(`@smithy/util-stream - invalid index ${n} given to flush()`)}function Yn(t){return t?.byteLength??t?.length??0}function rl(t,n=!0){if(n&&typeof Buffer<"u"&&t instanceof Buffer)return 2;if(t instanceof Uint8Array)return 1;if(typeof t==="string")return 0;return-1}function a8(t,n,s){if(en(t))return j8(t,n,s);let r=new Xs({read(){}}),i=!1,e=0,f=["",new ce((c)=>new Uint8Array(c)),new ce((c)=>Buffer.from(new Uint8Array(c)))],o=-1;return t.on("data",(c)=>{let h=rl(c,!0);if(o!==h){if(o>=0)r.push(zs(f,o));o=h}if(o===-1){r.push(c);return}let u=Yn(c);e+=u;let _=Yn(f[o]);if(u>=n&&_===0)r.push(c);else{let l=sl(f,o,c);if(!i&&e>n*2)i=!0,s?.warn(`@smithy/util-stream - stream chunk size ${u} is below threshold of ${n}, automatically buffering.`);if(l>=n)r.push(zs(f,o))}}),t.on("end",()=>{if(o!==-1){let c=zs(f,o);if(Yn(c)>0)r.push(c)}r.push(null)}),r}var p8=(t,n)=>{let{base64Encoder:s,bodyLengthChecker:r,checksumAlgorithmFn:i,checksumLocationName:e,streamHasher:f}=n,o=s!==void 0&&r!==void 0&&i!==void 0&&e!==void 0&&f!==void 0,c=o?f(i,t):void 0,h=t.getReader();return new ReadableStream({async pull(u){let{value:_,done:l}=await h.read();if(l){if(u.enqueue(`0\r
10
+ `)},qi={warn:console.warn},h8=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],qf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function u8(t){let n=t.getUTCFullYear(),s=t.getUTCMonth(),i=t.getUTCDay(),r=t.getUTCDate(),e=t.getUTCHours(),f=t.getUTCMinutes(),o=t.getUTCSeconds(),c=r<10?`0${r}`:`${r}`,h=e<10?`0${e}`:`${e}`,u=f<10?`0${f}`:`${f}`,l=o<10?`0${o}`:`${o}`;return`${h8[i]}, ${c} ${qf[s]} ${n} ${h}:${u}:${l} GMT`}var l8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),_8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=l8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,i,r,e,f,o,c,h]=n,u=qs(Cs(i)),l=rn(r,"month",1,12),_=rn(e,"day",1,31);return zi(u,l,_,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})},w8=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),A8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-3339 date-times must be expressed as strings");let n=w8.exec(t);if(!n)throw TypeError("Invalid RFC-3339 date-time value");let[s,i,r,e,f,o,c,h,u]=n,l=qs(Cs(i)),_=rn(r,"month",1,12),w=rn(e,"day",1,31),A=zi(l,_,w,{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h});if(u.toUpperCase()!="Z")A.setTime(A.getTime()-y8(u));return A},M8=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$/),g8=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$/),d8=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})$/),E8=(t)=>{if(t===null||t===void 0)return;if(typeof t!=="string")throw TypeError("RFC-7231 date-times must be expressed as strings");let n=M8.exec(t);if(n){let[s,i,r,e,f,o,c,h]=n;return zi(qs(Cs(e)),Nf(r),rn(i,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h})}if(n=g8.exec(t),n){let[s,i,r,e,f,o,c,h]=n;return S8(zi(b8(e),Nf(r),rn(i,"day",1,31),{hours:f,minutes:o,seconds:c,fractionalMilliseconds:h}))}if(n=d8.exec(t),n){let[s,i,r,e,f,o,c,h]=n;return zi(qs(Cs(h)),Nf(i),rn(r.trimLeft(),"day",1,31),{hours:e,minutes:f,seconds:o,fractionalMilliseconds:c})}throw TypeError("Invalid RFC-7231 date-time value")},R8=(t)=>{if(t===null||t===void 0)return;let n;if(typeof t==="number")n=t;else if(typeof t==="string")n=Xf(t);else if(typeof t==="object"&&t.tag===1)n=t.value;else throw TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(n)||n===1/0||n===-1/0)throw TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(n*1000))},zi=(t,n,s,i)=>{let r=n-1;return U8(t,r,s),new Date(Date.UTC(t,r,s,rn(i.hours,"hour",0,23),rn(i.minutes,"minute",0,59),rn(i.seconds,"seconds",0,60),I8(i.fractionalMilliseconds)))},b8=(t)=>{let n=new Date().getUTCFullYear(),s=Math.floor(n/100)*100+qs(Cs(t));if(s<n)return s+100;return s},T8=1576800000000,S8=(t)=>{if(t.getTime()-new Date().getTime()>T8)return new Date(Date.UTC(t.getUTCFullYear()-100,t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()));return t},Nf=(t)=>{let n=qf.indexOf(t);if(n<0)throw TypeError(`Invalid month: ${t}`);return n+1},$8=[31,28,31,30,31,30,31,31,30,31,30,31],U8=(t,n,s)=>{let i=$8[n];if(n===1&&L8(t))i=29;if(s>i)throw TypeError(`Invalid day for ${qf[n]} in ${t}: ${s}`)},L8=(t)=>{return t%4===0&&(t%100!==0||t%400===0)},rn=(t,n,s,i)=>{let r=kl(Cs(t));if(r<s||r>i)throw TypeError(`${n} must be between ${s} and ${i}, inclusive`);return r},I8=(t)=>{if(t===null||t===void 0)return 0;return Yl("0."+t)*1000},y8=(t)=>{let n=t[0],s=1;if(n=="+")s=1;else if(n=="-")s=-1;else throw TypeError(`Offset direction, ${n}, must be "+" or "-"`);let i=Number(t.substring(1,3)),r=Number(t.substring(4,6));return s*(i*60+r)*60*1000},Cs=(t)=>{let n=0;while(n<t.length-1&&t.charAt(n)==="0")n++;if(n===0)return t;return t.slice(n)},cs=function(n){return Object.assign(new String(n),{deserializeJSON(){return JSON.parse(String(n))},toString(){return String(n)},toJSON(){return String(n)}})};cs.from=(t)=>{if(t&&typeof t==="object"&&(t instanceof cs||("deserializeJSON"in t)))return t;else if(typeof t==="string"||Object.getPrototypeOf(t)===String.prototype)return cs(String(t));return cs(JSON.stringify(t))};cs.fromObject=cs.from;function O8(t){if(t.includes(",")||t.includes('"'))t=`"${t.replace(/"/g,"\\\"")}"`;return t}var Cf="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",Kf="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",Vf="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",zl="(\\d?\\d)",Xl="(\\d{4})",G8=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),B8=new RegExp(`^${Cf}, ${zl} ${Kf} ${Xl} ${Vf} GMT$`),F8=new RegExp(`^${Cf}, ${zl}-${Kf}-(\\d\\d) ${Vf} GMT$`),H8=new RegExp(`^${Cf} ${Kf} ( [1-9]|\\d\\d) ${Vf} ${Xl}$`),P8=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],N8=(t)=>{if(t==null)return;let n=NaN;if(typeof t==="number")n=t;else if(typeof t==="string"){if(!/^-?\d*\.?\d+$/.test(t))throw TypeError("parseEpochTimestamp - numeric string invalid.");n=Number.parseFloat(t)}else if(typeof t==="object"&&t.tag===1)n=t.value;if(isNaN(n)||Math.abs(n)===1/0)throw TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(n*1000))},W8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC3339 timestamps must be strings");let n=G8.exec(t);if(!n)throw TypeError(`Invalid RFC3339 timestamp format ${t}`);let[,s,i,r,e,f,o,,c,h]=n;Tn(i,1,12),Tn(r,1,31),Tn(e,0,23),Tn(f,0,59),Tn(o,0,60);let u=new Date(Date.UTC(Number(s),Number(i)-1,Number(r),Number(e),Number(f),Number(o),Number(c)?Math.round(parseFloat(`0.${c}`)*1000):0));if(u.setUTCFullYear(Number(s)),h.toUpperCase()!="Z"){let[,l,_,w]=/([+-])(\d\d):(\d\d)/.exec(h)||[void 0,"+",0,0],A=l==="-"?1:-1;u.setTime(u.getTime()+A*(Number(_)*60*60*1000+Number(w)*60*1000))}return u},D8=(t)=>{if(t==null)return;if(typeof t!=="string")throw TypeError("RFC7231 timestamps must be strings.");let n,s,i,r,e,f,o,c;if(c=B8.exec(t))[,n,s,i,r,e,f,o]=c;else if(c=F8.exec(t))[,n,s,i,r,e,f,o]=c,i=(Number(i)+1900).toString();else if(c=H8.exec(t))[,s,n,r,e,f,o,i]=c;if(i&&f){let h=Date.UTC(Number(i),P8.indexOf(s),Number(n),Number(r),Number(e),Number(f),o?Math.round(parseFloat(`0.${o}`)*1000):0);Tn(n,1,31),Tn(r,0,23),Tn(e,0,59),Tn(f,0,60);let u=new Date(h);return u.setUTCFullYear(Number(i)),u}throw TypeError(`Invalid RFC7231 date-time value ${t}.`)};function Tn(t,n,s){let i=Number(t);if(i<n||i>s)throw Error(`Value ${i} out of range [${n}, ${s}]`)}function m8(t,n,s){if(s<=0||!Number.isInteger(s))throw Error("Invalid number of delimiters ("+s+") for splitEvery.");let i=t.split(n);if(s===1)return i;let r=[],e="";for(let f=0;f<i.length;f++){if(e==="")e=i[f];else e+=n+i[f];if((f+1)%s===0)r.push(e),e=""}if(e!=="")r.push(e);return r}var Y8=(t)=>{let n=t.length,s=[],i=!1,r=void 0,e=0;for(let f=0;f<n;++f){let o=t[f];switch(o){case'"':if(r!=="\\")i=!i;break;case",":if(!i)s.push(t.slice(e,f)),e=f+1;break}r=o}return s.push(t.slice(e)),s.map((f)=>{f=f.trim();let o=f.length;if(o<2)return f;if(f[0]==='"'&&f[o-1]==='"')f=f.slice(1,o-1);return f.replace(/\\"/g,'"')})},yl=/^-?\d*(\.\d+)?$/;class le{string;type;constructor(t,n){if(this.string=t,this.type=n,!yl.test(t))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](t){if(!t||typeof t!=="object")return!1;let n=t;return le.prototype.isPrototypeOf(t)||n.type==="bigDecimal"&&yl.test(n.string)}}function Q8(t){return new le(String(t),"bigDecimal")}var xl={},Jf={};for(let t=0;t<256;t++){let n=t.toString(16).toLowerCase();if(n.length===1)n=`0${n}`;xl[t]=n,Jf[n]=t}function J8(t){if(t.length%2!==0)throw Error("Hex encoded strings must have an even number length");let n=new Uint8Array(t.length/2);for(let s=0;s<t.length;s+=2){let i=t.slice(s,s+2).toLowerCase();if(i in Jf)n[s/2]=Jf[i];else throw Error(`Cannot decode unrecognized sequence ${i} as hexadecimal`)}return n}function ql(t){let n="";for(let s=0;s<t.byteLength;s++)n+=xl[t[s]];return n}var k8=(t)=>{if(!t)return 0;if(typeof t==="string")return Buffer.byteLength(t);else if(typeof t.byteLength==="number")return t.byteLength;else if(typeof t.size==="number")return t.size;else if(typeof t.start==="number"&&typeof t.end==="number")return t.end+1-t.start;else if(t instanceof Q5){if(t.path!=null)return J5(t.path).size;else if(typeof t.fd==="number")return k5(t.fd).size}throw Error(`Body Length computation failed for ${t}`)},Cl=(t)=>{if(t instanceof Uint8Array)return t;if(typeof t==="string")return ue(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(t)};function _e(t,n){if(n===void 0){n=0;for(let r of t)n+=r.byteLength}let s=new Uint8Array(n),i=0;for(let r of t)s.set(r,i),i+=r.byteLength;return s}var Kl=(t,n)=>(s,i)=>async(r)=>{let{response:e}=await s(r);try{let f=await n(e,t);return{response:e,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:e,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){try{f.message+=`
11
+ Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`}catch(c){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 f.$responseBodyText<"u"){if(f.$response)f.$response.body=f.$responseBodyText}try{if(z5.isInstance(e)){let{headers:c={}}=e,h=Object.entries(c);f.$metadata={httpStatusCode:e.statusCode,requestId:Wf(/^x-[\w-]+-request-?id$/,h),extendedRequestId:Wf(/^x-[\w-]+-id-2$/,h),cfId:Wf(/^x-[\w-]+-cf-id$/,h)}}}catch(c){}}throw f}},Wf=(t,n)=>{return(n.find(([s])=>{return s.match(t)})||[void 0,void 0])[1]},Vl=(t,n)=>(s,i)=>async(r)=>{let e=t,f=i.endpointV2?async()=>X5(i.endpointV2):e.endpoint;if(!f)throw Error("No valid endpoint provider available.");let o=await n(r.input,{...t,endpoint:f});return s({...r,request:o})},jl={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},al={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function z8(t,n,s){return{applyToStack:(i)=>{i.add(Kl(t,s),jl),i.add(Vl(t,n),al)}}}class pl{algorithmIdentifier;secret;hash;constructor(t,n){this.algorithmIdentifier=t,this.secret=n,this.reset()}update(t,n){this.hash.update(Cl(Ol(t,n)))}digest(){return Promise.resolve(this.hash.digest())}reset(){this.hash=this.secret?D5(this.algorithmIdentifier,Ol(this.secret)):m5(this.algorithmIdentifier)}}function Ol(t,n){if(Buffer.isBuffer(t))return t;if(typeof t==="string")return he(t,n);if(ArrayBuffer.isView(t))return xs(t.buffer,t.byteOffset,t.byteLength);return xs(t)}var Zl=class extends zs{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:n,checksum:s,source:i,checksumSourceLocation:r,base64Encoder:e}){super();if(typeof i.pipe!=="function")throw Error(`@smithy/util-stream: unsupported source type ${i?.constructor?.name??i} in ChecksumStream.`);this.source=i,this.base64Encoder=e??kf,this.expectedChecksum=n,this.checksum=s,this.checksumSourceLocation=r,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=(n)=>{if(this.destroyed)return;try{this.checksum.update(n)}catch(s){this.destroy(s);return}if(!this.push(n))this.source.pause()};onSourceEnd=async()=>{if(this.destroyed)return;try{let n=await this.checksum.digest(),s=this.base64Encoder(n);if(this.expectedChecksum!==s){this.destroy(Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${s}" in response header "${this.checksumSourceLocation}".`));return}}catch(n){this.destroy(n);return}this.push(null)};onSourceError=(n)=>{this.destroy(n)};onSourceClose=()=>{if(!this.destroyed&&!this.source.readableEnded)this.destroy(Error("Connection lost or stream closed before all data was received."))};_read(n){this.source.resume()}_destroy(n,s){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(),s(n)}},en=(t)=>typeof ReadableStream==="function"&&(t?.constructor?.name===ReadableStream.name||t instanceof ReadableStream),we=(t)=>{return typeof Blob==="function"&&(t?.constructor?.name===Blob.name||t instanceof Blob)},X8=(t)=>new TextEncoder().encode(t),vl="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(vl).reduce((t,[n,s])=>{return t[s]=Number(n),t},{});var x8=vl.split(""),Df=6,Gl=8,q8=63;function t_(t){let n;if(typeof t==="string")n=X8(t);else n=t;let s=typeof n==="object"&&typeof n.length==="number",i=typeof n==="object"&&typeof n.byteOffset==="number"&&typeof n.byteLength==="number";if(!s&&!i)throw Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let r="";for(let e=0;e<n.length;e+=3){let f=0,o=0;for(let h=e,u=Math.min(e+3,n.length);h<u;h++)f|=n[h]<<(u-h-1)*Gl,o+=Gl;let c=Math.ceil(o/Df);f<<=c*Df-o;for(let h=1;h<=c;h++){let u=(c-h)*Df;r+=x8[(f&q8<<u)>>u]}r+="==".slice(0,4-c)}return r}var C8=typeof ReadableStream==="function"?ReadableStream:function(){};class n_ extends C8{}var K8=({expectedChecksum:t,checksum:n,source:s,checksumSourceLocation:i,base64Encoder:r})=>{if(!en(s))throw Error(`@smithy/util-stream: unsupported source type ${s?.constructor?.name??s} in ChecksumStream.`);let e=r??t_;if(typeof TransformStream!=="function")throw Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let f=new TransformStream({start(){},async transform(c,h){n.update(c),h.enqueue(c)},async flush(c){let h=await n.digest(),u=e(h);if(t!==u){let l=Error(`Checksum mismatch: expected "${t}" but received "${u}" in response header "${i}".`);c.error(l)}else c.terminate()}});s.pipeThrough(f);let o=f.readable;return Object.setPrototypeOf(o,n_.prototype),o};function V8(t){if(typeof ReadableStream==="function"&&en(t.source))return K8(t);return new Zl(t)}class ce{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength}flush(){if(this.byteArrays.length===1){let s=this.byteArrays[0];return this.reset(),s}let t=this.allocByteArray(this.byteLength),n=0;for(let s=0;s<this.byteArrays.length;++s){let i=this.byteArrays[s];t.set(i,n),n+=i.byteLength}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0}}function j8(t,n,s){let i=t.getReader(),r=!1,e=0,f=["",new ce((h)=>new Uint8Array(h))],o=-1,c=async(h)=>{let{value:u,done:l}=await i.read(),_=u;if(l){if(o!==-1){let w=Xs(f,o);if(mn(w)>0)h.enqueue(w)}h.close()}else{let w=i_(_,!1);if(o!==w){if(o>=0)h.enqueue(Xs(f,o));o=w}if(o===-1){h.enqueue(_);return}let A=mn(_);e+=A;let M=mn(f[o]);if(A>=n&&M===0)h.enqueue(_);else{let d=s_(f,o,_);if(!r&&e>n*2)r=!0,s?.warn(`@smithy/util-stream - stream chunk size ${A} is below threshold of ${n}, automatically buffering.`);if(d>=n)h.enqueue(Xs(f,o));else await c(h)}}};return new ReadableStream({pull:c})}function s_(t,n,s){switch(n){case 0:return t[0]+=s,mn(t[0]);case 1:case 2:return t[n].push(s),mn(t[n])}}function Xs(t,n){switch(n){case 0:let s=t[0];return t[0]="",s;case 1:case 2:return t[n].flush()}throw Error(`@smithy/util-stream - invalid index ${n} given to flush()`)}function mn(t){return t?.byteLength??t?.length??0}function i_(t,n=!0){if(n&&typeof Buffer<"u"&&t instanceof Buffer)return 2;if(t instanceof Uint8Array)return 1;if(typeof t==="string")return 0;return-1}function a8(t,n,s){if(en(t))return j8(t,n,s);let i=new zs({read(){}}),r=!1,e=0,f=["",new ce((c)=>new Uint8Array(c)),new ce((c)=>Buffer.from(new Uint8Array(c)))],o=-1;return t.on("data",(c)=>{let h=i_(c,!0);if(o!==h){if(o>=0)i.push(Xs(f,o));o=h}if(o===-1){i.push(c);return}let u=mn(c);e+=u;let l=mn(f[o]);if(u>=n&&l===0)i.push(c);else{let _=s_(f,o,c);if(!r&&e>n*2)r=!0,s?.warn(`@smithy/util-stream - stream chunk size ${u} is below threshold of ${n}, automatically buffering.`);if(_>=n)i.push(Xs(f,o))}}),t.on("end",()=>{if(o!==-1){let c=Xs(f,o);if(mn(c)>0)i.push(c)}i.push(null)}),i}var p8=(t,n)=>{let{base64Encoder:s,bodyLengthChecker:i,checksumAlgorithmFn:r,checksumLocationName:e,streamHasher:f}=n,o=s!==void 0&&i!==void 0&&r!==void 0&&e!==void 0&&f!==void 0,c=o?f(r,t):void 0,h=t.getReader();return new ReadableStream({async pull(u){let{value:l,done:_}=await h.read();if(_){if(u.enqueue(`0\r
12
12
  `),o){let w=s(await c);u.enqueue(`${e}:${w}\r
13
13
  `),u.enqueue(`\r
14
- `)}u.close()}else u.enqueue(`${(r(_)||0).toString(16)}\r
15
- ${_}\r
16
- `)}})};function Z8(t,n){let s=t,r=t;if(en(r))return p8(r,n);let{base64Encoder:i,bodyLengthChecker:e,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:c}=n,h=i!==void 0&&f!==void 0&&o!==void 0&&c!==void 0,u=h?c(f,s):void 0,_=new Xs({read:()=>{}});return s.on("data",(l)=>{let w=e(l)||0;if(w===0)return;_.push(`${w.toString(16)}\r
17
- `),_.push(l),_.push(`\r
18
- `)}),s.on("end",async()=>{if(_.push(`0\r
19
- `),h){let l=i(await u);_.push(`${o}:${l}\r
20
- `),_.push(`\r
21
- `)}_.push(null)}),_}async function v8(t,n){let s=0,r=[],i=t.getReader(),e=!1;while(!e){let{done:c,value:h}=await i.read();if(h)r.push(h),s+=h?.byteLength??0;if(s>=n)break;e=c}i.releaseLock();let f=new Uint8Array(Math.min(n,s)),o=0;for(let c of r){if(c.byteLength>f.byteLength-o){f.set(c.subarray(0,f.byteLength-o),o);break}else f.set(c,o);o+=c.length}return f}var tS=(t,n)=>{if(en(t))return v8(t,n);return new Promise((s,r)=>{let i=new nS;i.limit=n,t.pipe(i),t.on("error",(e)=>{i.end(),r(e)}),i.on("error",r),i.on("finish",function(){let e=le(this.buffers);s(e)})})},nS=class extends P_{buffers=[];limit=1/0;bytesBuffered=0;_write(n,s,r){if(this.buffers.push(n),this.bytesBuffered+=n.byteLength??0,this.bytesBuffered>=this.limit){let i=this.bytesBuffered-this.limit,e=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=e.subarray(0,e.byteLength-i),this.emit("finish")}r()}},sS=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)},rS=async(t)=>{if(we(t))return il(t);return el(t)};async function il(t){return t.arrayBuffer().then((n)=>new Uint8Array(n))}async function el(t){let n=[],s=t.getReader(),r=0;while(!0){let{done:i,value:e}=await s.read();if(e)n.push(e),r+=e.length;if(i)break}return le(n,r)}var B_="The stream has already been transformed.",iS=(t)=>{if(!F_(t)&&!en(t)){let i=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${i}`)}let n=!1,s=async()=>{if(n)throw Error(B_);return n=!0,await rS(t)},r=(i)=>{if(typeof i.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
22
- If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return i.stream()};return Object.assign(t,{transformToByteArray:s,transformToString:async(i)=>{let e=await s();if(i==="base64")return tl(e);else if(i==="hex")return q_(e);else if(i===void 0||i==="utf8"||i==="utf-8")return sS(e);else if(typeof TextDecoder==="function")return new TextDecoder(i).decode(e);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(n)throw Error(B_);if(n=!0,F_(t))return r(t);else if(en(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},F_=(t)=>typeof Blob==="function"&&t instanceof Blob,ol=(t)=>{if(we(t))return il(t);if(en(t))return el(t);return new Promise((n,s)=>{let r=new fl,i=t;i.pipe(r),i.on("error",(e)=>{r.end(),s(e)}),r.on("error",s),r.on("finish",function(){let e=le(this.bufferedBytes);n(e)})})};class fl extends P_{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var H_="The stream has already been transformed.",eS=(t)=>{if(!(t instanceof Xs))try{return iS(t)}catch(r){let i=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${i}`)}let n=!1,s=async()=>{if(n)throw Error(H_);return n=!0,await ol(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(r)=>{let i=await s();if(r===void 0||Buffer.isEncoding(r))return xs(i.buffer,i.byteOffset,i.byteLength).toString(r);else return new TextDecoder(r).decode(i)},transformToWebStream:()=>{if(n)throw Error(H_);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof Xs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,Xs.toWeb(t)}})};async function oS(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function fS(t){if(en(t)||we(t))return oS(t);let n=new I_,s=new I_;return t.pipe(n),t.pipe(s),[n,s]}class cl extends q5(D_,ue,kf,W_){}var cS=m5,hl=C5(cS),hS=hl;uS.ChecksumStream=Z_;uS.Hash=p_;uS.LazyJsonString=cs;uS.NumericValue=_e;uS.Uint8ArrayBlobAdapter=cl;uS._parseEpochTimestamp=N8;uS._parseRfc3339DateTimeWithOffset=W8;uS._parseRfc7231DateTime=D8;uS.calculateBodyLength=k8;uS.concatBytes=le;uS.copyDocumentWithTransform=K5;uS.createBufferedReadable=a8;uS.createChecksumStream=V8;uS.dateToUtcString=u8;uS.deserializerMiddleware=K_;uS.deserializerMiddlewareOption=j_;uS.expectBoolean=j5;uS.expectByte=Qf;uS.expectFloat32=oe;uS.expectInt=p5;uS.expectInt32=Yf;uS.expectLong=xr;uS.expectNonNull=v5;uS.expectNumber=zr;uS.expectObject=Y_;uS.expectShort=mf;uS.expectString=t8;uS.expectUnion=n8;uS.fromArrayBuffer=xs;uS.fromBase64=W_;uS.fromHex=J8;uS.fromString=he;uS.fromUtf8=ue;uS.generateIdempotencyToken=hS;uS.getAwsChunkedEncodingStream=Z8;uS.getSerdePlugin=X8;uS.handleFloat=i8;uS.headStream=tS;uS.isArrayBuffer=N_;uS.isBlob=we;uS.isReadableStream=en;uS.limitedParseDouble=xf;uS.limitedParseFloat=e8;uS.limitedParseFloat32=o8;uS.logger=qr;uS.nv=Q8;uS.parseBoolean=V5;uS.parseEpochTimestamp=R8;uS.parseRfc3339DateTime=l8;uS.parseRfc3339DateTimeWithOffset=A8;uS.parseRfc7231DateTime=d8;uS.quoteHeader=y8;uS.sdkStreamMixin=eS;uS.serializerMiddleware=V_;uS.serializerMiddlewareOption=a_;uS.splitEvery=Y8;uS.splitHeader=m8;uS.splitStream=fS;uS.streamCollector=ol;uS.strictParseByte=k_;uS.strictParseDouble=zf;uS.strictParseFloat=s8;uS.strictParseFloat32=m_;uS.strictParseInt=f8;uS.strictParseInt32=c8;uS.strictParseLong=J_;uS.strictParseShort=qs;uS.toBase64=kf;uS.toHex=q_;uS.toUint8Array=C_;uS.toUtf8=D_;uS.v4=hl});var tc=Z((p$)=>{var{createReadStream:G$}=nt("fs"),{Writable:B$}=nt("stream"),{toUint8Array:Vs,concatBytes:F$}=$t(),{createHash:Cr,createHmac:H$}=nt("crypto"),ul=nt("zlib");async function Ml(t,n,s=1048576){let r=t.size,i=0;while(i<r){let e=t.slice(i,Math.min(r,i+s));n(new Uint8Array(await e.arrayBuffer())),i+=e.size}}var P$=async function(n,s){let r=new n;return await Ml(s,(i)=>{r.update(i)}),r.digest()};class pf extends B${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Vs(t))}catch(r){return s(r)}s()}}var N$=(t,n)=>new Promise((s,r)=>{if(!W$(n)){r(Error("Unable to calculate hash for non-file streams."));return}let i=G$(n.path,{start:n.start,end:n.end}),e=new t,f=new pf(e);i.pipe(f),i.on("error",(o)=>{f.end(),r(o)}),f.on("error",r),f.on("finish",function(){e.digest().then(s).catch(r)})}),W$=(t)=>typeof t.path==="string",D$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,r=new pf(s);return n.pipe(r),new Promise((i,e)=>{n.on("error",(f)=>{r.end(),e(f)}),r.on("error",e),r.on("finish",()=>{s.digest().then(i).catch(e)})})};class Zf{digestLength=16;state=Uint32Array.from(_l);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Vs(t),s=0,r=n.byteLength;this.bytesHashed+=r;while(r>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--r,this.bufferLength===64)jf(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let t=Uint32Array.from(this.state),n=new DataView(this.writeBuffer.buffer.slice(0)),s=this.bufferLength,r=this.bytesHashed*8;if(n.setUint8(s++,128),this.bufferLength%64>=56){for(let f=s;f<64;++f)n.setUint8(f,0);jf(t,n),s=0}for(let f=s;f<56;++f)n.setUint8(f,0);n.setUint32(56,r>>>0,!0),n.setUint32(60,Math.floor(r/4294967296),!0),jf(t,n);let i=new Uint8Array(16),e=new DataView(i.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,t[f],!0);return i}reset(){this.state.set(_l),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var _l=[1732584193,4023233417,2562383102,271733878],mn=4294967295,Y$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),m$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function jf(t,n){let s=t[0],r=t[1],i=t[2],e=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=r&i|~r&e,c=f;else if(f<32)o=e&r|i&~e,c=(5*f+1)%16;else if(f<48)o=r^i^e,c=(3*f+5)%16;else o=i^(r|~e),c=7*f%16;let h=n.getUint32(c*4,!0),u=e;e=i,i=r;let _=Y$[(f>>4)*4+(f&3)],l=(s+o&mn)+(h+m$[f]&mn)&mn;r=r+((l<<_|l>>>32-_)>>>0)&mn,s=u}t[0]=t[0]+s&mn,t[1]=t[1]+r&mn,t[2]=t[2]+i&mn,t[3]=t[3]+e&mn}var Q$=(()=>{try{return Cr("md5"),!0}catch{return!1}})(),gl=Q$?J$():Zf;function J$(){return class{digestLength=16;hash=Cr("md5");update(n){this.hash.update(Vs(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Cr("md5")}}}var El=new Uint32Array(256);for(let t=0;t<256;++t){let n=t;for(let s=0;s<8;++s)n=n&1?3988292384^n>>>1:n>>>1;El[t]=n>>>0}var af=4294967295;class vf{digestLength=4;checksum=af;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^El[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^af)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=af}}var ll=typeof ul.crc32==="function"?ul.crc32:void 0,dl=ll?k$(ll):vf;function k$(t){return class{digestLength=4;value=0;update(s){this.value=t(s,this.value)}digestSync(){return this.value>>>0}async digest(){let s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,this.digestSync(),!1),s}reset(){this.value=0}}}var At=64,wl=32,X$=9007199254740991;class Sn{digestLength=wl;state=Int32Array.from(Al);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Sn.normalizeKey(t);this.inner=new Sn,this.outer=new Sn;let{inner:s,outer:r}=this,i=new Uint8Array(At*2);for(let e=0;e<At;++e)i[e]=54^n[e],i[e+At]=92^n[e];s.update(i.subarray(0,At)),r.update(i.subarray(At))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Vs(t),s=0,{byteLength:r}=n;if(this.bytesHashed+=r,this.bytesHashed*8>X$)throw Error("Cannot hash more than 2^53 - 1 bits");while(r>0)if(this.buffer[this.bufferLength++]=n[s++],r--,this.bufferLength===At)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:t,outer:n}=this;if(t&&n){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let s=t.digestSync();return n.update(s),n.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(Al),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let t=this.state.slice(),n=this.buffer.slice(),s=this.bufferLength,r=this.bytesHashed*8,i=new DataView(n.buffer,n.byteOffset,n.byteLength);if(i.setUint8(s++,128),(s-1)%At>=At-8){for(let f=s;f<At;++f)i.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<At-8;++f)i.setUint8(f,0);i.setUint32(At-8,Math.floor(r/4294967296),!1),i.setUint32(At-4,r,!1),this.hashBufferWith(t,n);let e=new Uint8Array(wl);for(let f=0;f<8;++f)e[f*4]=t[f]>>>24&255,e[f*4+1]=t[f]>>>16&255,e[f*4+2]=t[f]>>>8&255,e[f*4+3]=t[f]>>>0&255;return e}static normalizeKey(t){let n=Vs(t);if(n.byteLength>At){let s=new Sn;s.update(n);let r=s.digestSync(),i=new Uint8Array(At);return i.set(r),i}if(n.byteLength<At){let s=new Uint8Array(At);return s.set(n),s}return n}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(t,n){let s=this.w??=new Int32Array(64),r=t[0],i=t[1],e=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let _=0;_<At;++_){if(_<16)s[_]=(n[_*4]&255)<<24|(n[_*4+1]&255)<<16|(n[_*4+2]&255)<<8|n[_*4+3]&255;else{let A=s[_-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[_-15];let E=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[_]=(M+s[_-7]|0)+(E+s[_-16]|0)}let l=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(z$[_]+s[_]|0)|0)|0,w=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&i^r&e^i&e)|0;u=h,h=c,c=o,o=f+l|0,f=e,e=i,i=r,r=l+w|0}t[0]+=r,t[1]+=i,t[2]+=e,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var Al=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),z$=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),x$=(()=>{try{return Cr("sha256"),!0}catch{return!1}})(),Rl=x$?q$():Sn;function q$(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(n){this.secret=n,this.isHmac=!!n,this.hash=this.createHash()}update(n){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(n)}async digest(){let n;if(this.isHmac)this.finished=!0,n=this.hash.digest();else n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?H$("sha256",C$(this.secret)):Cr("sha256")}}}function C$(t){if(typeof t==="string")return t;if(ArrayBuffer.isView(t))return Buffer.from(t.buffer,t.byteOffset,t.byteLength);return Buffer.from(t)}var{digest:K$,sign:V$,importKey:j$}=globalThis?.crypto?.subtle??{},Ae=typeof K$==="function"&&typeof V$==="function"&&typeof j$==="function"?globalThis.crypto.subtle:void 0,a$=8388608;class bl{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Vs(t)}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(t);return}if(this.pending.push(t.slice()),this.pendingBytes+=t.byteLength,this.pendingBytes>=a$)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let t=F$(this.pending);if(Ae){if(this.secret){this.finished=!0;let r=await Ae.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await Ae.sign("HMAC",r,t);return new Uint8Array(i)}let s=await Ae.digest("SHA-256",t);return new Uint8Array(s)}let n=new Sn(this.secret);return n.update(t),n.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let t=new Sn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}p$.Crc32=dl;p$.Crc32Js=vf;p$.Crc32Node=dl;p$.Md5=gl;p$.Md5Js=Zf;p$.Md5Node=gl;p$.Sha256=Rl;p$.Sha256Js=Sn;p$.Sha256Node=Rl;p$.Sha256WebCrypto=bl;p$.blobHasher=P$;p$.blobReader=Ml;p$.fileStreamHasher=N$;p$.readableStreamHasher=D$});var Me=Z((NU)=>{var{Crc32:$l}=tc(),{toHex:js,fromHex:lU,toUtf8:wU,fromUtf8:AU}=$t(),{Readable:MU}=nt("stream");class as{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)Tl(n);return new as(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)Tl(t);return parseInt(js(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function Tl(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}class nc{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let i of Object.keys(t)){let e=this.fromUtf8(i);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[i]))}let s=new Uint8Array(n.reduce((i,e)=>i+e.byteLength,0)),r=0;for(let i of n)s.set(i,r),r+=i.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?it.boolTrue:it.boolFalse]);case"byte":return Uint8Array.from([it.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,it.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,it.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=it.long,r.set(t.value.bytes,1),r;case"binary":let i=new DataView(new ArrayBuffer(3+t.value.byteLength));i.setUint8(0,it.byteArray),i.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(i.buffer);return e.set(t.value,3),e;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,it.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=it.timestamp,h.set(as.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!UU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=it.uuid,u.set(lU(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let r=t.getUint8(s++),i=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,r));switch(s+=r,t.getUint8(s++)){case it.boolTrue:n[i]={type:Sl,value:!0};break;case it.boolFalse:n[i]={type:Sl,value:!1};break;case it.byte:n[i]={type:gU,value:t.getInt8(s++)};break;case it.short:n[i]={type:EU,value:t.getInt16(s,!1)},s+=2;break;case it.integer:n[i]={type:dU,value:t.getInt32(s,!1)},s+=4;break;case it.long:n[i]={type:RU,value:new as(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case it.byteArray:let e=t.getUint16(s,!1);s+=2,n[i]={type:bU,value:new Uint8Array(t.buffer,t.byteOffset+s,e)},s+=e;break;case it.string:let f=t.getUint16(s,!1);s+=2,n[i]={type:TU,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case it.timestamp:n[i]={type:SU,value:new Date(new as(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case it.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[i]={type:$U,value:`${js(o.subarray(0,4))}-${js(o.subarray(4,6))}-${js(o.subarray(6,8))}-${js(o.subarray(8,10))}-${js(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var it;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(it||(it={}));var Sl="boolean",gU="byte",EU="short",dU="integer",RU="long",bU="binary",TU="string",SU="timestamp",$U="uuid",UU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,Ul=4,Qn=Ul*2,hs=4,LU=Qn+hs*2;function IU({byteLength:t,byteOffset:n,buffer:s}){if(t<LU)throw Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(s,n,t),i=r.getUint32(0,!1);if(t!==i)throw Error("Reported message length does not match received message length");let e=r.getUint32(Ul,!1),f=r.getUint32(Qn,!1),o=r.getUint32(t-hs,!1),c=new $l;if(c.update(new Uint8Array(s,n,Qn)),f!==c.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(s,n+Qn,t-(Qn+hs))),o!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(s,n+Qn+hs,e),body:new Uint8Array(s,n+Qn+hs+e,i-e-(Qn+hs+hs))}}class sc{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new nc(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){let t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){let t=this.messageBuffer;this.messageBuffer=[];let n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){let s=this.headerMarshaller.format(t),r=s.byteLength+n.byteLength+16,i=new Uint8Array(r),e=new DataView(i.buffer,i.byteOffset,i.byteLength),f=new $l;return e.setUint32(0,r,!1),e.setUint32(4,s.byteLength,!1),f.update(i.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),i.set(s,12),i.set(n,s.byteLength+12),f.update(i.subarray(8,r-4)),e.setUint32(r-4,f.digestSync(),!1),i}decode(t){let{headers:n,body:s}=IU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class rc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.decoder.decode(t)}}class ic{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream)yield this.options.encoder.encode(t);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class ec{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream){let n=await this.options.deserializer(t);if(n===void 0)continue;yield n}}}class oc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.serializer(t)}}function Ll(t){let n=0,s=0,r=null,i=null,e=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);n=o,s=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,!1)},f=async function*(){let o=t[Symbol.asyncIterator]();while(!0){let{value:c,done:h}=await o.next();if(h){if(!n)return;else if(n===s)yield r;else throw Error("Truncated event message received.");return}let u=c.length,_=0;while(_<u){if(!r){let w=u-_;if(!i)i=new Uint8Array(4);let A=Math.min(4-s,w);if(i.set(c.slice(_,_+A),s),s+=A,_+=A,s<4)break;e(new DataView(i.buffer).getUint32(0,!1)),i=null}let l=Math.min(n-s,u-_);if(r.set(c.slice(_,_+l),s),s+=l,_+=l,n&&n===s)yield r,r=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function OU(t,n){let s=fc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let r of t){let i=n.eventStreamCodec.decode(r),e=await s(i);if(e===void 0)continue;yield e}}}}function fc(t,n){return async function(s){let{value:r}=s.headers[":message-type"];if(r==="error"){let i=Error(s.headers[":error-message"].value||"UnknownError");throw i.name=s.headers[":error-code"].value,i}else if(r==="exception"){let i=s.headers[":exception-type"].value,e={[i]:s},f=await t(e);if(f.$unknown){let o=Error(n(s.body));throw o.name=i,o}throw f[i]}else if(r==="event"){let i={[s.headers[":event-type"].value]:s},e=await t(i);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var cc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new sc(n,s),this.utfEncoder=n}deserialize(n,s){let r=Ll(n);return new ec({messageStream:new rc({inputStream:r,decoder:this.eventStreamCodec}),deserializer:fc(s,this.utfEncoder)})}serialize(n,s){return new ic({messageStream:new oc({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},yU=(t)=>new cc(t);class hc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new cc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:BU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return MU.from(this.universalMarshaller.serialize(t,n))}}var GU=(t)=>new hc(t);async function*BU(t){let n=!1,s=!1,r=[];t.on("error",(i)=>{if(!n)n=!0;if(i)throw i}),t.on("data",(i)=>{r.push(i)}),t.on("end",()=>{n=!0});while(!s){let i=await new Promise((e)=>setTimeout(()=>e(r.shift()),0));if(i)yield i;s=n&&r.length===0}}var FU=(t)=>({[Symbol.asyncIterator]:async function*(){let n=t.getReader();try{while(!0){let{done:s,value:r}=await n.read();if(s)return;yield r}}finally{n.releaseLock()}}}),HU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:r,value:i}=await n.next();if(r)return s.close();s.enqueue(i)}})},PU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class Il{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:r,defaultContentType:i}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=r,this.defaultContentType=i}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let r=this.marshaller,i=n.getEventStreamMember(),e=n.getMemberSchema(i),f=this.serializer,o=this.defaultContentType,c=Symbol("initialRequestMarker"),h={async*[Symbol.asyncIterator](){if(s){let u={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(n,s);let _=f.flush();yield{[c]:!0,headers:u,body:_}}for await(let u of t)yield u}};return r.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let _="";for(let d in u)if(d!=="__type"){_=d;break}let{additionalHeaders:l,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(_,e,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},...l},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let r=this.marshaller,i=n.getEventStreamMember(),f=n.getMemberSchema(i).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=r.deserialize(t.body,async(_)=>{let l="";for(let A in _)if(A!=="__type"){l=A;break}let w=_[l].body;if(l==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[i],{[o]:!0,...A}}else if(l in f){let A=f[l];if(A.isStructSchema()){let M={},E=!1;for(let[d,T]of A.structIterator()){let{eventHeader:U,eventPayload:S}=T.getMergedTraits();if(E=E||Boolean(U||S),S){if(T.isBlobSchema())M[d]=w;else if(T.isStringSchema())M[d]=(this.serdeContext?.utf8Encoder??wU)(w);else if(T.isStructSchema())M[d]=await this.deserializer.read(T,w)}else if(U){let O=_[l].headers[d]?.value;if(O!=null)if(T.isNumericSchema())if(O&&typeof O==="object"&&"bytes"in O)M[d]=BigInt(O.toString());else M[d]=Number(O);else M[d]=O}}if(E)return{[l]:M};if(w.byteLength===0)return{[l]:{}}}return{[l]:await this.deserializer.read(A,w)}}else return{$unknown:_}}),h=c[Symbol.asyncIterator](),u=await h.next();if(u.done)return c;if(u.value?.[o]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let _ in u.value)s[_]=u.value[_]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:_,value:l}=await h.next();if(_)break;yield l}}}}writeEventBody(t,n,s){let r=this.serializer,i=t,e=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[_,l]=s[t];i=_,r.write(15,l)}else{let _=n.getMemberSchema(t);if(_.isStructSchema()){for(let[l,w]of _.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)e=l;else if(A){let E=s[t][l],d="binary";if(w.isNumericSchema())if(-2147483648<=E&&E<=2147483647)d="integer";else d="long";else if(w.isTimestampSchema())d="timestamp";else if(w.isStringSchema())d="string";else if(w.isBooleanSchema())d="boolean";if(E!=null)c[l]={type:d,value:E},delete s[t][l]}}if(e!==null){let l=_.getMemberSchema(e);if(l.isBlobSchema())f="application/octet-stream";else if(l.isStringSchema())f="text/plain";r.write(l,s[t][e])}else r.write(_,s[t])}else if(_.isUnitSchema())r.write(_,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let h=r.flush()??new Uint8Array;return{body:typeof h==="string"?(this.serdeContext?.utf8Decoder??AU)(h):h,eventType:i,explicitPayloadContentType:f,additionalHeaders:c}}}NU.EventStreamCodec=sc;NU.EventStreamMarshaller=hc;NU.EventStreamSerde=Il;NU.HeaderMarshaller=nc;NU.Int64=as;NU.MessageDecoderStream=rc;NU.MessageEncoderStream=ic;NU.SmithyMessageDecoderStream=ec;NU.SmithyMessageEncoderStream=oc;NU.UniversalEventStreamMarshaller=cc;NU.eventStreamSerdeProvider=GU;NU.getChunkedStream=Ll;NU.getMessageUnmarshaller=fc;NU.getUnmarshalledStream=OU;NU.iterableToReadableStream=HU;NU.readableStreamToIterable=FU;NU.resolveEventStreamSerdeConfig=PU;NU.universalEventStreamSerdeProvider=yU});var Ut=Z((bL)=>{var{Uint8ArrayBlobAdapter:uc,sdkStreamMixin:vU,splitEvery:tL,splitHeader:Bl,fromBase64:Ol,_parseEpochTimestamp:nL,_parseRfc7231DateTime:sL,_parseRfc3339DateTimeWithOffset:rL,LazyJsonString:Fl,NumericValue:iL,toUtf8:Hl,fromUtf8:eL,generateIdempotencyToken:oL,toBase64:yl,dateToUtcString:fL,quoteHeader:cL}=$t(),{TypeRegistry:hL,NormalizedSchema:on,translateTraits:Pl}=Nn(),{HttpRequest:ps,HttpResponse:Nl,isValidHostname:Wl}=nn(),{parseQueryString:uL,parseUrl:_L}=nn();bL.HttpRequest=ps;bL.HttpResponse=Nl;bL.isValidHostname=Wl;bL.parseQueryString=uL;bL.parseUrl=_L;var{FieldPosition:lL}=is(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return uc.mutate(t);if(!t)return uc.mutate(new Uint8Array);let s=n.streamCollector(t);return uc.mutate(await s)};function Vr(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class Zs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class ge extends Zs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=hL.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return Nl}setSerdeContext(t){if(this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){if(t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,!t.query)t.query={};for(let[s,r]of n.url.searchParams.entries())t.query[s]=r;if(n.headers)for(let s in n.headers)t.headers[s]=n.headers[s].join(", ");return t}else{if(t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},n.headers)for(let s in n.headers)t.headers[s]=n.headers[s];return t}}setHostPrefix(t,n,s){if(this.serdeContext?.disableHostPrefix)return;let r=on.of(n.input),i=Pl(n.traits??{});if(i.endpoint){let e=i.endpoint?.[0];if(typeof e==="string"){for(let[f,o]of r.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let c=s[f];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);e=e.replace(`{${f}}`,c)}if(t.hostname=e+t.hostname,!Wl(t.hostname))throw Error(`[${t.hostname}] is not a valid hostname.`)}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s})}async loadEventStreamCapability(){let{EventStreamSerde:t,eventStreamSerdeProvider:n}=Me(),s=this.resolveEventStreamMarshaller(n);return new t({marshaller:s,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(t){let n=this.serdeContext;if(n.eventStreamMarshaller)return n.eventStreamMarshaller;return t(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,s,r,i){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class Dl extends ge{async serializeRequest(t,n,s){let r=n&&typeof n==="object"?n:{},i=this.serializer,e={},f={},o=await s.endpoint(),c=on.of(t?.input),h=[],u=[],_=!1,l,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,r);let A=Pl(t.traits);if(A.http){w.method=A.http[0];let[M,E]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let d=new URLSearchParams(E??"");for(let[T,U]of d)e[T]=U}}for(let[A,M]of c.structIterator()){let E=M.getMergedTraits()??{},d=r[A];if(d==null&&!M.isIdempotencyToken()){if(E.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(E.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(r[A])l=await this.serializeEventStream({eventStream:r[A],requestSchema:c})}else l=d;else i.write(M,d),l=i.flush();else if(E.httpLabel){i.write(M,d);let T=i.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,T.split("/").map(Vr).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Vr(T))}else if(E.httpHeader)i.write(M,d),f[E.httpHeader.toLowerCase()]=String(i.flush());else if(typeof E.httpPrefixHeaders==="string")for(let T in d){let U=d[T],S=E.httpPrefixHeaders+T;i.write([M.getValueSchema(),{httpHeader:S}],U),f[S.toLowerCase()]=i.flush()}else if(E.httpQuery||E.httpQueryParams)this.serializeQuery(M,d,e);else _=!0,h.push(A),u.push(M)}if(_&&r){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),E=c.getSchema()[6],d=[3,A,M,c.getMergedTraits(),h,u,void 0];if(E)d[6]=E;else d.pop();i.write(d,r),l=i.flush()}return w.headers=f,w.query=e,w.body=l,w}serializeQuery(t,n,s){let r=this.serializer,i=t.getMergedTraits();if(i.httpQueryParams){for(let e in n)if(!(e in s)){let f=n[e],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...i,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let e=!!t.getMergedTraits().sparse,f=[];for(let o of n){r.write([t.getValueSchema(),i],o);let c=r.flush();if(e||c!==void 0)f.push(c)}s[i.httpQuery]=f}else r.write([t,i],n),s[i.httpQuery]=r.flush()}async deserializeResponse(t,n,s){let r=this.deserializer,i=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=await this.deserializeHttpMessage(i,n,s,e);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await r.read(i,o);for(let h of f)if(c[h]!=null)e[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return e.$metadata=this.deserializeMetadata(s),e}async deserializeHttpMessage(t,n,s,r,i){let e;if(r instanceof Set)e=i;else e=r;let f=!0,o=this.deserializer,c=on.of(t),h=[];for(let[u,_]of c.structIterator()){let l=_.getMemberTraits();if(l.httpPayload){if(f=!1,_.isStreaming())if(_.isStructSchema())e[u]=await this.deserializeEventStream({response:s,responseSchema:c});else e[u]=vU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)e[u]=await o.read(_,A)}}else if(l.httpHeader){let w=String(l.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(_.isListSchema()){let M=_.getValueSchema();M.getMergedTraits().httpHeader=w;let E;if(M.isTimestampSchema()&&M.getSchema()===4)E=tL(A,",",2);else E=Bl(A);let d=[];for(let T of E)d.push(await o.read(M,T.trim()));e[u]=d}else e[u]=await o.read(_,A)}else if(l.httpPrefixHeaders!==void 0){e[u]={};for(let w in s.headers)if(w.startsWith(l.httpPrefixHeaders)){let A=s.headers[w],M=_.getValueSchema();M.getMergedTraits().httpHeader=w,e[u][w.slice(l.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(l.httpResponseCode)e[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class Yl extends ge{async serializeRequest(t,n,s){let r=this.serializer,i={},e={},f=await s.endpoint(),o=on.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},_=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:i,headers:e,body:void 0});if(f)this.updateServiceEndpoint(_,f),this.setHostPrefix(_,t,u);if(u){let l=o.getEventStreamMember();if(l){if(u[l]){let w={};for(let[A,M]of o.structIterator())if(A!==l&&u[A])r.write(M,u[A]),w[A]=r.flush();h=await this.serializeEventStream({eventStream:u[l],requestSchema:o,initialRequest:w})}}else r.write(c,u),h=r.flush()}return _.headers=Object.assign(_.headers,e),_.query=i,_.body=h,_.method="POST",_}async deserializeResponse(t,n,s){let r=this.deserializer,i=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=i.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:s,responseSchema:i,initialResponseContainer:e});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await r.read(i,o))}return e.$metadata=this.deserializeMetadata(s),e}}var ml=(t,n,s,r,i,e)=>{if(n!=null&&n[s]!==void 0){let f=r();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+s+".");t=t.replace(i,e?f.split("/").map((o)=>Vr(o)).join("/"):Vr(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function wL(t,n){return new _c(t,n)}class _c{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(t,n){this.input=t,this.context=n}async build(){let{hostname:t,protocol:n="https",port:s,path:r}=await this.context.endpoint();this.path=r;for(let i of this.resolvePathStack)i(this.path);return new ps({protocol:n,hostname:this.hostname||t,port:s,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(t){return this.hostname=t,this}bp(t){return this.resolvePathStack.push((n)=>{this.path=`${n?.endsWith("/")?n.slice(0,-1):n||""}`+t}),this}p(t,n,s,r){return this.resolvePathStack.push((i)=>{this.path=ml(i,this.input,t,n,s,r)}),this}h(t){return this.headers=t,this}q(t){return this.query=t,this}b(t){return this.body=t,this}m(t){return this.method=t,this}}function lc(t,n){if(n.timestampFormat.useTrait){if(t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema()}let{httpLabel:s,httpPrefixHeaders:r,httpHeader:i,httpQuery:e}=t.getMergedTraits();return(n.httpBindings?typeof r==="string"||Boolean(i)?6:Boolean(e)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class wc extends Zs{settings;constructor(t){super();this.settings=t}read(t,n){let s=on.of(t);if(s.isListSchema())return Bl(n).map((r)=>this.read(s.getValueSchema(),r));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??Ol)(n);if(s.isTimestampSchema())switch(lc(s,this.settings)){case 5:return rL(n);case 6:return sL(n);case 7:return nL(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(s.isStringSchema()){let r=s.getMergedTraits().mediaType,i=n;if(r){if(s.getMergedTraits().httpHeader)i=this.base64ToUtf8(i);if(r==="application/json"||r.endsWith("+json"))i=Fl.from(i);return i}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new iL(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??Hl)((this.serdeContext?.base64Decoder??Ol)(t))}}class Ql extends Zs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new wc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=on.of(t),r=s.getMergedTraits(),i=this.serdeContext?.utf8Encoder??Hl;if(r.httpHeader||r.httpResponseCode)return this.stringDeserializer.read(s,i(n));if(r.httpPayload){if(s.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??eL;if(typeof n==="string")return e(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return i(n);return n}}return this.codecDeserializer.read(s,n)}}class Ac extends Zs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=on.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(s.isTimestampSchema()){if(!(n instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${s.getName(!0)}`);switch(lc(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=fL(n);break;case 7:this.stringBuffer=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1000)}return}if(s.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??yl)(n);return}if(s.isListSchema()&&Array.isArray(n)){let e="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:cL(o);if(e!=="")e+=", ";e+=c}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let r=s.getMergedTraits().mediaType,i=n;if(r){if(r==="application/json"||r.endsWith("+json"))i=Fl.from(i);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??yl)(i.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=oL();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class Jl{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new Ac(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=on.of(t),r=s.getMergedTraits();if(r.httpHeader||r.httpLabel||r.httpQuery){this.stringSerializer.write(s,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(s,n)}flush(){if(this.buffer!==void 0){let t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}class kl{name;kind;values;constructor({name:t,kind:n=lL.HEADER,values:s=[]}){this.name=t,this.kind=n,this.values=s}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class Xl{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}var AL=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},ML=(t)=>{return{httpHandler:t.httpHandler()}},Gl="content-length";function zl(t){return(n)=>async(s)=>{let r=s.request;if(ps.isInstance(r)){let{body:i,headers:e}=r;if(i&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(Gl)===-1)try{let f=t(i);r.headers={...r.headers,[Gl]:String(f)}}catch(f){}}return n({...s,request:r})}}var xl={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},gL=(t)=>({applyToStack:(n)=>{n.add(zl(t.bodyLengthChecker),xl)}}),Kr=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,EL),EL=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,dL=(t)=>t.split("/").map(Kr).join("/");function RL(t){let n=[];for(let s of Object.keys(t).sort()){let r=t[s];if(s=Kr(s),Array.isArray(r))for(let i=0,e=r.length;i<e;i++)n.push(`${s}=${Kr(r[i])}`);else{let i=s;if(r||typeof r==="string")i+=`=${Kr(r)}`;n.push(i)}}return n.join("&")}bL.Field=kl;bL.Fields=Xl;bL.FromStringShapeDeserializer=wc;bL.HttpBindingProtocol=Dl;bL.HttpInterceptingShapeDeserializer=Ql;bL.HttpInterceptingShapeSerializer=Jl;bL.HttpProtocol=ge;bL.RequestBuilder=_c;bL.RpcProtocol=Yl;bL.SerdeContext=Zs;bL.ToStringShapeSerializer=Ac;bL.buildQueryString=RL;bL.collectBody=us;bL.contentLengthMiddleware=zl;bL.contentLengthMiddlewareOptions=xl;bL.determineTimestampFormat=lc;bL.escapeUri=Kr;bL.escapeUriPath=dL;bL.extendedEncodeURIComponent=Vr;bL.getContentLengthPlugin=gL;bL.getHttpHandlerExtensionConfiguration=AL;bL.requestBuilder=wL;bL.resolveHttpHandlerRuntimeConfig=ML;bL.resolvedPath=ml});var vr=Z((RI)=>{var{Readable:aL}=nt("stream"),{NoOpLogger:pL,normalizeProvider:ql}=Rn(),{HttpResponse:Cl,HttpRequest:de}=Ut(),{parseRfc7231DateTime:ZL,v4:Kl}=$t(),Vl=(t)=>t?.body instanceof aL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,vL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],tI=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nI=["TimeoutError","RequestTimeout","RequestTimeoutException"],sI=[500,502,503,504],rI=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],iI=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],dc=(t)=>t?.$retryable!==void 0,jl=(t)=>vL.includes(t.name),al=(t)=>t.$metadata?.clockSkewCorrected,pl=(t)=>{let n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(t&&t instanceof TypeError))return!1;return n.has(t.message)},ar=(t)=>t.$metadata?.httpStatusCode===429||tI.includes(t.name)||t.$retryable?.throttling==!0,pr=(t,n=0)=>dc(t)||al(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||nI.includes(t.name)||rI.includes(t?.code||"")||iI.includes(t?.code||"")||sI.includes(t.$metadata?.httpStatusCode||0)||pl(t)||vl(t)||t.cause!==void 0&&n<=10&&pr(t.cause,n+1),Zl=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!pr(t))return!0;return!1}return!1};function vl(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var tw=100,be=20000,nw=500,Re=500,sw=5,rw=10,Rc=1,Te="amz-sdk-invocation-id",Se="amz-sdk-request";function iw(t,n){if(!Cl.isInstance(t))return;for(let s of Object.keys(t.headers)){let r=s.toLowerCase();if(r==="retry-after"){let i=t.headers[s],e=NaN;if(i.endsWith("GMT"))try{e=(ZL(i).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.trace?.(f)}else if(i.match(/ GMT, ((\d+)|(\d+\.\d+))$/))e=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]);else if(i.match(/^((\d+)|(\d+\.\d+))$/))e=Number(i);else if(Date.parse(i)>=Date.now())e=(Date.parse(i)-Date.now())/1000;if(isNaN(e))return;return new Date(Date.now()+e*1000)}else if(r==="x-amz-retry-after"){let i=t.headers[s],e=Number(i);if(isNaN(e)){n?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+e)}}}function eI(t,n){return iw(t,n)}var ew=(t)=>{if(t instanceof Error)return t;if(t instanceof Object)return Object.assign(Error(),t);if(typeof t==="string")return Error(t);return Error(`AWS SDK error wrapper for ${t}`)};function ow(t){return(n)=>(s,r)=>async(i)=>{let e=await n.retryStrategy(),f=await n.maxAttempts();if(fI(e)){e=e;let o=await e.acquireInitialRetryToken((r.partition_id??"")+(r.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:_}=i,l=de.isInstance(_);if(l)_.headers[Te]=Kl();while(!0)try{if(l)_.headers[Se]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(i);return e.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=cI(w,n.logger);if(c=ew(w),l&&t(_))throw(r.logger instanceof pL?console:r.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(E){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=h+1,c.$metadata.totalRetryDelay=u,c}h=o.getRetryCount();let M=o.getRetryDelay();if(u+=(o?.$retryLog?.acquisitionDelay??0)+M,M>0)await oI(M)}}else{if(e=e,e?.mode)r.userAgent=[...r.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(s,i)}}}var oI=(t)=>new Promise((n)=>setTimeout(n,t)),fI=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",cI=(t,n)=>{let s={error:t,errorType:hI(t)},r=iw(t.$response,n);if(r)s.retryAfterHint=r;return s},hI=(t)=>{if(ar(t))return"THROTTLING";if(pr(t))return"TRANSIENT";if(Zl(t))return"SERVER_ERROR";return"CLIENT_ERROR"},fw={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function uI(t){let n=ow(t);return(s)=>({applyToStack:(r)=>{r.add(n(s),fw)}})}class Zr{static setTimeoutFn=(t,n)=>setTimeout(t,n);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??0.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??0.5,this.scaleConstant=t?.scaleConstant??0.4,this.smooth=t?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(t){let n;this.updateMeasuredRate();let s=t;if(s?.errorType==="THROTTLING"||ar(s?.error??t)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let i=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(i)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(t){if(!this.enabled)return;this.refillTokenBucket();while(t>this.availableTokens){let n=(t-this.availableTokens)/this.fillRate*1000;await new Promise((s)=>Zr.setTimeoutFn(s,n)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-t}refillTokenBucket(){let t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}let n=(t-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+n),this.lastTimestamp=t}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){let s=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(s*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}class _t{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return _t.v2026?50:100}static throttlingDelay(){return _t.v2026?1000:500}static cost(){return _t.v2026?14:5}static throttlingCost(){return _t.v2026?5:10}static modifiedCostType(){return _t.v2026?"THROTTLING":"TRANSIENT"}}class cw{x=_t.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,r=n*Math.min(this.x*2**t,be);return Math.floor(r)}setDelayBase(t){this.x=t}}class Mc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(t,n,s,r){this.delay=t,this.count=n,this.cost=s,this.longPoll=r}getRetryCount(){return this.count}getRetryDelay(){return Math.min(be,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var $n;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})($n||($n={}));var _s=3,hw=$n.STANDARD,Ee={incompatible:1,attempts:2,capacity:3},jr=class{mode=$n.STANDARD;retryBackoffStrategy;capacity=Re;maxAttemptsProvider;baseDelay;constructor(n){if(typeof n==="number")this.maxAttemptsProvider=async()=>n;else if(typeof n==="function")this.maxAttemptsProvider=n;else if(n&&typeof n==="object")this.maxAttemptsProvider=async()=>n.maxAttempts,this.baseDelay=n.baseDelay,this.retryBackoffStrategy=n.backoff;this.maxAttemptsProvider??=async()=>_s,this.baseDelay??=_t.delay(),this.retryBackoffStrategy??=new cw}async acquireInitialRetryToken(n){return new Mc(_t.delay(),0,void 0,_t.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let r=await this.getMaxAttempts(),i=this.retryCode(n,s,r),e=i===0,f=n.isLongPoll?.();if(e||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?_t.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(n.getRetryCount()),h=c;if(s.retryAfterHint instanceof Date)h=Math.max(c,Math.min(s.retryAfterHint.getTime()-Date.now(),c+5000));if(!e){let u=_t.v2026&&i===Ee.capacity&&f?h:0;if(u>0)await new Promise((_)=>setTimeout(_,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let _=new Mc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((l)=>setTimeout(l,h)),_.$retryLog.acquisitionDelay=h,_}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(Re,this.capacity+(n.getRetryCost()??Rc))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(n){return console.warn(`Max attempts provider could not resolve. Using default of ${_s}`),_s}}retryCode(n,s,r){let i=n.getRetryCount()+1,e=this.isRetryableError(s.errorType)?0:Ee.incompatible,f=i<r?0:Ee.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:Ee.capacity;return e||f||o}getCapacityCost(n){return n===_t.modifiedCostType()?_t.throttlingCost():_t.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},uw=class{mode=$n.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:r}=s??{};this.rateLimiter=r??new Zr,this.standardRetryStrategy=s?new jr({maxAttempts:typeof n==="number"?n:3,...s}):new jr(n)}async acquireInitialRetryToken(n){let s=await this.standardRetryStrategy.acquireInitialRetryToken(n);return await this.rateLimiter.getSendToken(),s}async refreshRetryTokenForRetry(n,s){this.rateLimiter.updateClientSendingRate(s);let r=await this.standardRetryStrategy.refreshRetryTokenForRetry(n,s);return await this.rateLimiter.getSendToken(),r}recordSuccess(n){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(n)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class _w extends jr{computeNextBackoffDelay;constructor(t,n=_t.delay()){super(typeof t==="function"?t:async()=>t);if(typeof n==="number")this.computeNextBackoffDelay=()=>n;else this.computeNextBackoffDelay=n;this.retryBackoffStrategy.computeNextBackoffDelay=(s)=>{let r=s+1;return this.computeNextBackoffDelay(r)}}}var _I=(t,n)=>{let s=t,r=Rc,i=sw,e=rw,f=t,o=(_)=>_.name==="TimeoutError"?e:i,c=(_)=>o(_)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(_)=>{if(!c(_))throw Error("No retry token available");let l=o(_);return f-=l,l},releaseRetryTokens:(_)=>{f+=_??r,f=Math.min(f,s)}})},lw=(t,n)=>Math.floor(Math.min(be,Math.random()*2**n*t)),ww=(t)=>{if(!t)return!1;return dc(t)||jl(t)||ar(t)||pr(t)};class bc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=$n.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??ww,this.delayDecider=n?.delayDecider??lw,this.retryQuota=n?.retryQuota??_I(Re)}shouldRetry(t,n,s){return n<s&&this.retryDecider(t)&&this.retryQuota.hasRetryTokens(t)}async getMaxAttempts(){let t;try{t=await this.maxAttemptsProvider()}catch(n){t=_s}return t}async retry(t,n,s){let r,i=0,e=0,f=await this.getMaxAttempts(),{request:o}=n;if(de.isInstance(o))o.headers[Te]=Kl();while(!0)try{if(de.isInstance(o))o.headers[Se]=`attempt=${i+1}; max=${f}`;if(s?.beforeRequest)await s.beforeRequest();let{response:c,output:h}=await t(n);if(s?.afterRequest)s.afterRequest(c);return this.retryQuota.releaseRetryTokens(r),h.$metadata.attempts=i+1,h.$metadata.totalRetryDelay=e,{response:c,output:h}}catch(c){let h=ew(c);if(i++,this.shouldRetry(h,i,f)){r=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(ar(h)?nw:tw,i),_=lI(h.$response),l=Math.max(_||0,u);e+=l,await new Promise((w)=>setTimeout(w,l));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=i,h.$metadata.totalRetryDelay=e,h}}}var lI=(t)=>{if(!Cl.isInstance(t))return;let n=Object.keys(t.headers).find((e)=>e.toLowerCase()==="retry-after");if(!n)return;let s=t.headers[n],r=Number(s);if(!Number.isNaN(r))return Math.min(r*1000,20000);let i=new Date(s);return Math.min(i.getTime()-Date.now(),20000)};class Aw extends bc{rateLimiter;constructor(t,n){let{rateLimiter:s,...r}=n??{};super(t,r);this.rateLimiter=s??new Zr,this.mode=$n.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var gc="AWS_MAX_ATTEMPTS",Ec="max_attempts",wI={environmentVariableSelector:(t)=>{let n=t[gc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${gc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[Ec];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${Ec} mast be a number, got "${n}"`);return s},default:_s},AI=(t,n)=>{let{retryStrategy:s,retryMode:r}=t,{defaultMaxAttempts:i=_s,defaultBaseDelay:e=_t.delay()}=n??{},f=ql(t.maxAttempts??i),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await ql(r)()===$n.ADAPTIVE)return new uw(f,{maxAttempts:h,baseDelay:e});return new jr({maxAttempts:h,baseDelay:e})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},Mw="AWS_RETRY_MODE",gw="retry_mode",MI={environmentVariableSelector:(t)=>t[Mw],configFileSelector:(t)=>t[gw],default:hw},Ew=()=>(t)=>async(n)=>{let{request:s}=n;if(de.isInstance(s))delete s.headers[Te],delete s.headers[Se];return t(n)},dw={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},gI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Ew(),dw)}}),EI=ow(Vl),dI=uI(Vl);RI.AdaptiveRetryStrategy=uw;RI.CONFIG_MAX_ATTEMPTS=Ec;RI.CONFIG_RETRY_MODE=gw;RI.ConfiguredRetryStrategy=_w;RI.DEFAULT_MAX_ATTEMPTS=_s;RI.DEFAULT_RETRY_DELAY_BASE=tw;RI.DEFAULT_RETRY_MODE=hw;RI.DefaultRateLimiter=Zr;RI.DeprecatedAdaptiveRetryStrategy=Aw;RI.DeprecatedStandardRetryStrategy=bc;RI.ENV_MAX_ATTEMPTS=gc;RI.ENV_RETRY_MODE=Mw;RI.INITIAL_RETRY_TOKENS=Re;RI.INVOCATION_ID_HEADER=Te;RI.MAXIMUM_RETRY_DELAY=be;RI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=wI;RI.NODE_RETRY_MODE_CONFIG_OPTIONS=MI;RI.NO_RETRY_INCREMENT=Rc;RI.REQUEST_HEADER=Se;RI.RETRY_COST=sw;RI.RETRY_MODES=$n;RI.Retry=_t;RI.StandardRetryStrategy=jr;RI.THROTTLING_RETRY_DELAY_BASE=nw;RI.TIMEOUT_RETRY_COST=rw;RI.defaultDelayDecider=lw;RI.defaultRetryDecider=ww;RI.getOmitRetryHeadersPlugin=gI;RI.getRetryAfterHint=eI;RI.getRetryPlugin=dI;RI.isBrowserNetworkError=pl;RI.isClockSkewCorrectedError=al;RI.isClockSkewError=jl;RI.isNodeJsHttp2TransientError=vl;RI.isRetryableByTrait=dc;RI.isServerError=Zl;RI.isThrottlingError=ar;RI.isTransientError=pr;RI.omitRetryHeadersMiddleware=Ew;RI.omitRetryHeadersMiddlewareOptions=dw;RI.resolveRetryConfig=AI;RI.retryMiddleware=EI;RI.retryMiddlewareOptions=fw});var bw=Z((hO)=>{var Jn={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},Tc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Tc)globalThis.awslambda=globalThis.awslambda||{};class $e{static PROTECTED_KEYS=Jn;isProtectedKey(t){return Object.values(Jn).includes(t)}getRequestId(){return this.get(Jn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Jn.X_RAY_TRACE_ID)}getTenantId(){return this.get(Jn.TENANT_ID)}getTraceparent(){return this.get(Jn.TRACEPARENT)}getTracestate(){return this.get(Jn.TRACESTATE)}getBaggage(){return this.get(Jn.BAGGAGE)}}class Rw extends $e{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(t){return this.currentContext?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);this.currentContext=this.currentContext||{},this.currentContext[t]=n}run(t,n){return this.currentContext=t,n()}}class $c extends $e{als;static async create(){let t=new $c,n=await import("async_hooks");return t.als=new n.AsyncLocalStorage,t}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(t){return this.als.getStore()?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);let s=this.als.getStore();if(!s)throw Error("No context available");s[t]=n}run(t,n){return this.als.run(t,n)}}hO.InvokeStore=void 0;(function(t){let n=null;async function s(r){if(!n)n=(async()=>{let e=r===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await $c.create():new Rw;if(!Tc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Tc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();return n}t.getInstanceAsync=s,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(n=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(hO.InvokeStore||(hO.InvokeStore={}));hO.InvokeStoreBase=$e});var kn=Z((IO)=>{var{getSmithyContext:Uc}=nn();IO.getSmithyContext=Uc;var{HttpRequest:Lc}=Ut(),{requestBuilder:_O}=Ut();IO.requestBuilder=_O;var{HttpApiKeyAuthLocation:Tw}=is(),lO=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let r of n)for(let i of t)if(i.schemeId.split("#")[1]===r)s.push(i);for(let r of t)if(!s.find(({schemeId:i})=>i===r.schemeId))s.push(r);return s};function wO(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Ic=(t,n)=>(s,r)=>async(i)=>{let e=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,r,i.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=lO(e,f),c=wO(t.httpAuthSchemes),h=Uc(r),u=[];for(let _ of o){let l=c.get(_.schemeId);if(!l){u.push(`HttpAuthScheme \`${_.schemeId}\` was not enabled for this service.`);continue}let w=l.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${_.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=_.propertiesExtractor?.(t,r)||{};_.identityProperties=Object.assign(_.identityProperties||{},A),_.signingProperties=Object.assign(_.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:_,identity:await w(_.identityProperties),signer:l.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
23
- `));return s(i)},Sw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},AO=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),Sw)}}),$w={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},MO=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(r)=>{r.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),$w)}}),gO=(t)=>(n)=>{throw n},EO=(t,n)=>{},Uw=(t)=>(n,s)=>async(r)=>{if(!Lc.isInstance(r.request))return n(r);let e=Uc(s).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=e,h=await n({...r,request:await c.sign(r.request,o,f)}).catch((c.errorHandler||gO)(f));return(c.successHandler||EO)(h.response,f),h},Lw={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},dO=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Uw(),Lw)}}),RO=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},bO=async(t,n,s,r=(e)=>e,...i)=>{let e=new t(s);return e=r(e)??e,await n.send(e,...i)};function TO(t,n,s,r,i){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],_=!0,l;while(_){if(h[s]=u,i)h[i]=h[i]??f.pageSize;if(f.client instanceof t)l=await bO(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield l;let w=u;u=SO(l,r),_=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var SO=(t,n)=>{let s=t,r=n.split(".");for(let i of r){if(!s||typeof s!=="object")return;s=s[i]}return s};function $O(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}class Iw{authSchemes=new Map;constructor(t){for(let n in t){let s=t[n];if(s!==void 0)this.authSchemes.set(n,s)}}getIdentityProvider(t){return this.authSchemes.get(t)}}class Ow{async sign(t,n,s){if(!s)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!s.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!s.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!n.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let r=Lc.clone(t);if(s.in===Tw.QUERY)r.query[s.name]=n.apiKey;else if(s.in===Tw.HEADER)r.headers[s.name]=s.scheme?`${s.scheme} ${n.apiKey}`:n.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+s.in+"`");return r}}class yw{async sign(t,n,s){let r=Lc.clone(t);if(!n.token)throw Error("request could not be signed with `token` since the `token` is not defined");return r.headers.Authorization=`Bearer ${n.token}`,r}}class Gw{async sign(t,n,s){return t}}var Bw=(t)=>function(s){return Hw(s)&&s.expiration.getTime()-Date.now()<t},Fw=300000,UO=Bw(Fw),Hw=(t)=>t.expiration!==void 0,LO=(t,n,s)=>{if(t===void 0)return;let r=typeof t!=="function"?async()=>Promise.resolve(t):t,i,e,f,o=!1,c=async(h)=>{if(!e)e=r(h);try{i=await e,f=!0,o=!1}finally{e=void 0}return i};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)i=await c(h);return i};return async(h)=>{if(!f||h?.forceRefresh)i=await c(h);if(o)return i;if(!s(i))return o=!0,i;if(n(i))return await c(h),i;return i}};IO.DefaultIdentityProviderConfig=Iw;IO.EXPIRATION_MS=Fw;IO.HttpApiKeyAuthSigner=Ow;IO.HttpBearerAuthSigner=yw;IO.NoAuthSigner=Gw;IO.createIsIdentityExpiredFunction=Bw;IO.createPaginator=TO;IO.doesIdentityRequireRefresh=Hw;IO.getHttpAuthSchemeEndpointRuleSetPlugin=AO;IO.getHttpAuthSchemePlugin=MO;IO.getHttpSigningPlugin=dO;IO.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Sw;IO.httpAuthSchemeMiddleware=Ic;IO.httpAuthSchemeMiddlewareOptions=$w;IO.httpSigningMiddleware=Uw;IO.httpSigningMiddlewareOptions=Lw;IO.isIdentityExpired=UO;IO.memoizeIdentityProvider=LO;IO.normalizeProvider=RO;IO.setFeature=$O});var Pw=Z((ti,Oc)=>{(function(t,n){typeof ti=="object"&&typeof Oc=="object"?Oc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof ti=="object"?ti.bowser=n():t.bowser=n()})(ti,function(){return function(t){var n={};function s(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,s),i.l=!0,i.exports}return s.m=t,s.c=n,s.d=function(r,i,e){s.o(r,i)||Object.defineProperty(r,i,{enumerable:!0,get:e})},s.r=function(r){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},s.t=function(r,i){if(1&i&&(r=s(r)),8&i)return r;if(4&i&&typeof r=="object"&&r&&r.__esModule)return r;var e=Object.create(null);if(s.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&i&&typeof r!="string")for(var f in r)s.d(e,f,function(o){return r[o]}.bind(null,f));return e},s.n=function(r){var i=r&&r.__esModule?function(){return r.default}:function(){return r};return s.d(i,"a",i),i},s.o=function(r,i){return Object.prototype.hasOwnProperty.call(r,i)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=s(18),i=function(){function e(){}return e.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},e.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},e.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},e.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(f){var o=f.split(".").splice(0,2).map(function(u){return parseInt(u,10)||0});o.push(0);var c=o[0],h=o[1];if(c===10)switch(h){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},e.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},e.getVersionPrecision=function(f){return f.split(".").length},e.compareVersions=function(f,o,c){c===void 0&&(c=!1);var h=e.getVersionPrecision(f),u=e.getVersionPrecision(o),_=Math.max(h,u),l=0,w=e.map([f,o],function(A){var M=_-e.getVersionPrecision(A),E=A+Array(M+1).join(".0");return e.map(E.split("."),function(d){return Array(20-d.length).join("0")+d}).reverse()});for(c&&(l=_-Math.min(h,u)),_-=1;_>=l;){if(w[0][_]>w[1][_])return 1;if(w[0][_]===w[1][_]){if(_===l)return 0;_-=1}else if(w[0][_]<w[1][_])return-1}},e.map=function(f,o){var c,h=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(c=0;c<f.length;c+=1)h.push(o(f[c]));return h},e.find=function(f,o){var c,h;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(c=0,h=f.length;c<h;c+=1){var u=f[c];if(o(u,c))return u}},e.assign=function(f){for(var o,c,h=f,u=arguments.length,_=Array(u>1?u-1:0),l=1;l<u;l++)_[l-1]=arguments[l];if(Object.assign)return Object.assign.apply(Object,[f].concat(_));var w=function(){var A=_[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=_.length;o<c;o+=1)w();return f},e.getBrowserAlias=function(f){return r.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return r.BROWSER_MAP[f]||""},e}();n.default=i,t.exports=n.default},18:function(t,n,s){n.__esModule=!0,n.ENGINE_MAP=n.OS_MAP=n.PLATFORMS_MAP=n.BROWSER_MAP=n.BROWSER_ALIASES_MAP=void 0,n.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},n.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},n.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},n.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},n.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(91))&&r.__esModule?r:{default:r},e=s(18);function f(c,h){for(var u=0;u<h.length;u++){var _=h[u];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(c,_.key,_)}}var o=function(){function c(){}var h,u,_;return c.getParser=function(l,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof l!="string")throw Error("UserAgent should be a string");return new i.default(l,w,A)},c.parse=function(l,w){return w===void 0&&(w=null),new i.default(l,w).getResult()},h=c,_=[{key:"BROWSER_MAP",get:function(){return e.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return e.ENGINE_MAP}},{key:"OS_MAP",get:function(){return e.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return e.PLATFORMS_MAP}}],(u=null)&&f(h.prototype,u),_&&f(h,_),c}();n.default=o,t.exports=n.default},91:function(t,n,s){n.__esModule=!0,n.default=void 0;var r=c(s(92)),i=c(s(93)),e=c(s(94)),f=c(s(95)),o=c(s(17));function c(u){return u&&u.__esModule?u:{default:u}}var h=function(){function u(l,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),l==null||l==="")throw Error("UserAgent parameter can't be empty");this._ua=l;var M=!1;typeof w=="boolean"?(M=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},M!==!0&&this.parse()}var _=u.prototype;return _.getHints=function(){return this._hints},_.hasBrand=function(l){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=l.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},_.getBrandVersion=function(l){if(this._hints&&Array.isArray(this._hints.brands)){var w=l.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},_.getUA=function(){return this._ua},_.test=function(l){return l.test(this._ua)},_.parseBrowser=function(){var l=this;this.parsedResult.browser={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},_.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},_.getBrowserName=function(l){return l?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},_.getBrowserVersion=function(){return this.getBrowser().version},_.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},_.parseOS=function(){var l=this;this.parsedResult.os={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},_.getOSName=function(l){var w=this.getOS().name;return l?String(w).toLowerCase()||"":w||""},_.getOSVersion=function(){return this.getOS().version},_.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},_.getPlatformType=function(l){l===void 0&&(l=!1);var w=this.getPlatform().type;return l?String(w).toLowerCase()||"":w||""},_.parsePlatform=function(){var l=this;this.parsedResult.platform={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},_.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},_.getEngineName=function(l){return l?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},_.parseEngine=function(){var l=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(l);if(Array.isArray(A.test))return A.test.some(function(M){return l.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},_.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},_.getResult=function(){return o.default.assign({},this.parsedResult)},_.satisfies=function(l){var w=this,A={},M=0,E={},d=0;if(Object.keys(l).forEach(function(J){var G=l[J];typeof G=="string"?(E[J]=G,d+=1):typeof G=="object"&&(A[J]=G,M+=1)}),M>0){var T=Object.keys(A),U=o.default.find(T,function(J){return w.isOS(J)});if(U){var S=this.satisfies(A[U]);if(S!==void 0)return S}var O=o.default.find(T,function(J){return w.isPlatform(J)});if(O){var D=this.satisfies(A[O]);if(D!==void 0)return D}}if(d>0){var q=Object.keys(E),tt=o.default.find(q,function(J){return w.isBrowser(J,!0)});if(tt!==void 0)return this.compareVersion(E[tt])}},_.isBrowser=function(l,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=l.toLowerCase(),E=o.default.getBrowserTypeByAlias(M);return w&&E&&(M=E.toLowerCase()),M===A},_.compareVersion=function(l){var w=[0],A=l,M=!1,E=this.getBrowserVersion();if(typeof E=="string")return l[0]===">"||l[0]==="<"?(A=l.substr(1),l[1]==="="?(M=!0,A=l.substr(2)):w=[],l[0]===">"?w.push(1):w.push(-1)):l[0]==="="?A=l.substr(1):l[0]==="~"&&(M=!0,A=l.substr(1)),w.indexOf(o.default.compareVersions(E,A,M))>-1},_.isOS=function(l){return this.getOSName(!0)===String(l).toLowerCase()},_.isPlatform=function(l){return this.getPlatformType(!0)===String(l).toLowerCase()},_.isEngine=function(l){return this.getEngineName(!0)===String(l).toLowerCase()},_.is=function(l,w){return w===void 0&&(w=!1),this.isBrowser(l,w)||this.isOS(l)||this.isPlatform(l)},_.some=function(l){var w=this;return l===void 0&&(l=[]),l.some(function(A){return w.is(A)})},u}();n.default=h,t.exports=n.default},92:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(17))&&r.__esModule?r:{default:r},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=i.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=i.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=i.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},h=i.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=i.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=i.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=i.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=i.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=i.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=i.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=i.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=i.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=i.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=i.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=i.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=i.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=i.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=i.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=i.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=i.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},h=i.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var c={name:"Opera"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},h=i.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},h=i.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=i.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=i.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},h=i.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=i.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},h=i.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},h=i.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=i.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},h=i.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},h=i.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},h=i.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=i.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=i.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return h&&(c.version=h),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},h=i.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=i.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=i.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},h=i.default.getFirstMatch(e,o)||i.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},h=i.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=i.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=i.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=i.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},h=i.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},h=i.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},h=i.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),_=i.default.getFirstMatch(/se ([\d.]+)x/i,o),l=h||u||_;return l&&(c.version=l),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=i.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var h={name:"DuckDuckGo"};if(c){var u=c.getBrandVersion("DuckDuckGo");if(u)return h.version=u,h}var _=i.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return _&&(h.version=_),h}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var h={name:"Brave"};if(c){var u=c.getBrandVersion("Brave");if(u)return h.version=u,h}return h}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},h=i.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=i.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},h=i.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c={name:"Android Browser"},h=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=i.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i.default.getFirstMatch(c,o),version:i.default.getSecondMatch(c,o)}}}];n.default=f,t.exports=n.default},93:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=i.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=i.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=i.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=i.default.getWindowsVersionName(c);return{name:e.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:e.OS_MAP.iOS},h=i.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=i.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=i.default.getMacOSVersionName(c),u={name:e.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=i.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=i.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c=i.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=i.default.getAndroidVersionName(c),u={name:e.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=i.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:e.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=i.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||i.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||i.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:e.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=i.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=i.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:e.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:e.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var c=i.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.PlayStation4,version:c}}}];n.default=f,t.exports=n.default},94:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:[/googlebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var c=i.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){var c=o.test(/ipod|iphone/i),h=o.test(/like (ipod|iphone)/i);return c&&!h},describe:function(o){var c=i.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var c=i.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{test:[/[^-]mobi/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:e.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var r,i=(r=s(17))&&r.__esModule?r:{default:r},e=s(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:e.ENGINE_MAP.Blink};var c=i.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:e.ENGINE_MAP.Trident},h=i.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:e.ENGINE_MAP.Presto},h=i.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=o.test(/gecko/i),h=o.test(/like gecko/i);return c&&!h},describe:function(o){var c={name:e.ENGINE_MAP.Gecko},h=i.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:e.ENGINE_MAP.WebKit},h=i.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var xt=Z((zy)=>{var{Retry:jO,RETRY_MODES:Nw}=vr(),{HttpRequest:Pc,parseUrl:aO}=Ut(),{InvokeStore:Ww}=bw(),{normalizeProvider:pO}=kn(),{platform:ZO,release:vO}=nt("os"),{versions:yc,env:Dw}=nt("process"),{isValidHostLabel:ty,isIpAddress:kw,customEndpointFunctions:ny}=fs(),{EndpointError:sy,resolveEndpoint:ry}=fs();zy.EndpointError=sy;zy.isIpAddress=kw;zy.resolveEndpoint=ry;var{loadConfig:iy,NODE_REGION_CONFIG_OPTIONS:Xw,NODE_REGION_CONFIG_FILE_OPTIONS:zw}=St(),{REGION_ENV_NAME:ey,REGION_INI_NAME:oy,resolveRegionConfig:fy}=St();zy.NODE_REGION_CONFIG_FILE_OPTIONS=zw;zy.NODE_REGION_CONFIG_OPTIONS=Xw;zy.REGION_ENV_NAME=ey;zy.REGION_INI_NAME=oy;zy.resolveRegionConfig=fy;var Le={warningEmitted:!1},cy=(t)=>{if(t&&!Le.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Le.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Le.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
14
+ `)}u.close()}else u.enqueue(`${(i(l)||0).toString(16)}\r
15
+ ${l}\r
16
+ `)}})};function Z8(t,n){let s=t,i=t;if(en(i))return p8(i,n);let{base64Encoder:r,bodyLengthChecker:e,checksumAlgorithmFn:f,checksumLocationName:o,streamHasher:c}=n,h=r!==void 0&&f!==void 0&&o!==void 0&&c!==void 0,u=h?c(f,s):void 0,l=new zs({read:()=>{}});return s.on("data",(_)=>{let w=e(_)||0;if(w===0)return;l.push(`${w.toString(16)}\r
17
+ `),l.push(_),l.push(`\r
18
+ `)}),s.on("end",async()=>{if(l.push(`0\r
19
+ `),h){let _=r(await u);l.push(`${o}:${_}\r
20
+ `),l.push(`\r
21
+ `)}l.push(null)}),l}async function v8(t,n){let s=0,i=[],r=t.getReader(),e=!1;while(!e){let{done:c,value:h}=await r.read();if(h)i.push(h),s+=h?.byteLength??0;if(s>=n)break;e=c}r.releaseLock();let f=new Uint8Array(Math.min(n,s)),o=0;for(let c of i){if(c.byteLength>f.byteLength-o){f.set(c.subarray(0,f.byteLength-o),o);break}else f.set(c,o);o+=c.length}return f}var tS=(t,n)=>{if(en(t))return v8(t,n);return new Promise((s,i)=>{let r=new nS;r.limit=n,t.pipe(r),t.on("error",(e)=>{r.end(),i(e)}),r.on("error",i),r.on("finish",function(){let e=_e(this.buffers);s(e)})})},nS=class extends Pl{buffers=[];limit=1/0;bytesBuffered=0;_write(n,s,i){if(this.buffers.push(n),this.bytesBuffered+=n.byteLength??0,this.bytesBuffered>=this.limit){let r=this.bytesBuffered-this.limit,e=this.buffers[this.buffers.length-1];this.buffers[this.buffers.length-1]=e.subarray(0,e.byteLength-r),this.emit("finish")}i()}},sS=(t)=>{if(typeof t==="string")return t;if(typeof t!=="object"||typeof t.byteOffset!=="number"||typeof t.byteLength!=="number")throw Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(t)},iS=async(t)=>{if(we(t))return r_(t);return e_(t)};async function r_(t){return t.arrayBuffer().then((n)=>new Uint8Array(n))}async function e_(t){let n=[],s=t.getReader(),i=0;while(!0){let{done:r,value:e}=await s.read();if(e)n.push(e),i+=e.length;if(r)break}return _e(n,i)}var Bl="The stream has already been transformed.",rS=(t)=>{if(!Fl(t)&&!en(t)){let r=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${r}`)}let n=!1,s=async()=>{if(n)throw Error(Bl);return n=!0,await iS(t)},i=(r)=>{if(typeof r.stream!=="function")throw Error(`Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.
22
+ If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body`);return r.stream()};return Object.assign(t,{transformToByteArray:s,transformToString:async(r)=>{let e=await s();if(r==="base64")return t_(e);else if(r==="hex")return ql(e);else if(r===void 0||r==="utf8"||r==="utf-8")return sS(e);else if(typeof TextDecoder==="function")return new TextDecoder(r).decode(e);else throw Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(n)throw Error(Bl);if(n=!0,Fl(t))return i(t);else if(en(t))return t;else throw Error(`Cannot transform payload to web stream, got ${t}`)}})},Fl=(t)=>typeof Blob==="function"&&t instanceof Blob,o_=(t)=>{if(we(t))return r_(t);if(en(t))return e_(t);return new Promise((n,s)=>{let i=new f_,r=t;r.pipe(i),r.on("error",(e)=>{i.end(),s(e)}),i.on("error",s),i.on("finish",function(){let e=_e(this.bufferedBytes);n(e)})})};class f_ extends Pl{bufferedBytes=[];_write(t,n,s){this.bufferedBytes.push(t),s()}}var Hl="The stream has already been transformed.",eS=(t)=>{if(!(t instanceof zs))try{return rS(t)}catch(i){let r=t?.__proto__?.constructor?.name||t;throw Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${r}`)}let n=!1,s=async()=>{if(n)throw Error(Hl);return n=!0,await o_(t)};return Object.assign(t,{transformToByteArray:s,transformToString:async(i)=>{let r=await s();if(i===void 0||Buffer.isEncoding(i))return xs(r.buffer,r.byteOffset,r.byteLength).toString(i);else return new TextDecoder(i).decode(r)},transformToWebStream:()=>{if(n)throw Error(Hl);if(t.readableFlowing!==null)throw Error("The stream has been consumed by other callbacks.");if(typeof zs.toWeb!=="function")throw Error("Readable.toWeb() is not supported. Please ensure a polyfill is available.");return n=!0,zs.toWeb(t)}})};async function oS(t){if(typeof t.stream==="function")t=t.stream();return t.tee()}async function fS(t){if(en(t)||we(t))return oS(t);let n=new Il,s=new Il;return t.pipe(n),t.pipe(s),[n,s]}class c_ extends q5(Dl,ue,kf,Wl){}var cS=Y5,h_=C5(cS),hS=h_;uS.ChecksumStream=Zl;uS.Hash=pl;uS.LazyJsonString=cs;uS.NumericValue=le;uS.Uint8ArrayBlobAdapter=c_;uS._parseEpochTimestamp=N8;uS._parseRfc3339DateTimeWithOffset=W8;uS._parseRfc7231DateTime=D8;uS.calculateBodyLength=k8;uS.concatBytes=_e;uS.copyDocumentWithTransform=K5;uS.createBufferedReadable=a8;uS.createChecksumStream=V8;uS.dateToUtcString=u8;uS.deserializerMiddleware=Kl;uS.deserializerMiddlewareOption=jl;uS.expectBoolean=j5;uS.expectByte=Qf;uS.expectFloat32=oe;uS.expectInt=p5;uS.expectInt32=mf;uS.expectLong=xi;uS.expectNonNull=v5;uS.expectNumber=Xi;uS.expectObject=ml;uS.expectShort=Yf;uS.expectString=t8;uS.expectUnion=n8;uS.fromArrayBuffer=xs;uS.fromBase64=Wl;uS.fromHex=J8;uS.fromString=he;uS.fromUtf8=ue;uS.generateIdempotencyToken=hS;uS.getAwsChunkedEncodingStream=Z8;uS.getSerdePlugin=z8;uS.handleFloat=r8;uS.headStream=tS;uS.isArrayBuffer=Nl;uS.isBlob=we;uS.isReadableStream=en;uS.limitedParseDouble=xf;uS.limitedParseFloat=e8;uS.limitedParseFloat32=o8;uS.logger=qi;uS.nv=Q8;uS.parseBoolean=V5;uS.parseEpochTimestamp=R8;uS.parseRfc3339DateTime=_8;uS.parseRfc3339DateTimeWithOffset=A8;uS.parseRfc7231DateTime=E8;uS.quoteHeader=O8;uS.sdkStreamMixin=eS;uS.serializerMiddleware=Vl;uS.serializerMiddlewareOption=al;uS.splitEvery=m8;uS.splitHeader=Y8;uS.splitStream=fS;uS.streamCollector=o_;uS.strictParseByte=kl;uS.strictParseDouble=Xf;uS.strictParseFloat=s8;uS.strictParseFloat32=Yl;uS.strictParseInt=f8;uS.strictParseInt32=c8;uS.strictParseLong=Jl;uS.strictParseShort=qs;uS.toBase64=kf;uS.toHex=ql;uS.toUint8Array=Cl;uS.toUtf8=Dl;uS.v4=h_});var tc=Z((p$)=>{var{createReadStream:G$}=nt("fs"),{Writable:B$}=nt("stream"),{toUint8Array:Vs,concatBytes:F$}=$t(),{createHash:Ci,createHmac:H$}=nt("crypto"),u_=nt("zlib");async function M_(t,n,s=1048576){let i=t.size,r=0;while(r<i){let e=t.slice(r,Math.min(i,r+s));n(new Uint8Array(await e.arrayBuffer())),r+=e.size}}var P$=async function(n,s){let i=new n;return await M_(s,(r)=>{i.update(r)}),i.digest()};class pf extends B${hash;constructor(t,n){super(n);this.hash=t}_write(t,n,s){try{this.hash.update(Vs(t))}catch(i){return s(i)}s()}}var N$=(t,n)=>new Promise((s,i)=>{if(!W$(n)){i(Error("Unable to calculate hash for non-file streams."));return}let r=G$(n.path,{start:n.start,end:n.end}),e=new t,f=new pf(e);r.pipe(f),r.on("error",(o)=>{f.end(),i(o)}),f.on("error",i),f.on("finish",function(){e.digest().then(s).catch(i)})}),W$=(t)=>typeof t.path==="string",D$=(t,n)=>{if(n.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let s=new t,i=new pf(s);return n.pipe(i),new Promise((r,e)=>{n.on("error",(f)=>{i.end(),e(f)}),i.on("error",e),i.on("finish",()=>{s.digest().then(r).catch(e)})})};class Zf{digestLength=16;state=Uint32Array.from(l_);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(t){let n=Vs(t),s=0,i=n.byteLength;this.bytesHashed+=i;while(i>0)if(this.writeBuffer.setUint8(this.bufferLength++,n[s++]),--i,this.bufferLength===64)jf(this.state,this.writeBuffer),this.bufferLength=0}async digest(){let t=Uint32Array.from(this.state),n=new DataView(this.writeBuffer.buffer.slice(0)),s=this.bufferLength,i=this.bytesHashed*8;if(n.setUint8(s++,128),this.bufferLength%64>=56){for(let f=s;f<64;++f)n.setUint8(f,0);jf(t,n),s=0}for(let f=s;f<56;++f)n.setUint8(f,0);n.setUint32(56,i>>>0,!0),n.setUint32(60,Math.floor(i/4294967296),!0),jf(t,n);let r=new Uint8Array(16),e=new DataView(r.buffer);for(let f=0;f<4;++f)e.setUint32(f*4,t[f],!0);return r}reset(){this.state.set(l_),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0}}var l_=[1732584193,4023233417,2562383102,271733878],Yn=4294967295,m$=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),Y$=Array.from({length:64},(t,n)=>Math.abs(Math.sin(n+1))*4294967296>>>0);function jf(t,n){let s=t[0],i=t[1],r=t[2],e=t[3];for(let f=0;f<64;++f){let o,c;if(f<16)o=i&r|~i&e,c=f;else if(f<32)o=e&i|r&~e,c=(5*f+1)%16;else if(f<48)o=i^r^e,c=(3*f+5)%16;else o=r^(i|~e),c=7*f%16;let h=n.getUint32(c*4,!0),u=e;e=r,r=i;let l=m$[(f>>4)*4+(f&3)],_=(s+o&Yn)+(h+Y$[f]&Yn)&Yn;i=i+((_<<l|_>>>32-l)>>>0)&Yn,s=u}t[0]=t[0]+s&Yn,t[1]=t[1]+i&Yn,t[2]=t[2]+r&Yn,t[3]=t[3]+e&Yn}var Q$=(()=>{try{return Ci("md5"),!0}catch{return!1}})(),g_=Q$?J$():Zf;function J$(){return class{digestLength=16;hash=Ci("md5");update(n){this.hash.update(Vs(n))}async digest(){let n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=Ci("md5")}}}var d_=new Uint32Array(256);for(let t=0;t<256;++t){let n=t;for(let s=0;s<8;++s)n=n&1?3988292384^n>>>1:n>>>1;d_[t]=n>>>0}var af=4294967295;class vf{digestLength=4;checksum=af;update(t){for(let n=0;n<t.length;++n)this.checksum=this.checksum>>>8^d_[(this.checksum^t[n])&255]}digestSync(){return(this.checksum^af)>>>0}async digest(){let t=this.digestSync(),n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t,!1),n}reset(){this.checksum=af}}var __=typeof u_.crc32==="function"?u_.crc32:void 0,E_=__?k$(__):vf;function k$(t){return class{digestLength=4;value=0;update(s){this.value=t(s,this.value)}digestSync(){return this.value>>>0}async digest(){let s=new Uint8Array(4);return new DataView(s.buffer).setUint32(0,this.digestSync(),!1),s}reset(){this.value=0}}}var At=64,w_=32,z$=9007199254740991;class Sn{digestLength=w_;state=Int32Array.from(A_);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=!1;inner;outer;constructor(t){if(t){let n=Sn.normalizeKey(t);this.inner=new Sn,this.outer=new Sn;let{inner:s,outer:i}=this,r=new Uint8Array(At*2);for(let e=0;e<At;++e)r[e]=54^n[e],r[e+At]=92^n[e];s.update(r.subarray(0,At)),i.update(r.subarray(At))}}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(t);return}let n=Vs(t),s=0,{byteLength:i}=n;if(this.bytesHashed+=i,this.bytesHashed*8>z$)throw Error("Cannot hash more than 2^53 - 1 bits");while(i>0)if(this.buffer[this.bufferLength++]=n[s++],i--,this.bufferLength===At)this.hashBuffer(),this.bufferLength=0}async digest(){let{inner:t,outer:n}=this;if(t&&n){if(this.finished)throw Error("Attempted to digest an already finished HMAC.");this.finished=!0;let s=t.digestSync();return n.update(s),n.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(A_),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0}digestSync(){let t=this.state.slice(),n=this.buffer.slice(),s=this.bufferLength,i=this.bytesHashed*8,r=new DataView(n.buffer,n.byteOffset,n.byteLength);if(r.setUint8(s++,128),(s-1)%At>=At-8){for(let f=s;f<At;++f)r.setUint8(f,0);this.hashBufferWith(t,n),s=0}for(let f=s;f<At-8;++f)r.setUint8(f,0);r.setUint32(At-8,Math.floor(i/4294967296),!1),r.setUint32(At-4,i,!1),this.hashBufferWith(t,n);let e=new Uint8Array(w_);for(let f=0;f<8;++f)e[f*4]=t[f]>>>24&255,e[f*4+1]=t[f]>>>16&255,e[f*4+2]=t[f]>>>8&255,e[f*4+3]=t[f]>>>0&255;return e}static normalizeKey(t){let n=Vs(t);if(n.byteLength>At){let s=new Sn;s.update(n);let i=s.digestSync(),r=new Uint8Array(At);return r.set(i),r}if(n.byteLength<At){let s=new Uint8Array(At);return s.set(n),s}return n}hashBuffer(){this.hashBufferWith(this.state,this.buffer)}hashBufferWith(t,n){let s=this.w??=new Int32Array(64),i=t[0],r=t[1],e=t[2],f=t[3],o=t[4],c=t[5],h=t[6],u=t[7];for(let l=0;l<At;++l){if(l<16)s[l]=(n[l*4]&255)<<24|(n[l*4+1]&255)<<16|(n[l*4+2]&255)<<8|n[l*4+3]&255;else{let A=s[l-2],M=(A>>>17|A<<15)^(A>>>19|A<<13)^A>>>10;A=s[l-15];let d=(A>>>7|A<<25)^(A>>>18|A<<14)^A>>>3;s[l]=(M+s[l-7]|0)+(d+s[l-16]|0)}let _=(((o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7))+(o&c^~o&h)|0)+(u+(X$[l]+s[l]|0)|0)|0,w=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&r^i&e^r&e)|0;u=h,h=c,c=o,o=f+_|0,f=e,e=r,r=i,i=_+w|0}t[0]+=i,t[1]+=r,t[2]+=e,t[3]+=f,t[4]+=o,t[5]+=c,t[6]+=h,t[7]+=u}}var A_=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),X$=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),x$=(()=>{try{return Ci("sha256"),!0}catch{return!1}})(),R_=x$?q$():Sn;function q$(){return class{digestLength=32;secret;hash;isHmac;finished=!1;constructor(n){this.secret=n,this.isHmac=!!n,this.hash=this.createHash()}update(n){if(this.finished)throw Error("Attempted to update an already finished hash.");this.hash.update(n)}async digest(){let n;if(this.isHmac)this.finished=!0,n=this.hash.digest();else n=this.hash.copy().digest();return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}reset(){this.hash=this.createHash(),this.finished=!1}createHash(){return this.secret?H$("sha256",C$(this.secret)):Ci("sha256")}}}function C$(t){if(typeof t==="string")return t;if(ArrayBuffer.isView(t))return Buffer.from(t.buffer,t.byteOffset,t.byteLength);return Buffer.from(t)}var{digest:K$,sign:V$,importKey:j$}=globalThis?.crypto?.subtle??{},Ae=typeof K$==="function"&&typeof V$==="function"&&typeof j$==="function"?globalThis.crypto.subtle:void 0,a$=8388608;class b_{digestLength=32;secret;pending=[];pendingBytes=0;fallback;finished=!1;constructor(t){if(t)this.secret=Vs(t)}update(t){if(this.finished)throw Error("Attempted to update an already finished HMAC.");if(this.fallback){this.fallback.update(t);return}if(this.pending.push(t.slice()),this.pendingBytes+=t.byteLength,this.pendingBytes>=a$)this.switchToFallback()}async digest(){if(this.fallback)return this.fallback.digest();if(this.secret&&this.finished)throw Error("Attempted to digest an already finished HMAC.");let t=F$(this.pending);if(Ae){if(this.secret){this.finished=!0;let i=await Ae.importKey("raw",this.secret,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),r=await Ae.sign("HMAC",i,t);return new Uint8Array(r)}let s=await Ae.digest("SHA-256",t);return new Uint8Array(s)}let n=new Sn(this.secret);return n.update(t),n.digest()}reset(){this.pending=[],this.pendingBytes=0,this.fallback=void 0,this.finished=!1}switchToFallback(){let t=new Sn(this.secret);for(let n of this.pending)t.update(n);this.fallback=t,this.pending=[],this.pendingBytes=0}}p$.Crc32=E_;p$.Crc32Js=vf;p$.Crc32Node=E_;p$.Md5=g_;p$.Md5Js=Zf;p$.Md5Node=g_;p$.Sha256=R_;p$.Sha256Js=Sn;p$.Sha256Node=R_;p$.Sha256WebCrypto=b_;p$.blobHasher=P$;p$.blobReader=M_;p$.fileStreamHasher=N$;p$.readableStreamHasher=D$});var Me=Z((NU)=>{var{Crc32:$_}=tc(),{toHex:js,fromHex:_U,toUtf8:wU,fromUtf8:AU}=$t(),{Readable:MU}=nt("stream");class as{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,i=Math.abs(Math.round(t));s>-1&&i>0;s--,i/=256)n[s]=i;if(t<0)T_(n);return new as(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)T_(t);return parseInt(js(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function T_(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}class nc{toUtf8;fromUtf8;constructor(t,n){this.toUtf8=t,this.fromUtf8=n}format(t){let n=[];for(let r of Object.keys(t)){let e=this.fromUtf8(r);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[r]))}let s=new Uint8Array(n.reduce((r,e)=>r+e.byteLength,0)),i=0;for(let r of n)s.set(r,i),i+=r.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?rt.boolTrue:rt.boolFalse]);case"byte":return Uint8Array.from([rt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,rt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,rt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let i=new Uint8Array(9);return i[0]=rt.long,i.set(t.value.bytes,1),i;case"binary":let r=new DataView(new ArrayBuffer(3+t.value.byteLength));r.setUint8(0,rt.byteArray),r.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(t.value,3),e;case"string":let f=this.fromUtf8(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,rt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=rt.timestamp,h.set(as.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!UU.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=rt.uuid,u.set(_U(t.value.replace(/-/g,"")),1),u}}parse(t){let n={},s=0;while(s<t.byteLength){let i=t.getUint8(s++),r=this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,i));switch(s+=i,t.getUint8(s++)){case rt.boolTrue:n[r]={type:S_,value:!0};break;case rt.boolFalse:n[r]={type:S_,value:!1};break;case rt.byte:n[r]={type:gU,value:t.getInt8(s++)};break;case rt.short:n[r]={type:dU,value:t.getInt16(s,!1)},s+=2;break;case rt.integer:n[r]={type:EU,value:t.getInt32(s,!1)},s+=4;break;case rt.long:n[r]={type:RU,value:new as(new Uint8Array(t.buffer,t.byteOffset+s,8))},s+=8;break;case rt.byteArray:let e=t.getUint16(s,!1);s+=2,n[r]={type:bU,value:new Uint8Array(t.buffer,t.byteOffset+s,e)},s+=e;break;case rt.string:let f=t.getUint16(s,!1);s+=2,n[r]={type:TU,value:this.toUtf8(new Uint8Array(t.buffer,t.byteOffset+s,f))},s+=f;break;case rt.timestamp:n[r]={type:SU,value:new Date(new as(new Uint8Array(t.buffer,t.byteOffset+s,8)).valueOf())},s+=8;break;case rt.uuid:let o=new Uint8Array(t.buffer,t.byteOffset+s,16);s+=16,n[r]={type:$U,value:`${js(o.subarray(0,4))}-${js(o.subarray(4,6))}-${js(o.subarray(6,8))}-${js(o.subarray(8,10))}-${js(o.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return n}}var rt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(rt||(rt={}));var S_="boolean",gU="byte",dU="short",EU="integer",RU="long",bU="binary",TU="string",SU="timestamp",$U="uuid",UU=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,U_=4,Qn=U_*2,hs=4,LU=Qn+hs*2;function IU({byteLength:t,byteOffset:n,buffer:s}){if(t<LU)throw Error("Provided message too short to accommodate event stream message overhead");let i=new DataView(s,n,t),r=i.getUint32(0,!1);if(t!==r)throw Error("Reported message length does not match received message length");let e=i.getUint32(U_,!1),f=i.getUint32(Qn,!1),o=i.getUint32(t-hs,!1),c=new $_;if(c.update(new Uint8Array(s,n,Qn)),f!==c.digestSync())throw Error(`The prelude checksum specified in the message (${f}) does not match the calculated CRC32 checksum (${c.digestSync()})`);if(c.update(new Uint8Array(s,n+Qn,t-(Qn+hs))),o!==c.digestSync())throw Error(`The message checksum (${c.digestSync()}) did not match the expected value of ${o}`);return{headers:new DataView(s,n+Qn+hs,e),body:new Uint8Array(s,n+Qn+hs+e,r-e-(Qn+hs+hs))}}class sc{headerMarshaller;messageBuffer;isEndOfStream;constructor(t,n){this.headerMarshaller=new nc(t,n),this.messageBuffer=[],this.isEndOfStream=!1}feed(t){this.messageBuffer.push(this.decode(t))}endOfStream(){this.isEndOfStream=!0}getMessage(){let t=this.messageBuffer.pop(),n=this.isEndOfStream;return{getMessage(){return t},isEndOfStream(){return n}}}getAvailableMessages(){let t=this.messageBuffer;this.messageBuffer=[];let n=this.isEndOfStream;return{getMessages(){return t},isEndOfStream(){return n}}}encode({headers:t,body:n}){let s=this.headerMarshaller.format(t),i=s.byteLength+n.byteLength+16,r=new Uint8Array(i),e=new DataView(r.buffer,r.byteOffset,r.byteLength),f=new $_;return e.setUint32(0,i,!1),e.setUint32(4,s.byteLength,!1),f.update(r.subarray(0,8)),e.setUint32(8,f.digestSync(),!1),r.set(s,12),r.set(n,s.byteLength+12),f.update(r.subarray(8,i-4)),e.setUint32(i-4,f.digestSync(),!1),r}decode(t){let{headers:n,body:s}=IU(t);return{headers:this.headerMarshaller.parse(n),body:s}}formatHeaders(t){return this.headerMarshaller.format(t)}}class ic{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.decoder.decode(t)}}class rc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream)yield this.options.encoder.encode(t);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class ec{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.messageStream){let n=await this.options.deserializer(t);if(n===void 0)continue;yield n}}}class oc{options;constructor(t){this.options=t}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let t of this.options.inputStream)yield this.options.serializer(t)}}function L_(t){let n=0,s=0,i=null,r=null,e=(o)=>{if(typeof o!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+o);n=o,s=4,i=new Uint8Array(o),new DataView(i.buffer).setUint32(0,o,!1)},f=async function*(){let o=t[Symbol.asyncIterator]();while(!0){let{value:c,done:h}=await o.next();if(h){if(!n)return;else if(n===s)yield i;else throw Error("Truncated event message received.");return}let u=c.length,l=0;while(l<u){if(!i){let w=u-l;if(!r)r=new Uint8Array(4);let A=Math.min(4-s,w);if(r.set(c.slice(l,l+A),s),s+=A,l+=A,s<4)break;e(new DataView(r.buffer).getUint32(0,!1)),r=null}let _=Math.min(n-s,u-l);if(i.set(c.slice(l,l+_),s),s+=_,l+=_,n&&n===s)yield i,i=null,n=0,s=0}}};return{[Symbol.asyncIterator]:f}}function yU(t,n){let s=fc(n.deserializer,n.toUtf8);return{[Symbol.asyncIterator]:async function*(){for await(let i of t){let r=n.eventStreamCodec.decode(i),e=await s(r);if(e===void 0)continue;yield e}}}}function fc(t,n){return async function(s){let{value:i}=s.headers[":message-type"];if(i==="error"){let r=Error(s.headers[":error-message"].value||"UnknownError");throw r.name=s.headers[":error-code"].value,r}else if(i==="exception"){let r=s.headers[":exception-type"].value,e={[r]:s},f=await t(e);if(f.$unknown){let o=Error(n(s.body));throw o.name=r,o}throw f[r]}else if(i==="event"){let r={[s.headers[":event-type"].value]:s},e=await t(r);if(e.$unknown)return;return e}else throw Error(`Unrecognizable event type: ${s.headers[":event-type"].value}`)}}var cc=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:n,utf8Decoder:s}){this.eventStreamCodec=new sc(n,s),this.utfEncoder=n}deserialize(n,s){let i=L_(n);return new ec({messageStream:new ic({inputStream:i,decoder:this.eventStreamCodec}),deserializer:fc(s,this.utfEncoder)})}serialize(n,s){return new rc({messageStream:new oc({inputStream:n,serializer:s}),encoder:this.eventStreamCodec,includeEndFrame:!0})}},OU=(t)=>new cc(t);class hc{universalMarshaller;constructor({utf8Encoder:t,utf8Decoder:n}){this.universalMarshaller=new cc({utf8Decoder:n,utf8Encoder:t})}deserialize(t,n){let s=typeof t[Symbol.asyncIterator]==="function"?t:BU(t);return this.universalMarshaller.deserialize(s,n)}serialize(t,n){return MU.from(this.universalMarshaller.serialize(t,n))}}var GU=(t)=>new hc(t);async function*BU(t){let n=!1,s=!1,i=[];t.on("error",(r)=>{if(!n)n=!0;if(r)throw r}),t.on("data",(r)=>{i.push(r)}),t.on("end",()=>{n=!0});while(!s){let r=await new Promise((e)=>setTimeout(()=>e(i.shift()),0));if(r)yield r;s=n&&i.length===0}}var FU=(t)=>({[Symbol.asyncIterator]:async function*(){let n=t.getReader();try{while(!0){let{done:s,value:i}=await n.read();if(s)return;yield i}}finally{n.releaseLock()}}}),HU=(t)=>{let n=t[Symbol.asyncIterator]();return new ReadableStream({async pull(s){let{done:i,value:r}=await n.next();if(i)return s.close();s.enqueue(r)}})},PU=(t)=>Object.assign(t,{eventStreamMarshaller:t.eventStreamSerdeProvider(t)});class I_{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:t,serializer:n,deserializer:s,serdeContext:i,defaultContentType:r}){this.marshaller=t,this.serializer=n,this.deserializer=s,this.serdeContext=i,this.defaultContentType=r}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){let i=this.marshaller,r=n.getEventStreamMember(),e=n.getMemberSchema(r),f=this.serializer,o=this.defaultContentType,c=Symbol("initialRequestMarker"),h={async*[Symbol.asyncIterator](){if(s){let u={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:o}};f.write(n,s);let l=f.flush();yield{[c]:!0,headers:u,body:l}}for await(let u of t)yield u}};return i.serialize(h,(u)=>{if(u[c])return{headers:u.headers,body:u.body};let l="";for(let E in u)if(E!=="__type"){l=E;break}let{additionalHeaders:_,body:w,eventType:A,explicitPayloadContentType:M}=this.writeEventBody(l,e,u);return{headers:{":event-type":{type:"string",value:A},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:M??o},..._},body:w}})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){let i=this.marshaller,r=n.getEventStreamMember(),f=n.getMemberSchema(r).getMemberSchemas(),o=Symbol("initialResponseMarker"),c=i.deserialize(t.body,async(l)=>{let _="";for(let A in l)if(A!=="__type"){_=A;break}let w=l[_].body;if(_==="initial-response"){let A=await this.deserializer.read(n,w);return delete A[r],{[o]:!0,...A}}else if(_ in f){let A=f[_];if(A.isStructSchema()){let M={},d=!1;for(let[E,T]of A.structIterator()){let{eventHeader:U,eventPayload:S}=T.getMergedTraits();if(d=d||Boolean(U||S),S){if(T.isBlobSchema())M[E]=w;else if(T.isStringSchema())M[E]=(this.serdeContext?.utf8Encoder??wU)(w);else if(T.isStructSchema())M[E]=await this.deserializer.read(T,w)}else if(U){let y=l[_].headers[E]?.value;if(y!=null)if(T.isNumericSchema())if(y&&typeof y==="object"&&"bytes"in y)M[E]=BigInt(y.toString());else M[E]=Number(y);else M[E]=y}}if(d)return{[_]:M};if(w.byteLength===0)return{[_]:{}}}return{[_]:await this.deserializer.read(A,w)}}else return{$unknown:l}}),h=c[Symbol.asyncIterator](),u=await h.next();if(u.done)return c;if(u.value?.[o]){if(!n)throw Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let l in u.value)s[l]=u.value[l]}return{async*[Symbol.asyncIterator](){if(!u?.value?.[o])yield u.value;while(!0){let{done:l,value:_}=await h.next();if(l)break;yield _}}}}writeEventBody(t,n,s){let i=this.serializer,r=t,e=null,f,o=(()=>{return n.getSchema()[4].includes(t)})(),c={};if(!o){let[l,_]=s[t];r=l,i.write(15,_)}else{let l=n.getMemberSchema(t);if(l.isStructSchema()){for(let[_,w]of l.structIterator()){let{eventHeader:A,eventPayload:M}=w.getMergedTraits();if(M)e=_;else if(A){let d=s[t][_],E="binary";if(w.isNumericSchema())if(-2147483648<=d&&d<=2147483647)E="integer";else E="long";else if(w.isTimestampSchema())E="timestamp";else if(w.isStringSchema())E="string";else if(w.isBooleanSchema())E="boolean";if(d!=null)c[_]={type:E,value:d},delete s[t][_]}}if(e!==null){let _=l.getMemberSchema(e);if(_.isBlobSchema())f="application/octet-stream";else if(_.isStringSchema())f="text/plain";i.write(_,s[t][e])}else i.write(l,s[t])}else if(l.isUnitSchema())i.write(l,{});else throw Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}let h=i.flush()??new Uint8Array;return{body:typeof h==="string"?(this.serdeContext?.utf8Decoder??AU)(h):h,eventType:r,explicitPayloadContentType:f,additionalHeaders:c}}}NU.EventStreamCodec=sc;NU.EventStreamMarshaller=hc;NU.EventStreamSerde=I_;NU.HeaderMarshaller=nc;NU.Int64=as;NU.MessageDecoderStream=ic;NU.MessageEncoderStream=rc;NU.SmithyMessageDecoderStream=ec;NU.SmithyMessageEncoderStream=oc;NU.UniversalEventStreamMarshaller=cc;NU.eventStreamSerdeProvider=GU;NU.getChunkedStream=L_;NU.getMessageUnmarshaller=fc;NU.getUnmarshalledStream=yU;NU.iterableToReadableStream=HU;NU.readableStreamToIterable=FU;NU.resolveEventStreamSerdeConfig=PU;NU.universalEventStreamSerdeProvider=OU});var Ut=Z((bL)=>{var{Uint8ArrayBlobAdapter:uc,sdkStreamMixin:vU,splitEvery:tL,splitHeader:B_,fromBase64:y_,_parseEpochTimestamp:nL,_parseRfc7231DateTime:sL,_parseRfc3339DateTimeWithOffset:iL,LazyJsonString:F_,NumericValue:rL,toUtf8:H_,fromUtf8:eL,generateIdempotencyToken:oL,toBase64:O_,dateToUtcString:fL,quoteHeader:cL}=$t(),{TypeRegistry:hL,NormalizedSchema:on,translateTraits:P_}=Nn(),{HttpRequest:ps,HttpResponse:N_,isValidHostname:W_}=nn(),{parseQueryString:uL,parseUrl:lL}=nn();bL.HttpRequest=ps;bL.HttpResponse=N_;bL.isValidHostname=W_;bL.parseQueryString=uL;bL.parseUrl=lL;var{FieldPosition:_L}=rs(),us=async(t=new Uint8Array,n)=>{if(t instanceof Uint8Array)return uc.mutate(t);if(!t)return uc.mutate(new Uint8Array);let s=n.streamCollector(t);return uc.mutate(await s)};function Vi(t){return encodeURIComponent(t).replace(/[!'()*]/g,function(n){return"%"+n.charCodeAt(0).toString(16).toUpperCase()})}class Zs{serdeContext;setSerdeContext(t){this.serdeContext=t}}class ge extends Zs{options;compositeErrorRegistry;constructor(t){super();this.options=t,this.compositeErrorRegistry=hL.for(t.defaultNamespace);for(let n of t.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(n)}getRequestType(){return ps}getResponseType(){return N_}setSerdeContext(t){if(this.serdeContext=t,this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t),this.getPayloadCodec())this.getPayloadCodec().setSerdeContext(t)}updateServiceEndpoint(t,n){if("url"in n){if(t.protocol=n.url.protocol,t.hostname=n.url.hostname,t.port=n.url.port?Number(n.url.port):void 0,t.path=n.url.pathname,t.fragment=n.url.hash||void 0,t.username=n.url.username||void 0,t.password=n.url.password||void 0,!t.query)t.query={};for(let[s,i]of n.url.searchParams.entries())t.query[s]=i;if(n.headers)for(let s in n.headers)t.headers[s]=n.headers[s].join(", ");return t}else{if(t.protocol=n.protocol,t.hostname=n.hostname,t.port=n.port?Number(n.port):void 0,t.path=n.path,t.query={...n.query},n.headers)for(let s in n.headers)t.headers[s]=n.headers[s];return t}}setHostPrefix(t,n,s){if(this.serdeContext?.disableHostPrefix)return;let i=on.of(n.input),r=P_(n.traits??{});if(r.endpoint){let e=r.endpoint?.[0];if(typeof e==="string"){for(let[f,o]of i.structIterator()){if(!o.getMergedTraits().hostLabel)continue;let c=s[f];if(typeof c!=="string")throw Error(`@smithy/core/schema - ${f} in input must be a string as hostLabel.`);e=e.replace(`{${f}}`,c)}if(t.hostname=e+t.hostname,!W_(t.hostname))throw Error(`[${t.hostname}] is not a valid hostname.`)}}}deserializeMetadata(t){return{httpStatusCode:t.statusCode,requestId:t.headers["x-amzn-requestid"]??t.headers["x-amzn-request-id"]??t.headers["x-amz-request-id"],extendedRequestId:t.headers["x-amz-id-2"],cfId:t.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:t,requestSchema:n,initialRequest:s})}async deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:t,responseSchema:n,initialResponseContainer:s})}async loadEventStreamCapability(){let{EventStreamSerde:t,eventStreamSerdeProvider:n}=Me(),s=this.resolveEventStreamMarshaller(n);return new t({marshaller:s,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(t){let n=this.serdeContext;if(n.eventStreamMarshaller)return n.eventStreamMarshaller;return t(this.serdeContext)}getDefaultContentType(){throw Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(t,n,s,i,r){return[]}getEventStreamMarshaller(){let t=this.serdeContext;if(!t.eventStreamMarshaller)throw Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return t.eventStreamMarshaller}}class D_ extends ge{async serializeRequest(t,n,s){let i=n&&typeof n==="object"?n:{},r=this.serializer,e={},f={},o=await s.endpoint(),c=on.of(t?.input),h=[],u=[],l=!1,_,w=new ps({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:e,headers:f,body:void 0});if(o){this.updateServiceEndpoint(w,o),this.setHostPrefix(w,t,i);let A=P_(t.traits);if(A.http){w.method=A.http[0];let[M,d]=A.http[1].split("?");if(w.path=="/")w.path=M;else w.path+=M;let E=new URLSearchParams(d??"");for(let[T,U]of E)e[T]=U}}for(let[A,M]of c.structIterator()){let d=M.getMergedTraits()??{},E=i[A];if(E==null&&!M.isIdempotencyToken()){if(d.httpLabel){if(w.path.includes(`{${A}+}`)||w.path.includes(`{${A}}`))throw Error(`No value provided for input HTTP label: ${A}.`)}continue}if(d.httpPayload)if(M.isStreaming())if(M.isStructSchema()){if(i[A])_=await this.serializeEventStream({eventStream:i[A],requestSchema:c})}else _=E;else r.write(M,E),_=r.flush();else if(d.httpLabel){r.write(M,E);let T=r.flush();if(w.path.includes(`{${A}+}`))w.path=w.path.replace(`{${A}+}`,T.split("/").map(Vi).join("/"));else if(w.path.includes(`{${A}}`))w.path=w.path.replace(`{${A}}`,Vi(T))}else if(d.httpHeader)r.write(M,E),f[d.httpHeader.toLowerCase()]=String(r.flush());else if(typeof d.httpPrefixHeaders==="string")for(let T in E){let U=E[T],S=d.httpPrefixHeaders+T;r.write([M.getValueSchema(),{httpHeader:S}],U),f[S.toLowerCase()]=r.flush()}else if(d.httpQuery||d.httpQueryParams)this.serializeQuery(M,E,e);else l=!0,h.push(A),u.push(M)}if(l&&i){let[A,M]=(c.getName(!0)??"#Unknown").split("#"),d=c.getSchema()[6],E=[3,A,M,c.getMergedTraits(),h,u,void 0];if(d)E[6]=d;else E.pop();r.write(E,i),_=r.flush()}return w.headers=f,w.query=e,w.body=_,w}serializeQuery(t,n,s){let i=this.serializer,r=t.getMergedTraits();if(r.httpQueryParams){for(let e in n)if(!(e in s)){let f=n[e],o=t.getValueSchema();Object.assign(o.getMergedTraits(),{...r,httpQuery:e,httpQueryParams:void 0}),this.serializeQuery(o,f,s)}return}if(t.isListSchema()){let e=!!t.getMergedTraits().sparse,f=[];for(let o of n){i.write([t.getValueSchema(),r],o);let c=i.flush();if(e||c!==void 0)f.push(c)}s[r.httpQuery]=f}else i.write([t,r],n),s[r.httpQuery]=i.flush()}async deserializeResponse(t,n,s){let i=this.deserializer,r=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=await this.deserializeHttpMessage(r,n,s,e);if(f.length){let o=await us(s.body,n);if(o.byteLength>0){let c=await i.read(r,o);for(let h of f)if(c[h]!=null)e[h]=c[h]}}else if(f.discardResponseBody)await us(s.body,n);return e.$metadata=this.deserializeMetadata(s),e}async deserializeHttpMessage(t,n,s,i,r){let e;if(i instanceof Set)e=r;else e=i;let f=!0,o=this.deserializer,c=on.of(t),h=[];for(let[u,l]of c.structIterator()){let _=l.getMemberTraits();if(_.httpPayload){if(f=!1,l.isStreaming())if(l.isStructSchema())e[u]=await this.deserializeEventStream({response:s,responseSchema:c});else e[u]=vU(s.body);else if(s.body){let A=await us(s.body,n);if(A.byteLength>0)e[u]=await o.read(l,A)}}else if(_.httpHeader){let w=String(_.httpHeader).toLowerCase(),A=s.headers[w];if(A!=null)if(l.isListSchema()){let M=l.getValueSchema();M.getMergedTraits().httpHeader=w;let d;if(M.isTimestampSchema()&&M.getSchema()===4)d=tL(A,",",2);else d=B_(A);let E=[];for(let T of d)E.push(await o.read(M,T.trim()));e[u]=E}else e[u]=await o.read(l,A)}else if(_.httpPrefixHeaders!==void 0){e[u]={};for(let w in s.headers)if(w.startsWith(_.httpPrefixHeaders)){let A=s.headers[w],M=l.getValueSchema();M.getMergedTraits().httpHeader=w,e[u][w.slice(_.httpPrefixHeaders.length)]=await o.read(M,A)}}else if(_.httpResponseCode)e[u]=s.statusCode;else h.push(u)}return h.discardResponseBody=f,h}}class m_ extends ge{async serializeRequest(t,n,s){let i=this.serializer,r={},e={},f=await s.endpoint(),o=on.of(t?.input),c=o.getSchema(),h,u=n&&typeof n==="object"?n:{},l=new ps({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:r,headers:e,body:void 0});if(f)this.updateServiceEndpoint(l,f),this.setHostPrefix(l,t,u);if(u){let _=o.getEventStreamMember();if(_){if(u[_]){let w={};for(let[A,M]of o.structIterator())if(A!==_&&u[A])i.write(M,u[A]),w[A]=i.flush();h=await this.serializeEventStream({eventStream:u[_],requestSchema:o,initialRequest:w})}}else i.write(c,u),h=i.flush()}return l.headers=Object.assign(l.headers,e),l.query=r,l.body=h,l.method="POST",l}async deserializeResponse(t,n,s){let i=this.deserializer,r=on.of(t.output),e={};if(s.statusCode>=300){let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(15,o));throw await this.handleError(t,n,s,e,this.deserializeMetadata(s)),Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let o in s.headers){let c=s.headers[o];delete s.headers[o],s.headers[o.toLowerCase()]=c}let f=r.getEventStreamMember();if(f)e[f]=await this.deserializeEventStream({response:s,responseSchema:r,initialResponseContainer:e});else{let o=await us(s.body,n);if(o.byteLength>0)Object.assign(e,await i.read(r,o))}return e.$metadata=this.deserializeMetadata(s),e}}var Y_=(t,n,s,i,r,e)=>{if(n!=null&&n[s]!==void 0){let f=i();if(f==null||f.length<=0)throw Error("Empty value provided for input HTTP label: "+s+".");t=t.replace(r,e?f.split("/").map((o)=>Vi(o)).join("/"):Vi(f))}else throw Error("No value provided for input HTTP label: "+s+".");return t};function wL(t,n){return new lc(t,n)}class lc{input;context;query={};method="";headers={};path="";body=null;hostname="";resolvePathStack=[];constructor(t,n){this.input=t,this.context=n}async build(){let{hostname:t,protocol:n="https",port:s,path:i}=await this.context.endpoint();this.path=i;for(let r of this.resolvePathStack)r(this.path);return new ps({protocol:n,hostname:this.hostname||t,port:s,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(t){return this.hostname=t,this}bp(t){return this.resolvePathStack.push((n)=>{this.path=`${n?.endsWith("/")?n.slice(0,-1):n||""}`+t}),this}p(t,n,s,i){return this.resolvePathStack.push((r)=>{this.path=Y_(r,this.input,t,n,s,i)}),this}h(t){return this.headers=t,this}q(t){return this.query=t,this}b(t){return this.body=t,this}m(t){return this.method=t,this}}function _c(t,n){if(n.timestampFormat.useTrait){if(t.isTimestampSchema()&&(t.getSchema()===5||t.getSchema()===6||t.getSchema()===7))return t.getSchema()}let{httpLabel:s,httpPrefixHeaders:i,httpHeader:r,httpQuery:e}=t.getMergedTraits();return(n.httpBindings?typeof i==="string"||Boolean(r)?6:Boolean(e)||Boolean(s)?5:void 0:void 0)??n.timestampFormat.default}class wc extends Zs{settings;constructor(t){super();this.settings=t}read(t,n){let s=on.of(t);if(s.isListSchema())return B_(n).map((i)=>this.read(s.getValueSchema(),i));if(s.isBlobSchema())return(this.serdeContext?.base64Decoder??y_)(n);if(s.isTimestampSchema())switch(_c(s,this.settings)){case 5:return iL(n);case 6:return sL(n);case 7:return nL(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(s.isStringSchema()){let i=s.getMergedTraits().mediaType,r=n;if(i){if(s.getMergedTraits().httpHeader)r=this.base64ToUtf8(r);if(i==="application/json"||i.endsWith("+json"))r=F_.from(r);return r}}if(s.isNumericSchema())return Number(n);if(s.isBigIntegerSchema())return BigInt(n);if(s.isBigDecimalSchema())return new rL(n,"bigDecimal");if(s.isBooleanSchema())return String(n).toLowerCase()==="true";return n}base64ToUtf8(t){return(this.serdeContext?.utf8Encoder??H_)((this.serdeContext?.base64Decoder??y_)(t))}}class Q_ extends Zs{codecDeserializer;stringDeserializer;constructor(t,n){super();this.codecDeserializer=t,this.stringDeserializer=new wc(n)}setSerdeContext(t){this.stringDeserializer.setSerdeContext(t),this.codecDeserializer.setSerdeContext(t),this.serdeContext=t}read(t,n){let s=on.of(t),i=s.getMergedTraits(),r=this.serdeContext?.utf8Encoder??H_;if(i.httpHeader||i.httpResponseCode)return this.stringDeserializer.read(s,r(n));if(i.httpPayload){if(s.isBlobSchema()){let e=this.serdeContext?.utf8Decoder??eL;if(typeof n==="string")return e(n);return n}else if(s.isStringSchema()){if("byteLength"in n)return r(n);return n}}return this.codecDeserializer.read(s,n)}}class Ac extends Zs{settings;stringBuffer="";constructor(t){super();this.settings=t}write(t,n){let s=on.of(t);switch(typeof n){case"object":if(n===null){this.stringBuffer="null";return}if(s.isTimestampSchema()){if(!(n instanceof Date))throw Error(`@smithy/core/protocols - received non-Date value ${n} when schema expected Date in ${s.getName(!0)}`);switch(_c(s,this.settings)){case 5:this.stringBuffer=n.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=fL(n);break;case 7:this.stringBuffer=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using epoch seconds",n),this.stringBuffer=String(n.getTime()/1000)}return}if(s.isBlobSchema()&&"byteLength"in n){this.stringBuffer=(this.serdeContext?.base64Encoder??O_)(n);return}if(s.isListSchema()&&Array.isArray(n)){let e="";for(let f of n){this.write([s.getValueSchema(),s.getMergedTraits()],f);let o=this.flush(),c=s.getValueSchema().isTimestampSchema()?o:cL(o);if(e!=="")e+=", ";e+=c}this.stringBuffer=e;return}this.stringBuffer=JSON.stringify(n,null,2);break;case"string":let i=s.getMergedTraits().mediaType,r=n;if(i){if(i==="application/json"||i.endsWith("+json"))r=F_.from(r);if(s.getMergedTraits().httpHeader){this.stringBuffer=(this.serdeContext?.base64Encoder??O_)(r.toString());return}}this.stringBuffer=n;break;default:if(s.isIdempotencyToken())this.stringBuffer=oL();else this.stringBuffer=String(n)}}flush(){let t=this.stringBuffer;return this.stringBuffer="",t}}class J_{codecSerializer;stringSerializer;buffer;constructor(t,n,s=new Ac(n)){this.codecSerializer=t,this.stringSerializer=s}setSerdeContext(t){this.codecSerializer.setSerdeContext(t),this.stringSerializer.setSerdeContext(t)}write(t,n){let s=on.of(t),i=s.getMergedTraits();if(i.httpHeader||i.httpLabel||i.httpQuery){this.stringSerializer.write(s,n),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(s,n)}flush(){if(this.buffer!==void 0){let t=this.buffer;return this.buffer=void 0,t}return this.codecSerializer.flush()}}class k_{name;kind;values;constructor({name:t,kind:n=_L.HEADER,values:s=[]}){this.name=t,this.kind=n,this.values=s}add(t){this.values.push(t)}set(t){this.values=t}remove(t){this.values=this.values.filter((n)=>n!==t)}toString(){return this.values.map((t)=>t.includes(",")||t.includes(" ")?`"${t}"`:t).join(", ")}get(){return this.values}}class z_{entries={};encoding;constructor({fields:t=[],encoding:n="utf-8"}){t.forEach(this.setField.bind(this)),this.encoding=n}setField(t){this.entries[t.name.toLowerCase()]=t}getField(t){return this.entries[t.toLowerCase()]}removeField(t){delete this.entries[t.toLowerCase()]}getByType(t){return Object.values(this.entries).filter((n)=>n.kind===t)}}var AL=(t)=>{return{setHttpHandler(n){t.httpHandler=n},httpHandler(){return t.httpHandler},updateHttpClientConfig(n,s){t.httpHandler?.updateHttpClientConfig(n,s)},httpHandlerConfigs(){return t.httpHandler.httpHandlerConfigs()}}},ML=(t)=>{return{httpHandler:t.httpHandler()}},G_="content-length";function X_(t){return(n)=>async(s)=>{let i=s.request;if(ps.isInstance(i)){let{body:r,headers:e}=i;if(r&&Object.keys(e).map((f)=>f.toLowerCase()).indexOf(G_)===-1)try{let f=t(r);i.headers={...i.headers,[G_]:String(f)}}catch(f){}}return n({...s,request:i})}}var x_={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},gL=(t)=>({applyToStack:(n)=>{n.add(X_(t.bodyLengthChecker),x_)}}),Ki=(t)=>encodeURIComponent(t).replace(/[!'()*]/g,dL),dL=(t)=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`,EL=(t)=>t.split("/").map(Ki).join("/");function RL(t){let n=[];for(let s of Object.keys(t).sort()){let i=t[s];if(s=Ki(s),Array.isArray(i))for(let r=0,e=i.length;r<e;r++)n.push(`${s}=${Ki(i[r])}`);else{let r=s;if(i||typeof i==="string")r+=`=${Ki(i)}`;n.push(r)}}return n.join("&")}bL.Field=k_;bL.Fields=z_;bL.FromStringShapeDeserializer=wc;bL.HttpBindingProtocol=D_;bL.HttpInterceptingShapeDeserializer=Q_;bL.HttpInterceptingShapeSerializer=J_;bL.HttpProtocol=ge;bL.RequestBuilder=lc;bL.RpcProtocol=m_;bL.SerdeContext=Zs;bL.ToStringShapeSerializer=Ac;bL.buildQueryString=RL;bL.collectBody=us;bL.contentLengthMiddleware=X_;bL.contentLengthMiddlewareOptions=x_;bL.determineTimestampFormat=_c;bL.escapeUri=Ki;bL.escapeUriPath=EL;bL.extendedEncodeURIComponent=Vi;bL.getContentLengthPlugin=gL;bL.getHttpHandlerExtensionConfiguration=AL;bL.requestBuilder=wL;bL.resolveHttpHandlerRuntimeConfig=ML;bL.resolvedPath=Y_});var vi=Z((RI)=>{var{Readable:aL}=nt("stream"),{NoOpLogger:pL,normalizeProvider:q_}=Rn(),{HttpResponse:C_,HttpRequest:Ee}=Ut(),{parseRfc7231DateTime:ZL,v4:K_}=$t(),V_=(t)=>t?.body instanceof aL||typeof ReadableStream<"u"&&t?.body instanceof ReadableStream,vL=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"],tI=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],nI=["TimeoutError","RequestTimeout","RequestTimeoutException"],sI=[500,502,503,504],iI=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],rI=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],Ec=(t)=>t?.$retryable!==void 0,j_=(t)=>vL.includes(t.name),a_=(t)=>t.$metadata?.clockSkewCorrected,p_=(t)=>{let n=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);if(!(t&&t instanceof TypeError))return!1;return n.has(t.message)},ai=(t)=>t.$metadata?.httpStatusCode===429||tI.includes(t.name)||t.$retryable?.throttling==!0,pi=(t,n=0)=>Ec(t)||a_(t)||t.name==="InvalidSignatureException"&&t.message?.includes("Signature expired")||nI.includes(t.name)||iI.includes(t?.code||"")||rI.includes(t?.code||"")||sI.includes(t.$metadata?.httpStatusCode||0)||p_(t)||v_(t)||t.cause!==void 0&&n<=10&&pi(t.cause,n+1),Z_=(t)=>{if(t.$metadata?.httpStatusCode!==void 0){let n=t.$metadata.httpStatusCode;if(500<=n&&n<=599&&!pi(t))return!0;return!1}return!1};function v_(t){return t.code==="ERR_HTTP2_STREAM_ERROR"&&t.message.includes("NGHTTP2_REFUSED_STREAM")}var tw=100,be=20000,nw=500,Re=500,sw=5,iw=10,Rc=1,Te="amz-sdk-invocation-id",Se="amz-sdk-request";function rw(t,n){if(!C_.isInstance(t))return;for(let s of Object.keys(t.headers)){let i=s.toLowerCase();if(i==="retry-after"){let r=t.headers[s],e=NaN;if(r.endsWith("GMT"))try{e=(ZL(r).getTime()-Date.now())/1000}catch(f){n?.trace?.("Failed to parse retry-after header"),n?.trace?.(f)}else if(r.match(/ GMT, ((\d+)|(\d+\.\d+))$/))e=Number(r.match(/ GMT, ([\d.]+)$/)?.[1]);else if(r.match(/^((\d+)|(\d+\.\d+))$/))e=Number(r);else if(Date.parse(r)>=Date.now())e=(Date.parse(r)-Date.now())/1000;if(isNaN(e))return;return new Date(Date.now()+e*1000)}else if(i==="x-amz-retry-after"){let r=t.headers[s],e=Number(r);if(isNaN(e)){n?.trace?.(`Failed to parse x-amz-retry-after=${r}`);return}return new Date(Date.now()+e)}}}function eI(t,n){return rw(t,n)}var ew=(t)=>{if(t instanceof Error)return t;if(t instanceof Object)return Object.assign(Error(),t);if(typeof t==="string")return Error(t);return Error(`AWS SDK error wrapper for ${t}`)};function ow(t){return(n)=>(s,i)=>async(r)=>{let e=await n.retryStrategy(),f=await n.maxAttempts();if(fI(e)){e=e;let o=await e.acquireInitialRetryToken((i.partition_id??"")+(i.__retryLongPoll?":longpoll":"")),c=Error(),h=0,u=0,{request:l}=r,_=Ee.isInstance(l);if(_)l.headers[Te]=K_();while(!0)try{if(_)l.headers[Se]=`attempt=${h+1}; max=${f}`;let{response:w,output:A}=await s(r);return e.recordSuccess(o),A.$metadata.attempts=h+1,A.$metadata.totalRetryDelay=u,{response:w,output:A}}catch(w){let A=cI(w,n.logger);if(c=ew(w),_&&t(l))throw(i.logger instanceof pL?console:i.logger)?.warn("An error was encountered in a non-retryable streaming request."),c;try{o=await e.refreshRetryTokenForRetry(o,A)}catch(d){if(!c.$metadata)c.$metadata={};throw c.$metadata.attempts=h+1,c.$metadata.totalRetryDelay=u,c}h=o.getRetryCount();let M=o.getRetryDelay();if(u+=(o?.$retryLog?.acquisitionDelay??0)+M,M>0)await oI(M)}}else{if(e=e,e?.mode)i.userAgent=[...i.userAgent||[],["cfg/retry-mode",e.mode]];return e.retry(s,r)}}}var oI=(t)=>new Promise((n)=>setTimeout(n,t)),fI=(t)=>typeof t.acquireInitialRetryToken<"u"&&typeof t.refreshRetryTokenForRetry<"u"&&typeof t.recordSuccess<"u",cI=(t,n)=>{let s={error:t,errorType:hI(t)},i=rw(t.$response,n);if(i)s.retryAfterHint=i;return s},hI=(t)=>{if(ai(t))return"THROTTLING";if(pi(t))return"TRANSIENT";if(Z_(t))return"SERVER_ERROR";return"CLIENT_ERROR"},fw={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function uI(t){let n=ow(t);return(s)=>({applyToStack:(i)=>{i.add(n(s),fw)}})}class Zi{static setTimeoutFn=(t,n)=>setTimeout(t,n);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(t){this.beta=t?.beta??0.7,this.minCapacity=t?.minCapacity??1,this.minFillRate=t?.minFillRate??0.5,this.scaleConstant=t?.scaleConstant??0.4,this.smooth=t?.smooth??0.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(t){let n;this.updateMeasuredRate();let s=t;if(s?.errorType==="THROTTLING"||ai(s?.error??t)){let e=!this.enabled?this.measuredTxRate:Math.min(this.measuredTxRate,this.fillRate);this.lastMaxRate=e,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),n=this.cubicThrottle(e),this.enableTokenBucket()}else this.calculateTimeWindow(),n=this.cubicSuccess(this.getCurrentTimeInSeconds());let r=Math.min(n,2*this.measuredTxRate);this.updateTokenBucketRate(r)}getCurrentTimeInSeconds(){return Date.now()/1000}async acquireTokenBucket(t){if(!this.enabled)return;this.refillTokenBucket();while(t>this.availableTokens){let n=(t-this.availableTokens)/this.fillRate*1000;await new Promise((s)=>Zi.setTimeoutFn(s,n)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-t}refillTokenBucket(){let t=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=t;return}let n=(t-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+n),this.lastTimestamp=t}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,0.3333333333333333))}cubicThrottle(t){return this.getPrecise(t*this.beta)}cubicSuccess(t){return this.getPrecise(this.scaleConstant*Math.pow(t-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(t){this.refillTokenBucket(),this.fillRate=Math.max(t,this.minFillRate),this.maxCapacity=Math.max(t,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){let t=this.getCurrentTimeInSeconds(),n=Math.floor(t*2)/2;if(this.requestCount++,n>this.lastTxRateBucket){let s=this.requestCount/(n-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(s*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=n}}getPrecise(t){return parseFloat(t.toFixed(8))}}class lt{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return lt.v2026?50:100}static throttlingDelay(){return lt.v2026?1000:500}static cost(){return lt.v2026?14:5}static throttlingCost(){return lt.v2026?5:10}static modifiedCostType(){return lt.v2026?"THROTTLING":"TRANSIENT"}}class cw{x=lt.delay();computeNextBackoffDelay(t){let n=Math.random(),s=2,i=n*Math.min(this.x*2**t,be);return Math.floor(i)}setDelayBase(t){this.x=t}}class Mc{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(t,n,s,i){this.delay=t,this.count=n,this.cost=s,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(be,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var $n;(function(t){t.STANDARD="standard",t.ADAPTIVE="adaptive"})($n||($n={}));var ls=3,hw=$n.STANDARD,de={incompatible:1,attempts:2,capacity:3},ji=class{mode=$n.STANDARD;retryBackoffStrategy;capacity=Re;maxAttemptsProvider;baseDelay;constructor(n){if(typeof n==="number")this.maxAttemptsProvider=async()=>n;else if(typeof n==="function")this.maxAttemptsProvider=n;else if(n&&typeof n==="object")this.maxAttemptsProvider=async()=>n.maxAttempts,this.baseDelay=n.baseDelay,this.retryBackoffStrategy=n.backoff;this.maxAttemptsProvider??=async()=>ls,this.baseDelay??=lt.delay(),this.retryBackoffStrategy??=new cw}async acquireInitialRetryToken(n){return new Mc(lt.delay(),0,void 0,lt.v2026&&n.includes(":longpoll"))}async refreshRetryTokenForRetry(n,s){let i=await this.getMaxAttempts(),r=this.retryCode(n,s,i),e=r===0,f=n.isLongPoll?.();if(e||f){let o=s.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?lt.throttlingDelay():this.baseDelay);let c=this.retryBackoffStrategy.computeNextBackoffDelay(n.getRetryCount()),h=c;if(s.retryAfterHint instanceof Date)h=Math.max(c,Math.min(s.retryAfterHint.getTime()-Date.now(),c+5000));if(!e){let u=lt.v2026&&r===de.capacity&&f?h:0;if(u>0)await new Promise((l)=>setTimeout(l,u))}else{let u=this.getCapacityCost(o);this.capacity-=u;let l=new Mc(0,n.getRetryCount()+1,u,n.isLongPoll?.()??!1);return await new Promise((_)=>setTimeout(_,h)),l.$retryLog.acquisitionDelay=h,l}}throw Error("No retry token available")}recordSuccess(n){this.capacity=Math.min(Re,this.capacity+(n.getRetryCost()??Rc))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(n){return console.warn(`Max attempts provider could not resolve. Using default of ${ls}`),ls}}retryCode(n,s,i){let r=n.getRetryCount()+1,e=this.isRetryableError(s.errorType)?0:de.incompatible,f=r<i?0:de.attempts,o=this.capacity>=this.getCapacityCost(s.errorType)?0:de.capacity;return e||f||o}getCapacityCost(n){return n===lt.modifiedCostType()?lt.throttlingCost():lt.cost()}isRetryableError(n){return n==="THROTTLING"||n==="TRANSIENT"}},uw=class{mode=$n.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(n,s){let{rateLimiter:i}=s??{};this.rateLimiter=i??new Zi,this.standardRetryStrategy=s?new ji({maxAttempts:typeof n==="number"?n:3,...s}):new ji(n)}async acquireInitialRetryToken(n){let s=await this.standardRetryStrategy.acquireInitialRetryToken(n);return await this.rateLimiter.getSendToken(),s}async refreshRetryTokenForRetry(n,s){this.rateLimiter.updateClientSendingRate(s);let i=await this.standardRetryStrategy.refreshRetryTokenForRetry(n,s);return await this.rateLimiter.getSendToken(),i}recordSuccess(n){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(n)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}};class lw extends ji{computeNextBackoffDelay;constructor(t,n=lt.delay()){super(typeof t==="function"?t:async()=>t);if(typeof n==="number")this.computeNextBackoffDelay=()=>n;else this.computeNextBackoffDelay=n;this.retryBackoffStrategy.computeNextBackoffDelay=(s)=>{let i=s+1;return this.computeNextBackoffDelay(i)}}}var lI=(t,n)=>{let s=t,i=Rc,r=sw,e=iw,f=t,o=(l)=>l.name==="TimeoutError"?e:r,c=(l)=>o(l)<=f;return Object.freeze({hasRetryTokens:c,retrieveRetryTokens:(l)=>{if(!c(l))throw Error("No retry token available");let _=o(l);return f-=_,_},releaseRetryTokens:(l)=>{f+=l??i,f=Math.min(f,s)}})},_w=(t,n)=>Math.floor(Math.min(be,Math.random()*2**n*t)),ww=(t)=>{if(!t)return!1;return Ec(t)||j_(t)||ai(t)||pi(t)};class bc{maxAttemptsProvider;retryDecider;delayDecider;retryQuota;mode=$n.STANDARD;constructor(t,n){this.maxAttemptsProvider=t,this.retryDecider=n?.retryDecider??ww,this.delayDecider=n?.delayDecider??_w,this.retryQuota=n?.retryQuota??lI(Re)}shouldRetry(t,n,s){return n<s&&this.retryDecider(t)&&this.retryQuota.hasRetryTokens(t)}async getMaxAttempts(){let t;try{t=await this.maxAttemptsProvider()}catch(n){t=ls}return t}async retry(t,n,s){let i,r=0,e=0,f=await this.getMaxAttempts(),{request:o}=n;if(Ee.isInstance(o))o.headers[Te]=K_();while(!0)try{if(Ee.isInstance(o))o.headers[Se]=`attempt=${r+1}; max=${f}`;if(s?.beforeRequest)await s.beforeRequest();let{response:c,output:h}=await t(n);if(s?.afterRequest)s.afterRequest(c);return this.retryQuota.releaseRetryTokens(i),h.$metadata.attempts=r+1,h.$metadata.totalRetryDelay=e,{response:c,output:h}}catch(c){let h=ew(c);if(r++,this.shouldRetry(h,r,f)){i=this.retryQuota.retrieveRetryTokens(h);let u=this.delayDecider(ai(h)?nw:tw,r),l=_I(h.$response),_=Math.max(l||0,u);e+=_,await new Promise((w)=>setTimeout(w,_));continue}if(!h.$metadata)h.$metadata={};throw h.$metadata.attempts=r,h.$metadata.totalRetryDelay=e,h}}}var _I=(t)=>{if(!C_.isInstance(t))return;let n=Object.keys(t.headers).find((e)=>e.toLowerCase()==="retry-after");if(!n)return;let s=t.headers[n],i=Number(s);if(!Number.isNaN(i))return Math.min(i*1000,20000);let r=new Date(s);return Math.min(r.getTime()-Date.now(),20000)};class Aw extends bc{rateLimiter;constructor(t,n){let{rateLimiter:s,...i}=n??{};super(t,i);this.rateLimiter=s??new Zi,this.mode=$n.ADAPTIVE}async retry(t,n){return super.retry(t,n,{beforeRequest:async()=>{return this.rateLimiter.getSendToken()},afterRequest:(s)=>{this.rateLimiter.updateClientSendingRate(s)}})}}var gc="AWS_MAX_ATTEMPTS",dc="max_attempts",wI={environmentVariableSelector:(t)=>{let n=t[gc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Environment variable ${gc} mast be a number, got "${n}"`);return s},configFileSelector:(t)=>{let n=t[dc];if(!n)return;let s=parseInt(n);if(Number.isNaN(s))throw Error(`Shared config file entry ${dc} mast be a number, got "${n}"`);return s},default:ls},AI=(t,n)=>{let{retryStrategy:s,retryMode:i}=t,{defaultMaxAttempts:r=ls,defaultBaseDelay:e=lt.delay()}=n??{},f=q_(t.maxAttempts??r),o=s?Promise.resolve(s):void 0,c=async()=>{let h=await f();if(await q_(i)()===$n.ADAPTIVE)return new uw(f,{maxAttempts:h,baseDelay:e});return new ji({maxAttempts:h,baseDelay:e})};return Object.assign(t,{maxAttempts:f,retryStrategy:()=>o??=c()})},Mw="AWS_RETRY_MODE",gw="retry_mode",MI={environmentVariableSelector:(t)=>t[Mw],configFileSelector:(t)=>t[gw],default:hw},dw=()=>(t)=>async(n)=>{let{request:s}=n;if(Ee.isInstance(s))delete s.headers[Te],delete s.headers[Se];return t(n)},Ew={name:"omitRetryHeadersMiddleware",tags:["RETRY","HEADERS","OMIT_RETRY_HEADERS"],relation:"before",toMiddleware:"awsAuthMiddleware",override:!0},gI=(t)=>({applyToStack:(n)=>{n.addRelativeTo(dw(),Ew)}}),dI=ow(V_),EI=uI(V_);RI.AdaptiveRetryStrategy=uw;RI.CONFIG_MAX_ATTEMPTS=dc;RI.CONFIG_RETRY_MODE=gw;RI.ConfiguredRetryStrategy=lw;RI.DEFAULT_MAX_ATTEMPTS=ls;RI.DEFAULT_RETRY_DELAY_BASE=tw;RI.DEFAULT_RETRY_MODE=hw;RI.DefaultRateLimiter=Zi;RI.DeprecatedAdaptiveRetryStrategy=Aw;RI.DeprecatedStandardRetryStrategy=bc;RI.ENV_MAX_ATTEMPTS=gc;RI.ENV_RETRY_MODE=Mw;RI.INITIAL_RETRY_TOKENS=Re;RI.INVOCATION_ID_HEADER=Te;RI.MAXIMUM_RETRY_DELAY=be;RI.NODE_MAX_ATTEMPT_CONFIG_OPTIONS=wI;RI.NODE_RETRY_MODE_CONFIG_OPTIONS=MI;RI.NO_RETRY_INCREMENT=Rc;RI.REQUEST_HEADER=Se;RI.RETRY_COST=sw;RI.RETRY_MODES=$n;RI.Retry=lt;RI.StandardRetryStrategy=ji;RI.THROTTLING_RETRY_DELAY_BASE=nw;RI.TIMEOUT_RETRY_COST=iw;RI.defaultDelayDecider=_w;RI.defaultRetryDecider=ww;RI.getOmitRetryHeadersPlugin=gI;RI.getRetryAfterHint=eI;RI.getRetryPlugin=EI;RI.isBrowserNetworkError=p_;RI.isClockSkewCorrectedError=a_;RI.isClockSkewError=j_;RI.isNodeJsHttp2TransientError=v_;RI.isRetryableByTrait=Ec;RI.isServerError=Z_;RI.isThrottlingError=ai;RI.isTransientError=pi;RI.omitRetryHeadersMiddleware=dw;RI.omitRetryHeadersMiddlewareOptions=Ew;RI.resolveRetryConfig=AI;RI.retryMiddleware=dI;RI.retryMiddlewareOptions=fw});var bw=Z((hy)=>{var Jn={REQUEST_ID:Symbol.for("_AWS_LAMBDA_REQUEST_ID"),X_RAY_TRACE_ID:Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"),TENANT_ID:Symbol.for("_AWS_LAMBDA_TENANT_ID"),TRACEPARENT:Symbol.for("_AWS_LAMBDA_TRACEPARENT"),TRACESTATE:Symbol.for("_AWS_LAMBDA_TRACESTATE"),BAGGAGE:Symbol.for("_AWS_LAMBDA_BAGGAGE")},Tc=["true","1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA??"");if(!Tc)globalThis.awslambda=globalThis.awslambda||{};class $e{static PROTECTED_KEYS=Jn;isProtectedKey(t){return Object.values(Jn).includes(t)}getRequestId(){return this.get(Jn.REQUEST_ID)??"-"}getXRayTraceId(){return this.get(Jn.X_RAY_TRACE_ID)}getTenantId(){return this.get(Jn.TENANT_ID)}getTraceparent(){return this.get(Jn.TRACEPARENT)}getTracestate(){return this.get(Jn.TRACESTATE)}getBaggage(){return this.get(Jn.BAGGAGE)}}class Rw extends $e{currentContext;getContext(){return this.currentContext}hasContext(){return this.currentContext!==void 0}get(t){return this.currentContext?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);this.currentContext=this.currentContext||{},this.currentContext[t]=n}run(t,n){return this.currentContext=t,n()}}class $c extends $e{als;static async create(){let t=new $c,n=await import("async_hooks");return t.als=new n.AsyncLocalStorage,t}getContext(){return this.als.getStore()}hasContext(){return this.als.getStore()!==void 0}get(t){return this.als.getStore()?.[t]}set(t,n){if(this.isProtectedKey(t))throw Error(`Cannot modify protected Lambda context field: ${String(t)}`);let s=this.als.getStore();if(!s)throw Error("No context available");s[t]=n}run(t,n){return this.als.run(t,n)}}hy.InvokeStore=void 0;(function(t){let n=null;async function s(i){if(!n)n=(async()=>{let e=i===!0||"AWS_LAMBDA_MAX_CONCURRENCY"in process.env?await $c.create():new Rw;if(!Tc&&globalThis.awslambda?.InvokeStore)return globalThis.awslambda.InvokeStore;else if(!Tc&&globalThis.awslambda)return globalThis.awslambda.InvokeStore=e,e;else return e})();return n}t.getInstanceAsync=s,t._testing=process.env.AWS_LAMBDA_BENCHMARK_MODE==="1"?{reset:()=>{if(n=null,globalThis.awslambda?.InvokeStore)delete globalThis.awslambda.InvokeStore;globalThis.awslambda={InvokeStore:void 0}}}:void 0})(hy.InvokeStore||(hy.InvokeStore={}));hy.InvokeStoreBase=$e});var kn=Z((Iy)=>{var{getSmithyContext:Uc}=nn();Iy.getSmithyContext=Uc;var{HttpRequest:Lc}=Ut(),{requestBuilder:ly}=Ut();Iy.requestBuilder=ly;var{HttpApiKeyAuthLocation:Tw}=rs(),_y=(t,n)=>{if(!n||n.length===0)return t;let s=[];for(let i of n)for(let r of t)if(r.schemeId.split("#")[1]===i)s.push(r);for(let i of t)if(!s.find(({schemeId:r})=>r===i.schemeId))s.push(i);return s};function wy(t){let n=new Map;for(let s of t)n.set(s.schemeId,s);return n}var Ic=(t,n)=>(s,i)=>async(r)=>{let e=t.httpAuthSchemeProvider(await n.httpAuthSchemeParametersProvider(t,i,r.input)),f=t.authSchemePreference?await t.authSchemePreference():[],o=_y(e,f),c=wy(t.httpAuthSchemes),h=Uc(i),u=[];for(let l of o){let _=c.get(l.schemeId);if(!_){u.push(`HttpAuthScheme \`${l.schemeId}\` was not enabled for this service.`);continue}let w=_.identityProvider(await n.identityProviderConfigProvider(t));if(!w){u.push(`HttpAuthScheme \`${l.schemeId}\` did not have an IdentityProvider configured.`);continue}let{identityProperties:A={},signingProperties:M={}}=l.propertiesExtractor?.(t,i)||{};l.identityProperties=Object.assign(l.identityProperties||{},A),l.signingProperties=Object.assign(l.signingProperties||{},M),h.selectedHttpAuthScheme={httpAuthOption:l,identity:await w(l.identityProperties),signer:_.signer};break}if(!h.selectedHttpAuthScheme)throw Error(u.join(`
23
+ `));return s(r)},Sw={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},Ay=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(i)=>{i.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),Sw)}}),$w={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"serializerMiddleware"},My=(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s})=>({applyToStack:(i)=>{i.addRelativeTo(Ic(t,{httpAuthSchemeParametersProvider:n,identityProviderConfigProvider:s}),$w)}}),gy=(t)=>(n)=>{throw n},dy=(t,n)=>{},Uw=(t)=>(n,s)=>async(i)=>{if(!Lc.isInstance(i.request))return n(i);let e=Uc(s).selectedHttpAuthScheme;if(!e)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:f={}},identity:o,signer:c}=e,h=await n({...i,request:await c.sign(i.request,o,f)}).catch((c.errorHandler||gy)(f));return(c.successHandler||dy)(h.response,f),h},Lw={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},Ey=(t)=>({applyToStack:(n)=>{n.addRelativeTo(Uw(),Lw)}}),Ry=(t)=>{if(typeof t==="function")return t;let n=Promise.resolve(t);return()=>n},by=async(t,n,s,i=(e)=>e,...r)=>{let e=new t(s);return e=i(e)??e,await n.send(e,...r)};function Ty(t,n,s,i,r){return async function*(f,o,...c){let h=o,u=f.startingToken??h[s],l=!0,_;while(l){if(h[s]=u,r)h[r]=h[r]??f.pageSize;if(f.client instanceof t)_=await by(n,f.client,o,f.withCommand,...c);else throw Error(`Invalid client, expected instance of ${t.name}`);yield _;let w=u;u=Sy(_,i),l=!!(u&&(!f.stopOnSameToken||u!==w))}return}}var Sy=(t,n)=>{let s=t,i=n.split(".");for(let r of i){if(!s||typeof s!=="object")return;s=s[r]}return s};function $y(t,n,s){if(!t.__smithy_context)t.__smithy_context={features:{}};else if(!t.__smithy_context.features)t.__smithy_context.features={};t.__smithy_context.features[n]=s}class Iw{authSchemes=new Map;constructor(t){for(let n in t){let s=t[n];if(s!==void 0)this.authSchemes.set(n,s)}}getIdentityProvider(t){return this.authSchemes.get(t)}}class yw{async sign(t,n,s){if(!s)throw Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing");if(!s.name)throw Error("request could not be signed with `apiKey` since the `name` signer property is missing");if(!s.in)throw Error("request could not be signed with `apiKey` since the `in` signer property is missing");if(!n.apiKey)throw Error("request could not be signed with `apiKey` since the `apiKey` is not defined");let i=Lc.clone(t);if(s.in===Tw.QUERY)i.query[s.name]=n.apiKey;else if(s.in===Tw.HEADER)i.headers[s.name]=s.scheme?`${s.scheme} ${n.apiKey}`:n.apiKey;else throw Error("request can only be signed with `apiKey` locations `query` or `header`, but found: `"+s.in+"`");return i}}class Ow{async sign(t,n,s){let i=Lc.clone(t);if(!n.token)throw Error("request could not be signed with `token` since the `token` is not defined");return i.headers.Authorization=`Bearer ${n.token}`,i}}class Gw{async sign(t,n,s){return t}}var Bw=(t)=>function(s){return Hw(s)&&s.expiration.getTime()-Date.now()<t},Fw=300000,Uy=Bw(Fw),Hw=(t)=>t.expiration!==void 0,Ly=(t,n,s)=>{if(t===void 0)return;let i=typeof t!=="function"?async()=>Promise.resolve(t):t,r,e,f,o=!1,c=async(h)=>{if(!e)e=i(h);try{r=await e,f=!0,o=!1}finally{e=void 0}return r};if(n===void 0)return async(h)=>{if(!f||h?.forceRefresh)r=await c(h);return r};return async(h)=>{if(!f||h?.forceRefresh)r=await c(h);if(o)return r;if(!s(r))return o=!0,r;if(n(r))return await c(h),r;return r}};Iy.DefaultIdentityProviderConfig=Iw;Iy.EXPIRATION_MS=Fw;Iy.HttpApiKeyAuthSigner=yw;Iy.HttpBearerAuthSigner=Ow;Iy.NoAuthSigner=Gw;Iy.createIsIdentityExpiredFunction=Bw;Iy.createPaginator=Ty;Iy.doesIdentityRequireRefresh=Hw;Iy.getHttpAuthSchemeEndpointRuleSetPlugin=Ay;Iy.getHttpAuthSchemePlugin=My;Iy.getHttpSigningPlugin=Ey;Iy.httpAuthSchemeEndpointRuleSetMiddlewareOptions=Sw;Iy.httpAuthSchemeMiddleware=Ic;Iy.httpAuthSchemeMiddlewareOptions=$w;Iy.httpSigningMiddleware=Uw;Iy.httpSigningMiddlewareOptions=Lw;Iy.isIdentityExpired=Uy;Iy.memoizeIdentityProvider=Ly;Iy.normalizeProvider=Ry;Iy.setFeature=$y});var Pw=Z((tr,yc)=>{(function(t,n){typeof tr=="object"&&typeof yc=="object"?yc.exports=n():typeof define=="function"&&define.amd?define([],n):typeof tr=="object"?tr.bowser=n():t.bowser=n()})(tr,function(){return function(t){var n={};function s(i){if(n[i])return n[i].exports;var r=n[i]={i,l:!1,exports:{}};return t[i].call(r.exports,r,r.exports,s),r.l=!0,r.exports}return s.m=t,s.c=n,s.d=function(i,r,e){s.o(i,r)||Object.defineProperty(i,r,{enumerable:!0,get:e})},s.r=function(i){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(i,"__esModule",{value:!0})},s.t=function(i,r){if(1&r&&(i=s(i)),8&r)return i;if(4&r&&typeof i=="object"&&i&&i.__esModule)return i;var e=Object.create(null);if(s.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:i}),2&r&&typeof i!="string")for(var f in i)s.d(e,f,function(o){return i[o]}.bind(null,f));return e},s.n=function(i){var r=i&&i.__esModule?function(){return i.default}:function(){return i};return s.d(r,"a",r),r},s.o=function(i,r){return Object.prototype.hasOwnProperty.call(i,r)},s.p="",s(s.s=90)}({17:function(t,n,s){n.__esModule=!0,n.default=void 0;var i=s(18),r=function(){function e(){}return e.getFirstMatch=function(f,o){var c=o.match(f);return c&&c.length>0&&c[1]||""},e.getSecondMatch=function(f,o){var c=o.match(f);return c&&c.length>1&&c[2]||""},e.matchAndReturnConst=function(f,o,c){if(f.test(o))return c},e.getWindowsVersionName=function(f){switch(f){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e.getMacOSVersionName=function(f){var o=f.split(".").splice(0,2).map(function(u){return parseInt(u,10)||0});o.push(0);var c=o[0],h=o[1];if(c===10)switch(h){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}switch(c){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}},e.getAndroidVersionName=function(f){var o=f.split(".").splice(0,2).map(function(c){return parseInt(c,10)||0});if(o.push(0),!(o[0]===1&&o[1]<5))return o[0]===1&&o[1]<6?"Cupcake":o[0]===1&&o[1]>=6?"Donut":o[0]===2&&o[1]<2?"Eclair":o[0]===2&&o[1]===2?"Froyo":o[0]===2&&o[1]>2?"Gingerbread":o[0]===3?"Honeycomb":o[0]===4&&o[1]<1?"Ice Cream Sandwich":o[0]===4&&o[1]<4?"Jelly Bean":o[0]===4&&o[1]>=4?"KitKat":o[0]===5?"Lollipop":o[0]===6?"Marshmallow":o[0]===7?"Nougat":o[0]===8?"Oreo":o[0]===9?"Pie":void 0},e.getVersionPrecision=function(f){return f.split(".").length},e.compareVersions=function(f,o,c){c===void 0&&(c=!1);var h=e.getVersionPrecision(f),u=e.getVersionPrecision(o),l=Math.max(h,u),_=0,w=e.map([f,o],function(A){var M=l-e.getVersionPrecision(A),d=A+Array(M+1).join(".0");return e.map(d.split("."),function(E){return Array(20-E.length).join("0")+E}).reverse()});for(c&&(_=l-Math.min(h,u)),l-=1;l>=_;){if(w[0][l]>w[1][l])return 1;if(w[0][l]===w[1][l]){if(l===_)return 0;l-=1}else if(w[0][l]<w[1][l])return-1}},e.map=function(f,o){var c,h=[];if(Array.prototype.map)return Array.prototype.map.call(f,o);for(c=0;c<f.length;c+=1)h.push(o(f[c]));return h},e.find=function(f,o){var c,h;if(Array.prototype.find)return Array.prototype.find.call(f,o);for(c=0,h=f.length;c<h;c+=1){var u=f[c];if(o(u,c))return u}},e.assign=function(f){for(var o,c,h=f,u=arguments.length,l=Array(u>1?u-1:0),_=1;_<u;_++)l[_-1]=arguments[_];if(Object.assign)return Object.assign.apply(Object,[f].concat(l));var w=function(){var A=l[o];typeof A=="object"&&A!==null&&Object.keys(A).forEach(function(M){h[M]=A[M]})};for(o=0,c=l.length;o<c;o+=1)w();return f},e.getBrowserAlias=function(f){return i.BROWSER_ALIASES_MAP[f]},e.getBrowserTypeByAlias=function(f){return i.BROWSER_MAP[f]||""},e}();n.default=r,t.exports=n.default},18:function(t,n,s){n.__esModule=!0,n.ENGINE_MAP=n.OS_MAP=n.PLATFORMS_MAP=n.BROWSER_MAP=n.BROWSER_ALIASES_MAP=void 0,n.BROWSER_ALIASES_MAP={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},n.BROWSER_MAP={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},n.PLATFORMS_MAP={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},n.OS_MAP={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},n.ENGINE_MAP={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"}},90:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(91))&&i.__esModule?i:{default:i},e=s(18);function f(c,h){for(var u=0;u<h.length;u++){var l=h[u];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(c,l.key,l)}}var o=function(){function c(){}var h,u,l;return c.getParser=function(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),typeof _!="string")throw Error("UserAgent should be a string");return new r.default(_,w,A)},c.parse=function(_,w){return w===void 0&&(w=null),new r.default(_,w).getResult()},h=c,l=[{key:"BROWSER_MAP",get:function(){return e.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return e.ENGINE_MAP}},{key:"OS_MAP",get:function(){return e.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return e.PLATFORMS_MAP}}],(u=null)&&f(h.prototype,u),l&&f(h,l),c}();n.default=o,t.exports=n.default},91:function(t,n,s){n.__esModule=!0,n.default=void 0;var i=c(s(92)),r=c(s(93)),e=c(s(94)),f=c(s(95)),o=c(s(17));function c(u){return u&&u.__esModule?u:{default:u}}var h=function(){function u(_,w,A){if(w===void 0&&(w=!1),A===void 0&&(A=null),_==null||_==="")throw Error("UserAgent parameter can't be empty");this._ua=_;var M=!1;typeof w=="boolean"?(M=w,this._hints=A):this._hints=w!=null&&typeof w=="object"?w:null,this.parsedResult={},M!==!0&&this.parse()}var l=u.prototype;return l.getHints=function(){return this._hints},l.hasBrand=function(_){if(!this._hints||!Array.isArray(this._hints.brands))return!1;var w=_.toLowerCase();return this._hints.brands.some(function(A){return A.brand&&A.brand.toLowerCase()===w})},l.getBrandVersion=function(_){if(this._hints&&Array.isArray(this._hints.brands)){var w=_.toLowerCase(),A=this._hints.brands.find(function(M){return M.brand&&M.brand.toLowerCase()===w});return A?A.version:void 0}},l.getUA=function(){return this._ua},l.test=function(_){return _.test(this._ua)},l.parseBrowser=function(){var _=this;this.parsedResult.browser={};var w=o.default.find(i.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.browser=w.describe(this.getUA(),this)),this.parsedResult.browser},l.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},l.getBrowserName=function(_){return _?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},l.getBrowserVersion=function(){return this.getBrowser().version},l.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},l.parseOS=function(){var _=this;this.parsedResult.os={};var w=o.default.find(r.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.os=w.describe(this.getUA())),this.parsedResult.os},l.getOSName=function(_){var w=this.getOS().name;return _?String(w).toLowerCase()||"":w||""},l.getOSVersion=function(){return this.getOS().version},l.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},l.getPlatformType=function(_){_===void 0&&(_=!1);var w=this.getPlatform().type;return _?String(w).toLowerCase()||"":w||""},l.parsePlatform=function(){var _=this;this.parsedResult.platform={};var w=o.default.find(e.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.platform=w.describe(this.getUA())),this.parsedResult.platform},l.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},l.getEngineName=function(_){return _?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},l.parseEngine=function(){var _=this;this.parsedResult.engine={};var w=o.default.find(f.default,function(A){if(typeof A.test=="function")return A.test(_);if(Array.isArray(A.test))return A.test.some(function(M){return _.test(M)});throw Error("Browser's test function is not valid")});return w&&(this.parsedResult.engine=w.describe(this.getUA())),this.parsedResult.engine},l.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},l.getResult=function(){return o.default.assign({},this.parsedResult)},l.satisfies=function(_){var w=this,A={},M=0,d={},E=0;if(Object.keys(_).forEach(function(J){var G=_[J];typeof G=="string"?(d[J]=G,E+=1):typeof G=="object"&&(A[J]=G,M+=1)}),M>0){var T=Object.keys(A),U=o.default.find(T,function(J){return w.isOS(J)});if(U){var S=this.satisfies(A[U]);if(S!==void 0)return S}var y=o.default.find(T,function(J){return w.isPlatform(J)});if(y){var D=this.satisfies(A[y]);if(D!==void 0)return D}}if(E>0){var q=Object.keys(d),tt=o.default.find(q,function(J){return w.isBrowser(J,!0)});if(tt!==void 0)return this.compareVersion(d[tt])}},l.isBrowser=function(_,w){w===void 0&&(w=!1);var A=this.getBrowserName().toLowerCase(),M=_.toLowerCase(),d=o.default.getBrowserTypeByAlias(M);return w&&d&&(M=d.toLowerCase()),M===A},l.compareVersion=function(_){var w=[0],A=_,M=!1,d=this.getBrowserVersion();if(typeof d=="string")return _[0]===">"||_[0]==="<"?(A=_.substr(1),_[1]==="="?(M=!0,A=_.substr(2)):w=[],_[0]===">"?w.push(1):w.push(-1)):_[0]==="="?A=_.substr(1):_[0]==="~"&&(M=!0,A=_.substr(1)),w.indexOf(o.default.compareVersions(d,A,M))>-1},l.isOS=function(_){return this.getOSName(!0)===String(_).toLowerCase()},l.isPlatform=function(_){return this.getPlatformType(!0)===String(_).toLowerCase()},l.isEngine=function(_){return this.getEngineName(!0)===String(_).toLowerCase()},l.is=function(_,w){return w===void 0&&(w=!1),this.isBrowser(_,w)||this.isOS(_)||this.isPlatform(_)},l.some=function(_){var w=this;return _===void 0&&(_=[]),_.some(function(A){return w.is(A)})},u}();n.default=h,t.exports=n.default},92:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=/version\/(\d+(\.?_?\d+)+)/i,f=[{test:[/gptbot/i],describe:function(o){var c={name:"GPTBot"},h=r.default.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chatgpt-user/i],describe:function(o){var c={name:"ChatGPT-User"},h=r.default.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/oai-searchbot/i],describe:function(o){var c={name:"OAI-SearchBot"},h=r.default.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(o){var c={name:"ClaudeBot"},h=r.default.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(o){var c={name:"Omgilibot"},h=r.default.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/diffbot/i],describe:function(o){var c={name:"Diffbot"},h=r.default.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexitybot/i],describe:function(o){var c={name:"PerplexityBot"},h=r.default.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/perplexity-user/i],describe:function(o){var c={name:"Perplexity-User"},h=r.default.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/youbot/i],describe:function(o){var c={name:"YouBot"},h=r.default.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-webindexer/i],describe:function(o){var c={name:"Meta-WebIndexer"},h=r.default.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalads/i],describe:function(o){var c={name:"Meta-ExternalAds"},h=r.default.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalagent/i],describe:function(o){var c={name:"Meta-ExternalAgent"},h=r.default.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/meta-externalfetcher/i],describe:function(o){var c={name:"Meta-ExternalFetcher"},h=r.default.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/googlebot/i],describe:function(o){var c={name:"Googlebot"},h=r.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/linespider/i],describe:function(o){var c={name:"Linespider"},h=r.default.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/amazonbot/i],describe:function(o){var c={name:"AmazonBot"},h=r.default.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/bingbot/i],describe:function(o){var c={name:"BingCrawler"},h=r.default.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/baiduspider/i],describe:function(o){var c={name:"BaiduSpider"},h=r.default.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/duckduckbot/i],describe:function(o){var c={name:"DuckDuckBot"},h=r.default.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ia_archiver/i],describe:function(o){var c={name:"InternetArchiveCrawler"},h=r.default.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(o){var c={name:"SlackBot"},h=r.default.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yahoo!?[\s/]*slurp/i],describe:function(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe:function(){return{name:"PingdomBot"}}},{test:[/opera/i],describe:function(o){var c={name:"Opera"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opr\/|opios/i],describe:function(o){var c={name:"Opera"},h=r.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/SamsungBrowser/i],describe:function(o){var c={name:"Samsung Internet for Android"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Whale/i],describe:function(o){var c={name:"NAVER Whale Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/PaleMoon/i],describe:function(o){var c={name:"Pale Moon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/MZBrowser/i],describe:function(o){var c={name:"MZ Browser"},h=r.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/focus/i],describe:function(o){var c={name:"Focus"},h=r.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/swing/i],describe:function(o){var c={name:"Swing"},h=r.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/coast/i],describe:function(o){var c={name:"Opera Coast"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(o){var c={name:"Opera Touch"},h=r.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/yabrowser/i],describe:function(o){var c={name:"Yandex Browser"},h=r.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/ucbrowser/i],describe:function(o){var c={name:"UC Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/Maxthon|mxios/i],describe:function(o){var c={name:"Maxthon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/epiphany/i],describe:function(o){var c={name:"Epiphany"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/puffin/i],describe:function(o){var c={name:"Puffin"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sleipnir/i],describe:function(o){var c={name:"Sleipnir"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/k-meleon/i],describe:function(o){var c={name:"K-Meleon"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/micromessenger/i],describe:function(o){var c={name:"WeChat"},h=r.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qqbrowser/i],describe:function(o){var c={name:/qqbrowserlite/i.test(o)?"QQ Browser Lite":"QQ Browser"},h=r.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/msie|trident/i],describe:function(o){var c={name:"Internet Explorer"},h=r.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/\sedg\//i],describe:function(o){var c={name:"Microsoft Edge"},h=r.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/edg([ea]|ios)/i],describe:function(o){var c={name:"Microsoft Edge"},h=r.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/vivaldi/i],describe:function(o){var c={name:"Vivaldi"},h=r.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/seamonkey/i],describe:function(o){var c={name:"SeaMonkey"},h=r.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sailfish/i],describe:function(o){var c={name:"Sailfish"},h=r.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,o);return h&&(c.version=h),c}},{test:[/silk/i],describe:function(o){var c={name:"Amazon Silk"},h=r.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/phantom/i],describe:function(o){var c={name:"PhantomJS"},h=r.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/slimerjs/i],describe:function(o){var c={name:"SlimerJS"},h=r.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c={name:"BlackBerry"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c={name:"WebOS Browser"},h=r.default.getFirstMatch(e,o)||r.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/bada/i],describe:function(o){var c={name:"Bada"},h=r.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/tizen/i],describe:function(o){var c={name:"Tizen"},h=r.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/qupzilla/i],describe:function(o){var c={name:"QupZilla"},h=r.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/librewolf/i],describe:function(o){var c={name:"LibreWolf"},h=r.default.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/firefox|iceweasel|fxios/i],describe:function(o){var c={name:"Firefox"},h=r.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/electron/i],describe:function(o){var c={name:"Electron"},h=r.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe:function(o){var c={name:"Sogou Browser"},h=r.default.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,o),u=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o),l=r.default.getFirstMatch(/se ([\d.]+)x/i,o),_=h||u||l;return _&&(c.version=_),c}},{test:[/MiuiBrowser/i],describe:function(o){var c={name:"Miui"},h=r.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return!!o.hasBrand("DuckDuckGo")||o.test(/\sDdg\/[\d.]+$/i)},describe:function(o,c){var h={name:"DuckDuckGo"};if(c){var u=c.getBrandVersion("DuckDuckGo");if(u)return h.version=u,h}var l=r.default.getFirstMatch(/\sDdg\/([\d.]+)$/i,o);return l&&(h.version=l),h}},{test:function(o){return o.hasBrand("Brave")},describe:function(o,c){var h={name:"Brave"};if(c){var u=c.getBrandVersion("Brave");if(u)return h.version=u,h}return h}},{test:[/chromium/i],describe:function(o){var c={name:"Chromium"},h=r.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,o)||r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/chrome|crios|crmo/i],describe:function(o){var c={name:"Chrome"},h=r.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/GSA/i],describe:function(o){var c={name:"Google Search"},h=r.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c={name:"Android Browser"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/playstation 4/i],describe:function(o){var c={name:"PlayStation 4"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/safari|applewebkit/i],describe:function(o){var c={name:"Safari"},h=r.default.getFirstMatch(e,o);return h&&(c.version=h),c}},{test:[/.*/i],describe:function(o){var c=o.search("\\(")!==-1?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:r.default.getFirstMatch(c,o),version:r.default.getSecondMatch(c,o)}}}];n.default=f,t.exports=n.default},93:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(18),f=[{test:[/Roku\/DVP/],describe:function(o){var c=r.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,o);return{name:e.OS_MAP.Roku,version:c}}},{test:[/windows phone/i],describe:function(o){var c=r.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.WindowsPhone,version:c}}},{test:[/windows /i],describe:function(o){var c=r.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,o),h=r.default.getWindowsVersionName(c);return{name:e.OS_MAP.Windows,version:c,versionName:h}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(o){var c={name:e.OS_MAP.iOS},h=r.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,o);return h&&(c.version=h),c}},{test:[/macintosh/i],describe:function(o){var c=r.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,o).replace(/[_\s]/g,"."),h=r.default.getMacOSVersionName(c),u={name:e.OS_MAP.MacOS,version:c};return h&&(u.versionName=h),u}},{test:[/(ipod|iphone|ipad)/i],describe:function(o){var c=r.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,o).replace(/[_\s]/g,".");return{name:e.OS_MAP.iOS,version:c}}},{test:[/OpenHarmony/i],describe:function(o){var c=r.default.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.HarmonyOS,version:c}}},{test:function(o){var c=!o.test(/like android/i),h=o.test(/android/i);return c&&h},describe:function(o){var c=r.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,o),h=r.default.getAndroidVersionName(c),u={name:e.OS_MAP.Android,version:c};return h&&(u.versionName=h),u}},{test:[/(web|hpw)[o0]s/i],describe:function(o){var c=r.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,o),h={name:e.OS_MAP.WebOS};return c&&c.length&&(h.version=c),h}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(o){var c=r.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,o)||r.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,o)||r.default.getFirstMatch(/\bbb(\d+)/i,o);return{name:e.OS_MAP.BlackBerry,version:c}}},{test:[/bada/i],describe:function(o){var c=r.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Bada,version:c}}},{test:[/tizen/i],describe:function(o){var c=r.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.Tizen,version:c}}},{test:[/linux/i],describe:function(){return{name:e.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:e.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(o){var c=r.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,o);return{name:e.OS_MAP.PlayStation4,version:c}}}];n.default=f,t.exports=n.default},94:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(18),f=[{test:[/googlebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Google"}}},{test:[/linespider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe:function(){return{type:e.PLATFORMS_MAP.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe:function(o){var c=r.default.getFirstMatch(/(can-l01)/i,o)&&"Nova",h={type:e.PLATFORMS_MAP.mobile,vendor:"Huawei"};return c&&(h.model=c),h}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){var c=o.test(/ipod|iphone/i),h=o.test(/like (ipod|iphone)/i);return c&&!h},describe:function(o){var c=r.default.getFirstMatch(/(ipod|iphone)/i,o);return{type:e.PLATFORMS_MAP.mobile,vendor:"Apple",model:c}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe:function(o){var c=r.default.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,o),h={type:e.PLATFORMS_MAP.mobile,vendor:"Nokia"};return c&&(h.model=c),h}},{test:[/[^-]mobi/i],describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName(!0)==="blackberry"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(o){return o.getBrowserName(!0)==="bada"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:function(o){return o.getBrowserName()==="windows phone"},describe:function(){return{type:e.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(o){var c=Number(String(o.getOSVersion()).split(".")[0]);return o.getOSName(!0)==="android"&&c>=3},describe:function(){return{type:e.PLATFORMS_MAP.tablet}}},{test:function(o){return o.getOSName(!0)==="android"},describe:function(){return{type:e.PLATFORMS_MAP.mobile}}},{test:[/smart-?tv|smarttv/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:[/netcast/i],describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="macos"},describe:function(){return{type:e.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(o){return o.getOSName(!0)==="windows"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="linux"},describe:function(){return{type:e.PLATFORMS_MAP.desktop}}},{test:function(o){return o.getOSName(!0)==="playstation 4"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}},{test:function(o){return o.getOSName(!0)==="roku"},describe:function(){return{type:e.PLATFORMS_MAP.tv}}}];n.default=f,t.exports=n.default},95:function(t,n,s){n.__esModule=!0,n.default=void 0;var i,r=(i=s(17))&&i.__esModule?i:{default:i},e=s(18),f=[{test:function(o){return o.getBrowserName(!0)==="microsoft edge"},describe:function(o){if(/\sedg\//i.test(o))return{name:e.ENGINE_MAP.Blink};var c=r.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,o);return{name:e.ENGINE_MAP.EdgeHTML,version:c}}},{test:[/trident/i],describe:function(o){var c={name:e.ENGINE_MAP.Trident},h=r.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){return o.test(/presto/i)},describe:function(o){var c={name:e.ENGINE_MAP.Presto},h=r.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:function(o){var c=o.test(/gecko/i),h=o.test(/like gecko/i);return c&&!h},describe:function(o){var c={name:e.ENGINE_MAP.Gecko},h=r.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:e.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(o){var c={name:e.ENGINE_MAP.WebKit},h=r.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,o);return h&&(c.version=h),c}}];n.default=f,t.exports=n.default}})})});var xt=Z((XO)=>{var{Retry:jy,RETRY_MODES:Nw}=vi(),{HttpRequest:Pc,parseUrl:ay}=Ut(),{InvokeStore:Ww}=bw(),{normalizeProvider:py}=kn(),{platform:Zy,release:vy}=nt("os"),{versions:Oc,env:Dw}=nt("process"),{isValidHostLabel:tO,isIpAddress:kw,customEndpointFunctions:nO}=fs(),{EndpointError:sO,resolveEndpoint:iO}=fs();XO.EndpointError=sO;XO.isIpAddress=kw;XO.resolveEndpoint=iO;var{loadConfig:rO,NODE_REGION_CONFIG_OPTIONS:zw,NODE_REGION_CONFIG_FILE_OPTIONS:Xw}=St(),{REGION_ENV_NAME:eO,REGION_INI_NAME:oO,resolveRegionConfig:fO}=St();XO.NODE_REGION_CONFIG_FILE_OPTIONS=Xw;XO.NODE_REGION_CONFIG_OPTIONS=zw;XO.REGION_ENV_NAME=eO;XO.REGION_INI_NAME=oO;XO.resolveRegionConfig=fO;var Le={warningEmitted:!1},cO=(t)=>{if(t&&!Le.warningEmitted){if(process.env.AWS_SDK_JS_NODE_VERSION_SUPPORT_WARNING_DISABLED==="true"){Le.warningEmitted=!0;return}let n=parseInt(t.substring(1,t.indexOf("."))),s=22;if(n<s)Le.warningEmitted=!0,process.emitWarning(`NodeVersionSupportWarning: The AWS SDK for JavaScript (v3)
24
24
  versions published after the first week of January 2027
25
25
  will require node >=${s}. You are running node ${t}.
26
26
 
27
27
  To continue receiving updates to AWS services, bug fixes,
28
28
  and security updates please upgrade to node >=${s}.
29
29
 
30
- More information can be found at: https://a.co/c895JFp`)}},hy=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},uy={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},_y=(t)=>({applyToStack:(n)=>{n.add(hy(),uy)}});function ly(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}jO.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function fn(t,n,s){if(!t.__aws_sdk_context)t.__aws_sdk_context={features:{}};else if(!t.__aws_sdk_context.features)t.__aws_sdk_context.features={};t.__aws_sdk_context.features[n]=s}function wy(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function Ay(t){return t}var xw=(t)=>(n)=>async(s)=>{if(!Pc.isInstance(s.request))return n(s);let{request:r}=s,{handlerProtocol:i=""}=t.requestHandler.metadata||{};if(i.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 e=r.hostname;if(r.port!=null)e+=`:${r.port}`;r.headers.host=e}return n(s)},qw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},My=(t)=>({applyToStack:(n)=>{n.add(xw(t),qw)}}),Cw=()=>(t,n)=>async(s)=>{try{let r=await t(s),{clientName:i,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,_=h??n.outputFilterSensitiveLog,{$metadata:l,...w}=r.output;return f?.info?.({clientName:i,commandName:e,input:u(s.input),output:_(w),metadata:l}),r}catch(r){let{clientName:i,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:i,commandName:e,input:h(s.input),error:r,metadata:r.$metadata}),r}},Kw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},gy=(t)=>({applyToStack:(n)=>{n.add(Cw(),Kw)}}),Vw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},Ey="AWS_LAMBDA_FUNCTION_NAME",dy="_X_AMZN_TRACE_ID",Gc="X-Amzn-Trace-Id",Hc="traceparent",jw="tracestate",aw="baggage",pw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Pc.isInstance(s))return t(n);let r;{let i=Object.keys(s.headers??{}).find((e)=>e.toLowerCase()===Gc.toLowerCase())??Gc;if(!s.headers.hasOwnProperty(i)){let e=process.env[Ey],f=process.env[dy];r??=await Ww.getInstanceAsync();let c=r?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(e)&&h(c))s.headers[Gc]=c}}if(Ry(s.headers),!s.headers[Hc]){let e=(r??=await Ww.getInstanceAsync())?.getTraceparent?.();if(e){s.headers[Hc]=e;let f=r?.getTracestate?.();if(f)s.headers[jw]=f;let o=r?.getBaggage?.();if(o)s.headers[aw]=o}}return t(n)};function Ry(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Hc||s===jw||s===aw))t[s]=t[n],delete t[n]}}var by=(t)=>({applyToStack:(n)=>{n.add(pw(),Vw)}}),Nc=void 0;function Ty(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function Sy(t){let n=pO(t.userAgentAppId??Nc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let r=await n();if(!Ty(r)){let i=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof r!=="string")i?.warn("userAgentAppId must be a string or undefined.");else if(r.length>50)i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return r}})}var Zw={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"},vw=Zw,tA="",nA=(t)=>{let{partitions:n}=vw;for(let r of n){let{regions:i,outputs:e}=r;for(let[f,o]of Object.entries(i))if(f===t)return{...e,...o}}for(let r of n){let{regionRegex:i,outputs:e}=r;if(new RegExp(i).test(t))return{...e}}let s=n.find((r)=>r.id==="aws");if(!s)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...s.outputs}},sA=(t,n="")=>{vw=t,tA=n},$y=()=>{sA(Zw,"")},rA=()=>tA,Uy=/\d{12}\.ddb/;async function Ly(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")fn(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let e=await n.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case Nw.ADAPTIVE:fn(t,"RETRY_MODE_ADAPTIVE","F");break;case Nw.STANDARD:fn(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let e=t.endpointV2;if(String(e?.url?.hostname).match(Uy))fn(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":fn(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":fn(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":fn(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let i=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){let e=i;if(e.accountId)fn(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))fn(t,f,o)}}var Yw="user-agent",Bc="x-amz-user-agent",mw=" ",Fc="/",Iy=/[^!$%&'*+\-.^_`|~\w]/g,Oy=/[^!$%&'*+\-.^_`|~\w#]/g,Qw="-",yy=1024;function Gy(t){let n="";for(let s in t){let r=t[s];if(n.length+r.length+1<=yy){if(n.length)n+=","+r;else n+=r;continue}break}return n}var iA=(t)=>(n,s)=>async(r)=>{let{request:i}=r;if(!Pc.isInstance(i))return n(r);let{headers:e}=i,f=s?.userAgent?.map(Ue)||[],o=(await t.defaultUserAgentProvider()).map(Ue);await Ly(s,t,r);let c=s;o.push(`m/${Gy(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ue)||[],u=await t.userAgentAppId();if(u)o.push(Ue(["app",`${u}`]));let _=rA(),l=(_?[_]:[]).concat([...o,...f,...h]).join(mw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(mw);if(t.runtime!=="browser"){if(w)e[Bc]=e[Bc]?`${e[Yw]} ${w}`:w;e[Yw]=l}else e[Bc]=l;return n({...r,request:i})},Ue=(t)=>{let n=t[0].split(Fc).map((f)=>f.replace(Iy,Qw)).join(Fc),s=t[1]?.replace(Oy,Qw),r=n.indexOf(Fc),i=n.substring(0,r),e=n.substring(r+1);if(i==="api")e=e.toLowerCase();return[i,e,s].filter((f)=>f&&f.length>0).reduce((f,o,c)=>{switch(c){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},eA={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},By=(t)=>({applyToStack:(n)=>{n.add(iA(t),eA)}}),Fy=()=>{let t=["deno","bun","llrt"];for(let n of t)if(yc[n])return[`md/${n}`,yc[n]];return["md/nodejs",yc.node]},oA={isCrtAvailable:!1},Hy=()=>{if(oA.isCrtAvailable)return["md/crt-avail"];return null},fA=({serviceId:t,clientVersion:n})=>{let s=Fy();return async(r)=>{let i=[["aws-sdk-js",n],["ua","2.1"],[`os/${ZO()}`,vO()],["lang/js"],s],e=Hy();if(e)i.push(e);if(t)i.push([`api/${t}`,n]);if(Dw.AWS_EXECUTION_ENV)i.push([`exec-env/${Dw.AWS_EXECUTION_ENV}`]);let f=await r?.userAgentAppId?.();return f?[...i,[`app/${f}`]]:[...i]}},Py=fA,cA="AWS_SDK_UA_APP_ID",hA="sdk_ua_app_id",Ny="sdk-ua-app-id",Wy={environmentVariableSelector:(t)=>t[cA],configFileSelector:(t)=>t[hA]??t[Ny],default:Nc},Dy=({serviceId:t,clientVersion:n})=>async(s)=>{let r=Pw(),i=r.parse??r.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?i(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},Yy={os(t){if(/iPhone|iPad|iPod/.test(t))return"iOS";if(/Macintosh|Mac OS X/.test(t))return"macOS";if(/Windows NT/.test(t))return"Windows";if(/Android/.test(t))return"Android";if(/Linux/.test(t))return"Linux";return},browser(t){if(/EdgiOS|EdgA|Edg\//.test(t))return"Microsoft Edge";if(/Firefox\//.test(t))return"Firefox";if(/Chrome\//.test(t))return"Chrome";if(/Safari\//.test(t))return"Safari";return}},Wc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!Wc(s))return!1;return!0}if(!ty(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(kw(t))return!1;return!0},Jw=":",my="/",uA=(t)=>{let n=t.split(Jw);if(n.length<6)return null;let[s,r,i,e,f,...o]=n;if(s!=="arn"||r===""||i===""||o.join(Jw)==="")return null;let c=o.map((h)=>h.split(my)).flat();return{partition:r,service:i,region:e,accountId:f,resourceId:c}},_A={isVirtualHostableS3Bucket:Wc,parseArn:uA,partition:nA};ny.aws=_A;var Qy=(t)=>{if(typeof t.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{return lA(t.endpointProvider({Region:typeof t.region==="function"?await t.region():t.region,UseDualStack:typeof t.useDualstackEndpoint==="function"?await t.useDualstackEndpoint():t.useDualstackEndpoint,UseFIPS:typeof t.useFipsEndpoint==="function"?await t.useFipsEndpoint():t.useFipsEndpoint,Endpoint:void 0},{logger:t.logger}))};return t},lA=(t)=>aO(t.url);function Jy(t={}){return iy({...Xw,async default(){if(!wA.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...zw,...t})}var wA={silence:!1},ky=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},Xy=(t)=>{return{region:t.region()}};zy.DEFAULT_UA_APP_ID=Nc;zy.NODE_APP_ID_CONFIG_OPTIONS=Wy;zy.UA_APP_ID_ENV_NAME=cA;zy.UA_APP_ID_INI_NAME=hA;zy.awsEndpointFunctions=_A;zy.createDefaultUserAgentProvider=fA;zy.createUserAgentStringParsingProvider=Dy;zy.crtAvailability=oA;zy.defaultUserAgent=Py;zy.emitWarningIfUnsupportedVersion=cy;zy.fallback=Yy;zy.getAwsRegionExtensionConfiguration=ky;zy.getHostHeaderPlugin=My;zy.getLoggerPlugin=gy;zy.getLongPollPlugin=_y;zy.getRecursionDetectionPlugin=by;zy.getUserAgentMiddlewareOptions=eA;zy.getUserAgentPlugin=By;zy.getUserAgentPrefix=rA;zy.hostHeaderMiddleware=xw;zy.hostHeaderMiddlewareOptions=qw;zy.isVirtualHostableS3Bucket=Wc;zy.loggerMiddleware=Cw;zy.loggerMiddlewareOptions=Kw;zy.parseArn=uA;zy.partition=nA;zy.recursionDetectionMiddleware=pw;zy.recursionDetectionMiddlewareOptions=Vw;zy.resolveAwsRegionExtensionConfiguration=Xy;zy.resolveDefaultAwsRegionalEndpointsConfig=Qy;zy.resolveHostHeaderConfig=Ay;zy.resolveUserAgentConfig=Sy;zy.setCredentialFeature=ly;zy.setFeature=fn;zy.setPartitionInfo=sA;zy.setTokenFeature=wy;zy.state=Le;zy.stsRegionDefaultResolver=Jy;zy.stsRegionWarning=wA;zy.toEndpointV1=lA;zy.useDefaultPartitionInfo=$y;zy.userAgentMiddleware=iA});var CA=Z((vG)=>{var{fromUtf8:bA,fromHex:XG,toHex:ls,toUint8Array:ii,isArrayBuffer:zG}=$t(),{normalizeProvider:TA}=Rn(),{escapeUri:Ie,HttpRequest:UA}=Ut();class LA{format(t){let n=[];for(let i of Object.keys(t)){let e=bA(i);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[i]))}let s=new Uint8Array(n.reduce((i,e)=>i+e.byteLength,0)),r=0;for(let i of n)s.set(i,r),r+=i.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Wt.boolTrue:Wt.boolFalse]);case"byte":return Uint8Array.from([Wt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Wt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Wt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let r=new Uint8Array(9);return r[0]=Wt.long,r.set(t.value.bytes,1),r;case"binary":let i=new DataView(new ArrayBuffer(3+t.value.byteLength));i.setUint8(0,Wt.byteArray),i.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(i.buffer);return e.set(t.value,3),e;case"string":let f=bA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Wt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=Wt.timestamp,h.set(Qc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!xG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Wt.uuid,u.set(XG(t.value.replace(/-/g,"")),1),u}}}var Wt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Wt||(Wt={}));var xG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Qc{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,r=Math.abs(Math.round(t));s>-1&&r>0;s--,r/=256)n[s]=r;if(t<0)SA(n);return new Qc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)SA(t);return parseInt(ls(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function SA(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var IA="X-Amz-Algorithm",OA="X-Amz-Credential",Jc="X-Amz-Date",yA="X-Amz-SignedHeaders",GA="X-Amz-Expires",kc="X-Amz-Signature",Xc="X-Amz-Security-Token",qG="X-Amz-Region-Set",zc="authorization",xc=Jc.toLowerCase(),BA="date",FA=[zc,xc,BA],HA=kc.toLowerCase(),Fe="x-amz-content-sha256",PA=Xc.toLowerCase(),CG="host",NA={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},WA=/^proxy-/,DA=/^sec-/,KG=[/^proxy-/i,/^sec-/i],Oe="AWS4-HMAC-SHA256",VG="AWS4-ECDSA-P256-SHA256",YA="AWS4-HMAC-SHA256-PAYLOAD",mA="UNSIGNED-PAYLOAD",QA=50,qc="aws4_request",JA=604800,kA=({query:t={}})=>{let n=[],s={};for(let r of Object.keys(t)){if(r.toLowerCase()===HA)continue;let i=Ie(r);n.push(i);let e=t[r];if(typeof e==="string")s[i]=`${i}=${Ie(e)}`;else if(Array.isArray(e))s[i]=e.slice(0).reduce((f,o)=>f.concat([`${i}=${Ie(o)}`]),[]).sort().join("&")}return n.sort().map((r)=>s[r]).filter((r)=>r).join("&")},jG=(t)=>aG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),aG=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class Cc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e=!0}){this.service=r,this.sha256=i,this.uriEscapePath=e,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=TA(s),this.credentialProvider=TA(n)}createCanonicalRequest(t,n,s){let r=Object.keys(n).sort();return`${t.method}
30
+ More information can be found at: https://a.co/c895JFp`)}},hO=()=>(t,n)=>async(s)=>{return n.__retryLongPoll=!0,t(s)},uO={name:"longPollMiddleware",tags:["RETRY"],step:"initialize",override:!0},lO=(t)=>({applyToStack:(n)=>{n.add(hO(),uO)}});function _O(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}jy.v2026||=typeof process==="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function fn(t,n,s){if(!t.__aws_sdk_context)t.__aws_sdk_context={features:{}};else if(!t.__aws_sdk_context.features)t.__aws_sdk_context.features={};t.__aws_sdk_context.features[n]=s}function wO(t,n,s){if(!t.$source)t.$source={};return t.$source[n]=s,t}function AO(t){return t}var xw=(t)=>(n)=>async(s)=>{if(!Pc.isInstance(s.request))return n(s);let{request:i}=s,{handlerProtocol:r=""}=t.requestHandler.metadata||{};if(r.indexOf("h2")>=0&&!i.headers[":authority"])delete i.headers.host,i.headers[":authority"]=i.hostname+(i.port?":"+i.port:"");else if(!i.headers.host){let e=i.hostname;if(i.port!=null)e+=`:${i.port}`;i.headers.host=e}return n(s)},qw={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},MO=(t)=>({applyToStack:(n)=>{n.add(xw(t),qw)}}),Cw=()=>(t,n)=>async(s)=>{try{let i=await t(s),{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c,overrideOutputFilterSensitiveLog:h}=o,u=c??n.inputFilterSensitiveLog,l=h??n.outputFilterSensitiveLog,{$metadata:_,...w}=i.output;return f?.info?.({clientName:r,commandName:e,input:u(s.input),output:l(w),metadata:_}),i}catch(i){let{clientName:r,commandName:e,logger:f,dynamoDbDocumentClientOptions:o={}}=n,{overrideInputFilterSensitiveLog:c}=o,h=c??n.inputFilterSensitiveLog;throw f?.error?.({clientName:r,commandName:e,input:h(s.input),error:i,metadata:i.$metadata}),i}},Kw={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},gO=(t)=>({applyToStack:(n)=>{n.add(Cw(),Kw)}}),Vw={step:"build",tags:["RECURSION_DETECTION","TRACE_CONTEXT_PROPAGATION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"},dO="AWS_LAMBDA_FUNCTION_NAME",EO="_X_AMZN_TRACE_ID",Gc="X-Amzn-Trace-Id",Hc="traceparent",jw="tracestate",aw="baggage",pw=()=>(t)=>async(n)=>{let{request:s}=n;if(!Pc.isInstance(s))return t(n);let i;{let r=Object.keys(s.headers??{}).find((e)=>e.toLowerCase()===Gc.toLowerCase())??Gc;if(!s.headers.hasOwnProperty(r)){let e=process.env[dO],f=process.env[EO];i??=await Ww.getInstanceAsync();let c=i?.getXRayTraceId()??f,h=(u)=>typeof u==="string"&&u.length>0;if(h(e)&&h(c))s.headers[Gc]=c}}if(RO(s.headers),!s.headers[Hc]){let e=(i??=await Ww.getInstanceAsync())?.getTraceparent?.();if(e){s.headers[Hc]=e;let f=i?.getTracestate?.();if(f)s.headers[jw]=f;let o=i?.getBaggage?.();if(o)s.headers[aw]=o}}return t(n)};function RO(t){for(let n of Object.keys(t)){let s=n.toLowerCase();if(n!==s&&(s===Hc||s===jw||s===aw))t[s]=t[n],delete t[n]}}var bO=(t)=>({applyToStack:(n)=>{n.add(pw(),Vw)}}),Nc=void 0;function TO(t){if(t===void 0)return!0;return typeof t==="string"&&t.length<=50}function SO(t){let n=py(t.userAgentAppId??Nc),{customUserAgent:s}=t;return Object.assign(t,{customUserAgent:typeof s==="string"?[[s]]:s,userAgentAppId:async()=>{let i=await n();if(!TO(i)){let r=t.logger?.constructor?.name==="NoOpLogger"||!t.logger?console:t.logger;if(typeof i!=="string")r?.warn("userAgentAppId must be a string or undefined.");else if(i.length>50)r?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return i}})}var Zw={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"},vw=Zw,tA="",nA=(t)=>{let{partitions:n}=vw;for(let i of n){let{regions:r,outputs:e}=i;for(let[f,o]of Object.entries(r))if(f===t)return{...e,...o}}for(let i of n){let{regionRegex:r,outputs:e}=i;if(new RegExp(r).test(t))return{...e}}let s=n.find((i)=>i.id==="aws");if(!s)throw Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...s.outputs}},sA=(t,n="")=>{vw=t,tA=n},$O=()=>{sA(Zw,"")},iA=()=>tA,UO=/\d{12}\.ddb/;async function LO(t,n,s){if(s.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor")fn(t,"PROTOCOL_RPC_V2_CBOR","M");if(typeof n.retryStrategy==="function"){let e=await n.retryStrategy();if(typeof e.mode==="string")switch(e.mode){case Nw.ADAPTIVE:fn(t,"RETRY_MODE_ADAPTIVE","F");break;case Nw.STANDARD:fn(t,"RETRY_MODE_STANDARD","E");break}}if(typeof n.accountIdEndpointMode==="function"){let e=t.endpointV2;if(String(e?.url?.hostname).match(UO))fn(t,"ACCOUNT_ID_ENDPOINT","O");switch(await n.accountIdEndpointMode?.()){case"disabled":fn(t,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":fn(t,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":fn(t,"ACCOUNT_ID_MODE_REQUIRED","R");break}}let r=t.__smithy_context?.selectedHttpAuthScheme?.identity;if(r?.$source){let e=r;if(e.accountId)fn(t,"RESOLVED_ACCOUNT_ID","T");for(let[f,o]of Object.entries(e.$source??{}))fn(t,f,o)}}var mw="user-agent",Bc="x-amz-user-agent",Yw=" ",Fc="/",IO=/[^!$%&'*+\-.^_`|~\w]/g,yO=/[^!$%&'*+\-.^_`|~\w#]/g,Qw="-",OO=1024;function GO(t){let n="";for(let s in t){let i=t[s];if(n.length+i.length+1<=OO){if(n.length)n+=","+i;else n+=i;continue}break}return n}var rA=(t)=>(n,s)=>async(i)=>{let{request:r}=i;if(!Pc.isInstance(r))return n(i);let{headers:e}=r,f=s?.userAgent?.map(Ue)||[],o=(await t.defaultUserAgentProvider()).map(Ue);await LO(s,t,i);let c=s;o.push(`m/${GO(Object.assign({},s.__smithy_context?.features,c.__aws_sdk_context?.features))}`);let h=t?.customUserAgent?.map(Ue)||[],u=await t.userAgentAppId();if(u)o.push(Ue(["app",`${u}`]));let l=iA(),_=(l?[l]:[]).concat([...o,...f,...h]).join(Yw),w=[...o.filter((A)=>A.startsWith("aws-sdk-")),...h].join(Yw);if(t.runtime!=="browser"){if(w)e[Bc]=e[Bc]?`${e[mw]} ${w}`:w;e[mw]=_}else e[Bc]=_;return n({...i,request:r})},Ue=(t)=>{let n=t[0].split(Fc).map((f)=>f.replace(IO,Qw)).join(Fc),s=t[1]?.replace(yO,Qw),i=n.indexOf(Fc),r=n.substring(0,i),e=n.substring(i+1);if(r==="api")e=e.toLowerCase();return[r,e,s].filter((f)=>f&&f.length>0).reduce((f,o,c)=>{switch(c){case 0:return o;case 1:return`${f}/${o}`;default:return`${f}#${o}`}},"")},eA={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},BO=(t)=>({applyToStack:(n)=>{n.add(rA(t),eA)}}),FO=()=>{let t=["deno","bun","llrt"];for(let n of t)if(Oc[n])return[`md/${n}`,Oc[n]];return["md/nodejs",Oc.node]},oA={isCrtAvailable:!1},HO=()=>{if(oA.isCrtAvailable)return["md/crt-avail"];return null},fA=({serviceId:t,clientVersion:n})=>{let s=FO();return async(i)=>{let r=[["aws-sdk-js",n],["ua","2.1"],[`os/${Zy()}`,vy()],["lang/js"],s],e=HO();if(e)r.push(e);if(t)r.push([`api/${t}`,n]);if(Dw.AWS_EXECUTION_ENV)r.push([`exec-env/${Dw.AWS_EXECUTION_ENV}`]);let f=await i?.userAgentAppId?.();return f?[...r,[`app/${f}`]]:[...r]}},PO=fA,cA="AWS_SDK_UA_APP_ID",hA="sdk_ua_app_id",NO="sdk-ua-app-id",WO={environmentVariableSelector:(t)=>t[cA],configFileSelector:(t)=>t[hA]??t[NO],default:Nc},DO=({serviceId:t,clientVersion:n})=>async(s)=>{let i=Pw(),r=i.parse??i.default.parse??(()=>""),e=typeof window<"u"&&window?.navigator?.userAgent?r(window.navigator.userAgent):void 0,f=[["aws-sdk-js",n],["ua","2.1"],[`os/${e?.os?.name||"other"}`,e?.os?.version],["lang/js"],["md/browser",`${e?.browser?.name??"unknown"}_${e?.browser?.version??"unknown"}`]];if(t)f.push([`api/${t}`,n]);let o=await s?.userAgentAppId?.();if(o)f.push([`app/${o}`]);return f},mO={os(t){if(/iPhone|iPad|iPod/.test(t))return"iOS";if(/Macintosh|Mac OS X/.test(t))return"macOS";if(/Windows NT/.test(t))return"Windows";if(/Android/.test(t))return"Android";if(/Linux/.test(t))return"Linux";return},browser(t){if(/EdgiOS|EdgA|Edg\//.test(t))return"Microsoft Edge";if(/Firefox\//.test(t))return"Firefox";if(/Chrome\//.test(t))return"Chrome";if(/Safari\//.test(t))return"Safari";return}},Wc=(t,n=!1)=>{if(n){for(let s of t.split("."))if(!Wc(s))return!1;return!0}if(!tO(t))return!1;if(t.length<3||t.length>63)return!1;if(t!==t.toLowerCase())return!1;if(kw(t))return!1;return!0},Jw=":",YO="/",uA=(t)=>{let n=t.split(Jw);if(n.length<6)return null;let[s,i,r,e,f,...o]=n;if(s!=="arn"||i===""||r===""||o.join(Jw)==="")return null;let c=o.map((h)=>h.split(YO)).flat();return{partition:i,service:r,region:e,accountId:f,resourceId:c}},lA={isVirtualHostableS3Bucket:Wc,parseArn:uA,partition:nA};nO.aws=lA;var QO=(t)=>{if(typeof t.endpointProvider!=="function")throw Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client.");let{endpoint:n}=t;if(n===void 0)t.endpoint=async()=>{return _A(t.endpointProvider({Region:typeof t.region==="function"?await t.region():t.region,UseDualStack:typeof t.useDualstackEndpoint==="function"?await t.useDualstackEndpoint():t.useDualstackEndpoint,UseFIPS:typeof t.useFipsEndpoint==="function"?await t.useFipsEndpoint():t.useFipsEndpoint,Endpoint:void 0},{logger:t.logger}))};return t},_A=(t)=>ay(t.url);function JO(t={}){return rO({...zw,async default(){if(!wA.silence)console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly.");return"us-east-1"}},{...Xw,...t})}var wA={silence:!1},kO=(t)=>{return{setRegion(n){t.region=n},region(){return t.region}}},zO=(t)=>{return{region:t.region()}};XO.DEFAULT_UA_APP_ID=Nc;XO.NODE_APP_ID_CONFIG_OPTIONS=WO;XO.UA_APP_ID_ENV_NAME=cA;XO.UA_APP_ID_INI_NAME=hA;XO.awsEndpointFunctions=lA;XO.createDefaultUserAgentProvider=fA;XO.createUserAgentStringParsingProvider=DO;XO.crtAvailability=oA;XO.defaultUserAgent=PO;XO.emitWarningIfUnsupportedVersion=cO;XO.fallback=mO;XO.getAwsRegionExtensionConfiguration=kO;XO.getHostHeaderPlugin=MO;XO.getLoggerPlugin=gO;XO.getLongPollPlugin=lO;XO.getRecursionDetectionPlugin=bO;XO.getUserAgentMiddlewareOptions=eA;XO.getUserAgentPlugin=BO;XO.getUserAgentPrefix=iA;XO.hostHeaderMiddleware=xw;XO.hostHeaderMiddlewareOptions=qw;XO.isVirtualHostableS3Bucket=Wc;XO.loggerMiddleware=Cw;XO.loggerMiddlewareOptions=Kw;XO.parseArn=uA;XO.partition=nA;XO.recursionDetectionMiddleware=pw;XO.recursionDetectionMiddlewareOptions=Vw;XO.resolveAwsRegionExtensionConfiguration=zO;XO.resolveDefaultAwsRegionalEndpointsConfig=QO;XO.resolveHostHeaderConfig=AO;XO.resolveUserAgentConfig=SO;XO.setCredentialFeature=_O;XO.setFeature=fn;XO.setPartitionInfo=sA;XO.setTokenFeature=wO;XO.state=Le;XO.stsRegionDefaultResolver=JO;XO.stsRegionWarning=wA;XO.toEndpointV1=_A;XO.useDefaultPartitionInfo=$O;XO.userAgentMiddleware=rA});var CA=Z((vG)=>{var{fromUtf8:bA,fromHex:zG,toHex:_s,toUint8Array:rr,isArrayBuffer:XG}=$t(),{normalizeProvider:TA}=Rn(),{escapeUri:Ie,HttpRequest:UA}=Ut();class LA{format(t){let n=[];for(let r of Object.keys(t)){let e=bA(r);n.push(Uint8Array.from([e.byteLength]),e,this.formatHeaderValue(t[r]))}let s=new Uint8Array(n.reduce((r,e)=>r+e.byteLength,0)),i=0;for(let r of n)s.set(r,i),i+=r.byteLength;return s}formatHeaderValue(t){switch(t.type){case"boolean":return Uint8Array.from([t.value?Wt.boolTrue:Wt.boolFalse]);case"byte":return Uint8Array.from([Wt.byte,t.value]);case"short":let n=new DataView(new ArrayBuffer(3));return n.setUint8(0,Wt.short),n.setInt16(1,t.value,!1),new Uint8Array(n.buffer);case"integer":let s=new DataView(new ArrayBuffer(5));return s.setUint8(0,Wt.integer),s.setInt32(1,t.value,!1),new Uint8Array(s.buffer);case"long":let i=new Uint8Array(9);return i[0]=Wt.long,i.set(t.value.bytes,1),i;case"binary":let r=new DataView(new ArrayBuffer(3+t.value.byteLength));r.setUint8(0,Wt.byteArray),r.setUint16(1,t.value.byteLength,!1);let e=new Uint8Array(r.buffer);return e.set(t.value,3),e;case"string":let f=bA(t.value),o=new DataView(new ArrayBuffer(3+f.byteLength));o.setUint8(0,Wt.string),o.setUint16(1,f.byteLength,!1);let c=new Uint8Array(o.buffer);return c.set(f,3),c;case"timestamp":let h=new Uint8Array(9);return h[0]=Wt.timestamp,h.set(Qc.fromNumber(t.value.valueOf()).bytes,1),h;case"uuid":if(!xG.test(t.value))throw Error(`Invalid UUID received: ${t.value}`);let u=new Uint8Array(17);return u[0]=Wt.uuid,u.set(zG(t.value.replace(/-/g,"")),1),u}}}var Wt;(function(t){t[t.boolTrue=0]="boolTrue",t[t.boolFalse=1]="boolFalse",t[t.byte=2]="byte",t[t.short=3]="short",t[t.integer=4]="integer",t[t.long=5]="long",t[t.byteArray=6]="byteArray",t[t.string=7]="string",t[t.timestamp=8]="timestamp",t[t.uuid=9]="uuid"})(Wt||(Wt={}));var xG=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class Qc{bytes;constructor(t){if(this.bytes=t,t.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(t){if(t>9223372036854776000||t<-9223372036854776000)throw Error(`${t} is too large (or, if negative, too small) to represent as an Int64`);let n=new Uint8Array(8);for(let s=7,i=Math.abs(Math.round(t));s>-1&&i>0;s--,i/=256)n[s]=i;if(t<0)SA(n);return new Qc(n)}valueOf(){let t=this.bytes.slice(0),n=t[0]&128;if(n)SA(t);return parseInt(_s(t),16)*(n?-1:1)}toString(){return String(this.valueOf())}}function SA(t){for(let n=0;n<8;n++)t[n]^=255;for(let n=7;n>-1;n--)if(t[n]++,t[n]!==0)break}var IA="X-Amz-Algorithm",yA="X-Amz-Credential",Jc="X-Amz-Date",OA="X-Amz-SignedHeaders",GA="X-Amz-Expires",kc="X-Amz-Signature",zc="X-Amz-Security-Token",qG="X-Amz-Region-Set",Xc="authorization",xc=Jc.toLowerCase(),BA="date",FA=[Xc,xc,BA],HA=kc.toLowerCase(),Fe="x-amz-content-sha256",PA=zc.toLowerCase(),CG="host",NA={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},WA=/^proxy-/,DA=/^sec-/,KG=[/^proxy-/i,/^sec-/i],ye="AWS4-HMAC-SHA256",VG="AWS4-ECDSA-P256-SHA256",mA="AWS4-HMAC-SHA256-PAYLOAD",YA="UNSIGNED-PAYLOAD",QA=50,qc="aws4_request",JA=604800,kA=({query:t={}})=>{let n=[],s={};for(let i of Object.keys(t)){if(i.toLowerCase()===HA)continue;let r=Ie(i);n.push(r);let e=t[i];if(typeof e==="string")s[r]=`${r}=${Ie(e)}`;else if(Array.isArray(e))s[r]=e.slice(0).reduce((f,o)=>f.concat([`${r}=${Ie(o)}`]),[]).sort().join("&")}return n.sort().map((i)=>s[i]).filter((i)=>i).join("&")},jG=(t)=>aG(t).toISOString().replace(/\.\d{3}Z$/,"Z"),aG=(t)=>{if(typeof t==="number")return new Date(t*1000);if(typeof t==="string"){if(Number(t))return new Date(Number(t)*1000);return new Date(t)}return t};class Cc{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:t,credentials:n,region:s,service:i,sha256:r,uriEscapePath:e=!0}){this.service=i,this.sha256=r,this.uriEscapePath=e,this.applyChecksum=typeof t==="boolean"?t:!0,this.regionProvider=TA(s),this.credentialProvider=TA(n)}createCanonicalRequest(t,n,s){let i=Object.keys(n).sort();return`${t.method}
31
31
  ${this.getCanonicalPath(t)}
32
32
  ${kA(t)}
33
- ${r.map((i)=>`${i}:${n[i]}`).join(`
33
+ ${i.map((r)=>`${r}:${n[r]}`).join(`
34
34
  `)}
35
35
 
36
- ${r.join(";")}
37
- ${s}`}async createStringToSign(t,n,s,r){let i=new this.sha256;i.update(ii(s));let e=await i.digest();return`${r}
36
+ ${i.join(";")}
37
+ ${s}`}async createStringToSign(t,n,s,i){let r=new this.sha256;r.update(rr(s));let e=await r.digest();return`${i}
38
38
  ${t}
39
39
  ${n}
40
- ${ls(e)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let i of t.split("/")){if(i?.length===0)continue;if(i===".")continue;if(i==="..")n.pop();else n.push(i)}let s=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return Ie(s).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=jG(t).replace(/[-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}var nr={},ye=[],Ge=(t,n,s)=>`${t}/${n}/${s}/${qc}`,XA=async(t,n,s,r,i)=>{let e=await $A(t,n.secretAccessKey,n.accessKeyId),f=`${s}:${r}:${i}:${ls(e)}:${n.sessionToken}`;if(f in nr)return nr[f];ye.push(f);while(ye.length>QA)delete nr[ye.shift()];let o=`AWS4${n.secretAccessKey}`;for(let c of[s,r,i,qc])o=await $A(t,o,c);return nr[f]=o},pG=()=>{ye.length=0,Object.keys(nr).forEach((t)=>{delete nr[t]})},$A=(t,n,s)=>{let r=new t(n);return r.update(ii(s)),r.digest()},Yc=({headers:t},n,s)=>{let r={};for(let i of Object.keys(t).sort()){if(t[i]==null)continue;let e=i.toLowerCase();if(e in NA||n?.has(e)||WA.test(e)||DA.test(e)){if(!s||s&&!s.has(e))continue}r[e]=t[i].trim().replace(/\s+/g," ")}return r},Be=async({headers:t,body:n},s)=>{for(let r of Object.keys(t))if(r.toLowerCase()===Fe)return t[r];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||zG(n)){let r=new s;return r.update(ii(n)),ls(await r.digest())}return mA},zA=(t,n)=>{t=t.toLowerCase();for(let s of Object.keys(n))if(t===s.toLowerCase())return!0;return!1},xA=(t,n={})=>{let{headers:s,query:r={}}=UA.clone(t);for(let i of Object.keys(s)){let e=i.toLowerCase();if(e.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(e)||n.hoistableHeaders?.has(e))r[i]=s[i],delete s[i]}return{...t,headers:s,query:r}},mc=(t)=>{t=UA.clone(t);for(let n of Object.keys(t.headers))if(FA.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t};class qA extends Cc{headerFormatter=new LA;constructor({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e=!0}){super({applyChecksum:t,credentials:n,region:s,service:r,sha256:i,uriEscapePath:e})}async presign(t,n={}){let{signingDate:s=new Date,expiresIn:r=3600,unsignableHeaders:i,unhoistableHeaders:e,signableHeaders:f,hoistableHeaders:o,signingRegion:c,signingService:h}=n,u=await this.credentialProvider();this.validateResolvedCredentials(u);let _=c??await this.regionProvider(),{longDate:l,shortDate:w}=this.formatDate(s);if(r>JA)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Ge(w,_,h??this.service),M=xA(mc(t),{unhoistableHeaders:e,hoistableHeaders:o});if(u.sessionToken)M.query[Xc]=u.sessionToken;M.query[IA]=Oe,M.query[OA]=`${u.accessKeyId}/${A}`,M.query[Jc]=l,M.query[GA]=r.toString(10);let E=Yc(M,i,f);return M.query[yA]=this.getCanonicalHeaderList(E),M.query[kc]=await this.getSignature(l,A,this.getSigningKey(u,_,w,h),this.createCanonicalRequest(M,E,await Be(t,this.sha256))),M}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:s=new Date,priorSignature:r,signingRegion:i,signingService:e,eventStreamCredentials:f}){let o=i??await this.regionProvider(),{shortDate:c,longDate:h}=this.formatDate(s),u=Ge(c,o,e??this.service),_=await Be({headers:{},body:n},this.sha256),l=new this.sha256;l.update(t);let w=ls(await l.digest()),A=[YA,h,u,r,w,_].join(`
41
- `);return this.signString(A,{signingDate:s,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:i}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:r,priorSignature:t.priorSignature,eventStreamCredentials:i}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:r,eventStreamCredentials:i}={}){let e=i??await this.credentialProvider();this.validateResolvedCredentials(e);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(e,f,o,r));return c.update(ii(t)),ls(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:r,signingRegion:i,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=i??await this.regionProvider(),c=mc(t),{longDate:h,shortDate:u}=this.formatDate(n),_=Ge(u,o,e??this.service);if(c.headers[xc]=h,f.sessionToken)c.headers[PA]=f.sessionToken;let l=await Be(c,this.sha256);if(!zA(Fe,c.headers)&&this.applyChecksum)c.headers[Fe]=l;let w=Yc(c,r,s),A=await this.getSignature(h,_,this.getSigningKey(f,o,u,e),this.createCanonicalRequest(c,w,l));return c.headers[zc]=`${Oe} Credential=${f.accessKeyId}/${_}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,r){let i=await this.createStringToSign(t,n,r,Oe),e=new this.sha256(await s);return e.update(ii(i)),ls(await e.digest())}getSigningKey(t,n,s,r){return XA(this.sha256,t,s,n,r||this.service)}}var ZG={SignatureV4a:null};vG.ALGORITHM_IDENTIFIER=Oe;vG.ALGORITHM_IDENTIFIER_V4A=VG;vG.ALGORITHM_QUERY_PARAM=IA;vG.ALWAYS_UNSIGNABLE_HEADERS=NA;vG.AMZ_DATE_HEADER=xc;vG.AMZ_DATE_QUERY_PARAM=Jc;vG.AUTH_HEADER=zc;vG.CREDENTIAL_QUERY_PARAM=OA;vG.DATE_HEADER=BA;vG.EVENT_ALGORITHM_IDENTIFIER=YA;vG.EXPIRES_QUERY_PARAM=GA;vG.GENERATED_HEADERS=FA;vG.HOST_HEADER=CG;vG.KEY_TYPE_IDENTIFIER=qc;vG.MAX_CACHE_SIZE=QA;vG.MAX_PRESIGNED_TTL=JA;vG.PROXY_HEADER_PATTERN=WA;vG.REGION_SET_PARAM=qG;vG.SEC_HEADER_PATTERN=DA;vG.SHA256_HEADER=Fe;vG.SIGNATURE_HEADER=HA;vG.SIGNATURE_QUERY_PARAM=kc;vG.SIGNED_HEADERS_QUERY_PARAM=yA;vG.SignatureV4=qA;vG.SignatureV4Base=Cc;vG.TOKEN_HEADER=PA;vG.TOKEN_QUERY_PARAM=Xc;vG.UNSIGNABLE_PATTERNS=KG;vG.UNSIGNED_PAYLOAD=mA;vG.clearCredentialCache=pG;vG.createScope=Ge;vG.getCanonicalHeaders=Yc;vG.getCanonicalQuery=kA;vG.getPayloadHash=Be;vG.getSigningKey=XA;vG.hasHeader=zA;vG.moveHeadersToQuery=xA;vG.prepareRequest=mc;vG.signatureV4aContainer=ZG});var jc=Z((ZB)=>{var{HttpResponse:QB,HttpRequest:tM}=Ut(),{normalizeProvider:ei,memoizeIdentityProvider:JB,isIdentityExpired:kB,doesIdentityRequireRefresh:XB}=kn(),{ProviderError:KA}=St(),{setCredentialFeature:zB}=xt(),{SignatureV4:VA}=CA(),jA=(t)=>QB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Kc=(t)=>new Date(Date.now()+t),xB=(t,n)=>Math.abs(Kc(n).getTime()-t)>=300000,aA=(t,n)=>{let s=Date.parse(t);if(xB(s,n))return s-Date.now();return n},oi=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Vc=async(t)=>{let n=oi("context",t.context),s=oi("config",t.config),r=n.endpointV2?.properties?.authSchemes?.[0],e=await oi("signer",s.signer)(r),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:e,signingRegion:f,signingRegionSet:o,signingName:c}};class He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let r=await Vc(s),{config:i,signer:e}=r,{signingRegion:f,signingName:o}=r,c=s.context;if(c?.authSchemes?.length??!1){let[u,_]=c.authSchemes;if(u?.name==="sigv4a"&&_?.name==="sigv4")f=_?.signingRegion??f,o=_?.signingName??o}return s._preRequestSystemClockOffset=i.systemClockOffset,await e.sign(t,{signingDate:Kc(i.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,r=s.ServerTime??jA(s.$response);if(r){let i=oi("config",t.config),e=t._preRequestSystemClockOffset,f=aA(r,i.systemClockOffset);if((f!==i.systemClockOffset||e!==void 0&&e!==f)&&s.$metadata)i.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=jA(t);if(s){let r=oi("config",n.config);r.systemClockOffset=aA(s,r.systemClockOffset)}}}var qB=He;class nM extends He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:r,signer:i,signingRegion:e,signingRegionSet:f,signingName:o}=await Vc(s),h=(await r.sigv4aSigningRegionSet?.()??f??[e]).join(",");return s._preRequestSystemClockOffset=r.systemClockOffset,await i.sign(t,{signingDate:Kc(r.systemClockOffset),signingRegion:h,signingService:o})}}var pA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],sM=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,ZA="AWS_AUTH_SCHEME_PREFERENCE",vA="auth_scheme_preference",CB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(sM(n.signingName)in t)return["httpBearerAuth"]}if(!(ZA in t))return;return pA(t[ZA])},configFileSelector:(t)=>{if(!(vA in t))return;return pA(t[vA])},default:[]},KB=(t)=>{return t.sigv4aSigningRegionSet=ei(t.sigv4aSigningRegionSet),t},VB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new KA("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(t){if(t.sigv4a_signing_region_set)return(t.sigv4a_signing_region_set??"").split(",").map((n)=>n.trim());throw new KA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},rM=(t)=>{let n=t.credentials,s=!!t.credentials,r=void 0;Object.defineProperty(t,"credentials",{set(h){if(h&&h!==n&&h!==r)s=!0;n=h;let u=aB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),_=pB(t,u);if(s&&!_.attributed){let l=typeof n==="object"&&n!==null;r=async(w)=>{let M=await _(w);if(l&&(!M.$source||Object.keys(M.$source).length===0))return zB(M,"CREDENTIALS_CODE","e");return M},r.memoized=_.memoized,r.configBound=_.configBound,r.attributed=!0}else r=_},get(){return r},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:i=!0,systemClockOffset:e=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=ei(t.signer);else if(t.regionInfoProvider)o=()=>ei(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:_,signingService:l}=h;t.signingRegion=t.signingRegion||_||u,t.signingName=t.signingName||l||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:i};return new(t.signerConstructor||VA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await ei(t.region)(),properties:{}},h);let{signingRegion:u,signingName:_}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||_||t.serviceId;let l={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:i};return new(t.signerConstructor||VA)(l)};return Object.assign(t,{systemClockOffset:e,signingEscapePath:i,signer:o})},jB=rM;function aB(t,{credentials:n,credentialDefaultProvider:s}){let r;if(n)if(!n?.memoized)r=JB(n,kB,XB);else r=n;else if(s)r=ei(s(Object.assign({},t,{parentClientConfig:t})));else r=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return r.memoized=!0,r}function pB(t,n){if(n.configBound)return n;let s=async(r)=>n({...r,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}ZB.AWSSDKSigV4Signer=qB;ZB.AwsSdkSigV4ASigner=nM;ZB.AwsSdkSigV4Signer=He;ZB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=CB;ZB.NODE_SIGV4A_CONFIG_OPTIONS=VB;ZB.getBearerTokenEnvKey=sM;ZB.resolveAWSSDKSigV4Config=jB;ZB.resolveAwsSdkSigV4AConfig=KB;ZB.resolveAwsSdkSigV4Config=rM;ZB.validateSigningProperties=Vc});var me=Z((b3)=>{var{buildQueryString:uM,HttpResponse:_M}=Ut(),Pe=nt("https"),{Readable:h3}=nt("stream"),ac=nt("http2"),{streamCollector:u3}=$t();b3.streamCollector=u3;function We(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let i=Error("Request aborted");return i.name="AbortError",i.cause=n,i}let r=Error(String(n));return r.name="AbortError",r}let s=Error("Request aborted");return s.name="AbortError",s}var _3=["ECONNRESET","EPIPE","ETIMEDOUT"],lM=(t)=>{let n={};for(let s in t){let r=t[s];n[s]=Array.isArray(r)?r.join(","):r}return n},Mt={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},eM=1000,l3=(t,n,s=0)=>{if(!s)return-1;let r=(i)=>{let e=Mt.setTimeout(()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${s} ms.`),{name:"TimeoutError"}))},s-i),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Mt.clearTimeout(e)});else Mt.clearTimeout(e)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return r(0),0;return Mt.setTimeout(r.bind(null,eM),eM)},w3=(t,n,s=0,r,i)=>{if(s)return Mt.setTimeout(()=>{let e=`@smithy/node-http-handler - [${r?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(r){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",i?.warn?.(e)},s);return-1},A3=3000,M3=(t,{keepAlive:n,keepAliveMsecs:s},r=A3)=>{if(n!==!0)return-1;let i=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(e)=>{e.setKeepAlive(n,s||0)})};if(r===0)return i(),0;return Mt.setTimeout(i,r)},oM=3000,g3=(t,n,s=0)=>{let r=(i)=>{let e=s-i,f=()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${s} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(t.socket)t.socket.setTimeout(e,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(e,f)};if(0<s&&s<6000)return r(0),0;return Mt.setTimeout(r.bind(null,s===0?0:oM),oM)},fM=6000;async function wM(t,n,s=fM,r=!1){let i=n.headers,e=i?i.Expect||i.expect:void 0,f=-1,o=!0;if(!r&&e==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(Mt.setTimeout(()=>c(!0),Math.max(fM,s)))}),new Promise((c)=>{t.on("continue",()=>{Mt.clearTimeout(f),c(!0)}),t.on("response",()=>{Mt.clearTimeout(f),c(!1)}),t.on("error",()=>{Mt.clearTimeout(f),c(!1)})})]);if(o)E3(t,n.body)}function E3(t,n){if(n instanceof h3){n.pipe(t);return}if(n){let s=Buffer.isBuffer(n);if(s||typeof n==="string"){if(s&&n.byteLength===0)t.end();else t.end(n);return}let i=n;if(typeof i==="object"&&i.buffer&&typeof i.byteOffset==="number"&&typeof i.byteLength==="number"){t.end(Buffer.from(i.buffer,i.byteOffset,i.byteLength));return}t.end(Buffer.from(n));return}t.end()}var d3=0,Ne=void 0,cM=void 0;class De{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new De(t)}static checkSocketUsage(t,n,s=console){let{sockets:r,requests:i,maxSockets:e}=t;if(typeof e!=="number"||e===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(r&&i)for(let o in r){let c=r[o]?.length??0,h=i[o]?.length??0;if(c>=e&&h>=2*e)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
40
+ ${_s(e)}`}getCanonicalPath({path:t}){if(this.uriEscapePath){let n=[];for(let r of t.split("/")){if(r?.length===0)continue;if(r===".")continue;if(r==="..")n.pop();else n.push(r)}let s=`${t?.startsWith("/")?"/":""}${n.join("/")}${n.length>0&&t?.endsWith("/")?"/":""}`;return Ie(s).replace(/%2F/g,"/")}return t}validateResolvedCredentials(t){if(typeof t!=="object"||typeof t.accessKeyId!=="string"||typeof t.secretAccessKey!=="string")throw Error("Resolved credential object is not valid")}formatDate(t){let n=jG(t).replace(/[-:]/g,"");return{longDate:n,shortDate:n.slice(0,8)}}getCanonicalHeaderList(t){return Object.keys(t).sort().join(";")}}var ni={},Oe=[],Ge=(t,n,s)=>`${t}/${n}/${s}/${qc}`,zA=async(t,n,s,i,r)=>{let e=await $A(t,n.secretAccessKey,n.accessKeyId),f=`${s}:${i}:${r}:${_s(e)}:${n.sessionToken}`;if(f in ni)return ni[f];Oe.push(f);while(Oe.length>QA)delete ni[Oe.shift()];let o=`AWS4${n.secretAccessKey}`;for(let c of[s,i,r,qc])o=await $A(t,o,c);return ni[f]=o},pG=()=>{Oe.length=0,Object.keys(ni).forEach((t)=>{delete ni[t]})},$A=(t,n,s)=>{let i=new t(n);return i.update(rr(s)),i.digest()},mc=({headers:t},n,s)=>{let i={};for(let r of Object.keys(t).sort()){if(t[r]==null)continue;let e=r.toLowerCase();if(e in NA||n?.has(e)||WA.test(e)||DA.test(e)){if(!s||s&&!s.has(e))continue}i[e]=t[r].trim().replace(/\s+/g," ")}return i},Be=async({headers:t,body:n},s)=>{for(let i of Object.keys(t))if(i.toLowerCase()===Fe)return t[i];if(n==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";else if(typeof n==="string"||ArrayBuffer.isView(n)||XG(n)){let i=new s;return i.update(rr(n)),_s(await i.digest())}return YA},XA=(t,n)=>{t=t.toLowerCase();for(let s of Object.keys(n))if(t===s.toLowerCase())return!0;return!1},xA=(t,n={})=>{let{headers:s,query:i={}}=UA.clone(t);for(let r of Object.keys(s)){let e=r.toLowerCase();if(e.slice(0,6)==="x-amz-"&&!n.unhoistableHeaders?.has(e)||n.hoistableHeaders?.has(e))i[r]=s[r],delete s[r]}return{...t,headers:s,query:i}},Yc=(t)=>{t=UA.clone(t);for(let n of Object.keys(t.headers))if(FA.indexOf(n.toLowerCase())>-1)delete t.headers[n];return t};class qA extends Cc{headerFormatter=new LA;constructor({applyChecksum:t,credentials:n,region:s,service:i,sha256:r,uriEscapePath:e=!0}){super({applyChecksum:t,credentials:n,region:s,service:i,sha256:r,uriEscapePath:e})}async presign(t,n={}){let{signingDate:s=new Date,expiresIn:i=3600,unsignableHeaders:r,unhoistableHeaders:e,signableHeaders:f,hoistableHeaders:o,signingRegion:c,signingService:h}=n,u=await this.credentialProvider();this.validateResolvedCredentials(u);let l=c??await this.regionProvider(),{longDate:_,shortDate:w}=this.formatDate(s);if(i>JA)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");let A=Ge(w,l,h??this.service),M=xA(Yc(t),{unhoistableHeaders:e,hoistableHeaders:o});if(u.sessionToken)M.query[zc]=u.sessionToken;M.query[IA]=ye,M.query[yA]=`${u.accessKeyId}/${A}`,M.query[Jc]=_,M.query[GA]=i.toString(10);let d=mc(M,r,f);return M.query[OA]=this.getCanonicalHeaderList(d),M.query[kc]=await this.getSignature(_,A,this.getSigningKey(u,l,w,h),this.createCanonicalRequest(M,d,await Be(t,this.sha256))),M}async sign(t,n){if(typeof t==="string")return this.signString(t,n);else if(t.headers&&t.payload)return this.signEvent(t,n);else if(t.message)return this.signMessage(t,n);else return this.signRequest(t,n)}async signEvent({headers:t,payload:n},{signingDate:s=new Date,priorSignature:i,signingRegion:r,signingService:e,eventStreamCredentials:f}){let o=r??await this.regionProvider(),{shortDate:c,longDate:h}=this.formatDate(s),u=Ge(c,o,e??this.service),l=await Be({headers:{},body:n},this.sha256),_=new this.sha256;_.update(t);let w=_s(await _.digest()),A=[mA,h,u,i,w,l].join(`
41
+ `);return this.signString(A,{signingDate:s,signingRegion:o,signingService:e,eventStreamCredentials:f})}async signMessage(t,{signingDate:n=new Date,signingRegion:s,signingService:i,eventStreamCredentials:r}){return this.signEvent({headers:this.headerFormatter.format(t.message.headers),payload:t.message.body},{signingDate:n,signingRegion:s,signingService:i,priorSignature:t.priorSignature,eventStreamCredentials:r}).then((f)=>{return{message:t.message,signature:f}})}async signString(t,{signingDate:n=new Date,signingRegion:s,signingService:i,eventStreamCredentials:r}={}){let e=r??await this.credentialProvider();this.validateResolvedCredentials(e);let f=s??await this.regionProvider(),{shortDate:o}=this.formatDate(n),c=new this.sha256(await this.getSigningKey(e,f,o,i));return c.update(rr(t)),_s(await c.digest())}async signRequest(t,{signingDate:n=new Date,signableHeaders:s,unsignableHeaders:i,signingRegion:r,signingService:e}={}){let f=await this.credentialProvider();this.validateResolvedCredentials(f);let o=r??await this.regionProvider(),c=Yc(t),{longDate:h,shortDate:u}=this.formatDate(n),l=Ge(u,o,e??this.service);if(c.headers[xc]=h,f.sessionToken)c.headers[PA]=f.sessionToken;let _=await Be(c,this.sha256);if(!XA(Fe,c.headers)&&this.applyChecksum)c.headers[Fe]=_;let w=mc(c,i,s),A=await this.getSignature(h,l,this.getSigningKey(f,o,u,e),this.createCanonicalRequest(c,w,_));return c.headers[Xc]=`${ye} Credential=${f.accessKeyId}/${l}, SignedHeaders=${this.getCanonicalHeaderList(w)}, Signature=${A}`,c}async getSignature(t,n,s,i){let r=await this.createStringToSign(t,n,i,ye),e=new this.sha256(await s);return e.update(rr(r)),_s(await e.digest())}getSigningKey(t,n,s,i){return zA(this.sha256,t,s,n,i||this.service)}}var ZG={SignatureV4a:null};vG.ALGORITHM_IDENTIFIER=ye;vG.ALGORITHM_IDENTIFIER_V4A=VG;vG.ALGORITHM_QUERY_PARAM=IA;vG.ALWAYS_UNSIGNABLE_HEADERS=NA;vG.AMZ_DATE_HEADER=xc;vG.AMZ_DATE_QUERY_PARAM=Jc;vG.AUTH_HEADER=Xc;vG.CREDENTIAL_QUERY_PARAM=yA;vG.DATE_HEADER=BA;vG.EVENT_ALGORITHM_IDENTIFIER=mA;vG.EXPIRES_QUERY_PARAM=GA;vG.GENERATED_HEADERS=FA;vG.HOST_HEADER=CG;vG.KEY_TYPE_IDENTIFIER=qc;vG.MAX_CACHE_SIZE=QA;vG.MAX_PRESIGNED_TTL=JA;vG.PROXY_HEADER_PATTERN=WA;vG.REGION_SET_PARAM=qG;vG.SEC_HEADER_PATTERN=DA;vG.SHA256_HEADER=Fe;vG.SIGNATURE_HEADER=HA;vG.SIGNATURE_QUERY_PARAM=kc;vG.SIGNED_HEADERS_QUERY_PARAM=OA;vG.SignatureV4=qA;vG.SignatureV4Base=Cc;vG.TOKEN_HEADER=PA;vG.TOKEN_QUERY_PARAM=zc;vG.UNSIGNABLE_PATTERNS=KG;vG.UNSIGNED_PAYLOAD=YA;vG.clearCredentialCache=pG;vG.createScope=Ge;vG.getCanonicalHeaders=mc;vG.getCanonicalQuery=kA;vG.getPayloadHash=Be;vG.getSigningKey=zA;vG.hasHeader=XA;vG.moveHeadersToQuery=xA;vG.prepareRequest=Yc;vG.signatureV4aContainer=ZG});var jc=Z((ZB)=>{var{HttpResponse:QB,HttpRequest:tM}=Ut(),{normalizeProvider:er,memoizeIdentityProvider:JB,isIdentityExpired:kB,doesIdentityRequireRefresh:zB}=kn(),{ProviderError:KA}=St(),{setCredentialFeature:XB}=xt(),{SignatureV4:VA}=CA(),jA=(t)=>QB.isInstance(t)?t.headers?.date??t.headers?.Date:void 0,Kc=(t)=>new Date(Date.now()+t),xB=(t,n)=>Math.abs(Kc(n).getTime()-t)>=300000,aA=(t,n)=>{let s=Date.parse(t);if(xB(s,n))return s-Date.now();return n},or=(t,n)=>{if(!n)throw Error(`Property \`${t}\` is not resolved for AWS SDK SigV4Auth`);return n},Vc=async(t)=>{let n=or("context",t.context),s=or("config",t.config),i=n.endpointV2?.properties?.authSchemes?.[0],e=await or("signer",s.signer)(i),f=t?.signingRegion,o=t?.signingRegionSet,c=t?.signingName;return{config:s,signer:e,signingRegion:f,signingRegionSet:o,signingName:c}};class He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let i=await Vc(s),{config:r,signer:e}=i,{signingRegion:f,signingName:o}=i,c=s.context;if(c?.authSchemes?.length??!1){let[u,l]=c.authSchemes;if(u?.name==="sigv4a"&&l?.name==="sigv4")f=l?.signingRegion??f,o=l?.signingName??o}return s._preRequestSystemClockOffset=r.systemClockOffset,await e.sign(t,{signingDate:Kc(r.systemClockOffset),signingRegion:f,signingService:o})}errorHandler(t){return(n)=>{let s=n,i=s.ServerTime??jA(s.$response);if(i){let r=or("config",t.config),e=t._preRequestSystemClockOffset,f=aA(i,r.systemClockOffset);if((f!==r.systemClockOffset||e!==void 0&&e!==f)&&s.$metadata)r.systemClockOffset=f,s.$metadata.clockSkewCorrected=!0}throw n}}successHandler(t,n){let s=jA(t);if(s){let i=or("config",n.config);i.systemClockOffset=aA(s,i.systemClockOffset)}}}var qB=He;class nM extends He{async sign(t,n,s){if(!tM.isInstance(t))throw Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:i,signer:r,signingRegion:e,signingRegionSet:f,signingName:o}=await Vc(s),h=(await i.sigv4aSigningRegionSet?.()??f??[e]).join(",");return s._preRequestSystemClockOffset=i.systemClockOffset,await r.sign(t,{signingDate:Kc(i.systemClockOffset),signingRegion:h,signingService:o})}}var pA=(t)=>typeof t==="string"&&t.length>0?t.split(",").map((n)=>n.trim()):[],sM=(t)=>`AWS_BEARER_TOKEN_${t.replace(/[\s-]/g,"_").toUpperCase()}`,ZA="AWS_AUTH_SCHEME_PREFERENCE",vA="auth_scheme_preference",CB={environmentVariableSelector:(t,n)=>{if(n?.signingName){if(sM(n.signingName)in t)return["httpBearerAuth"]}if(!(ZA in t))return;return pA(t[ZA])},configFileSelector:(t)=>{if(!(vA in t))return;return pA(t[vA])},default:[]},KB=(t)=>{return t.sigv4aSigningRegionSet=er(t.sigv4aSigningRegionSet),t},VB={environmentVariableSelector(t){if(t.AWS_SIGV4A_SIGNING_REGION_SET)return t.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((n)=>n.trim());throw new KA("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:!0})},configFileSelector(t){if(t.sigv4a_signing_region_set)return(t.sigv4a_signing_region_set??"").split(",").map((n)=>n.trim());throw new KA("sigv4a_signing_region_set not set in profile.",{tryNextLink:!0})},default:void 0},iM=(t)=>{let n=t.credentials,s=!!t.credentials,i=void 0;Object.defineProperty(t,"credentials",{set(h){if(h&&h!==n&&h!==i)s=!0;n=h;let u=aB(t,{credentials:n,credentialDefaultProvider:t.credentialDefaultProvider}),l=pB(t,u);if(s&&!l.attributed){let _=typeof n==="object"&&n!==null;i=async(w)=>{let M=await l(w);if(_&&(!M.$source||Object.keys(M.$source).length===0))return XB(M,"CREDENTIALS_CODE","e");return M},i.memoized=l.memoized,i.configBound=l.configBound,i.attributed=!0}else i=l},get(){return i},enumerable:!0,configurable:!0}),t.credentials=n;let{signingEscapePath:r=!0,systemClockOffset:e=t.systemClockOffset||0,sha256:f}=t,o;if(t.signer)o=er(t.signer);else if(t.regionInfoProvider)o=()=>er(t.region)().then(async(h)=>[await t.regionInfoProvider(h,{useFipsEndpoint:await t.useFipsEndpoint(),useDualstackEndpoint:await t.useDualstackEndpoint()})||{},h]).then(([h,u])=>{let{signingRegion:l,signingService:_}=h;t.signingRegion=t.signingRegion||l||u,t.signingName=t.signingName||_||t.serviceId;let w={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:r};return new(t.signerConstructor||VA)(w)});else o=async(h)=>{h=Object.assign({},{name:"sigv4",signingName:t.signingName||t.defaultSigningName,signingRegion:await er(t.region)(),properties:{}},h);let{signingRegion:u,signingName:l}=h;t.signingRegion=t.signingRegion||u,t.signingName=t.signingName||l||t.serviceId;let _={...t,credentials:t.credentials,region:t.signingRegion,service:t.signingName,sha256:f,uriEscapePath:r};return new(t.signerConstructor||VA)(_)};return Object.assign(t,{systemClockOffset:e,signingEscapePath:r,signer:o})},jB=iM;function aB(t,{credentials:n,credentialDefaultProvider:s}){let i;if(n)if(!n?.memoized)i=JB(n,kB,zB);else i=n;else if(s)i=er(s(Object.assign({},t,{parentClientConfig:t})));else i=async()=>{throw Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};return i.memoized=!0,i}function pB(t,n){if(n.configBound)return n;let s=async(i)=>n({...i,callerClientConfig:t});return s.memoized=n.memoized,s.configBound=!0,s}ZB.AWSSDKSigV4Signer=qB;ZB.AwsSdkSigV4ASigner=nM;ZB.AwsSdkSigV4Signer=He;ZB.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS=CB;ZB.NODE_SIGV4A_CONFIG_OPTIONS=VB;ZB.getBearerTokenEnvKey=sM;ZB.resolveAWSSDKSigV4Config=jB;ZB.resolveAwsSdkSigV4AConfig=KB;ZB.resolveAwsSdkSigV4Config=iM;ZB.validateSigningProperties=Vc});var Ye=Z((b3)=>{var{buildQueryString:uM,HttpResponse:lM}=Ut(),Pe=nt("https"),{Readable:h3}=nt("stream"),ac=nt("http2"),{streamCollector:u3}=$t();b3.streamCollector=u3;function We(t){let n=t&&typeof t==="object"&&"reason"in t?t.reason:void 0;if(n){if(n instanceof Error){let r=Error("Request aborted");return r.name="AbortError",r.cause=n,r}let i=Error(String(n));return i.name="AbortError",i}let s=Error("Request aborted");return s.name="AbortError",s}var l3=["ECONNRESET","EPIPE","ETIMEDOUT"],_M=(t)=>{let n={};for(let s in t){let i=t[s];n[s]=Array.isArray(i)?i.join(","):i}return n},Mt={setTimeout:(t,n)=>setTimeout(t,n),clearTimeout:(t)=>clearTimeout(t)},eM=1000,_3=(t,n,s=0)=>{if(!s)return-1;let i=(r)=>{let e=Mt.setTimeout(()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${s} ms.`),{name:"TimeoutError"}))},s-r),f=(o)=>{if(o?.connecting)o.on("connect",()=>{Mt.clearTimeout(e)});else Mt.clearTimeout(e)};if(t.socket)f(t.socket);else t.on("socket",f)};if(s<2000)return i(0),0;return Mt.setTimeout(i.bind(null,eM),eM)},w3=(t,n,s=0,i,r)=>{if(s)return Mt.setTimeout(()=>{let e=`@smithy/node-http-handler - [${i?"ERROR":"WARN"}] a request has exceeded the configured ${s} ms requestTimeout.`;if(i){let f=Object.assign(Error(e),{name:"TimeoutError",code:"ETIMEDOUT"});t.destroy(f),n(f)}else e+=" Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.",r?.warn?.(e)},s);return-1},A3=3000,M3=(t,{keepAlive:n,keepAliveMsecs:s},i=A3)=>{if(n!==!0)return-1;let r=()=>{if(t.socket)t.socket.setKeepAlive(n,s||0);else t.on("socket",(e)=>{e.setKeepAlive(n,s||0)})};if(i===0)return r(),0;return Mt.setTimeout(r,i)},oM=3000,g3=(t,n,s=0)=>{let i=(r)=>{let e=s-r,f=()=>{t.destroy(),n(Object.assign(Error(`@smithy/node-http-handler - the request socket timed out after ${s} ms of inactivity (configured by client requestHandler).`),{name:"TimeoutError"}))};if(t.socket)t.socket.setTimeout(e,f),t.on("close",()=>t.socket?.removeListener("timeout",f));else t.setTimeout(e,f)};if(0<s&&s<6000)return i(0),0;return Mt.setTimeout(i.bind(null,s===0?0:oM),oM)},fM=6000;async function wM(t,n,s=fM,i=!1){let r=n.headers,e=r?r.Expect||r.expect:void 0,f=-1,o=!0;if(!i&&e==="100-continue")o=await Promise.race([new Promise((c)=>{f=Number(Mt.setTimeout(()=>c(!0),Math.max(fM,s)))}),new Promise((c)=>{t.on("continue",()=>{Mt.clearTimeout(f),c(!0)}),t.on("response",()=>{Mt.clearTimeout(f),c(!1)}),t.on("error",()=>{Mt.clearTimeout(f),c(!1)})})]);if(o)d3(t,n.body)}function d3(t,n){if(n instanceof h3){n.pipe(t);return}if(n){let s=Buffer.isBuffer(n);if(s||typeof n==="string"){if(s&&n.byteLength===0)t.end();else t.end(n);return}let r=n;if(typeof r==="object"&&r.buffer&&typeof r.byteOffset==="number"&&typeof r.byteLength==="number"){t.end(Buffer.from(r.buffer,r.byteOffset,r.byteLength));return}t.end(Buffer.from(n));return}t.end()}var E3=0,Ne=void 0,cM=void 0;class De{config;configProvider;socketWarningTimestamp=0;externalAgent=!1;metadata={handlerProtocol:"http/1.1"};static create(t){if(typeof t?.handle==="function")return t;return new De(t)}static checkSocketUsage(t,n,s=console){let{sockets:i,requests:r,maxSockets:e}=t;if(typeof e!=="number"||e===1/0)return n;let f=15000;if(Date.now()-f<n)return n;if(i&&r)for(let o in i){let c=i[o]?.length??0,h=r[o]?.length??0;if(c>=e&&h>=2*e)return s?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${c} and ${h} additional requests are enqueued.
42
42
  See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
43
- or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return n}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(this.resolveDefaultConfig(r))}).catch(s);else n(this.resolveDefaultConfig(t))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(t,{abortSignal:n,requestTimeout:s}={}){if(!this.config)this.config=await this.configProvider;let r=this.config,i=t.protocol==="https:";if(!i&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,c=-1,h=-1,u=-1,_=-1,l=-1,w=()=>{Mt.clearTimeout(c),Mt.clearTimeout(h),Mt.clearTimeout(u),Mt.clearTimeout(_),Mt.clearTimeout(l)},A=async(R)=>{await o,w(),e(R)},M=async(R)=>{await o,w(),f(R)};if(n?.aborted){let R=We(n);M(R);return}let E=t.headers,d=E?(E.Expect??E.expect)==="100-continue":!1,T=i?r.httpsAgent:r.httpAgent;if(d&&!this.externalAgent)T=new(i?Pe.Agent:Ne)({keepAlive:!1,maxSockets:1/0});c=Mt.setTimeout(()=>{this.socketWarningTimestamp=De.checkSocketUsage(T,this.socketWarningTimestamp,r.logger)},r.socketAcquisitionWarningTimeout??(r.requestTimeout??2000)+(r.connectionTimeout??1000));let U=t.query?uM(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let R=t.username??"",W=t.password??"";S=`${R}:${W}`}let O=t.path;if(U)O+=`?${U}`;if(t.fragment)O+=`#${t.fragment}`;let D=t.hostname??"";if(D[0]==="["&&D.endsWith("]"))D=t.hostname.slice(1,-1);else D=t.hostname;let q={headers:t.headers,host:D,method:t.method,path:O,port:t.port,agent:T,auth:S},J=(i?Pe.request:cM)(q,(R)=>{let W=new _M({statusCode:R.statusCode||-1,reason:R.statusMessage,headers:lM(R.headers),body:R});A({response:W})});if(J.on("error",(R)=>{if(_3.includes(R.code))M(Object.assign(R,{name:"TimeoutError"}));else M(R)}),n){let R=()=>{J.destroy();let W=We(n);M(W)};if(typeof n.addEventListener==="function"){let W=n;W.addEventListener("abort",R,{once:!0}),J.once("close",()=>W.removeEventListener("abort",R))}else n.onabort=R}let G=s??r.requestTimeout;h=l3(J,M,r.connectionTimeout),u=w3(J,M,G,r.throwOnRequestTimeout,r.logger??console),_=g3(J,M,r.socketTimeout);let K=q.agent;if(typeof K==="object"&&"keepAlive"in K)l=M3(J,{keepAlive:K.keepAlive,keepAliveMsecs:K.keepAliveMsecs});o=wM(J,t,G,this.externalAgent).catch((R)=>{return w(),f(R)})})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(t){let{requestTimeout:n,connectionTimeout:s,socketTimeout:r,socketAcquisitionWarningTimeout:i,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:r,socketAcquisitionWarningTimeout:i,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let _=nt("http"),{Agent:l,request:w}=_.default??_;if(cM=w,Ne=l,e instanceof Ne||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ne({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof Pe.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Pe.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var R3=new Uint16Array(1);class Ye{id=R3[0]++;total=0;max=0;session;refs=0;constructor(t){t.unref(),this.session=t}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class AM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new Ye(n))}poll(){let t=!1;for(let n of this.sessions){if(n.deref().destroyed){t=!0;continue}if(!this.maxConcurrency||n.useCount()<this.maxConcurrency)return n}if(t){for(let n of this.sessions)if(n.deref().destroyed)this.remove(n)}}offerLast(t){this.sessions.push(t)}remove(t){let n=this.sessions.indexOf(t);if(n>-1)this.sessions.splice(n,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(t){this.maxConcurrency=t}destroy(t){this.remove(t),t.destroy()}}class MM{config;connectOptions;connectionPools=new Map;constructor(t){if(this.config=t,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(t,n){let s=this.getUrlString(t),r=this.getPool(s);if(!this.config.disableConcurrency&&!n.isEventStream){let c=r.poll();if(c)return c.retain(),c}let i=new Ye(this.connect(s)),e=i.deref();if(this.config.maxConcurrency)e.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+t.destination.toString())});let f=()=>{this.removeFromPoolAndClose(s,i)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,i)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),n.requestTimeout)e.setTimeout(n.requestTimeout,o);return r.offerLast(i),i.retain(),i}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),r=new Ye(this.connect(s)),i=r.deref();i.settings({maxConcurrentStreams:1});let e=()=>{r.destroy()};if(i.on("error",e),i.on("frameError",e),i.on("close",e),n.requestTimeout)i.setTimeout(n.requestTimeout,e);return r.retain(),r}destroy(){for(let[t,n]of this.connectionPools){for(let s of[...n])s.destroy();this.connectionPools.delete(t)}}setMaxConcurrentStreams(t){if(t&&t<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=t;for(let n of this.connectionPools.values())n.setMaxConcurrency(t)}setDisableConcurrentStreams(t){this.config.disableConcurrency=t}setNodeHttp2ConnectOptions(t){this.connectOptions=t}debug(){let t={};for(let[n,s]of this.connectionPools){let r=[];for(let i of s)r.push({id:i.id,active:i.useCount(),maxConcurrent:i.max,totalRequests:i.total});t[n]={sessions:r}}return t}removeFromPoolAndClose(t,n){this.connectionPools.get(t)?.remove(n),n.close()}removeFromPoolAndCheckedDestroy(t,n){this.connectionPools.get(t)?.remove(n),n.destroy()}getPool(t){if(!this.connectionPools.has(t)){let n=new AM;if(this.config.maxConcurrency)n.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(t,n)}return this.connectionPools.get(t)}getUrlString(t){return t.destination.toString()}connect(t){return this.connectOptions===void 0?ac.connect(t):ac.connect(t,this.connectOptions)}}var{constants:hM}=ac;class pc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new MM({});static create(t){if(typeof t?.handle==="function")return t;return new pc(t)}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((r)=>{n(r||{})}).catch(s);else n(t||{})})}destroy(){this.connectionManager.destroy()}async handle(t,{abortSignal:n,requestTimeout:s,isEventStream:r}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:h,nodeHttp2ConnectOptions:u}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),h)this.connectionManager.setMaxConcurrentStreams(h);if(u)this.connectionManager.setNodeHttp2ConnectOptions(u)}let{requestTimeout:i,disableConcurrentStreams:e}=this.config,f=e||r,o=s??i;return new Promise((c,h)=>{let u=!1,_=void 0,l=async(W)=>{await _,c(W)},w=async(W)=>{await _,h(W)};if(n?.aborted){u=!0;let W=We(n);w(W);return}let{hostname:A,method:M,port:E,protocol:d,query:T}=t,U="";if(t.username!=null||t.password!=null){let W=t.username??"",k=t.password??"";U=`${W}:${k}@`}let S=`${d}//${U}${A}${E?`:${E}`:""}`,O={destination:new URL(S)},D={requestTimeout:this.config?.sessionTimeout,isEventStream:r},q=f?this.connectionManager.createIsolatedSession(O,D):this.connectionManager.lease(O,D),tt=q.deref(),J=(W)=>{if(f)q.destroy();u=!0,w(W)},G=T?uM(T):"",K=t.path;if(G)K+=`?${G}`;if(t.fragment)K+=`#${t.fragment}`;let R=tt.request({...t.headers,[hM.HTTP2_HEADER_PATH]:K,[hM.HTTP2_HEADER_METHOD]:M});if(o)R.setTimeout(o,()=>{R.close();let W=Error(`Stream timed out because of no activity for ${o} ms`);W.name="TimeoutError",J(W)});if(n){let W=()=>{R.close();let k=We(n);J(k)};if(typeof n.addEventListener==="function"){let k=n;k.addEventListener("abort",W,{once:!0}),R.once("close",()=>k.removeEventListener("abort",W))}else n.onabort=W}R.on("frameError",(W,k,st)=>{J(Error(`Frame type id ${W} in stream id ${st} has failed with code ${k}.`))}),R.on("error",J),R.on("aborted",()=>{J(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${R.rstCode}.`))}),R.on("response",(W)=>{let k=new _M({statusCode:W[":status"]??-1,headers:lM(W),body:R});if(u=!0,l({response:k}),f)tt.close()}),R.on("close",()=>{if(f)q.destroy();else this.connectionManager.release(O,q);if(!u)J(Error("Unexpected error: http2 request did not get a response"))}),_=wM(R,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}b3.DEFAULT_REQUEST_TIMEOUT=d3;b3.NodeHttp2Handler=pc;b3.NodeHttpHandler=De});var OM=Z((rF)=>{var{nv:L3,NumericValue:bM,calculateBodyLength:I3,_parseEpochTimestamp:gM,fromBase64:TM,generateIdempotencyToken:O3}=$t(),{HttpRequest:y3,collectBody:G3,SerdeContext:rh,RpcProtocol:B3}=Ut(),{NormalizedSchema:ih,deref:F3,TypeRegistry:EM}=Nn(),{getSmithyContext:H3}=nn();function er(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var eh=Symbol("@smithy/core/cbor::tagSymbol");function oh(t){return t[eh]=!0,t}var SM=typeof Buffer<"u",fh=new TextDecoder,C=er(0),ch=!1,qt=new DataView(C.buffer,C.byteOffset,C.byteLength),m=0;function P3(t){C=t,ch=SM&&C instanceof Buffer,qt=new DataView(C.buffer,C.byteOffset,C.byteLength)}function zn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(C[t]&224)>>5,r=C[t]&31;if(r===31&&2<=s&&s<=5)return N3(t,n);switch(s){case 0:case 1:case 6:{let i,e;if(r<24)i=r,e=1;else switch(r){case 24:if(n-t<2)cn(1);i=C[t+1],e=2;break;case 25:if(n-t<3)cn(2);i=qt.getUint16(t+1),e=3;break;case 26:if(n-t<5)cn(4);i=qt.getUint32(t+1),e=5;break;case 27:if(n-t<9)cn(8);{let f=qt.getUint32(t+1);if(f<2097152)i=f*4294967296+qt.getUint32(t+5);else i=qt.getBigUint64(t+1)}e=9;break;default:uh(r)}if(s===0)return m=e,th(i);else if(s===1){let f;if(typeof i==="bigint")f=BigInt(-1)-i;else f=-1-i;return m=e,th(f)}else return X3(t,n,r,i,e)}case 3:return hi(t,n);case 5:return D3(t,n);case 4:return Q3(t,n);case 2:return hh(t,n);default:return z3(t,n)}}function N3(t,n){let s=(C[t]&224)>>5;if((C[t]&31)===31)switch(s){case 3:return C3(t,n);case 5:return x3(t,n);case 4:return q3(t,n);case 2:return K3(t,n)}}function W3(t,n){let s=t>>7,r=(t&124)>>2,i=(t&3)<<8|n,e=s===0?1:-1;if(r===0){if(i===0)return 0;return e*(Math.pow(2,-14)*(i/1024))}else if(r===31){if(i===0)return e*(1/0);return NaN}return e*(Math.pow(2,r-15)*(1+i/1024))}function D3(t,n){let s=ui(t,n);if(s<15)return m3(t,n,s);return Y3(t,n,s)}function Y3(t,n,s){let r=m;t+=r;let i=t,e=Object.create(null);for(let f=0;f<s;++f){let o=hi(t,n);if(t+=m,(C[t]&224)>>5===3)e[o]=hi(t,n);else e[o]=zn(t,n);t+=m}return m=r+(t-i),Object.setPrototypeOf(e,Object.prototype),e}function m3(t,n,s){let r=m;t+=r;let i=t,e={};for(let f=0;f<s;++f){let o=hi(t,n);t+=m,e[o]=zn(t,n),t+=m}return m=r+(t-i),e}function Q3(t,n){let s=ui(t,n),r=m;t+=r;let i=t,e=Array(s);for(let f=0;f<s;++f)e[f]=zn(t,n),t+=m;return m=r+(t-i),e}function hi(t,n){let s=ui(t,n),r=m;if(t+=r,n-t<s)cn(s);if(m=r+s,s<24)return k3(t,s);if(ch)return C.toString("utf-8",t,t+s);return fh.decode(C.subarray(t,t+s))}var dM=Array(2048),Zc=new Uint16Array(2048),fi=0;function J3(){fi=fi+1&65535}function k3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+C[t+f]|0;let r=s>>>0&2047,i=dM[r];if(i!==void 0){if(i.length===n){let f=!0;for(let o=0;o<n;++o)if(i.charCodeAt(o)!==C[t+o]){f=!1;break}if(f)return Zc[r]=fi,i}}let e=ch?C.toString("utf-8",t,t+n):fh.decode(C.subarray(t,t+n));if(Zc[r]!==fi)dM[r]=e,Zc[r]=fi;return e}function hh(t,n){let s=ui(t,n),r=m;if(t+=r,n-t<s)cn(s);let i=C.subarray(t,t+s);return m=r+s,i}function X3(t,n,s,r,i){if(s===2||s===3){let e=ui(t+i,n),f=BigInt(0),o=t+i+m;for(let c=o;c<o+e;++c)f=f<<BigInt(8)|BigInt(C[c]);return m=i+m+e,s===3?-f-BigInt(1):f}else if(s===4){let e=zn(t+i,n),[f,o]=e,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,_=o<0?"-":"";if(u=f===0?h:h.slice(0,h.length+f)+"."+h.slice(f),u=u.replace(/^0+/g,""),u==="")u="0";if(u[0]===".")u="0"+u;return u=_+u,m=i+m,L3(u)}else{let e=zn(t+i,n);return m=i+m,oh({tag:th(r),value:e})}}function z3(t,n){let s=C[t]&31;switch(s){case 21:case 20:return m=1,s===21;case 22:return m=1,null;case 23:return m=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return m=3,W3(C[t+1],C[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return m=5,qt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return m=9,qt.getFloat64(t+1);default:uh(s)}}function ui(t,n){let s=C[t]&31;if(s<24)return m=1,s;switch(s){case 24:if(n-t<2)cn(1);return m=2,C[t+1];case 25:if(n-t<3)cn(2);return m=3,qt.getUint16(t+1);case 26:if(n-t<5)cn(4);return m=5,qt.getUint32(t+1);case 27:if(n-t<9)cn(8);return m=9,V3(qt.getBigUint64(t+1));default:uh(s)}}function x3(t,n){t+=1;let s=t,r={};for(;t<n;){if(C[t]===255)return m=t-s+2,r;let i=hi(t,n);t+=m,r[i]=zn(t,n),t+=m}throw Error("expected break marker.")}function q3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255)return m=t-r+2,s;s.push(zn(t,n)),t+=m}throw Error("expected break marker.")}function C3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255){let c=er(s.length);if(c.set(s,0),m=t-r+2,SM)return c.toString("utf-8",0,c.length);return fh.decode(c)}let i=(C[t]&224)>>5,e=C[t]&31;if(i!==3)$M(i);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=m;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function K3(t,n){t+=1;let s=[];for(let r=t;t<n;){if(C[t]===255){let c=er(s.length);return c.set(s,0),m=t-r+2,c}let i=(C[t]&224)>>5,e=C[t]&31;if(i!==2)$M(i);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=m;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function th(t){if(typeof t==="number")return t;let n=Number(t);if(Number.MIN_SAFE_INTEGER<=n&&n<=Number.MAX_SAFE_INTEGER)return n;return t}function V3(t){let n=Number(t);if(n<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<n)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${t}) to ${n} with loss of precision.`));return n}function cn(t){throw Error(`length ${t} greater than remaining buf len.`)}function uh(t){throw Error(`unexpected minor value ${t}.`)}function $M(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var j3=typeof Buffer<"u",rr=new Map,ci=0,nh=!1,a3=2048,H=er(a3),Dt=new DataView(H.buffer,H.byteOffset,H.byteLength),I=0;function p3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let r=s.length;if(j3)if(ir(r*3+9),r>23)vc(3,Buffer.byteLength(s)),I+=H.write(s,I);else v3(s);else{let i=r*3;ir(i+9);let e=I,o=new TextEncoder().encodeInto(s,H.subarray(I+9)).written,c;if(o<24)c=1;else if(o<256)c=2;else if(o<65536)c=3;else if(o<4294967296)c=5;else c=9;if(c<9)H.copyWithin(e+c,e+9,e+9+o);I=e,ws(3,o),I+=o}continue}if(H.byteLength-I<9)ir(64);if(typeof s==="number"){if(Number.isInteger(s)){let r=s>=0,i=r?0:1,e=r?s:-s-1;if(e<24)H[I++]=i<<5|e;else if(e<256)H[I++]=i<<5|24,H[I++]=e;else if(e<65536)H[I++]=i<<5|25,H[I++]=e>>8,H[I++]=e&255;else if(e<4294967296)H[I++]=i<<5|26,Dt.setUint32(I,e),I+=4;else{H[I++]=i<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;Dt.setUint32(I,f),Dt.setUint32(I+4,o),I+=8}continue}H[I++]=251,Dt.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let r=s>=0,i=r?0:1,e=r?s:-s-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)ws(i,f);else H[I++]=i<<5|27,Dt.setBigUint64(I,e),I+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=e,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);ir(o.byteLength*2+16),H[I++]=r?194:195,vc(2,o.byteLength),H.set(o,I),I+=o.byteLength}continue}else if(s===null){H[I++]=246;continue}else if(typeof s==="boolean"){H[I++]=224|(s?21:20);continue}else if(typeof s>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(s)){ws(4,s.length),ir(s.length*9+64);for(let r=s.length-1;r>=0;--r)n.push(s[r]);continue}else if(typeof s.byteLength==="number"){ir(s.length*2+9),ws(2,s.length),H.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof bM){let e=s.string.indexOf("."),f=e===-1?0:e-s.string.length+1,o=BigInt(s.string.replace(".",""));H[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[eh])if("tag"in s&&"value"in s){n.push(s.value),vc(6,s.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(s));let r=Object.keys(s),i=r.length;ws(5,i);for(let e=i-1;e>=0;--e)n.push(s[r[e]]),n.push(r[e]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function Z3(){ci=ci+1&65535,nh=!1}function RM(){let t=er(I);return t.set(H.subarray(0,I),0),I=0,t}function sh(t){let n=H;if(H=er(t),n)if(n.copy)n.copy(H,0,0,n.byteLength);else H.set(n,0);Dt=new DataView(H.buffer,H.byteOffset,H.byteLength)}function v3(t){let n=rr.get(t);if(n!==void 0){H.set(n.bytes,I),I+=n.bytes.length,n.epoch=ci;return}let s=I,r=Buffer.byteLength(t);ws(3,r),I+=H.write(t,I);let i=Uint8Array.prototype.slice.call(H,s,I);if(rr.size>=2048){if(nh)return;let e=0;for(let[f,o]of rr){if(e>=1024)break;if(o.epoch!==ci)rr.delete(f),e++}if(e===0){nh=!0;return}}if(rr.size<2048)rr.set(t,{epoch:ci,bytes:i})}function ir(t){if(H.byteLength-I<t)if(I<16000000)sh(Math.max(H.byteLength*4,H.byteLength+t));else sh(H.byteLength+t+16000000)}function vc(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,Dt.setUint16(I,n),I+=2;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else H[I++]=t<<5|27,Dt.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,H[I++]=n>>8,H[I++]=n&255;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else{H[I++]=t<<5|27;let s=n/4294967296|0,r=n-s*4294967296|0;Dt.setUint32(I,s),Dt.setUint32(I+4,r),I+=8}}var Je={deserialize(t){return J3(),P3(t),zn(0,t.length)},serialize(t){Z3();try{return p3(t),RM()}catch(n){throw RM(),n}},resizeEncodingBuffer(t){sh(t)}},UM=(t,n)=>{return G3(t,n).then(async(s)=>{if(s.length)try{return Je.deserialize(s)}catch(r){throw Object.defineProperty(r,"$responseBodyText",{value:n.utf8Encoder(s)}),r}return{}})},Qe=(t)=>{return oh({tag:1,value:t.getTime()/1000})},tF=async(t,n)=>{let s=await UM(t,n);return s.message=s.message??s.Message,s},LM=(t,n)=>{let s=(i)=>{let e=i;if(typeof e==="number")e=e.toString();if(e.indexOf(",")>=0)e=e.split(",")[0];if(e.indexOf(":")>=0)e=e.split(":")[0];if(e.indexOf("#")>=0)e=e.split("#")[1];return e};if(n.__type!==void 0)return s(n.__type);let r;for(let i in n)if(i.toLowerCase()==="code"){r=i;break}if(r&&n[r]!==void 0)return s(n[r])},nF=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},sF=async(t,n,s,r,i)=>{let e=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=e,u={protocol:o,hostname:f,port:c,method:"POST",path:h.endsWith("/")?h.slice(0,-1)+s:h+s,headers:{...n}};if(r!==void 0)u.hostname=r;if(e.headers)for(let _ in e.headers)u.headers[_]=e.headers[_];if(i!==void 0){u.body=i;try{u.headers["content-length"]=String(I3(i))}catch(_){}}return new y3(u)};class _h extends rh{createSerializer(){let t=new lh;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new wh;return t.setSerdeContext(this.serdeContext),t}}class lh extends rh{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=ih.of(t);if(n==null){if(s.isIdempotencyToken())return O3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Qe(new Date(Number(n)/1000|0));return Qe(n)}if(typeof n==="function"||typeof n==="object"){let r=n;if(s.isListSchema()&&Array.isArray(r)){let e=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of r){let h=this.serialize(s.getValueSchema(),c);if(h!=null||e)f[o++]=h}return f}if(r instanceof Date)return Qe(r);let i={};if(s.isMapSchema()){let e=!!s.getMergedTraits().sparse;for(let f in r){let o=this.serialize(s.getValueSchema(),r[f]);if(o!=null||e)i[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,r[f]);if(c!=null)i[f]=c}if(s.isUnionSchema()&&Array.isArray(r.$unknown)){let[f,o]=r.$unknown;i[f]=o}else if(typeof r.__type==="string"){for(let f in r)if(!(f in i))i[f]=this.serialize(15,r[f])}}else if(s.isDocumentSchema())for(let e in r)i[e]=this.serialize(s.getValueSchema(),r[e]);else if(s.isBigDecimalSchema())return r;return i}return n}flush(){let t=Je.serialize(this.value);return this.value=void 0,t}}class wh extends rh{read(t,n){let s=Je.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=ih.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return gM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return gM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(typeof n>"u"||typeof n==="boolean"||typeof n==="number"||typeof n==="string"||typeof n==="bigint"||typeof n==="symbol")return n;else if(typeof n==="object"){if(n===null)return null;if("byteLength"in n)return n;if(n instanceof Date)return n;if(s.isDocumentSchema())return n;if(s.isListSchema()){let i=[],e=s.getValueSchema();for(let f of n){let o=this.readValue(e,f);i.push(o)}return i}let r={};if(s.isMapSchema()){let i=s.getValueSchema();for(let e in n){let f=this.readValue(i,n[e]);r[e]=f}}else if(s.isStructSchema()){let i=s.isUnionSchema(),e;if(i){e=new Set;for(let f in n)if(f!=="__type")e.add(f)}for(let[f,o]of s.structIterator()){if(i)e.delete(f);if(n[f]!=null)r[f]=this.readValue(o,n[f])}if(i&&e?.size===1){let f=!0;for(let o in r){f=!1;break}if(f){let o=e.values().next().value;r.$unknown=[o,n[o]]}}else if(typeof n.__type==="string"){for(let f in n)if(!(f in r))r[f]=n[f]}}else if(n instanceof bM)return n;return r}else return n}}class IM extends B3{codec=new _h;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(Object.assign(r.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),F3(t.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:i,operation:e}=H3(s),f=`/service/${i}/operation/${e}`;if(r.path.endsWith("/"))r.path+=f.slice(1);else r.path+=f;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,i){let e=LM(s,r)??"Unknown",f={$metadata:i,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let c=this.compositeErrorRegistry,h=EM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(e)}catch(E){if(r.Message)r.message=r.Message;let d=EM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(d);let T=c.getBaseException();if(T){let U=c.getErrorCtor(T);throw Object.assign(new U({name:e}),f,r)}throw Object.assign(Error(e),f,r)}let _=ih.of(u),l=c.getErrorCtor(u),w=r.message??r.Message??"Unknown",A=new l({}),M={};for(let[E,d]of _.structIterator())M[E]=this.deserializer.readValue(d,r[E]);throw Object.assign(A,f,{$fault:_.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}rF.CborCodec=_h;rF.CborShapeDeserializer=wh;rF.CborShapeSerializer=lh;rF.SmithyRpcV2CborProtocol=IM;rF.buildHttpRpcRequest=sF;rF.cbor=Je;rF.checkCborResponse=nF;rF.dateToTag=Qe;rF.loadSmithyRpcV2CborErrorCode=LM;rF.parseCborBody=UM;rF.parseCborErrorBody=tF;rF.tag=oh;rF.tagSymbol=eh});var yM=Z((UF)=>{var EF=/[&<>"]/g,dF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function RF(t){return t.replace(EF,(n)=>dF[n])}var bF=/[&"'<>\r\n\u0085\u2028]/g,TF={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function SF(t){return t.replace(bF,(n)=>TF[n])}class Ah{value;constructor(t){this.value=t}toString(){return SF(""+this.value)}}class _i{name;children;attributes={};static of(t,n,s){let r=new _i(t);if(n!==void 0)r.addChildNode(new Ah(n));if(s!==void 0)r.withName(s);return r}constructor(t,n=[]){this.name=t,this.children=n}withName(t){return this.name=t,this}addAttribute(t,n){return this.attributes[t]=n,this}addChildNode(t){return this.children.push(t),this}removeAttribute(t){return delete this.attributes[t],this}n(t){return this.name=t,this}c(t){return this.children.push(t),this}a(t,n){if(n!=null)this.attributes[t]=n;return this}cc(t,n,s=n){if(t[n]!=null){let r=_i.of(n,t[n]).withName(s);this.c(r)}}l(t,n,s,r){if(t[n]!=null)r().map((e)=>{e.withName(s),this.c(e)})}lc(t,n,s,r){if(t[n]!=null){let i=r(),e=new _i(s);i.map((f)=>{e.c(f)}),this.c(e)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let r of Object.keys(s)){let i=s[r];if(i!=null)n+=` ${r}="${RF(""+i)}"`}return n+=!t?"/>":`>${this.children.map((r)=>r.toString()).join("")}</${this.name}>`}}function $F(t){return new Mh(t).parse()}class Mh{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
44
- `),this.z=this.x.length}parse(){let t=this,{z:n}=t;while(t.i<n){if(t.trim(),t.i>=n)break;if(t.isNext("<?"))t.readTo("?>"),t.trim();else if(t.isNext("<!--"))t.readTo("-->"),t.trim();else if(t.isNext("<!DOCTYPE",!1))t.skipDoctype(),t.trim();else if(t.x[t.i]==="<"){let s=t.parseTag();return{[s.tag]:s.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(t,n=!0){let s=this;if(n)return s.x.startsWith(t,s.i);return s.x.toLowerCase().startsWith(t.toLowerCase(),s.i)}readTo(t){let n=this,s=n.x.indexOf(t,n.i);if(s===-1)throw Error(`@aws-sdk XML parse error: expected "${t}" not found.`);let r=n.x.slice(n.i,s);return n.i=s+t.length,r}trim(){let t=this;while(t.i<t.z&&` \r
43
+ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`),Date.now()}return n}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((i)=>{n(this.resolveDefaultConfig(i))}).catch(s);else n(this.resolveDefaultConfig(t))})}destroy(){this.config?.httpAgent?.destroy(),this.config?.httpsAgent?.destroy()}async handle(t,{abortSignal:n,requestTimeout:s}={}){if(!this.config)this.config=await this.configProvider;let i=this.config,r=t.protocol==="https:";if(!r&&!this.config.httpAgent)this.config.httpAgent=await this.config.httpAgentProvider();return new Promise((e,f)=>{let o=void 0,c=-1,h=-1,u=-1,l=-1,_=-1,w=()=>{Mt.clearTimeout(c),Mt.clearTimeout(h),Mt.clearTimeout(u),Mt.clearTimeout(l),Mt.clearTimeout(_)},A=async(R)=>{await o,w(),e(R)},M=async(R)=>{await o,w(),f(R)};if(n?.aborted){let R=We(n);M(R);return}let d=t.headers,E=d?(d.Expect??d.expect)==="100-continue":!1,T=r?i.httpsAgent:i.httpAgent;if(E&&!this.externalAgent)T=new(r?Pe.Agent:Ne)({keepAlive:!1,maxSockets:1/0});c=Mt.setTimeout(()=>{this.socketWarningTimestamp=De.checkSocketUsage(T,this.socketWarningTimestamp,i.logger)},i.socketAcquisitionWarningTimeout??(i.requestTimeout??2000)+(i.connectionTimeout??1000));let U=t.query?uM(t.query):"",S=void 0;if(t.username!=null||t.password!=null){let R=t.username??"",W=t.password??"";S=`${R}:${W}`}let y=t.path;if(U)y+=`?${U}`;if(t.fragment)y+=`#${t.fragment}`;let D=t.hostname??"";if(D[0]==="["&&D.endsWith("]"))D=t.hostname.slice(1,-1);else D=t.hostname;let q={headers:t.headers,host:D,method:t.method,path:y,port:t.port,agent:T,auth:S},J=(r?Pe.request:cM)(q,(R)=>{let W=new lM({statusCode:R.statusCode||-1,reason:R.statusMessage,headers:_M(R.headers),body:R});A({response:W})});if(J.on("error",(R)=>{if(l3.includes(R.code))M(Object.assign(R,{name:"TimeoutError"}));else M(R)}),n){let R=()=>{J.destroy();let W=We(n);M(W)};if(typeof n.addEventListener==="function"){let W=n;W.addEventListener("abort",R,{once:!0}),J.once("close",()=>W.removeEventListener("abort",R))}else n.onabort=R}let G=s??i.requestTimeout;h=_3(J,M,i.connectionTimeout),u=w3(J,M,G,i.throwOnRequestTimeout,i.logger??console),l=g3(J,M,i.socketTimeout);let K=q.agent;if(typeof K==="object"&&"keepAlive"in K)_=M3(J,{keepAlive:K.keepAlive,keepAliveMsecs:K.keepAliveMsecs});o=wM(J,t,G,this.externalAgent).catch((R)=>{return w(),f(R)})})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}resolveDefaultConfig(t){let{requestTimeout:n,connectionTimeout:s,socketTimeout:i,socketAcquisitionWarningTimeout:r,httpAgent:e,httpsAgent:f,throwOnRequestTimeout:o,logger:c}=t||{},h=!0,u=50;return{connectionTimeout:s,requestTimeout:n,socketTimeout:i,socketAcquisitionWarningTimeout:r,throwOnRequestTimeout:o,httpAgentProvider:async()=>{let l=nt("http"),{Agent:_,request:w}=l.default??l;if(cM=w,Ne=_,e instanceof Ne||typeof e?.destroy==="function")return this.externalAgent=!0,e;return new Ne({keepAlive:!0,maxSockets:50,...e})},httpsAgent:(()=>{if(f instanceof Pe.Agent||typeof f?.destroy==="function")return this.externalAgent=!0,f;return new Pe.Agent({keepAlive:!0,maxSockets:50,...f})})(),logger:c}}}var R3=new Uint16Array(1);class me{id=R3[0]++;total=0;max=0;session;refs=0;constructor(t){t.unref(),this.session=t}retain(){if(this.session.destroyed)throw Error("@smithy/node-http-handler - cannot acquire reference to destroyed session.");this.refs+=1,this.total+=1,this.max=Math.max(this.refs,this.max),this.session.ref()}free(){if(this.session.destroyed)return;if(this.refs-=1,this.refs===0)this.session.unref();if(this.refs<0)throw Error("@smithy/node-http-handler - ClientHttp2Session refcount at zero, cannot decrement.")}deref(){return this.session}close(){if(!this.session.closed)this.session.close()}destroy(){if(this.refs=0,!this.session.destroyed)this.session.destroy()}useCount(){return this.refs}}class AM{sessions=[];maxConcurrency=0;constructor(t){this.sessions=(t??[]).map((n)=>new me(n))}poll(){let t=!1;for(let n of this.sessions){if(n.deref().destroyed){t=!0;continue}if(!this.maxConcurrency||n.useCount()<this.maxConcurrency)return n}if(t){for(let n of this.sessions)if(n.deref().destroyed)this.remove(n)}}offerLast(t){this.sessions.push(t)}remove(t){let n=this.sessions.indexOf(t);if(n>-1)this.sessions.splice(n,1)}[Symbol.iterator](){return this.sessions[Symbol.iterator]()}setMaxConcurrency(t){this.maxConcurrency=t}destroy(t){this.remove(t),t.destroy()}}class MM{config;connectOptions;connectionPools=new Map;constructor(t){if(this.config=t,this.config.maxConcurrency&&this.config.maxConcurrency<=0)throw RangeError("maxConcurrency must be greater than zero.")}lease(t,n){let s=this.getUrlString(t),i=this.getPool(s);if(!this.config.disableConcurrency&&!n.isEventStream){let c=i.poll();if(c)return c.retain(),c}let r=new me(this.connect(s)),e=r.deref();if(this.config.maxConcurrency)e.settings({maxConcurrentStreams:this.config.maxConcurrency},(c)=>{if(c)throw Error("Fail to set maxConcurrentStreams to "+this.config.maxConcurrency+"when creating new session for "+t.destination.toString())});let f=()=>{this.removeFromPoolAndClose(s,r)},o=()=>{this.removeFromPoolAndCheckedDestroy(s,r)};if(e.on("goaway",f),e.on("error",o),e.on("frameError",o),e.on("close",o),n.requestTimeout)e.setTimeout(n.requestTimeout,o);return i.offerLast(r),r.retain(),r}release(t,n){n.free()}createIsolatedSession(t,n){let s=this.getUrlString(t),i=new me(this.connect(s)),r=i.deref();r.settings({maxConcurrentStreams:1});let e=()=>{i.destroy()};if(r.on("error",e),r.on("frameError",e),r.on("close",e),n.requestTimeout)r.setTimeout(n.requestTimeout,e);return i.retain(),i}destroy(){for(let[t,n]of this.connectionPools){for(let s of[...n])s.destroy();this.connectionPools.delete(t)}}setMaxConcurrentStreams(t){if(t&&t<=0)throw RangeError("maxConcurrentStreams must be greater than zero.");this.config.maxConcurrency=t;for(let n of this.connectionPools.values())n.setMaxConcurrency(t)}setDisableConcurrentStreams(t){this.config.disableConcurrency=t}setNodeHttp2ConnectOptions(t){this.connectOptions=t}debug(){let t={};for(let[n,s]of this.connectionPools){let i=[];for(let r of s)i.push({id:r.id,active:r.useCount(),maxConcurrent:r.max,totalRequests:r.total});t[n]={sessions:i}}return t}removeFromPoolAndClose(t,n){this.connectionPools.get(t)?.remove(n),n.close()}removeFromPoolAndCheckedDestroy(t,n){this.connectionPools.get(t)?.remove(n),n.destroy()}getPool(t){if(!this.connectionPools.has(t)){let n=new AM;if(this.config.maxConcurrency)n.setMaxConcurrency(this.config.maxConcurrency);this.connectionPools.set(t,n)}return this.connectionPools.get(t)}getUrlString(t){return t.destination.toString()}connect(t){return this.connectOptions===void 0?ac.connect(t):ac.connect(t,this.connectOptions)}}var{constants:hM}=ac;class pc{config;configProvider;metadata={handlerProtocol:"h2"};connectionManager=new MM({});static create(t){if(typeof t?.handle==="function")return t;return new pc(t)}constructor(t){this.configProvider=new Promise((n,s)=>{if(typeof t==="function")t().then((i)=>{n(i||{})}).catch(s);else n(t||{})})}destroy(){this.connectionManager.destroy()}async handle(t,{abortSignal:n,requestTimeout:s,isEventStream:i}={}){if(!this.config){this.config=await this.configProvider;let{disableConcurrentStreams:c,maxConcurrentStreams:h,nodeHttp2ConnectOptions:u}=this.config;if(this.connectionManager.setDisableConcurrentStreams(c??!1),h)this.connectionManager.setMaxConcurrentStreams(h);if(u)this.connectionManager.setNodeHttp2ConnectOptions(u)}let{requestTimeout:r,disableConcurrentStreams:e}=this.config,f=e||i,o=s??r;return new Promise((c,h)=>{let u=!1,l=void 0,_=async(W)=>{await l,c(W)},w=async(W)=>{await l,h(W)};if(n?.aborted){u=!0;let W=We(n);w(W);return}let{hostname:A,method:M,port:d,protocol:E,query:T}=t,U="";if(t.username!=null||t.password!=null){let W=t.username??"",k=t.password??"";U=`${W}:${k}@`}let S=`${E}//${U}${A}${d?`:${d}`:""}`,y={destination:new URL(S)},D={requestTimeout:this.config?.sessionTimeout,isEventStream:i},q=f?this.connectionManager.createIsolatedSession(y,D):this.connectionManager.lease(y,D),tt=q.deref(),J=(W)=>{if(f)q.destroy();u=!0,w(W)},G=T?uM(T):"",K=t.path;if(G)K+=`?${G}`;if(t.fragment)K+=`#${t.fragment}`;let R=tt.request({...t.headers,[hM.HTTP2_HEADER_PATH]:K,[hM.HTTP2_HEADER_METHOD]:M});if(o)R.setTimeout(o,()=>{R.close();let W=Error(`Stream timed out because of no activity for ${o} ms`);W.name="TimeoutError",J(W)});if(n){let W=()=>{R.close();let k=We(n);J(k)};if(typeof n.addEventListener==="function"){let k=n;k.addEventListener("abort",W,{once:!0}),R.once("close",()=>k.removeEventListener("abort",W))}else n.onabort=W}R.on("frameError",(W,k,st)=>{J(Error(`Frame type id ${W} in stream id ${st} has failed with code ${k}.`))}),R.on("error",J),R.on("aborted",()=>{J(Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${R.rstCode}.`))}),R.on("response",(W)=>{let k=new lM({statusCode:W[":status"]??-1,headers:_M(W),body:R});if(u=!0,_({response:k}),f)tt.close()}),R.on("close",()=>{if(f)q.destroy();else this.connectionManager.release(y,q);if(!u)J(Error("Unexpected error: http2 request did not get a response"))}),l=wM(R,t,o)})}updateHttpClientConfig(t,n){this.config=void 0,this.configProvider=this.configProvider.then((s)=>{return{...s,[t]:n}})}httpHandlerConfigs(){return this.config??{}}}b3.DEFAULT_REQUEST_TIMEOUT=E3;b3.NodeHttp2Handler=pc;b3.NodeHttpHandler=De});var yM=Z((iF)=>{var{nv:L3,NumericValue:bM,calculateBodyLength:I3,_parseEpochTimestamp:gM,fromBase64:TM,generateIdempotencyToken:y3}=$t(),{HttpRequest:O3,collectBody:G3,SerdeContext:ih,RpcProtocol:B3}=Ut(),{NormalizedSchema:rh,deref:F3,TypeRegistry:dM}=Nn(),{getSmithyContext:H3}=nn();function ei(t){return typeof Buffer<"u"?Buffer.alloc(t):new Uint8Array(t)}var eh=Symbol("@smithy/core/cbor::tagSymbol");function oh(t){return t[eh]=!0,t}var SM=typeof Buffer<"u",fh=new TextDecoder,C=ei(0),ch=!1,qt=new DataView(C.buffer,C.byteOffset,C.byteLength),Y=0;function P3(t){C=t,ch=SM&&C instanceof Buffer,qt=new DataView(C.buffer,C.byteOffset,C.byteLength)}function Xn(t,n){if(t>=n)throw Error("unexpected end of (decode) payload.");let s=(C[t]&224)>>5,i=C[t]&31;if(i===31&&2<=s&&s<=5)return N3(t,n);switch(s){case 0:case 1:case 6:{let r,e;if(i<24)r=i,e=1;else switch(i){case 24:if(n-t<2)cn(1);r=C[t+1],e=2;break;case 25:if(n-t<3)cn(2);r=qt.getUint16(t+1),e=3;break;case 26:if(n-t<5)cn(4);r=qt.getUint32(t+1),e=5;break;case 27:if(n-t<9)cn(8);{let f=qt.getUint32(t+1);if(f<2097152)r=f*4294967296+qt.getUint32(t+5);else r=qt.getBigUint64(t+1)}e=9;break;default:uh(i)}if(s===0)return Y=e,th(r);else if(s===1){let f;if(typeof r==="bigint")f=BigInt(-1)-r;else f=-1-r;return Y=e,th(f)}else return z3(t,n,i,r,e)}case 3:return hr(t,n);case 5:return D3(t,n);case 4:return Q3(t,n);case 2:return hh(t,n);default:return X3(t,n)}}function N3(t,n){let s=(C[t]&224)>>5;if((C[t]&31)===31)switch(s){case 3:return C3(t,n);case 5:return x3(t,n);case 4:return q3(t,n);case 2:return K3(t,n)}}function W3(t,n){let s=t>>7,i=(t&124)>>2,r=(t&3)<<8|n,e=s===0?1:-1;if(i===0){if(r===0)return 0;return e*(Math.pow(2,-14)*(r/1024))}else if(i===31){if(r===0)return e*(1/0);return NaN}return e*(Math.pow(2,i-15)*(1+r/1024))}function D3(t,n){let s=ur(t,n);if(s<15)return Y3(t,n,s);return m3(t,n,s)}function m3(t,n,s){let i=Y;t+=i;let r=t,e=Object.create(null);for(let f=0;f<s;++f){let o=hr(t,n);if(t+=Y,(C[t]&224)>>5===3)e[o]=hr(t,n);else e[o]=Xn(t,n);t+=Y}return Y=i+(t-r),Object.setPrototypeOf(e,Object.prototype),e}function Y3(t,n,s){let i=Y;t+=i;let r=t,e={};for(let f=0;f<s;++f){let o=hr(t,n);t+=Y,e[o]=Xn(t,n),t+=Y}return Y=i+(t-r),e}function Q3(t,n){let s=ur(t,n),i=Y;t+=i;let r=t,e=Array(s);for(let f=0;f<s;++f)e[f]=Xn(t,n),t+=Y;return Y=i+(t-r),e}function hr(t,n){let s=ur(t,n),i=Y;if(t+=i,n-t<s)cn(s);if(Y=i+s,s<24)return k3(t,s);if(ch)return C.toString("utf-8",t,t+s);return fh.decode(C.subarray(t,t+s))}var EM=Array(2048),Zc=new Uint16Array(2048),fr=0;function J3(){fr=fr+1&65535}function k3(t,n){let s=n;for(let f=0;f<n;++f)s=s*31+C[t+f]|0;let i=s>>>0&2047,r=EM[i];if(r!==void 0){if(r.length===n){let f=!0;for(let o=0;o<n;++o)if(r.charCodeAt(o)!==C[t+o]){f=!1;break}if(f)return Zc[i]=fr,r}}let e=ch?C.toString("utf-8",t,t+n):fh.decode(C.subarray(t,t+n));if(Zc[i]!==fr)EM[i]=e,Zc[i]=fr;return e}function hh(t,n){let s=ur(t,n),i=Y;if(t+=i,n-t<s)cn(s);let r=C.subarray(t,t+s);return Y=i+s,r}function z3(t,n,s,i,r){if(s===2||s===3){let e=ur(t+r,n),f=BigInt(0),o=t+r+Y;for(let c=o;c<o+e;++c)f=f<<BigInt(8)|BigInt(C[c]);return Y=r+Y+e,s===3?-f-BigInt(1):f}else if(s===4){let e=Xn(t+r,n),[f,o]=e,c=o<0?-1:1,h="0".repeat(Math.abs(f)+1)+String(BigInt(c)*BigInt(o)),u,l=o<0?"-":"";if(u=f===0?h:h.slice(0,h.length+f)+"."+h.slice(f),u=u.replace(/^0+/g,""),u==="")u="0";if(u[0]===".")u="0"+u;return u=l+u,Y=r+Y,L3(u)}else{let e=Xn(t+r,n);return Y=r+Y,oh({tag:th(i),value:e})}}function X3(t,n){let s=C[t]&31;switch(s){case 21:case 20:return Y=1,s===21;case 22:return Y=1,null;case 23:return Y=1,null;case 25:if(n-t<3)throw Error("incomplete float16 at end of buf.");return Y=3,W3(C[t+1],C[t+2]);case 26:if(n-t<5)throw Error("incomplete float32 at end of buf.");return Y=5,qt.getFloat32(t+1);case 27:if(n-t<9)throw Error("incomplete float64 at end of buf.");return Y=9,qt.getFloat64(t+1);default:uh(s)}}function ur(t,n){let s=C[t]&31;if(s<24)return Y=1,s;switch(s){case 24:if(n-t<2)cn(1);return Y=2,C[t+1];case 25:if(n-t<3)cn(2);return Y=3,qt.getUint16(t+1);case 26:if(n-t<5)cn(4);return Y=5,qt.getUint32(t+1);case 27:if(n-t<9)cn(8);return Y=9,V3(qt.getBigUint64(t+1));default:uh(s)}}function x3(t,n){t+=1;let s=t,i={};for(;t<n;){if(C[t]===255)return Y=t-s+2,i;let r=hr(t,n);t+=Y,i[r]=Xn(t,n),t+=Y}throw Error("expected break marker.")}function q3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255)return Y=t-i+2,s;s.push(Xn(t,n)),t+=Y}throw Error("expected break marker.")}function C3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255){let c=ei(s.length);if(c.set(s,0),Y=t-i+2,SM)return c.toString("utf-8",0,c.length);return fh.decode(c)}let r=(C[t]&224)>>5,e=C[t]&31;if(r!==3)$M(r);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=Y;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function K3(t,n){t+=1;let s=[];for(let i=t;t<n;){if(C[t]===255){let c=ei(s.length);return c.set(s,0),Y=t-i+2,c}let r=(C[t]&224)>>5,e=C[t]&31;if(r!==2)$M(r);if(e===31)throw Error("nested indefinite string.");let f=hh(t,n);t+=Y;for(let c=0;c<f.length;++c)s.push(f[c])}throw Error("expected break marker.")}function th(t){if(typeof t==="number")return t;let n=Number(t);if(Number.MIN_SAFE_INTEGER<=n&&n<=Number.MAX_SAFE_INTEGER)return n;return t}function V3(t){let n=Number(t);if(n<Number.MIN_SAFE_INTEGER||Number.MAX_SAFE_INTEGER<n)console.warn(Error(`@smithy/core/cbor - truncating BigInt(${t}) to ${n} with loss of precision.`));return n}function cn(t){throw Error(`length ${t} greater than remaining buf len.`)}function uh(t){throw Error(`unexpected minor value ${t}.`)}function $M(t){throw Error(`unexpected major type ${t} in indefinite string.`)}var j3=typeof Buffer<"u",ii=new Map,cr=0,nh=!1,a3=2048,H=ei(a3),Dt=new DataView(H.buffer,H.byteOffset,H.byteLength),I=0;function p3(t){let n=[t];while(n.length){let s=n.pop();if(typeof s==="string"){let i=s.length;if(j3)if(ri(i*3+9),i>23)vc(3,Buffer.byteLength(s)),I+=H.write(s,I);else v3(s);else{let r=i*3;ri(r+9);let e=I,o=new TextEncoder().encodeInto(s,H.subarray(I+9)).written,c;if(o<24)c=1;else if(o<256)c=2;else if(o<65536)c=3;else if(o<4294967296)c=5;else c=9;if(c<9)H.copyWithin(e+c,e+9,e+9+o);I=e,ws(3,o),I+=o}continue}if(H.byteLength-I<9)ri(64);if(typeof s==="number"){if(Number.isInteger(s)){let i=s>=0,r=i?0:1,e=i?s:-s-1;if(e<24)H[I++]=r<<5|e;else if(e<256)H[I++]=r<<5|24,H[I++]=e;else if(e<65536)H[I++]=r<<5|25,H[I++]=e>>8,H[I++]=e&255;else if(e<4294967296)H[I++]=r<<5|26,Dt.setUint32(I,e),I+=4;else{H[I++]=r<<5|27;let f=e/4294967296|0,o=e-f*4294967296|0;Dt.setUint32(I,f),Dt.setUint32(I+4,o),I+=8}continue}H[I++]=251,Dt.setFloat64(I,s),I+=8;continue}else if(typeof s==="bigint"){let i=s>=0,r=i?0:1,e=i?s:-s-BigInt(1);if(e<BigInt("18446744073709551616")){let f=Number(e);if(f<4294967296)ws(r,f);else H[I++]=r<<5|27,Dt.setBigUint64(I,e),I+=8}else{let f=e.toString(2),o=new Uint8Array(Math.ceil(f.length/8)),c=e,h=0;while(o.byteLength-++h>=0)o[o.byteLength-h]=Number(c&BigInt(255)),c>>=BigInt(8);ri(o.byteLength*2+16),H[I++]=i?194:195,vc(2,o.byteLength),H.set(o,I),I+=o.byteLength}continue}else if(s===null){H[I++]=246;continue}else if(typeof s==="boolean"){H[I++]=224|(s?21:20);continue}else if(typeof s>"u")throw Error("@smithy/core/cbor: client may not serialize undefined value.");else if(Array.isArray(s)){ws(4,s.length),ri(s.length*9+64);for(let i=s.length-1;i>=0;--i)n.push(s[i]);continue}else if(typeof s.byteLength==="number"){ri(s.length*2+9),ws(2,s.length),H.set(s,I),I+=s.byteLength;continue}else if(typeof s==="object"){if(s instanceof bM){let e=s.string.indexOf("."),f=e===-1?0:e-s.string.length+1,o=BigInt(s.string.replace(".",""));H[I++]=196,ws(4,2),n.push(o),n.push(f);continue}if(s[eh])if("tag"in s&&"value"in s){n.push(s.value),vc(6,s.tag);continue}else throw Error("tag encountered with missing fields, need 'tag' and 'value', found: "+JSON.stringify(s));let i=Object.keys(s),r=i.length;ws(5,r);for(let e=r-1;e>=0;--e)n.push(s[i[e]]),n.push(i[e]);continue}throw Error(`data type ${s?.constructor?.name??typeof s} not compatible for encoding.`)}}function Z3(){cr=cr+1&65535,nh=!1}function RM(){let t=ei(I);return t.set(H.subarray(0,I),0),I=0,t}function sh(t){let n=H;if(H=ei(t),n)if(n.copy)n.copy(H,0,0,n.byteLength);else H.set(n,0);Dt=new DataView(H.buffer,H.byteOffset,H.byteLength)}function v3(t){let n=ii.get(t);if(n!==void 0){H.set(n.bytes,I),I+=n.bytes.length,n.epoch=cr;return}let s=I,i=Buffer.byteLength(t);ws(3,i),I+=H.write(t,I);let r=Uint8Array.prototype.slice.call(H,s,I);if(ii.size>=2048){if(nh)return;let e=0;for(let[f,o]of ii){if(e>=1024)break;if(o.epoch!==cr)ii.delete(f),e++}if(e===0){nh=!0;return}}if(ii.size<2048)ii.set(t,{epoch:cr,bytes:r})}function ri(t){if(H.byteLength-I<t)if(I<16000000)sh(Math.max(H.byteLength*4,H.byteLength+t));else sh(H.byteLength+t+16000000)}function vc(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,Dt.setUint16(I,n),I+=2;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else H[I++]=t<<5|27,Dt.setBigUint64(I,typeof n==="bigint"?n:BigInt(n)),I+=8}function ws(t,n){if(n<24)H[I++]=t<<5|n;else if(n<256)H[I++]=t<<5|24,H[I++]=n;else if(n<65536)H[I++]=t<<5|25,H[I++]=n>>8,H[I++]=n&255;else if(n<4294967296)H[I++]=t<<5|26,Dt.setUint32(I,n),I+=4;else{H[I++]=t<<5|27;let s=n/4294967296|0,i=n-s*4294967296|0;Dt.setUint32(I,s),Dt.setUint32(I+4,i),I+=8}}var Je={deserialize(t){return J3(),P3(t),Xn(0,t.length)},serialize(t){Z3();try{return p3(t),RM()}catch(n){throw RM(),n}},resizeEncodingBuffer(t){sh(t)}},UM=(t,n)=>{return G3(t,n).then(async(s)=>{if(s.length)try{return Je.deserialize(s)}catch(i){throw Object.defineProperty(i,"$responseBodyText",{value:n.utf8Encoder(s)}),i}return{}})},Qe=(t)=>{return oh({tag:1,value:t.getTime()/1000})},tF=async(t,n)=>{let s=await UM(t,n);return s.message=s.message??s.Message,s},LM=(t,n)=>{let s=(r)=>{let e=r;if(typeof e==="number")e=e.toString();if(e.indexOf(",")>=0)e=e.split(",")[0];if(e.indexOf(":")>=0)e=e.split(":")[0];if(e.indexOf("#")>=0)e=e.split("#")[1];return e};if(n.__type!==void 0)return s(n.__type);let i;for(let r in n)if(r.toLowerCase()==="code"){i=r;break}if(i&&n[i]!==void 0)return s(n[i])},nF=(t)=>{if(String(t.headers["smithy-protocol"]).toLowerCase()!=="rpc-v2-cbor")throw Error("Malformed RPCv2 CBOR response, status: "+t.statusCode)},sF=async(t,n,s,i,r)=>{let e=await t.endpoint(),{hostname:f,protocol:o="https",port:c,path:h}=e,u={protocol:o,hostname:f,port:c,method:"POST",path:h.endsWith("/")?h.slice(0,-1)+s:h+s,headers:{...n}};if(i!==void 0)u.hostname=i;if(e.headers)for(let l in e.headers)u.headers[l]=e.headers[l];if(r!==void 0){u.body=r;try{u.headers["content-length"]=String(I3(r))}catch(l){}}return new O3(u)};class lh extends ih{createSerializer(){let t=new _h;return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new wh;return t.setSerdeContext(this.serdeContext),t}}class _h extends ih{value;write(t,n){this.value=this.serialize(t,n)}serialize(t,n){let s=rh.of(t);if(n==null){if(s.isIdempotencyToken())return y3();return n}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(s.isTimestampSchema()){if(typeof n==="number"||typeof n==="bigint")return Qe(new Date(Number(n)/1000|0));return Qe(n)}if(typeof n==="function"||typeof n==="object"){let i=n;if(s.isListSchema()&&Array.isArray(i)){let e=!!s.getMergedTraits().sparse,f=[],o=0;for(let c of i){let h=this.serialize(s.getValueSchema(),c);if(h!=null||e)f[o++]=h}return f}if(i instanceof Date)return Qe(i);let r={};if(s.isMapSchema()){let e=!!s.getMergedTraits().sparse;for(let f in i){let o=this.serialize(s.getValueSchema(),i[f]);if(o!=null||e)r[f]=o}}else if(s.isStructSchema()){for(let[f,o]of s.structIterator()){let c=this.serialize(o,i[f]);if(c!=null)r[f]=c}if(s.isUnionSchema()&&Array.isArray(i.$unknown)){let[f,o]=i.$unknown;r[f]=o}else if(typeof i.__type==="string"){for(let f in i)if(!(f in r))r[f]=this.serialize(15,i[f])}}else if(s.isDocumentSchema())for(let e in i)r[e]=this.serialize(s.getValueSchema(),i[e]);else if(s.isBigDecimalSchema())return i;return r}return n}flush(){let t=Je.serialize(this.value);return this.value=void 0,t}}class wh extends ih{read(t,n){let s=Je.deserialize(n);return this.readValue(t,s)}readValue(t,n){let s=rh.of(t);if(s.isTimestampSchema()){if(typeof n==="number")return gM(n);if(typeof n==="object"){if(n.tag===1&&"value"in n)return gM(n.value)}}if(s.isBlobSchema()){if(typeof n==="string")return(this.serdeContext?.base64Decoder??TM)(n);return n}if(typeof n>"u"||typeof n==="boolean"||typeof n==="number"||typeof n==="string"||typeof n==="bigint"||typeof n==="symbol")return n;else if(typeof n==="object"){if(n===null)return null;if("byteLength"in n)return n;if(n instanceof Date)return n;if(s.isDocumentSchema())return n;if(s.isListSchema()){let r=[],e=s.getValueSchema();for(let f of n){let o=this.readValue(e,f);r.push(o)}return r}let i={};if(s.isMapSchema()){let r=s.getValueSchema();for(let e in n){let f=this.readValue(r,n[e]);i[e]=f}}else if(s.isStructSchema()){let r=s.isUnionSchema(),e;if(r){e=new Set;for(let f in n)if(f!=="__type")e.add(f)}for(let[f,o]of s.structIterator()){if(r)e.delete(f);if(n[f]!=null)i[f]=this.readValue(o,n[f])}if(r&&e?.size===1){let f=!0;for(let o in i){f=!1;break}if(f){let o=e.values().next().value;i.$unknown=[o,n[o]]}}else if(typeof n.__type==="string"){for(let f in n)if(!(f in i))i[f]=n[f]}}else if(n instanceof bM)return n;return i}else return n}}class IM extends B3{codec=new lh;serializer=this.codec.createSerializer();deserializer=this.codec.createDeserializer();constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n})}getShapeId(){return"smithy.protocols#rpcv2Cbor"}getPayloadCodec(){return this.codec}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(Object.assign(i.headers,{"content-type":this.getDefaultContentType(),"smithy-protocol":"rpc-v2-cbor",accept:this.getDefaultContentType()}),F3(t.input)==="unit")delete i.body,delete i.headers["content-type"];else{if(!i.body)this.serializer.write(15,{}),i.body=this.serializer.flush();try{i.headers["content-length"]=String(i.body.byteLength)}catch(o){}}let{service:r,operation:e}=H3(s),f=`/service/${r}/operation/${e}`;if(i.path.endsWith("/"))i.path+=f.slice(1);else i.path+=f;return i}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,i,r){let e=LM(s,i)??"Unknown",f={$metadata:r,$fault:s.statusCode<=500?"client":"server"},o=this.options.defaultNamespace;if(e.includes("#"))[o]=e.split("#");let c=this.compositeErrorRegistry,h=dM.for(o);c.copyFrom(h);let u;try{u=c.getSchema(e)}catch(d){if(i.Message)i.message=i.Message;let E=dM.for("smithy.ts.sdk.synthetic."+o);c.copyFrom(E);let T=c.getBaseException();if(T){let U=c.getErrorCtor(T);throw Object.assign(new U({name:e}),f,i)}throw Object.assign(Error(e),f,i)}let l=rh.of(u),_=c.getErrorCtor(u),w=i.message??i.Message??"Unknown",A=new _({}),M={};for(let[d,E]of l.structIterator())M[d]=this.deserializer.readValue(E,i[d]);throw Object.assign(A,f,{$fault:l.getMergedTraits().error,message:w},M)}getDefaultContentType(){return"application/cbor"}}iF.CborCodec=lh;iF.CborShapeDeserializer=wh;iF.CborShapeSerializer=_h;iF.SmithyRpcV2CborProtocol=IM;iF.buildHttpRpcRequest=sF;iF.cbor=Je;iF.checkCborResponse=nF;iF.dateToTag=Qe;iF.loadSmithyRpcV2CborErrorCode=LM;iF.parseCborBody=UM;iF.parseCborErrorBody=tF;iF.tag=oh;iF.tagSymbol=eh});var OM=Z((UF)=>{var dF=/[&<>"]/g,EF={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"};function RF(t){return t.replace(dF,(n)=>EF[n])}var bF=/[&"'<>\r\n\u0085\u2028]/g,TF={"&":"&amp;",'"':"&quot;","'":"&apos;","<":"&lt;",">":"&gt;","\r":"&#x0D;","\n":"&#x0A;","\x85":"&#x85;","\u2028":"&#x2028;"};function SF(t){return t.replace(bF,(n)=>TF[n])}class Ah{value;constructor(t){this.value=t}toString(){return SF(""+this.value)}}class lr{name;children;attributes={};static of(t,n,s){let i=new lr(t);if(n!==void 0)i.addChildNode(new Ah(n));if(s!==void 0)i.withName(s);return i}constructor(t,n=[]){this.name=t,this.children=n}withName(t){return this.name=t,this}addAttribute(t,n){return this.attributes[t]=n,this}addChildNode(t){return this.children.push(t),this}removeAttribute(t){return delete this.attributes[t],this}n(t){return this.name=t,this}c(t){return this.children.push(t),this}a(t,n){if(n!=null)this.attributes[t]=n;return this}cc(t,n,s=n){if(t[n]!=null){let i=lr.of(n,t[n]).withName(s);this.c(i)}}l(t,n,s,i){if(t[n]!=null)i().map((e)=>{e.withName(s),this.c(e)})}lc(t,n,s,i){if(t[n]!=null){let r=i(),e=new lr(s);r.map((f)=>{e.c(f)}),this.c(e)}}toString(){let t=Boolean(this.children.length),n=`<${this.name}`,s=this.attributes;for(let i of Object.keys(s)){let r=s[i];if(r!=null)n+=` ${i}="${RF(""+r)}"`}return n+=!t?"/>":`>${this.children.map((i)=>i.toString()).join("")}</${this.name}>`}}function $F(t){return new Mh(t).parse()}class Mh{x;i=0;z;constructor(t){this.x=t,this.x=t.replace(/\r\n?/g,`
44
+ `),this.z=this.x.length}parse(){let t=this,{z:n}=t;while(t.i<n){if(t.trim(),t.i>=n)break;if(t.isNext("<?"))t.readTo("?>"),t.trim();else if(t.isNext("<!--"))t.readTo("-->"),t.trim();else if(t.isNext("<!DOCTYPE",!1))t.skipDoctype(),t.trim();else if(t.x[t.i]==="<"){let s=t.parseTag();return{[s.tag]:s.value}}else throw Error("@aws-sdk XML parse error: unexpected content.")}throw Error("@aws-sdk XML parse error: no root element.")}isNext(t,n=!0){let s=this;if(n)return s.x.startsWith(t,s.i);return s.x.toLowerCase().startsWith(t.toLowerCase(),s.i)}readTo(t){let n=this,s=n.x.indexOf(t,n.i);if(s===-1)throw Error(`@aws-sdk XML parse error: expected "${t}" not found.`);let i=n.x.slice(n.i,s);return n.i=s+t.length,i}trim(){let t=this;while(t.i<t.z&&` \r
45
45
  `.includes(t.x[t.i]))++t.i}readAttrValue(){let t=this,n=t.x[t.i];++t.i;let s="";while(t.i<t.z&&t.x[t.i]!==n)s+=t.x[t.i++];return++t.i,t.decodeEntities(s)}parseTag(){let t=this;++t.i;let n="";while(t.i<t.z&&!` \r
46
- >/`.includes(t.x[t.i]))n+=t.x[t.i++];let s=!1,r=Object.create(null);while(t.i<t.z){if(t.trim(),">/".includes(t.x[t.i]))break;let h="";while(t.i<t.z&&!`= \r
47
- >/?`.includes(t.x[t.i]))h+=t.x[t.i++];if(t.trim(),t.x[t.i]!=="=")break;++t.i,t.trim(),r[h]=t.readAttrValue(),s=!0}if(t.i>=t.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(t.x[t.i]==="/"){if(++t.i,t.i>=t.z||t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++t.i,Object.setPrototypeOf(r,Object.prototype),{tag:n,value:s?r:""}}if(t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++t.i;let i=[],e=[],f=!1;while(t.i<t.z){if(t.isNext("</"))break;if(t.x[t.i]==="<")if(t.isNext("<!--"))t.readTo("-->");else if(t.isNext("<![CDATA["))t.i+=9,i.push(t.readTo("]]>"));else if(t.isNext("<?"))t.readTo("?>");else f=!0,e.push(t.parseTag());else{let h="";while(t.i<t.z&&t.x[t.i]!=="<")h+=t.x[t.i++];i.push(t.decodeEntities(h))}}if(!t.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${n}>.`);t.i+=2;let o=t.readTo(">").trim();if(o!==n)throw Error(`@aws-sdk XML parse error: mismatched tags <${n}> and </${o}>.`);if(!s&&i.length===0&&!f)return{tag:n,value:""};if(!s&&!f){let h=i.length===1?i[0]:i.join("");if(h.trim()===""&&h.includes(`
48
- `))return{tag:n,value:""};return{tag:n,value:h}}let c=Object.create(null);for(let h of i){if(h.trim()===""&&h.includes(`
49
- `))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of e)if(h.tag in c)if(Array.isArray(c[h.tag]))c[h.tag].push(h.value);else c[h.tag]=[c[h.tag],h.value];else c[h.tag]=h.value;for(let[h,u]of Object.entries(r))c[h]=u;return Object.setPrototypeOf(c,Object.prototype),{tag:n,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let t=this;t.i+=9;let n=0;while(t.i<t.z){let s=t.x[t.i];if(s==="[")++n;else if(s==="]")--n;else if(s===">"&&n===0){++t.i;return}++t.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(t){return t.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(n,s,r,i)=>{if(s)return String.fromCharCode(parseInt(s,16));if(r)return String.fromCharCode(parseInt(r,10));return Mh.ENTITIES[i]??""})}}UF.XmlNode=_i;UF.XmlText=Ah;UF.parseXML=$F});var Oh=Z((XF)=>{var{SmithyRpcV2CborProtocol:yF,loadSmithyRpcV2CborErrorCode:GF}=OM(),{TypeRegistry:GM,NormalizedSchema:ft,deref:WM}=Nn(),{decorateServiceException:BM,getValueFromTextNode:DM}=Rn(),{collectBody:Eh,determineTimestampFormat:ze,RpcProtocol:YM,HttpBindingProtocol:mM,HttpInterceptingShapeSerializer:QM,HttpInterceptingShapeDeserializer:JM,FromStringShapeDeserializer:BF,extendedEncodeURIComponent:FM}=Ut(),{NumericValue:hn,toUtf8:kM,fromBase64:XM,LazyJsonString:zM,parseEpochTimestamp:FF,parseRfc7231DateTime:HF,parseRfc3339DateTimeWithOffset:PF,toBase64:ke,dateToUtcString:Xe,generateIdempotencyToken:dh,expectUnion:NF}=$t(),{parseXML:xM,XmlNode:Ct,XmlText:HM}=yM();class or{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),r=Object.values(s).find((i)=>{return!!i.getMergedTraits().httpPayload});if(r){let i=r.getMergedTraits().mediaType;if(i)return i;else if(r.isStringSchema())return"text/plain";else if(r.isBlobSchema())return"application/octet-stream";else return t}else if(!n.isUnitSchema()){if(Object.values(s).find((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=e.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,r,i,e){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:i,$fault:s.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:e?.(this.errorRegistry,f)??this.errorRegistry.getSchema(t),errorMetadata:o}}catch(c){r.message=r.message??r.Message??"UnknownError";let h=this.errorRegistry,u=h.getBaseException();if(u){let w=h.getErrorCtor(u)??Error;throw this.decorateServiceException(Object.assign(new w({name:f}),o),r)}let _=r,l=_?.message??_?.Message??_?.Error?.Message??_?.Error?.message;throw this.decorateServiceException(Object.assign(Error(l),{name:f},o),r)}}compose(t,n,s){let r=s;if(n.includes("#"))[r]=n.split("#");let i=GM.for(r),e=GM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(i),t.copyFrom(e),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,r=BM(t,n);if(s)r.message=s;let i=r.Error??{};i.Type=r.Error?.Type,i.Code=r.Error?.Code,i.Message=r.Error?.message??r.Error?.Message??s,r.Error=i;let e=r.$metadata.requestId;if(e)r.RequestId=e;return r}return BM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[r,i]=s.split(";"),e=Object.keys(t),f={Code:r,Type:i};t.Code=r,t.Type=i;for(let o=0;o<e.length;o++){let c=e[o];f[c==="message"?"Message":c]=t[c]}delete f.__type,t.Error=f}}queryCompatOutput(t,n){if(t.Error)n.Error=t.Error;if(t.Type)n.Type=t.Type;if(t.Code)n.Code=t.Code}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch(s){return t.find((r)=>ft.of(r).getMergedTraits().awsQueryError?.[0]===n)}}}class qM extends yF{awsQueryCompatible;mixin;constructor({defaultNamespace:t,errorTypeRegistries:n,awsQueryCompatible:s}){super({defaultNamespace:t,errorTypeRegistries:n});this.awsQueryCompatible=!!s,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";return r}async handleError(t,n,s,r,i){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(r,s);let e=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return GF(s,r)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=ft.of(f),h=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),l={};for(let[w,A]of c.structIterator())if(r[w]!=null)l[w]=this.deserializer.readValue(A,r[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(r,l);throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),r)}}var WF=(t)=>{if(t==null)return t;if(typeof t==="number"||typeof t==="bigint"){let n=Error(`Received number ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}if(typeof t==="boolean"){let n=Error(`Received boolean ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}return t},DF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=t.toLowerCase();if(t!==""&&n!=="false"&&n!=="true"){let s=Error(`Received string "${t}" where a boolean was expected.`);s.name="Warning",console.warn(s)}return t!==""&&n!=="false"}return t},YF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=Number(t);if(n.toString()!==t){let s=Error(`Received string "${t}" where a number was expected.`);return s.name="Warning",console.warn(s),t}return n}return t};class xn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class Rh{from;to;keys;constructor(t,n){this.from=t,this.to=n;let s=Object.keys(this.from),r=new Set(s);r.delete("__type"),this.keys=r}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function mF(t,n,s){if(s?.source){let r=s.source;if(typeof n==="number"){if(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER||r!==String(n))if(r.includes("."))return new hn(r,"bigDecimal");else return BigInt(r)}}return n}var CM=(t,n)=>Eh(t,n).then((s)=>(n?.utf8Encoder??kM)(s)),bh=(t,n)=>CM(t,n).then((s)=>{if(s.length)try{return JSON.parse(s)}catch(r){if(r?.name==="SyntaxError")Object.defineProperty(r,"$responseBodyText",{value:s});throw r}return{}}),QF=async(t,n)=>{let s=await bh(t,n);return s.message=s.message??s.Message,s},PM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),gh=(t)=>{let n=t;if(typeof n==="number")n=n.toString();if(n.indexOf(",")>=0)n=n.split(",")[0];if(n.indexOf(":")>=0)n=n.split(":")[0];if(n.indexOf("#")>=0)n=n.split("#")[1];return n},KM=(t,n)=>{return jM(t,n,["header","code","type"])},VM=(t,n,s=!1)=>{return jM(t,n,s?["code","header","type"]:["type","code","header"])},jM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let i=PM(t??{},"x-amzn-errortype");if(i!==void 0)return gh(t[i]);break;case"code":let e=PM(n??{},"code");if(e&&n[e]!==void 0)return gh(n[e]);break;case"type":if(n?.__type!==void 0)return gh(n.__type);break}};class Th extends xn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,mF):await bh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",r=ft.of(t);if(s){if(r.isStructSchema()){let e=n,f=r.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new Rh(e,o);for(let[_,l]of r.structIterator()){let w=_;if(h)w=l.getMergedTraits().jsonName??w,c[w]=_;if(f)u.mark(w);if(e[w]!=null)o[_]=this._read(l,e[w])}if(f)u.writeUnknown();else if(typeof e.__type==="string")for(let _ in e){let l=e[_],w=h?c[_]??_:_;if(!(w in o))o[w]=l}return o}if(Array.isArray(n)&&r.isListSchema()){let e=r.getValueSchema(),f=[];for(let o of n)f.push(this._read(e,o));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={};for(let o in n)f[o]=this._read(e,n[o]);return f}}if(r.isBlobSchema()&&typeof n==="string")return XM(n);let i=r.getMergedTraits().mediaType;if(r.isStringSchema()&&typeof n==="string"&&i){if(i==="application/json"||i.endsWith("+json"))return zM.from(n);return n}if(r.isTimestampSchema()&&n!=null)switch(ze(r,this.settings)){case 5:return PF(n);case 6:return HF(n);case 7:return FF(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(r.isBigIntegerSchema()&&(typeof n==="number"||typeof n==="string"))return BigInt(n);if(r.isBigDecimalSchema()&&n!=null){if(n instanceof hn)return n;let e=n;if(e.type==="bigDecimal"&&"string"in e)return new hn(e.string,e.type);return new hn(String(n),"bigDecimal")}if(r.isNumericSchema()&&typeof n==="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(r.isDocumentSchema())if(s){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)e[f]=o;else e[f]=this._read(r,o)}return e}else return structuredClone(n);return n}}var NM=String.fromCharCode(925);class aM{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof hn){let s=`${NM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),r=`${NM+"b"+this.counter++}_`+s;return this.values.set(`"${r}"`,s),r}return n}}replaceInJson(t){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(let[n,s]of this.values)t=t.replace(n,s);return t}}class Sh extends xn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=ft.of(t),this.buffer=this._write(this.rootSchema,n)}flush(){let{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);let s=new aM;return s.replaceInJson(JSON.stringify(this.buffer,s.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(t,n){if(this.write(t,n),typeof this.buffer==="object")this.buffer.__type=ft.of(t).getName(!0)}_write(t,n,s){let r=n!==null&&typeof n==="object",i=ft.of(t);if(r){if(i.isStructSchema()){let e=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,_]of i.structIterator()){let l=this._write(_,e[u],i);if(l!==void 0){let w=u;if(o)w=_.getMergedTraits().jsonName??u,c[u]=w;f[w]=l,h++}}if(i.isUnionSchema()&&h===0){let{$unknown:u}=e;if(Array.isArray(u)){let[_,l]=u;f[_]=this._write(15,l)}}else if(typeof e.__type==="string")for(let u in e){let _=e[u],l=o?c[u]??u:u;if(!(l in f))f[l]=this._write(15,_)}return f}if(Array.isArray(n)&&i.isListSchema()){let e=i.getValueSchema(),f=[],o=!!i.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(e,c));return f}if(i.isMapSchema()){let e=i.getValueSchema(),f={},o=!!i.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(e,h)}return f}if(n instanceof Uint8Array&&(i.isBlobSchema()||i.isDocumentSchema())){if(i===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(n instanceof Date&&(i.isTimestampSchema()||i.isDocumentSchema()))switch(ze(i,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return Xe(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof hn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(i.isStringSchema()){if(typeof n>"u"&&i.isIdempotencyToken())return dh();let e=i.getMergedTraits().mediaType;if(n!=null&&e){if(e==="application/json"||e.endsWith("+json"))return zM.from(n)}return n}if(typeof n==="number"&&i.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&i.isBlobSchema()){if(i===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(i.isDocumentSchema())if(r){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)this.useReplacer=!0,e[f]=o;else e[f]=this._write(i,o)}return e}else return structuredClone(n);return n}}class xe extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Sh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Th(this.settings);return t.setSerdeContext(this.serdeContext),t}}class qe extends YM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=i??new xe({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!r,this.mixin=new or(this.awsQueryCompatible)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,r.headers["x-amz-target"]=`${this.serviceTarget}.${t.name}`,this.awsQueryCompatible)r.headers["x-amzn-query-mode"]="true";if(WM(t.input)==="unit"||!r.body)r.body="{}";return r}getPayloadCodec(){return this.codec}async handleError(t,n,s,r,i){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(r,s);let f=VM(s,r,e)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,s,r,i,e?this.mixin.findQueryCompatibleError:void 0),h=ft.of(o),u=r.message??r.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,E]of h.structIterator())if(r[M]!=null)w[M]=A.readObject(E,r[M]);if(e)this.mixin.queryCompatOutput(r,w);throw this.mixin.decorateServiceException(Object.assign(l,c,{$fault:h.getMergedTraits().error,message:u},w),r)}}class pM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ZM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:r,jsonCodec:i})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class vM extends mM{serializer;deserializer;codec;mixin=new or;constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new xe(s),this.serializer=new QM(this.codec.createSerializer(),s),this.deserializer=new JM(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),i=ft.of(t.input);if(!r.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(e)r.headers["content-type"]=e}if(r.body==null&&r.headers["content-type"]===this.getDefaultContentType())r.body="{}";return r}async deserializeResponse(t,n,s){let r=await super.deserializeResponse(t,n,s),i=ft.of(t.output);for(let[e,f]of i.structIterator())if(f.getMemberTraits().httpPayload&&!(e in r))r[e]=null;return r}async handleError(t,n,s,r,i){let e=KM(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i),c=ft.of(f),h=r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let l={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let E=M.getMergedTraits().jsonName??A;l[A]=w.readObject(M,r[E])}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),r)}getDefaultContentType(){return"application/json"}}var JF=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return NF(t)};class Ce extends xn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new BF(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let r=ft.of(t),i=r.getMemberSchemas();if(r.isStructSchema()&&r.isMemberSchema()&&!!Object.values(i).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(i)[0];if(i[h].isBlobSchema())c[h]=n;else c[h]=this.read(i[h],n);return c}let f=(this.serdeContext?.utf8Encoder??kM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=ft.of(t);if(s.isUnitSchema())return;let r=s.getMergedTraits();if(s.isListSchema()&&!Array.isArray(n))return this.readSchema(s,[n]);if(n==null)return n;if(typeof n==="object"){let i=!!r.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=i?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let _ of u)o.push(this.readSchema(f,_));return o}let e={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(i)c=Array.isArray(n)?n:[n];else c=Array.isArray(n.entry)?n.entry:[n.entry];let h=f.getMergedTraits().xmlName??"key",u=o.getMergedTraits().xmlName??"value";for(let _ of c){let l=_[h],w=_[u];e[l]=this.readSchema(o,w)}return e}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new Rh(n,e);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),_=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(_);if(n[_]!=null)e[c]=this.readSchema(h,n[_])}if(f)o.writeUnknown();return e}if(s.isDocumentSchema())return n;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${s.getName(!0)}`)}if(s.isListSchema())return[];if(s.isMapSchema()||s.isStructSchema())return{};return this.stringDeserializer.read(s,n)}parseXml(t){if(t.length){let n;try{n=xM(t)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:t});throw e}let s="#text",r=Object.keys(n)[0],i=n[r];if(i[s])i[r]=i[s],delete i[s];return DM(i)}return{}}}class $h extends xn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let r=ft.of(t);if(s&&!s.endsWith("."))s+=".";if(r.isBlobSchema()){if(typeof n==="string"||n instanceof Uint8Array)this.writeKey(s),this.writeValue((this.serdeContext?.base64Encoder??ke)(n))}else if(r.isBooleanSchema()||r.isNumericSchema()||r.isStringSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n));else if(r.isIdempotencyToken())this.writeKey(s),this.writeValue(dh())}else if(r.isBigIntegerSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n))}else if(r.isBigDecimalSchema()){if(n!=null)this.writeKey(s),this.writeValue(n instanceof hn?n.string:String(n))}else if(r.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),ze(r,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(Xe(n));break;case 7:this.writeValue(String(n.getTime()/1000));break}}else if(r.isDocumentSchema())if(Array.isArray(n))this.write(79,n,s);else if(n instanceof Date)this.write(4,n,s);else if(n instanceof Uint8Array)this.write(21,n,s);else if(n&&typeof n==="object")this.write(143,n,s);else this.writeKey(s),this.writeValue(String(n));else if(r.isListSchema()){if(Array.isArray(n))if(n.length===0){if(this.settings.serializeEmptyLists)this.writeKey(s),this.writeValue("")}else{let i=r.getValueSchema(),e=this.settings.flattenLists||r.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=i.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=e?`${s}${f}`:`${s}${h}.${f}`;this.write(i,o,u),++f}}}else if(r.isMapSchema()){if(n&&typeof n==="object"){let i=r.getKeySchema(),e=r.getValueSchema(),f=r.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=i.getMergedTraits(),_=this.getKey("key",u.xmlName,u.ec2QueryName),l=f?`${s}${o}.${_}`:`${s}entry.${o}.${_}`,w=e.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(i,c,l),this.write(e,h,M),++o}}}else if(r.isStructSchema()){if(n&&typeof n==="object"){let i=!1;for(let[e,f]of r.structIterator()){if(n[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[e],h),i=!0}if(!i&&r.isUnionSchema()){let{$unknown:e}=n;if(Array.isArray(e)){let[f,o]=e,c=`${s}${f}`;this.write(15,o,c)}}}}else if(r.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${r.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let t=this.buffer;return delete this.buffer,t}getKey(t,n,s,r){let{ec2:i,capitalizeKeys:e}=this.settings;if(i&&s)return s;let f=n??t;if(e&&r==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(t){if(t.endsWith("."))t=t.slice(0,t.length-1);this.buffer+=`&${FM(t)}=`}writeValue(t){this.buffer+=FM(t)}}class Uh extends YM{options;serializer;deserializer;mixin=new or;constructor(t){super({defaultNamespace:t.defaultNamespace,errorTypeRegistries:t.errorTypeRegistries});this.options=t;let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace,serializeEmptyLists:!0};this.serializer=new $h(n),this.deserializer=new Ce(n)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(t){this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s);if(!r.path.endsWith("/"))r.path+="/";if(r.headers["content-type"]="application/x-www-form-urlencoded",WM(t.input)==="unit"||!r.body)r.body="";let i=t.name.split("#")[1]??t.name;if(r.body=`Action=${i}&Version=${this.options.version}`+r.body,r.body.endsWith("&"))r.body=r.body.slice(-1);return r}async deserializeResponse(t,n,s){let r=this.deserializer,i=ft.of(t.output),e={};if(s.statusCode>=300){let h=await Eh(s.body,n);if(h.byteLength>0)Object.assign(e,await r.read(15,h));await this.handleError(t,n,s,e,this.deserializeMetadata(s))}for(let h in s.headers){let u=s.headers[h];delete s.headers[h],s.headers[h.toLowerCase()]=u}let f=t.name.split("#")[1]??t.name,o=i.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await Eh(s.body,n);if(c.byteLength>0)Object.assign(e,await r.read(i,c,o));return e.$metadata=this.deserializeMetadata(s),e}useNestedResult(){return!0}async handleError(t,n,s,r,i){let e=this.loadQueryErrorCode(s,r)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let f=this.loadQueryError(r)??{},o=this.loadQueryErrorMessage(r);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:c,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,f,i,this.mixin.findQueryCompatibleError),u=ft.of(c),l=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),w={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,M]of u.structIterator()){let E=M.getMergedTraits().xmlName??A,d=f[E]??r[E];w[A]=this.deserializer.readSchema(M,d)}throw this.mixin.decorateServiceException(Object.assign(l,h,{$fault:u.getMergedTraits().error,message:o},w),r)}loadQueryErrorCode(t,n){let s=(n.Errors?.[0]?.Error??n.Errors?.Error??n.Error)?.Code;if(s!==void 0)return s;if(t.statusCode==404)return"NotFound"}loadQueryError(t){return t.Errors?.[0]?.Error??t.Errors?.Error??t.Error}loadQueryErrorMessage(t){let n=this.loadQueryError(t);return n?.message??n?.Message??t.message??t.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class t1 extends Uh{options;constructor(t){super(t);this.options=t;let n={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,n)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var n1=(t,n)=>CM(t,n).then((s)=>{if(s.length){let r;try{r=xM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let i="#text",e=Object.keys(r)[0],f=r[e];if(f[i])f[e]=f[i],delete f[i];return DM(f)}return{}}),kF=async(t,n)=>{let s=await n1(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},s1=(t,n)=>{if(n?.Error?.Code!==void 0)return n.Error.Code;if(n?.Code!==void 0)return n.Code;if(t.statusCode==404)return"NotFound"};class Lh extends xn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=ft.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??XM)(n);else{this.buffer=this.writeStruct(s,n,void 0);let r=s.getMergedTraits();if(r.httpPayload&&!r.xmlName)this.buffer.withName(s.getName())}}flush(){if(this.byteBuffer!==void 0){let n=this.byteBuffer;return delete this.byteBuffer,n}if(this.stringBuffer!==void 0){let n=this.stringBuffer;return delete this.stringBuffer,n}let t=this.buffer;if(this.settings.xmlNamespace){if(!t?.attributes?.xmlns)t.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,t.toString()}writeStruct(t,n,s){let r=t.getMergedTraits(),i=t.isMemberSchema()&&!r.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():r.xmlName??t.getName();if(!i||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let e=Ct.of(i),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let _=n[h];if(_!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){e.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,_));continue}if(u.isListSchema())this.writeList(u,_,e,o);else if(u.isMapSchema())this.writeMap(u,_,e,o);else if(u.isStructSchema())e.addChildNode(this.writeStruct(u,_,o));else{let l=Ct.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,_,l,o),e.addChildNode(l)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,_=Ct.of(h);if(typeof u!=="string")if(n instanceof Ct||n instanceof HM)e.addChildNode(n);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,u,_,o),e.addChildNode(_)}if(o)e.addAttribute(f,o);return e}writeList(t,n,s,r){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${t.getName(!0)}`);let i=t.getMergedTraits(),e=t.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,c=!!i.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,r),_=(l,w)=>{if(e.isListSchema())this.writeList(e,Array.isArray(w)?w:[w],l,u);else if(e.isMapSchema())this.writeMap(e,w,l,u);else if(e.isStructSchema()){let A=this.writeStruct(e,w,u);l.addChildNode(A.withName(c?i.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=Ct.of(c?i.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,w,A,u),l.addChildNode(A)}};if(c){for(let l of n)if(o||l!=null)_(s,l)}else{let l=Ct.of(i.xmlName??t.getMemberName());if(u)l.addAttribute(h,u);for(let w of n)if(o||w!=null)_(l,w);s.addChildNode(l)}}writeMap(t,n,s,r,i=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let e=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),_=u.xmlName??"value",l=!!u.sparse,w=!!e.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,r),E=(d,T,U)=>{let S=Ct.of(c,T),[O,D]=this.getXmlnsAttribute(f,M);if(D)S.addAttribute(O,D);d.addChildNode(S);let q=Ct.of(_);if(h.isListSchema())this.writeList(h,U,q,M);else if(h.isMapSchema())this.writeMap(h,U,q,M,!0);else if(h.isStructSchema())q=this.writeStruct(h,U,M);else this.writeSimpleInto(h,U,q,M);d.addChildNode(q)};if(w)for(let d in n){let T=n[d];if(l||T!=null){let U=Ct.of(e.xmlName??t.getMemberName());E(U,d,T),s.addChildNode(U)}}else{let d;if(!i){if(d=Ct.of(e.xmlName??t.getMemberName()),M)d.addAttribute(A,M);s.addChildNode(d)}for(let T in n){let U=n[T];if(l||U!=null){let S=Ct.of("entry");E(S,T,U),(i?s:d).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=ft.of(t),r=null;if(n&&typeof n==="object")if(s.isBlobSchema())r=(this.serdeContext?.base64Encoder??ke)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(ze(s,this.settings)){case 5:r=n.toISOString().replace(".000Z","Z");break;case 6:r=Xe(n);break;case 7:r=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),r=Xe(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof hn)return n.string;return String(n)}else if(s.isMapSchema()||s.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${s.getName(!0)}`);if(s.isBooleanSchema()||s.isNumericSchema()||s.isBigIntegerSchema()||s.isBigDecimalSchema())r=String(n);if(s.isStringSchema())if(n===void 0&&s.isIdempotencyToken())r=dh();else r=String(n);if(r===null)throw Error(`Unhandled schema-value pair ${s.getName(!0)}=${n}`);return r}writeSimpleInto(t,n,s,r){let i=this.writeSimple(t,n),e=ft.of(t),f=new HM(i),[o,c]=this.getXmlnsAttribute(e,r);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[r,i]=s.xmlNamespace??[];if(i&&i!==n)return[r?`xmlns:${r}`:"xmlns",i];return[void 0,void 0]}}class Ih extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Lh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ce(this.settings);return t.setSerdeContext(this.serdeContext),t}}class r1 extends mM{codec;serializer;deserializer;mixin=new or;constructor(t){super(t);let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace};this.codec=new Ih(n),this.serializer=new QM(this.codec.createSerializer(),n),this.deserializer=new JM(this.codec.createDeserializer(),n)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(t,n,s){let r=await super.serializeRequest(t,n,s),i=ft.of(t.input);if(!r.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),i);if(e)r.headers["content-type"]=e}if(typeof r.body==="string"&&r.headers["content-type"]===this.getDefaultContentType()&&!r.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(i))r.body='<?xml version="1.0" encoding="UTF-8"?>'+r.body;return r}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,r,i){let e=s1(s,r)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,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&&!i.requestId)i.requestId=r.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,r,i),c=ft.of(f),h=r.Error?.message??r.Error?.Message??r.message??r.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,r);let l={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let E=M.getMergedTraits().xmlName??A,d=r.Error?.[E]??r[E];l[A]=w.readSchema(M,d)}throw this.mixin.decorateServiceException(Object.assign(_,o,{$fault:c.getMergedTraits().error,message:h},l),r)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(t){for(let[,n]of t.structIterator())if(n.getMergedTraits().httpPayload)return!(n.isStructSchema()||n.isMapSchema()||n.isListSchema());return!1}}XF.AwsEc2QueryProtocol=t1;XF.AwsJson1_0Protocol=pM;XF.AwsJson1_1Protocol=ZM;XF.AwsJsonRpcProtocol=qe;XF.AwsQueryProtocol=Uh;XF.AwsRestJsonProtocol=vM;XF.AwsRestXmlProtocol=r1;XF.AwsSmithyRpcV2CborProtocol=qM;XF.JsonCodec=xe;XF.JsonShapeDeserializer=Th;XF.JsonShapeSerializer=Sh;XF.QueryShapeSerializer=$h;XF.XmlCodec=Ih;XF.XmlShapeDeserializer=Ce;XF.XmlShapeSerializer=Lh;XF._toBool=DF;XF._toNum=YF;XF._toStr=WF;XF.awsExpectUnion=JF;XF.loadJsonRpcErrorCode=VM;XF.loadRestJsonErrorCode=KM;XF.loadRestXmlErrorCode=s1;XF.parseJsonBody=bh;XF.parseJsonErrorBody=QF;XF.parseXmlBody=n1;XF.parseXmlErrorBody=kF});var Ph=Z((GN)=>{var{awsEndpointFunctions:MH,emitWarningIfUnsupportedVersion:gH,createDefaultUserAgentProvider:EH,NODE_APP_ID_CONFIG_OPTIONS:dH,getAwsRegionExtensionConfiguration:RH,resolveAwsRegionExtensionConfiguration:bH,resolveUserAgentConfig:TH,resolveHostHeaderConfig:SH,getUserAgentPlugin:$H,getHostHeaderPlugin:UH,getLoggerPlugin:LH,getRecursionDetectionPlugin:IH}=xt(),{NoAuthSigner:OH,getHttpAuthSchemeEndpointRuleSetPlugin:yH,DefaultIdentityProviderConfig:GH,getHttpSigningPlugin:BH}=kn(),{normalizeProvider:c1,getSmithyContext:FH,ServiceException:HH,NoOpLogger:PH,emitWarningIfUnsupportedVersion:NH,loadConfigsForDefaultMode:WH,getDefaultExtensionConfiguration:DH,resolveDefaultRuntimeConfig:YH,Client:h1,makeBuilder:mH,createAggregatedClient:QH}=Rn(),{Command:JH}=Rn();GN.$Command=JH;GN.__Client=h1;var{resolveDefaultsModeConfig:kH,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:XH,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:zH,NODE_REGION_CONFIG_OPTIONS:xH,NODE_REGION_CONFIG_FILE_OPTIONS:qH,resolveRegionConfig:CH}=St(),{BinaryDecisionDiagram:KH,EndpointCache:VH,decideEndpoint:jH,customEndpointFunctions:aH,resolveEndpointConfig:pH,getEndpointPlugin:ZH}=fs(),{parseUrl:vH,getHttpHandlerExtensionConfiguration:tP,resolveHttpHandlerRuntimeConfig:nP,getContentLengthPlugin:sP}=Ut(),{DEFAULT_RETRY_MODE:rP,NODE_RETRY_MODE_CONFIG_OPTIONS:iP,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:eP,resolveRetryConfig:oP,getRetryPlugin:fP}=vr(),{TypeRegistry:u1,getSchemaSerdePlugin:cP}=Nn(),{resolveAwsSdkSigV4Config:hP,AwsSdkSigV4Signer:uP,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:_P}=jc(),{toUtf8:lP,fromUtf8:wP,toBase64:AP,fromBase64:MP,calculateBodyLength:gP}=$t(),{streamCollector:EP,NodeHttpHandler:dP}=me(),{AwsRestJsonProtocol:RP}=Oh(),{Sha256:bP}=tc(),TP=async(t,n,s)=>{return{operation:FH(n).operation,region:await c1(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function SP(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function $P(t){return{schemeId:"smithy.api#noAuth"}}var UP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push($P());break}default:n.push(SP(t))}return n},LP=(t)=>{let n=hP(t);return Object.assign(n,{authSchemePreference:c1(t.authSchemePreference??[])})},IP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},OP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},yP="3.997.32",GP={version:yP},li="ref",Ms=-1,Ke=!0,i1="isSet",_1="PartitionResult",Ve="booleanEquals",yh="getAttr",e1={[li]:"Endpoint"},Gh={[li]:_1},fr={},o1=[{[li]:"Region"}],f1={conditions:[[i1,[e1]],[i1,o1],["aws.partition",o1,_1],[Ve,[{[li]:"UseFIPS"},Ke]],[Ve,[{[li]:"UseDualStack"},Ke]],[Ve,[{fn:yh,argv:[Gh,"supportsDualStack"]},Ke]],[Ve,[{fn:yh,argv:[Gh,"supportsFIPS"]},Ke]],["stringEquals",[{fn:yh,argv:[Gh,"name"]},"aws-us-gov"]]],results:[[Ms],[Ms,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ms,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[e1,fr],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",fr],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",fr],[Ms,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",fr],[Ms,"Invalid Configuration: Missing Region"]]},BP=2,Lt=1e8,FP=new Int32Array([-1,1,-1,0,13,3,1,4,Lt+12,2,5,Lt+12,3,8,6,4,7,Lt+11,5,Lt+9,Lt+10,4,11,9,6,10,Lt+8,7,Lt+6,Lt+7,5,12,Lt+5,6,Lt+4,Lt+5,3,Lt+1,14,4,Lt+2,Lt+3]),HP=KH.from(FP,BP,f1.conditions,f1.results),PP=new VH({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NP=(t,n={})=>{return PP.get(t,()=>jH(HP,{endpointParams:t,logger:n.logger}))};aH.aws=MH;class Rt extends HH{constructor(t){super(t);Object.setPrototypeOf(this,Rt.prototype)}}class je extends Rt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,je.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ae extends Rt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ae.prototype),this.error=t.error,this.error_description=t.error_description}}class pe extends Rt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,pe.prototype),this.error=t.error,this.error_description=t.error_description}}class Ze extends Rt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Ze.prototype),this.error=t.error,this.error_description=t.error_description}}class ve extends Rt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ve.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends Rt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends Rt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class so extends Rt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}class ro extends Rt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,ro.prototype),this.error=t.error,this.error_description=t.error_description}}class io extends Rt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,io.prototype),this.error=t.error,this.error_description=t.error_description}}class eo extends Rt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,eo.prototype),this.error=t.error,this.error_description=t.error_description}}var WP="AccessDeniedException",DP="AuthorizationPendingException",YP="AccessToken",mP="ClientSecret",QP="CreateToken",JP="CreateTokenRequest",kP="CreateTokenResponse",XP="CodeVerifier",zP="ExpiredTokenException",xP="InvalidClientException",qP="InvalidGrantException",CP="InvalidRequestException",KP="InternalServerException",VP="InvalidScopeException",jP="IdToken",aP="RefreshToken",pP="SlowDownException",ZP="UnauthorizedClientException",vP="UnsupportedGrantTypeException",tN="accessToken",un="client",nN="clientId",sN="clientSecret",rN="codeVerifier",iN="code",eN="deviceCode",et="error",oN="expiresIn",Kt="error_description",fN="grantType",cN="http",Vt="httpError",hN="idToken",l1="reason",w1="refreshToken",uN="redirectUri",A1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",_N="scope",lN="server",wN="tokenType",ct="com.amazonaws.ssooidc",M1=u1.for(A1),g1=[-3,A1,"SSOOIDCServiceException",0,[],[]];M1.registerError(g1,Rt);var Yt=u1.for(ct),E1=[-3,ct,WP,{[et]:un,[Vt]:400},[et,l1,Kt],[0,0,0]];Yt.registerError(E1,je);var d1=[-3,ct,DP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(d1,ae);var R1=[-3,ct,zP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(R1,pe);var b1=[-3,ct,KP,{[et]:lN,[Vt]:500},[et,Kt],[0,0]];Yt.registerError(b1,Ze);var T1=[-3,ct,xP,{[et]:un,[Vt]:401},[et,Kt],[0,0]];Yt.registerError(T1,ve);var S1=[-3,ct,qP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(S1,to);var $1=[-3,ct,CP,{[et]:un,[Vt]:400},[et,l1,Kt],[0,0,0]];Yt.registerError($1,no);var U1=[-3,ct,VP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(U1,so);var L1=[-3,ct,pP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(L1,ro);var I1=[-3,ct,ZP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(I1,io);var O1=[-3,ct,vP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];Yt.registerError(O1,eo);var y1=[M1,Yt],AN=[0,ct,YP,8,0],MN=[0,ct,mP,8,0],gN=[0,ct,XP,8,0],EN=[0,ct,jP,8,0],G1=[0,ct,aP,8,0],B1=[3,ct,JP,0,[nN,sN,fN,eN,iN,w1,_N,uN,rN],[0,[()=>MN,0],0,0,0,[()=>G1,0],64,0,[()=>gN,0]],3],F1=[3,ct,kP,0,[tN,wN,oN,w1,hN],[[()=>AN,0],0,1,[()=>G1,0],[()=>EN,0]]],H1=[9,ct,QP,{[cN]:["POST","/token",200]},()=>B1,()=>F1],dN=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??MP,base64Encoder:t?.base64Encoder??AP,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??NP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??UP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new uP},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new OH}],logger:t?.logger??new PH,protocol:t?.protocol??RP,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:y1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??bP,urlParser:t?.urlParser??vH,utf8Decoder:t?.utf8Decoder??wP,utf8Encoder:t?.utf8Encoder??lP}},RN=(t)=>{NH(process.version);let n=kH(t),s=()=>n().then(WH),r=dN(t);gH(process.version);let i={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(_P,i),bodyLengthChecker:t?.bodyLengthChecker??gP,defaultUserAgentProvider:t?.defaultUserAgentProvider??EH({serviceId:r.serviceId,clientVersion:GP.version}),maxAttempts:t?.maxAttempts??As(eP,t),region:t?.region??As(xH,{...qH,...i}),requestHandler:dP.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...iP,default:async()=>(await s()).retryMode||rP},t),streamCollector:t?.streamCollector??EP,useDualstackEndpoint:t?.useDualstackEndpoint??As(zH,i),useFipsEndpoint:t?.useFipsEndpoint??As(XH,i),userAgentAppId:t?.userAgentAppId??As(dH,i)}},bN=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:r}=t;return{setHttpAuthScheme(i){let e=n.findIndex((f)=>f.schemeId===i.schemeId);if(e===-1)n.push(i);else n.splice(e,1,i)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(i){s=i},httpAuthSchemeProvider(){return s},setCredentials(i){r=i},credentials(){return r}}},TN=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},SN=(t,n)=>{let s=Object.assign(RH(t),DH(t),tP(t),bN(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,bH(s),YH(s),nP(s),TN(s))};class Bh extends h1{config;constructor(...[t]){let n=RN(t||{});super(n);this.initConfig=n;let s=IP(n),r=TH(s),i=oP(r),e=CH(i),f=SH(e),o=pH(f),c=LP(o),h=SN(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(cP(this.config)),this.middlewareStack.use($H(this.config)),this.middlewareStack.use(fP(this.config)),this.middlewareStack.use(sP(this.config)),this.middlewareStack.use(UH(this.config)),this.middlewareStack.use(LH(this.config)),this.middlewareStack.use(IH(this.config)),this.middlewareStack.use(yH(this.config,{httpAuthSchemeParametersProvider:TP,identityProviderConfigProvider:async(u)=>new GH({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(BH(this.config))}destroy(){super.destroy()}}var $N=mH(OP,"AWSSSOOIDCService","SSOOIDCClient",ZH),UN={},LN=(t,n,s,r)=>[];class Fh extends $N(UN,LN,"CreateToken",H1){}var IN={CreateTokenCommand:Fh};class Hh extends Bh{}QH(IN,Hh);var ON={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},yN={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};GN.AccessDeniedException=je;GN.AccessDeniedException$=E1;GN.AccessDeniedExceptionReason=ON;GN.AuthorizationPendingException=ae;GN.AuthorizationPendingException$=d1;GN.CreateToken$=H1;GN.CreateTokenCommand=Fh;GN.CreateTokenRequest$=B1;GN.CreateTokenResponse$=F1;GN.ExpiredTokenException=pe;GN.ExpiredTokenException$=R1;GN.InternalServerException=Ze;GN.InternalServerException$=b1;GN.InvalidClientException=ve;GN.InvalidClientException$=T1;GN.InvalidGrantException=to;GN.InvalidGrantException$=S1;GN.InvalidRequestException=no;GN.InvalidRequestException$=$1;GN.InvalidRequestExceptionReason=yN;GN.InvalidScopeException=so;GN.InvalidScopeException$=U1;GN.SSOOIDC=Hh;GN.SSOOIDCClient=Bh;GN.SSOOIDCServiceException=Rt;GN.SSOOIDCServiceException$=g1;GN.SlowDownException=ro;GN.SlowDownException$=L1;GN.UnauthorizedClientException=io;GN.UnauthorizedClientException$=I1;GN.UnsupportedGrantTypeException=eo;GN.UnsupportedGrantTypeException$=O1;GN.errorTypeRegistries=y1});import{existsSync as sR,readFileSync as rR}from"fs";import{homedir as iR}from"os";import{join as G0}from"path";var g={};zE(g,{void:()=>Od,util:()=>x,unknown:()=>Ld,union:()=>Fd,undefined:()=>Sd,tuple:()=>Nd,transformer:()=>xd,symbol:()=>Td,string:()=>I0,strictObject:()=>Bd,setErrorMap:()=>CE,set:()=>Yd,record:()=>Wd,quotelessJson:()=>xE,promise:()=>zd,preprocess:()=>Kd,pipeline:()=>Vd,ostring:()=>jd,optional:()=>qd,onumber:()=>ad,oboolean:()=>pd,objectUtil:()=>Jo,object:()=>Gd,number:()=>O0,nullable:()=>Cd,null:()=>$d,never:()=>Id,nativeEnum:()=>Xd,nan:()=>dd,map:()=>Dd,makeIssue:()=>gr,literal:()=>Jd,lazy:()=>Qd,late:()=>gd,isValid:()=>On,isDirty:()=>Si,isAsync:()=>Ss,isAborted:()=>Ti,intersection:()=>Pd,instanceof:()=>Ed,getParsedType:()=>at,getErrorMap:()=>Ts,function:()=>md,enum:()=>kd,effect:()=>xd,discriminatedUnion:()=>Hd,defaultErrorMap:()=>An,datetimeRegex:()=>$0,date:()=>bd,custom:()=>L0,coerce:()=>Zd,boolean:()=>y0,bigint:()=>Rd,array:()=>yd,any:()=>Ud,addIssueToContext:()=>L,ZodVoid:()=>dr,ZodUnknown:()=>yn,ZodUnion:()=>ys,ZodUndefined:()=>Is,ZodType:()=>X,ZodTuple:()=>Zt,ZodTransformer:()=>Xt,ZodSymbol:()=>Er,ZodString:()=>mt,ZodSet:()=>pn,ZodSchema:()=>X,ZodRecord:()=>Rr,ZodReadonly:()=>Ws,ZodPromise:()=>Zn,ZodPipeline:()=>Sr,ZodParsedType:()=>$,ZodOptional:()=>Jt,ZodObject:()=>rt,ZodNumber:()=>Gn,ZodNullable:()=>gn,ZodNull:()=>Os,ZodNever:()=>pt,ZodNativeEnum:()=>Hs,ZodNaN:()=>Tr,ZodMap:()=>br,ZodLiteral:()=>Fs,ZodLazy:()=>Bs,ZodIssueCode:()=>b,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>N,ZodError:()=>bt,ZodEnum:()=>Fn,ZodEffects:()=>Xt,ZodDiscriminatedUnion:()=>$i,ZodDefault:()=>Ps,ZodDate:()=>jn,ZodCatch:()=>Ns,ZodBranded:()=>Ui,ZodBoolean:()=>Ls,ZodBigInt:()=>Bn,ZodArray:()=>Qt,ZodAny:()=>an,Schema:()=>X,ParseStatus:()=>lt,OK:()=>gt,NEVER:()=>vd,INVALID:()=>P,EMPTY_PATH:()=>KE,DIRTY:()=>Vn,BRAND:()=>Md});var x;(function(t){t.assertEqual=(i)=>{};function n(i){}t.assertIs=n;function s(i){throw Error()}t.assertNever=s,t.arrayToEnum=(i)=>{let e={};for(let f of i)e[f]=f;return e},t.getValidEnumValues=(i)=>{let e=t.objectKeys(i).filter((o)=>typeof i[i[o]]!=="number"),f={};for(let o of e)f[o]=i[o];return t.objectValues(f)},t.objectValues=(i)=>{return t.objectKeys(i).map(function(e){return i[e]})},t.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let e=[];for(let f in i)if(Object.prototype.hasOwnProperty.call(i,f))e.push(f);return e},t.find=(i,e)=>{for(let f of i)if(e(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,e=" | "){return i.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}t.joinValues=r,t.jsonStringifyReplacer=(i,e)=>{if(typeof e==="bigint")return e.toString();return e}})(x||(x={}));var Jo;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Jo||(Jo={}));var $=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=(t)=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(t))return $.array;if(t===null)return $.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return $.promise;if(typeof Map<"u"&&t instanceof Map)return $.map;if(typeof Set<"u"&&t instanceof Set)return $.set;if(typeof Date<"u"&&t instanceof Date)return $.date;return $.object;default:return $.unknown}};var b=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),xE=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class bt extends Error{get errors(){return this.issues}constructor(t){super();this.issues=[],this.addIssue=(s)=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=t}format(t){let n=t||function(i){return i.message},s={_errors:[]},r=(i)=>{for(let e of i.issues)if(e.code==="invalid_union")e.unionErrors.map(r);else if(e.code==="invalid_return_type")r(e.returnTypeError);else if(e.code==="invalid_arguments")r(e.argumentsError);else if(e.path.length===0)s._errors.push(n(e));else{let f=s,o=0;while(o<e.path.length){let c=e.path[o];if(o!==e.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(e));f=f[c],o++}}};return r(this),s}static assert(t){if(!(t instanceof bt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=(n)=>n.message){let n={},s=[];for(let r of this.issues)if(r.path.length>0){let i=r.path[0];n[i]=n[i]||[],n[i].push(t(r))}else s.push(t(r));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}bt.create=(t)=>{return new bt(t)};var qE=(t,n)=>{let s;switch(t.code){case b.invalid_type:if(t.received===$.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:s=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case b.invalid_union:s="Invalid input";break;case b.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case b.invalid_enum_value:s=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:s="Invalid function arguments";break;case b.invalid_return_type:s="Invalid function return type";break;case b.invalid_date:s="Invalid date";break;case b.invalid_string:if(typeof t.validation==="object")if("includes"in t.validation){if(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position==="number")s=`${s} at one or more positions greater than or equal to ${t.validation.position}`}else if("startsWith"in t.validation)s=`Invalid input: must start with "${t.validation.startsWith}"`;else if("endsWith"in t.validation)s=`Invalid input: must end with "${t.validation.endsWith}"`;else x.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case b.too_small:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="bigint")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`;else s="Invalid input";break;case b.too_big:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="bigint")s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`;else s="Invalid input";break;case b.custom:s="Invalid input";break;case b.invalid_intersection_types:s="Intersection results could not be merged";break;case b.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:s="Number must be finite";break;default:s=n.defaultError,x.assertNever(t)}return{message:s}},An=qE;var d0=An;function CE(t){d0=t}function Ts(){return d0}var gr=(t)=>{let{data:n,path:s,errorMaps:r,issueData:i}=t,e=[...s,...i.path||[]],f={...i,path:e};if(i.message!==void 0)return{...i,path:e,message:i.message};let o="",c=r.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...i,path:e,message:o}},KE=[];function L(t,n){let s=Ts(),r=gr({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===An?void 0:An].filter((i)=>!!i)});t.common.issues.push(r)}class lt{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(t,n){let s=[];for(let r of n){if(r.status==="aborted")return P;if(r.status==="dirty")t.dirty();s.push(r.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){let s=[];for(let r of n){let i=await r.key,e=await r.value;s.push({key:i,value:e})}return lt.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let r of n){let{key:i,value:e}=r;if(i.status==="aborted")return P;if(e.status==="aborted")return P;if(i.status==="dirty")t.dirty();if(e.status==="dirty")t.dirty();if(i.value!=="__proto__"&&(typeof e.value<"u"||r.alwaysSet))s[i.value]=e.value}return{status:t.value,value:s}}}var P=Object.freeze({status:"aborted"}),Vn=(t)=>({status:"dirty",value:t}),gt=(t)=>({status:"valid",value:t}),Ti=(t)=>t.status==="aborted",Si=(t)=>t.status==="dirty",On=(t)=>t.status==="valid",Ss=(t)=>typeof Promise<"u"&&t instanceof Promise;var y;(function(t){t.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},t.toString=(n)=>typeof n==="string"?n:n?.message})(y||(y={}));class kt{constructor(t,n,s,r){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,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 R0=(t,n)=>{if(On(n))return{success:!0,data:n.value};else{if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let s=new bt(t.common.issues);return this._error=s,this._error}}}};function Q(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:r,description:i}=t;if(n&&(s||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:i};return{errorMap:(f,o)=>{let{message:c}=t;if(f.code==="invalid_enum_value")return{message:c??o.defaultError};if(typeof o.data>"u")return{message:c??r??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:c??s??o.defaultError}},description:i}}class X{get description(){return this._def.description}_getType(t){return at(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new lt,ctx:{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ss(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){let s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},r=this._parseSync({data:t,path:s.path,parent:s});return R0(s,r)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return On(s)?{value:s.value}:{issues:n.common.issues}}catch(s){if(s?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then((s)=>On(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){let s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){let s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},r=this._parse({data:t,path:s.path,parent:s}),i=await(Ss(r)?r:Promise.resolve(r));return R0(s,i)}refine(t,n){let s=(r)=>{if(typeof n==="string"||typeof n>"u")return{message:n};else if(typeof n==="function")return n(r);else return n};return this._refinement((r,i)=>{let e=t(r),f=()=>i.addIssue({code:b.custom,...s(r)});if(typeof Promise<"u"&&e instanceof Promise)return e.then((o)=>{if(!o)return f(),!1;else return!0});if(!e)return f(),!1;else return!0})}refinement(t,n){return this._refinement((s,r)=>{if(!t(s))return r.addIssue(typeof n==="function"?n(s,r):n),!1;else return!0})}_refinement(t){return new Xt({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Jt.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return Zn.create(this,this._def)}or(t){return ys.create([this,t],this._def)}and(t){return Gs.create(this,t,this._def)}transform(t){return new Xt({...Q(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...Q(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Ui({typeName:N.ZodBranded,type:this,...Q(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Ns({...Q(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return Sr.create(this,t)}readonly(){return Ws.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var VE=/^c[^\s-]{8,}$/i,jE=/^[0-9a-z]+$/,aE=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pE=/^[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,ZE=/^[a-z0-9_-]{21}$/i,vE=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,td=/^[-+]?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)?)??$/,nd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ko,rd=/^(?:(?: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])$/,id=/^(?:(?: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])$/,ed=/^(([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]))$/,od=/^(([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])$/,fd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T0="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",hd=new RegExp(`^${T0}$`);function S0(t){let n="[0-5]\\d";if(t.precision)n=`${n}\\.\\d{${t.precision}}`;else if(t.precision==null)n=`${n}(\\.\\d+)?`;let s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function ud(t){return new RegExp(`^${S0(t)}$`)}function $0(t){let n=`${T0}T${S0(t)}`,s=[];if(s.push(t.local?"Z?":"Z"),t.offset)s.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function _d(t,n){if((n==="v4"||!n)&&rd.test(t))return!0;if((n==="v6"||!n)&&ed.test(t))return!0;return!1}function ld(t,n){if(!vE.test(t))return!1;try{let[s]=t.split(".");if(!s)return!1;let r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),i=JSON.parse(atob(r));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(n&&i.alg!==n)return!1;return!0}catch{return!1}}function wd(t,n){if((n==="v4"||!n)&&id.test(t))return!0;if((n==="v6"||!n)&&od.test(t))return!0;return!1}class mt extends X{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==$.string){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.string,received:i.parsedType}),P}let s=new lt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(t.data.length<i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty()}else if(i.kind==="max"){if(t.data.length>i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),s.dirty()}else if(i.kind==="length"){let e=t.data.length>i.value,f=t.data.length<i.value;if(e||f){if(r=this._getOrReturnCtx(t,r),e)L(r,{code:b.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(f)L(r,{code:b.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});s.dirty()}}else if(i.kind==="email"){if(!nd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"email",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="emoji"){if(!ko)ko=new RegExp(sd,"u");if(!ko.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"emoji",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="uuid"){if(!pE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"uuid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="nanoid"){if(!ZE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"nanoid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cuid"){if(!VE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cuid2"){if(!jE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"cuid2",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="ulid"){if(!aE.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"ulid",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="url")try{new URL(t.data)}catch{r=this._getOrReturnCtx(t,r),L(r,{validation:"url",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"regex",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="trim")t.data=t.data.trim();else if(i.kind==="includes"){if(!t.data.includes(i.value,i.position))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),s.dirty()}else if(i.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(i.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(i.kind==="startsWith"){if(!t.data.startsWith(i.value))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{startsWith:i.value},message:i.message}),s.dirty()}else if(i.kind==="endsWith"){if(!t.data.endsWith(i.value))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:{endsWith:i.value},message:i.message}),s.dirty()}else if(i.kind==="datetime"){if(!$0(i).test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"datetime",message:i.message}),s.dirty()}else if(i.kind==="date"){if(!hd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"date",message:i.message}),s.dirty()}else if(i.kind==="time"){if(!ud(i).test(t.data))r=this._getOrReturnCtx(t,r),L(r,{code:b.invalid_string,validation:"time",message:i.message}),s.dirty()}else if(i.kind==="duration"){if(!td.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"duration",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="ip"){if(!_d(t.data,i.version))r=this._getOrReturnCtx(t,r),L(r,{validation:"ip",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="jwt"){if(!ld(t.data,i.alg))r=this._getOrReturnCtx(t,r),L(r,{validation:"jwt",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="cidr"){if(!wd(t.data,i.version))r=this._getOrReturnCtx(t,r),L(r,{validation:"cidr",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="base64"){if(!fd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"base64",code:b.invalid_string,message:i.message}),s.dirty()}else if(i.kind==="base64url"){if(!cd.test(t.data))r=this._getOrReturnCtx(t,r),L(r,{validation:"base64url",code:b.invalid_string,message:i.message}),s.dirty()}else x.assertNever(i);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((r)=>t.test(r),{validation:n,code:b.invalid_string,...y.errToObj(s)})}_addCheck(t){return new mt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...y.errToObj(t)})}url(t){return this._addCheck({kind:"url",...y.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...y.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...y.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...y.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...y.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...y.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...y.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...y.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...y.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...y.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...y.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...y.errToObj(t)})}datetime(t){if(typeof t==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t});return this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...y.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){if(typeof t==="string")return this._addCheck({kind:"time",precision:null,message:t});return this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...y.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...y.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...y.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...y.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...y.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...y.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...y.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...y.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...y.errToObj(n)})}nonempty(t){return this.min(1,y.errToObj(t))}trim(){return new mt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new mt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new mt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((t)=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find((t)=>t.kind==="date")}get isTime(){return!!this._def.checks.find((t)=>t.kind==="time")}get isDuration(){return!!this._def.checks.find((t)=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find((t)=>t.kind==="email")}get isURL(){return!!this._def.checks.find((t)=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find((t)=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find((t)=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((t)=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((t)=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((t)=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find((t)=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find((t)=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find((t)=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find((t)=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find((t)=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxLength(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}mt.create=(t)=>{return new mt({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...Q(t)})};function Ad(t,n){let s=(t.toString().split(".")[1]||"").length,r=(n.toString().split(".")[1]||"").length,i=s>r?s:r,e=Number.parseInt(t.toFixed(i).replace(".","")),f=Number.parseInt(n.toFixed(i).replace(".",""));return e%f/10**i}class Gn extends X{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce)t.data=Number(t.data);if(this._getType(t)!==$.number){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.number,received:i.parsedType}),P}let s=void 0,r=new lt;for(let i of this._def.checks)if(i.kind==="int"){if(!x.isInteger(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()}else if(i.kind==="min"){if(i.inclusive?t.data<i.value:t.data<=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?t.data>i.value:t.data>=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(Ad(t.data,i.value)!==0)s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_finite,message:i.message}),r.dirty()}else x.assertNever(i);return{status:r.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new Gn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new Gn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}get isInt(){return!!this._def.checks.find((t)=>t.kind==="int"||t.kind==="multipleOf"&&x.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let s of this._def.checks)if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;else if(s.kind==="min"){if(n===null||s.value>n)n=s.value}else if(s.kind==="max"){if(t===null||s.value<t)t=s.value}return Number.isFinite(n)&&Number.isFinite(t)}}Gn.create=(t)=>{return new Gn({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...Q(t)})};class Bn extends X{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==$.bigint)return this._getInvalidInput(t);let s=void 0,r=new lt;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?t.data<i.value:t.data<=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="max"){if(i.inclusive?t.data>i.value:t.data>=i.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()}else if(i.kind==="multipleOf"){if(t.data%i.value!==BigInt(0))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()}else x.assertNever(i);return{status:r.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,y.toString(n))}gt(t,n){return this.setLimit("min",t,!1,y.toString(n))}lte(t,n){return this.setLimit("max",t,!0,y.toString(n))}lt(t,n){return this.setLimit("max",t,!1,y.toString(n))}setLimit(t,n,s,r){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:y.toString(r)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Bn.create=(t)=>{return new Bn({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...Q(t)})};class Ls extends X{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==$.boolean){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.boolean,received:s.parsedType}),P}return gt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...Q(t)})};class jn extends X{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==$.date){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_type,expected:$.date,received:i.parsedType}),P}if(Number.isNaN(t.data.getTime())){let i=this._getOrReturnCtx(t);return L(i,{code:b.invalid_date}),P}let s=new lt,r=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(t.data.getTime()<i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),s.dirty()}else if(i.kind==="max"){if(t.data.getTime()>i.value)r=this._getOrReturnCtx(t,r),L(r,{code:b.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),s.dirty()}else x.assertNever(i);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:y.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:y.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t!=null?new Date(t):null}}jn.create=(t)=>{return new jn({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...Q(t)})};class Er extends X{_parse(t){if(this._getType(t)!==$.symbol){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.symbol,received:s.parsedType}),P}return gt(t.data)}}Er.create=(t)=>{return new Er({typeName:N.ZodSymbol,...Q(t)})};class Is extends X{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.undefined,received:s.parsedType}),P}return gt(t.data)}}Is.create=(t)=>{return new Is({typeName:N.ZodUndefined,...Q(t)})};class Os extends X{_parse(t){if(this._getType(t)!==$.null){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.null,received:s.parsedType}),P}return gt(t.data)}}Os.create=(t)=>{return new Os({typeName:N.ZodNull,...Q(t)})};class an extends X{constructor(){super(...arguments);this._any=!0}_parse(t){return gt(t.data)}}an.create=(t)=>{return new an({typeName:N.ZodAny,...Q(t)})};class yn extends X{constructor(){super(...arguments);this._unknown=!0}_parse(t){return gt(t.data)}}yn.create=(t)=>{return new yn({typeName:N.ZodUnknown,...Q(t)})};class pt extends X{_parse(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.never,received:n.parsedType}),P}}pt.create=(t)=>{return new pt({typeName:N.ZodNever,...Q(t)})};class dr extends X{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.void,received:s.parsedType}),P}return gt(t.data)}}dr.create=(t)=>{return new dr({typeName:N.ZodVoid,...Q(t)})};class Qt extends X{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),r=this._def;if(n.parsedType!==$.array)return L(n,{code:b.invalid_type,expected:$.array,received:n.parsedType}),P;if(r.exactLength!==null){let e=n.data.length>r.exactLength.value,f=n.data.length<r.exactLength.value;if(e||f)L(n,{code:e?b.too_big:b.too_small,minimum:f?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty()}if(r.minLength!==null){if(n.data.length<r.minLength.value)L(n,{code:b.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()}if(r.maxLength!==null){if(n.data.length>r.maxLength.value)L(n,{code:b.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()}if(n.common.async)return Promise.all([...n.data].map((e,f)=>{return r.type._parseAsync(new kt(n,e,n.path,f))})).then((e)=>{return lt.mergeArray(s,e)});let i=[...n.data].map((e,f)=>{return r.type._parseSync(new kt(n,e,n.path,f))});return lt.mergeArray(s,i)}get element(){return this._def.type}min(t,n){return new Qt({...this._def,minLength:{value:t,message:y.toString(n)}})}max(t,n){return new Qt({...this._def,maxLength:{value:t,message:y.toString(n)}})}length(t,n){return new Qt({...this._def,exactLength:{value:t,message:y.toString(n)}})}nonempty(t){return this.min(1,t)}}Qt.create=(t,n)=>{return new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...Q(n)})};function $s(t){if(t instanceof rt){let n={};for(let s in t.shape){let r=t.shape[s];n[s]=Jt.create($s(r))}return new rt({...t._def,shape:()=>n})}else if(t instanceof Qt)return new Qt({...t._def,type:$s(t.element)});else if(t instanceof Jt)return Jt.create($s(t.unwrap()));else if(t instanceof gn)return gn.create($s(t.unwrap()));else if(t instanceof Zt)return Zt.create(t.items.map((n)=>$s(n)));else return t}class rt extends X{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=x.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let c=this._getOrReturnCtx(t);return L(c,{code:b.invalid_type,expected:$.object,received:c.parsedType}),P}let{status:s,ctx:r}=this._processInputParams(t),{shape:i,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof pt&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!e.includes(c))f.push(c)}let o=[];for(let c of e){let h=i[c],u=r.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new kt(r,u,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof pt){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of f)o.push({key:{status:"valid",value:h},value:{status:"valid",value:r.data[h]}});else if(c==="strict"){if(f.length>0)L(r,{code:b.unrecognized_keys,keys:f}),s.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of f){let u=r.data[h];o.push({key:{status:"valid",value:h},value:c._parse(new kt(r,u,r.path,h)),alwaysSet:h in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let h of o){let u=await h.key,_=await h.value;c.push({key:u,value:_,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return lt.mergeObjectSync(s,c)});else return lt.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new rt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{let r=this._def.errorMap?.(n,s).message??s.defaultError;if(n.code==="unrecognized_keys")return{message:y.errToObj(t).message??r};return{message:r}}}:{}})}strip(){return new rt({...this._def,unknownKeys:"strip"})}passthrough(){return new rt({...this._def,unknownKeys:"passthrough"})}extend(t){return new rt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new rt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new rt({...this._def,catchall:t})}pick(t){let n={};for(let s of x.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new rt({...this._def,shape:()=>n})}omit(t){let n={};for(let s of x.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new rt({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of x.objectKeys(this.shape)){let r=this.shape[s];if(t&&!t[s])n[s]=r;else n[s]=r.optional()}return new rt({...this._def,shape:()=>n})}required(t){let n={};for(let s of x.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let i=this.shape[s];while(i instanceof Jt)i=i._def.innerType;n[s]=i}return new rt({...this._def,shape:()=>n})}keyof(){return U0(x.objectKeys(this.shape))}}rt.create=(t,n)=>{return new rt({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};rt.strictCreate=(t,n)=>{return new rt({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};rt.lazycreate=(t,n)=>{return new rt({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};class ys extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function r(i){for(let f of i)if(f.result.status==="valid")return f.result;for(let f of i)if(f.result.status==="dirty")return n.common.issues.push(...f.ctx.common.issues),f.result;let e=i.map((f)=>new bt(f.ctx.common.issues));return L(n,{code:b.invalid_union,unionErrors:e}),P}if(n.common.async)return Promise.all(s.map(async(i)=>{let e={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:e}),ctx:e}})).then(r);else{let i=void 0,e=[];for(let o of s){let c={...n,common:{...n.common,issues:[]},parent:null},h=o._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;else if(h.status==="dirty"&&!i)i={result:h,ctx:c};if(c.common.issues.length)e.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let f=e.map((o)=>new bt(o));return L(n,{code:b.invalid_union,unionErrors:f}),P}}get options(){return this._def.options}}ys.create=(t,n)=>{return new ys({options:t,typeName:N.ZodUnion,...Q(n)})};var Mn=(t)=>{if(t instanceof Bs)return Mn(t.schema);else if(t instanceof Xt)return Mn(t.innerType());else if(t instanceof Fs)return[t.value];else if(t instanceof Fn)return t.options;else if(t instanceof Hs)return x.objectValues(t.enum);else if(t instanceof Ps)return Mn(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof Os)return[null];else if(t instanceof Jt)return[void 0,...Mn(t.unwrap())];else if(t instanceof gn)return[null,...Mn(t.unwrap())];else if(t instanceof Ui)return Mn(t.unwrap());else if(t instanceof Ws)return Mn(t.unwrap());else if(t instanceof Ns)return Mn(t._def.innerType);else return[]};class $i extends X{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return L(n,{code:b.invalid_type,expected:$.object,received:n.parsedType}),P;let s=this.discriminator,r=n.data[s],i=this.optionsMap.get(r);if(!i)return L(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),P;if(n.common.async)return i._parseAsync({data:n.data,path:n.path,parent:n});else return i._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){let r=new Map;for(let i of n){let e=Mn(i.shape[t]);if(!e.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of e){if(r.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);r.set(f,i)}}return new $i({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:r,...Q(s)})}}function Xo(t,n){let s=at(t),r=at(n);if(t===n)return{valid:!0,data:t};else if(s===$.object&&r===$.object){let i=x.objectKeys(n),e=x.objectKeys(t).filter((o)=>i.indexOf(o)!==-1),f={...t,...n};for(let o of e){let c=Xo(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===$.array&&r===$.array){if(t.length!==n.length)return{valid:!1};let i=[];for(let e=0;e<t.length;e++){let f=t[e],o=n[e],c=Xo(f,o);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else if(s===$.date&&r===$.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=(i,e)=>{if(Ti(i)||Ti(e))return P;let f=Xo(i.value,e.value);if(!f.valid)return L(s,{code:b.invalid_intersection_types}),P;if(Si(i)||Si(e))n.dirty();return{status:n.value,value:f.data}};if(s.common.async)return Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([i,e])=>r(i,e));else return r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Gs.create=(t,n,s)=>{return new Gs({left:t,right:n,typeName:N.ZodIntersection,...Q(s)})};class Zt extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.array)return L(s,{code:b.invalid_type,expected:$.array,received:s.parsedType}),P;if(s.data.length<this._def.items.length)return L(s,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;if(!this._def.rest&&s.data.length>this._def.items.length)L(s,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let i=[...s.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new kt(s,e,s.path,f))}).filter((e)=>!!e);if(s.common.async)return Promise.all(i).then((e)=>{return lt.mergeArray(n,e)});else return lt.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Zt({...this._def,rest:t})}}Zt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:N.ZodTuple,rest:null,...Q(n)})};class Rr extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.object)return L(s,{code:b.invalid_type,expected:$.object,received:s.parsedType}),P;let r=[],i=this._def.keyType,e=this._def.valueType;for(let f in s.data)r.push({key:i._parse(new kt(s,f,s.path,f)),value:e._parse(new kt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return lt.mergeObjectAsync(n,r);else return lt.mergeObjectSync(n,r)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof X)return new Rr({keyType:t,valueType:n,typeName:N.ZodRecord,...Q(s)});return new Rr({keyType:mt.create(),valueType:t,typeName:N.ZodRecord,...Q(n)})}}class br extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.map)return L(s,{code:b.invalid_type,expected:$.map,received:s.parsedType}),P;let r=this._def.keyType,i=this._def.valueType,e=[...s.data.entries()].map(([f,o],c)=>{return{key:r._parse(new kt(s,f,s.path,[c,"key"])),value:i._parse(new kt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}})}else{let f=new Map;for(let o of e){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}br.create=(t,n,s)=>{return new br({valueType:n,keyType:t,typeName:N.ZodMap,...Q(s)})};class pn extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.set)return L(s,{code:b.invalid_type,expected:$.set,received:s.parsedType}),P;let r=this._def;if(r.minSize!==null){if(s.data.size<r.minSize.value)L(s,{code:b.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),n.dirty()}if(r.maxSize!==null){if(s.data.size>r.maxSize.value)L(s,{code:b.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),n.dirty()}let i=this._def.valueType;function e(o){let c=new Set;for(let h of o){if(h.status==="aborted")return P;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>i._parse(new kt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>e(o));else return e(f)}min(t,n){return new pn({...this._def,minSize:{value:t,message:y.toString(n)}})}max(t,n){return new pn({...this._def,maxSize:{value:t,message:y.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}pn.create=(t,n)=>{return new pn({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...Q(n)})};class Us extends X{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return L(n,{code:b.invalid_type,expected:$.function,received:n.parsedType}),P;function s(f,o){return gr({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_arguments,argumentsError:o}})}function r(f,o){return gr({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_return_type,returnTypeError:o}})}let i={errorMap:n.common.contextualErrorMap},e=n.data;if(this._def.returns instanceof Zn){let f=this;return gt(async function(...o){let c=new bt([]),h=await f._def.args.parseAsync(o,i).catch((l)=>{throw c.addIssue(s(o,l)),c}),u=await Reflect.apply(e,this,h);return await f._def.returns._def.type.parseAsync(u,i).catch((l)=>{throw c.addIssue(r(u,l)),c})})}else{let f=this;return gt(function(...o){let c=f._def.args.safeParse(o,i);if(!c.success)throw new bt([s(o,c.error)]);let h=Reflect.apply(e,this,c.data),u=f._def.returns.safeParse(h,i);if(!u.success)throw new bt([r(h,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Us({...this._def,args:Zt.create(t).rest(yn.create())})}returns(t){return new Us({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new Us({args:t?t:Zt.create([]).rest(yn.create()),returns:n||yn.create(),typeName:N.ZodFunction,...Q(s)})}}class Bs extends X{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bs.create=(t,n)=>{return new Bs({getter:t,typeName:N.ZodLazy,...Q(n)})};class Fs extends X{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}}Fs.create=(t,n)=>{return new Fs({value:t,typeName:N.ZodLiteral,...Q(n)})};function U0(t,n){return new Fn({values:t,typeName:N.ZodEnum,...Q(n)})}class Fn extends X{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{expected:x.joinValues(s),received:n.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{received:n.data,code:b.invalid_enum_value,options:s}),P}return gt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Fn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Fn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Fn.create=U0;class Hs extends X{_parse(t){let n=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==$.string&&s.parsedType!==$.number){let r=x.objectValues(n);return L(s,{expected:x.joinValues(r),received:s.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(x.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let r=x.objectValues(n);return L(s,{received:s.data,code:b.invalid_enum_value,options:r}),P}return gt(t.data)}get enum(){return this._def.values}}Hs.create=(t,n)=>{return new Hs({values:t,typeName:N.ZodNativeEnum,...Q(n)})};class Zn extends X{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return L(n,{code:b.invalid_type,expected:$.promise,received:n.parsedType}),P;let s=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return gt(s.then((r)=>{return this._def.type.parseAsync(r,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Zn.create=(t,n)=>{return new Zn({type:t,typeName:N.ZodPromise,...Q(n)})};class Xt extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),r=this._def.effect||null,i={addIssue:(e)=>{if(L(s,e),e.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){let e=r.transform(s.data,i);if(s.common.async)return Promise.resolve(e).then(async(f)=>{if(n.value==="aborted")return P;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return P;if(o.status==="dirty")return Vn(o.value);if(n.value==="dirty")return Vn(o.value);return o});else{if(n.value==="aborted")return P;let f=this._def.schema._parseSync({data:e,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")return Vn(f.value);if(n.value==="dirty")return Vn(f.value);return f}}if(r.type==="refinement"){let e=(f)=>{let o=r.refinement(f,i);if(s.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value),{status:n.value,value:f.value}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((f)=>{if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(r.type==="transform")if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!On(e))return P;let f=r.transform(e.value,i);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e)=>{if(!On(e))return P;return Promise.resolve(r.transform(e.value,i)).then((f)=>({status:n.value,value:f}))});x.assertNever(r)}}Xt.create=(t,n,s)=>{return new Xt({schema:t,typeName:N.ZodEffects,effect:n,...Q(s)})};Xt.createWithPreprocess=(t,n,s)=>{return new Xt({schema:n,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...Q(s)})};class Jt extends X{_parse(t){if(this._getType(t)===$.undefined)return gt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Jt.create=(t,n)=>{return new Jt({innerType:t,typeName:N.ZodOptional,...Q(n)})};class gn extends X{_parse(t){if(this._getType(t)===$.null)return gt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gn.create=(t,n)=>{return new gn({innerType:t,typeName:N.ZodNullable,...Q(n)})};class Ps extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===$.undefined)s=this._def.defaultValue();return this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ps.create=(t,n)=>{return new Ps({innerType:t,typeName:N.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...Q(n)})};class Ns extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});if(Ss(r))return r.then((i)=>{return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}});else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:N.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...Q(n)})};class Tr extends X{_parse(t){if(this._getType(t)!==$.nan){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.nan,received:s.parsedType}),P}return{status:"valid",value:t.data}}}Tr.create=(t)=>{return new Tr({typeName:N.ZodNaN,...Q(t)})};var Md=Symbol("zod_brand");class Ui extends X{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Sr extends X{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(i.status==="aborted")return P;if(i.status==="dirty")return n.dirty(),Vn(i.value);else return this._def.out._parseAsync({data:i.value,path:s.path,parent:s})})();else{let r=this._def.in._parseSync({data:s.data,path:s.path,parent:s});if(r.status==="aborted")return P;if(r.status==="dirty")return n.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:s.path,parent:s})}}static create(t,n){return new Sr({in:t,out:n,typeName:N.ZodPipeline})}}class Ws extends X{_parse(t){let n=this._def.innerType._parse(t),s=(r)=>{if(On(r))r.value=Object.freeze(r.value);return r};return Ss(n)?n.then((r)=>s(r)):s(n)}unwrap(){return this._def.innerType}}Ws.create=(t,n)=>{return new Ws({innerType:t,typeName:N.ZodReadonly,...Q(n)})};function b0(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function L0(t,n={},s){if(t)return an.create().superRefine((r,i)=>{let e=t(r);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=b0(n,r),c=o.fatal??s??!0;i.addIssue({code:"custom",...o,fatal:c})}});if(!e){let f=b0(n,r),o=f.fatal??s??!0;i.addIssue({code:"custom",...f,fatal:o})}return});return an.create()}var gd={object:rt.lazycreate},N;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(N||(N={}));var Ed=(t,n={message:`Input not instance of ${t.name}`})=>L0((s)=>s instanceof t,n),I0=mt.create,O0=Gn.create,dd=Tr.create,Rd=Bn.create,y0=Ls.create,bd=jn.create,Td=Er.create,Sd=Is.create,$d=Os.create,Ud=an.create,Ld=yn.create,Id=pt.create,Od=dr.create,yd=Qt.create,Gd=rt.create,Bd=rt.strictCreate,Fd=ys.create,Hd=$i.create,Pd=Gs.create,Nd=Zt.create,Wd=Rr.create,Dd=br.create,Yd=pn.create,md=Us.create,Qd=Bs.create,Jd=Fs.create,kd=Fn.create,Xd=Hs.create,zd=Zn.create,xd=Xt.create,qd=Jt.create,Cd=gn.create,Kd=Xt.createWithPreprocess,Vd=Sr.create,jd=()=>I0().optional(),ad=()=>O0().optional(),pd=()=>y0().optional(),Zd={string:(t)=>mt.create({...t,coerce:!0}),number:(t)=>Gn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Bn.create({...t,coerce:!0}),date:(t)=>jn.create({...t,coerce:!0})};var vd=P;var Li=g.enum(["low","medium","high","xhigh","max"]),vn=g.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var tR=g.array(g.string()).transform((t)=>t.map((n)=>n.trim()).filter((n)=>n.length>0)).refine((t)=>t.length>0,{message:"api_keys must contain at least one non-empty key"}),nR=g.preprocess((t)=>typeof t==="string"&&t.trim().length===0?null:t,g.string().trim().refine((t)=>URL.canParse(t),{message:"proxy_url must be a valid URL"}).refine((t)=>{if(!URL.canParse(t))return!1;let n=new URL(t).protocol;return n==="http:"||n==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),zo=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:tR,proxy_url:nR,default_region:g.string().default("us-east-1"),account_selection_strategy:g.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:g.number().default(3),rate_limit_retry_delay_ms:g.number().default(5000),max_request_iterations:g.number().default(20),request_timeout_ms:g.number().default(120000),stream_idle_timeout_ms:g.number().default(60000),max_request_body_bytes:g.number().default(10485760),token_expiry_buffer_ms:g.number().default(300000),effort:Li.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class $r extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var eR=zo.partial();function oR(t){let n=t.XDG_CONFIG_HOME??G0(iR(),".config");return G0(n,"kiro-provider","config.json")}function fR(t){if(!sR(t))return{};try{let n=JSON.parse(rR(t,"utf8"));return eR.parse(n)}catch(n){if(n instanceof g.ZodError)throw new $r(`Invalid configuration file ${t}: ${B0(n)}`,{cause:n});if(n instanceof Error)throw new $r(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function cR(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function hR(t){let n={},s={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[o,c]of Object.entries(s)){let h=t[o];if(h!==void 0)n[c]=h}let r={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms"};for(let[o,c]of Object.entries(r)){let h=t[o];if(h!==void 0)n[c]=Number(h)}let i=t.KIRO_PROVIDER_API_KEYS;if(i!==void 0)n.api_keys=i.split(",");let e=t.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)n.proxy_url=e.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=cR(f);return n}function B0(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function F0(t={}){let n=t.env??process.env,s=t.configPath??oR(n);try{return zo.parse({...fR(s),...hR(n),...t.overrides})}catch(r){if(r instanceof $r)throw r;if(r instanceof g.ZodError)throw new $r(`Invalid configuration: ${B0(r)}`,{cause:r});throw r}}function Ii(t){let n=t.split("|"),s=n[0]??"";if(n.length<2)return{refreshToken:s,authMethod:"desktop"};if(n.at(-1)==="idc")return{refreshToken:s,clientId:n[1],clientSecret:n[2],authMethod:"idc"};return{refreshToken:s,authMethod:"desktop"}}function H0(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function Oi(t){if(t.authMethod==="idc"){if(!t.clientId||!t.clientSecret)throw Error("Missing credentials");return`${t.refreshToken}|${t.clientId}|${t.clientSecret}|idc`}return`${t.refreshToken}|desktop`}function uR(t){if(!t)return!1;return t.includes("Invalid refresh token")||t.includes("Invalid grant provided")||t.includes("invalid_grant")||t.includes("ExpiredTokenException")||t.includes("InvalidTokenException")||t.includes("ExpiredClientException")||t.includes("Client is expired")||t.includes("HTTP_401")||t.includes("HTTP_403")}function yi(t){if(!t)return!1;let n=t.toLowerCase();return n.includes("bearer token included in the request is invalid")||n.includes("access token has expired")||n.includes("access_token expired")||n.includes("the access token expired")}function xo(t){return uR(t)}var P0=4;class N0 extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function _R(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Ur(t){return{...t}}function lR(t){return{refresh:Oi({refreshToken:t.refreshToken,authMethod:t.authMethod,...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.profileArn?{profileArn:t.profileArn}:{}}),access:t.accessToken,expires:t.expiresAt,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email?{email:t.email}:{},...t.profileArn?{profileArn:t.profileArn}:{}}}class qo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Ur)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Ur)}getMinWaitTime(){let t=Date.now(),n=this.accounts.map(({rateLimitResetTime:s})=>s-t).filter((s)=>s>0);return n.length===0?0:Math.min(...n)}reconcileFromDb(t=this.database){let n=new Map(this.accounts.map((s)=>[s.id,s]));if(this.accounts=t.getAccounts().map((s)=>{let r=n.get(s.id);return r?.generation===s.generation?r:Ur(s)}),this.stickyId&&!this.accounts.some(({id:s})=>s===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(){let t=Date.now(),n=this.accounts.filter((r)=>this.isSelectable(r,t)).sort((r,i)=>r.id.localeCompare(i.id));if(n.length===0)return null;let s=this.selectCandidate(n);return this.patchAccount(s.id,(r)=>({...r,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(r.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(t,n){return this.patchAccount(t.id,(s)=>({...s,rateLimitResetTime:n}))}markUnhealthy(t,n,s){let r=Date.now();return this.patchAccount(t.id,(i)=>{if(xo(n))return{...i,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:r};let e=i.failCount+1;return{...i,failCount:e,isHealthy:e<10,unhealthyReason:n,recoveryTime:e>=10?s??r+3600000:void 0,lastUsed:r}})}updateFromAuth(t,n){let s=Ii(n.refresh);for(let r=0;r<P0;r+=1){let i=r===0?t:this.database.getById(t.id);if(!i||!this.isSameLogin(t,i)){this.reconcileFromDb();return}let e={...i,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:i.generation+1};return this.replaceAccount(f),Ur(f)}}this.reconcileFromDb();return}toAuthDetails(t){return lR(t)}isSelectable(t,n){if(xo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||yi(t.unhealthyReason))return!0;return t.recoveryTime!==void 0&&t.recoveryTime<=n}isSameLogin(t,n){return n.refreshToken===t.refreshToken&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.email===t.email&&n.startUrl===t.startUrl}selectCandidate(t){switch(this.strategy){case"sticky":{let s=t.find(({id:r})=>r===this.stickyId)??t[0];if(!s)throw RangeError("Candidate list cannot be empty");return this.stickyId=s.id,s}case"round-robin":{let n=t[this.roundRobinCursor%t.length];if(!n)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,n}case"lowest-usage":{let n=[...t].sort((s,r)=>(s.usedCount??0)-(r.usedCount??0)||(s.lastUsed??0)-(r.lastUsed??0)||s.id.localeCompare(r.id))[0];if(!n)throw RangeError("Candidate list cannot be empty");return n}default:return _R(this.strategy)}}patchAccount(t,n){for(let s=0;s<P0;s+=1){let r=this.database.getById(t);if(!r){this.accounts=this.accounts.filter((e)=>e.id!==t);return}let i=n(r);if(this.database.updateExistingAccounts([i])===1){let e={...i,generation:r.generation+1};return this.replaceAccount(e),Ur(e)}}throw this.reconcileFromDb(),new N0(t)}replaceAccount(t){let n=this.accounts.findIndex(({id:s})=>s===t.id);if(n===-1)this.accounts.push(t);else this.accounts[n]=t}}var j0=Y(Vo(),1);import*as tn from"net";import*as Ir from"tls";import VR from"assert";import*as x0 from"net";import*as q0 from"http";import{Agent as KR}from"https";var vt=Symbol("AgentBaseInternalState");class jo extends q0.Agent{constructor(t){super(t);this[vt]={}}isSecureEndpoint(t){if(t){if(typeof t.secureEndpoint==="boolean")return t.secureEndpoint;if(typeof t.protocol==="string")return t.protocol==="https:"}let{stack:n}=Error();if(typeof n!=="string")return!1;return n.split(`
50
- `).some((s)=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(t){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[t])this.sockets[t]=[];let n=new x0.Socket({writable:!1});return this.sockets[t].push(n),this.totalSocketCount++,n}decrementSockets(t,n){if(!this.sockets[t]||n===null)return;let s=this.sockets[t],r=s.indexOf(n);if(r!==-1){if(s.splice(r,1),this.totalSocketCount--,s.length===0)delete this.sockets[t]}}getName(t){if(this.isSecureEndpoint(t))return KR.prototype.getName.call(this,t);return super.getName(t)}createSocket(t,n,s){let r={...n,secureEndpoint:this.isSecureEndpoint(n)},i=this.getName(r),e=this.incrementSockets(i);Promise.resolve().then(()=>this.connect(t,r)).then((f)=>{if(this.decrementSockets(i,e),typeof f.addRequest==="function")try{return f.addRequest(t,r)}catch(o){return s(o)}this[vt].currentSocket=f,super.createSocket(t,n,s)},(f)=>{this.decrementSockets(i,e),s(f)})}createConnection(){let t=this[vt].currentSocket;if(this[vt].currentSocket=void 0,!t)throw Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(t){if(this[vt])this[vt].defaultPort=t}get protocol(){return this[vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){if(this[vt])this[vt].protocol=t}}import{URL as jR}from"url";var C0=Y(Vo(),1),Pi=C0.default("https-proxy-agent:parse-proxy-response");function ao(t){return new Promise((n,s)=>{let r=0,i=[];function e(){let u=t.read();if(u)h(u);else t.once("readable",e)}function f(){t.removeListener("end",o),t.removeListener("error",c),t.removeListener("readable",e)}function o(){f(),Pi("onend"),s(Error("Proxy connection ended before receiving CONNECT response"))}function c(u){f(),Pi("onerror %o",u),s(u)}function h(u){i.push(u),r+=u.length;let _=Buffer.concat(i,r),l=_.indexOf(`\r
46
+ >/`.includes(t.x[t.i]))n+=t.x[t.i++];let s=!1,i=Object.create(null);while(t.i<t.z){if(t.trim(),">/".includes(t.x[t.i]))break;let h="";while(t.i<t.z&&!`= \r
47
+ >/?`.includes(t.x[t.i]))h+=t.x[t.i++];if(t.trim(),t.x[t.i]!=="=")break;++t.i,t.trim(),i[h]=t.readAttrValue(),s=!0}if(t.i>=t.z)throw Error("@aws-sdk XML parse error: unexpected end of input.");if(t.x[t.i]==="/"){if(++t.i,t.i>=t.z||t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of self-closing tag.");return++t.i,Object.setPrototypeOf(i,Object.prototype),{tag:n,value:s?i:""}}if(t.x[t.i]!==">")throw Error("@aws-sdk XML parse error: expected > at the end of opening tag.");++t.i;let r=[],e=[],f=!1;while(t.i<t.z){if(t.isNext("</"))break;if(t.x[t.i]==="<")if(t.isNext("<!--"))t.readTo("-->");else if(t.isNext("<![CDATA["))t.i+=9,r.push(t.readTo("]]>"));else if(t.isNext("<?"))t.readTo("?>");else f=!0,e.push(t.parseTag());else{let h="";while(t.i<t.z&&t.x[t.i]!=="<")h+=t.x[t.i++];r.push(t.decodeEntities(h))}}if(!t.isNext("</"))throw Error(`@aws-sdk XML parse error: missing closing tag </${n}>.`);t.i+=2;let o=t.readTo(">").trim();if(o!==n)throw Error(`@aws-sdk XML parse error: mismatched tags <${n}> and </${o}>.`);if(!s&&r.length===0&&!f)return{tag:n,value:""};if(!s&&!f){let h=r.length===1?r[0]:r.join("");if(h.trim()===""&&h.includes(`
48
+ `))return{tag:n,value:""};return{tag:n,value:h}}let c=Object.create(null);for(let h of r){if(h.trim()===""&&h.includes(`
49
+ `))continue;c["#text"]="#text"in c?c["#text"]+h:h}for(let h of e)if(h.tag in c)if(Array.isArray(c[h.tag]))c[h.tag].push(h.value);else c[h.tag]=[c[h.tag],h.value];else c[h.tag]=h.value;for(let[h,u]of Object.entries(i))c[h]=u;return Object.setPrototypeOf(c,Object.prototype),{tag:n,value:c}}static ENTITIES={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};skipDoctype(){let t=this;t.i+=9;let n=0;while(t.i<t.z){let s=t.x[t.i];if(s==="[")++n;else if(s==="]")--n;else if(s===">"&&n===0){++t.i;return}++t.i}throw Error("@aws-sdk XML parse error: unclosed DOCTYPE.")}decodeEntities(t){return t.replace(/&(?:#x([0-9a-fA-F]{1,6})|#(\d{1,7})|([a-zA-Z][a-zA-Z0-9]{0,30}));/g,(n,s,i,r)=>{if(s)return String.fromCharCode(parseInt(s,16));if(i)return String.fromCharCode(parseInt(i,10));return Mh.ENTITIES[r]??""})}}UF.XmlNode=lr;UF.XmlText=Ah;UF.parseXML=$F});var yh=Z((zF)=>{var{SmithyRpcV2CborProtocol:OF,loadSmithyRpcV2CborErrorCode:GF}=yM(),{TypeRegistry:GM,NormalizedSchema:ft,deref:WM}=Nn(),{decorateServiceException:BM,getValueFromTextNode:DM}=Rn(),{collectBody:dh,determineTimestampFormat:Xe,RpcProtocol:mM,HttpBindingProtocol:YM,HttpInterceptingShapeSerializer:QM,HttpInterceptingShapeDeserializer:JM,FromStringShapeDeserializer:BF,extendedEncodeURIComponent:FM}=Ut(),{NumericValue:hn,toUtf8:kM,fromBase64:zM,LazyJsonString:XM,parseEpochTimestamp:FF,parseRfc7231DateTime:HF,parseRfc3339DateTimeWithOffset:PF,toBase64:ke,dateToUtcString:ze,generateIdempotencyToken:Eh,expectUnion:NF}=$t(),{parseXML:xM,XmlNode:Ct,XmlText:HM}=OM();class oi{queryCompat;errorRegistry;constructor(t=!1){this.queryCompat=t}resolveRestContentType(t,n){let s=n.getMemberSchemas(),i=Object.values(s).find((r)=>{return!!r.getMergedTraits().httpPayload});if(i){let r=i.getMergedTraits().mediaType;if(r)return r;else if(i.isStringSchema())return"text/plain";else if(i.isBlobSchema())return"application/octet-stream";else return t}else if(!n.isUnitSchema()){if(Object.values(s).find((e)=>{let{httpQuery:f,httpQueryParams:o,httpHeader:c,httpLabel:h,httpPrefixHeaders:u}=e.getMergedTraits();return!f&&!o&&!c&&!h&&u===void 0}))return t}}async getErrorSchemaOrThrowBaseException(t,n,s,i,r,e){let f=t;if(t.includes("#"))[,f]=t.split("#");let o={$metadata:r,$fault:s.statusCode<500?"client":"server"};if(!this.errorRegistry)throw Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:e?.(this.errorRegistry,f)??this.errorRegistry.getSchema(t),errorMetadata:o}}catch(c){i.message=i.message??i.Message??"UnknownError";let h=this.errorRegistry,u=h.getBaseException();if(u){let w=h.getErrorCtor(u)??Error;throw this.decorateServiceException(Object.assign(new w({name:f}),o),i)}let l=i,_=l?.message??l?.Message??l?.Error?.Message??l?.Error?.message;throw this.decorateServiceException(Object.assign(Error(_),{name:f},o),i)}}compose(t,n,s){let i=s;if(n.includes("#"))[i]=n.split("#");let r=GM.for(i),e=GM.for("smithy.ts.sdk.synthetic."+s);t.copyFrom(r),t.copyFrom(e),this.errorRegistry=t}decorateServiceException(t,n={}){if(this.queryCompat){let s=t.Message??n.Message,i=BM(t,n);if(s)i.message=s;let r=i.Error??{};r.Type=i.Error?.Type,r.Code=i.Error?.Code,r.Message=i.Error?.message??i.Error?.Message??s,i.Error=r;let e=i.$metadata.requestId;if(e)i.RequestId=e;return i}return BM(t,n)}setQueryCompatError(t,n){let s=n.headers?.["x-amzn-query-error"];if(t!==void 0&&s!=null){let[i,r]=s.split(";"),e=Object.keys(t),f={Code:i,Type:r};t.Code=i,t.Type=r;for(let o=0;o<e.length;o++){let c=e[o];f[c==="message"?"Message":c]=t[c]}delete f.__type,t.Error=f}}queryCompatOutput(t,n){if(t.Error)n.Error=t.Error;if(t.Type)n.Type=t.Type;if(t.Code)n.Code=t.Code}findQueryCompatibleError(t,n){try{return t.getSchema(n)}catch(s){return t.find((i)=>ft.of(i).getMergedTraits().awsQueryError?.[0]===n)}}}class qM extends OF{awsQueryCompatible;mixin;constructor({defaultNamespace:t,errorTypeRegistries:n,awsQueryCompatible:s}){super({defaultNamespace:t,errorTypeRegistries:n});this.awsQueryCompatible=!!s,this.mixin=new oi(this.awsQueryCompatible)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(this.awsQueryCompatible)i.headers["x-amzn-query-mode"]="true";return i}async handleError(t,n,s,i,r){if(this.awsQueryCompatible)this.mixin.setQueryCompatError(i,s);let e=(()=>{let w=s.headers["x-amzn-query-error"];if(w&&this.awsQueryCompatible)return w.split(";")[0];return GF(s,i)??"Unknown"})();this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r,this.awsQueryCompatible?this.mixin.findQueryCompatibleError:void 0),c=ft.of(f),h=i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({}),_={};for(let[w,A]of c.structIterator())if(i[w]!=null)_[w]=this.deserializer.readValue(A,i[w]);if(this.awsQueryCompatible)this.mixin.queryCompatOutput(i,_);throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}}var WF=(t)=>{if(t==null)return t;if(typeof t==="number"||typeof t==="bigint"){let n=Error(`Received number ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}if(typeof t==="boolean"){let n=Error(`Received boolean ${t} where a string was expected.`);return n.name="Warning",console.warn(n),String(t)}return t},DF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=t.toLowerCase();if(t!==""&&n!=="false"&&n!=="true"){let s=Error(`Received string "${t}" where a boolean was expected.`);s.name="Warning",console.warn(s)}return t!==""&&n!=="false"}return t},mF=(t)=>{if(t==null)return t;if(typeof t==="string"){let n=Number(t);if(n.toString()!==t){let s=Error(`Received string "${t}" where a number was expected.`);return s.name="Warning",console.warn(s),t}return n}return t};class xn{serdeContext;setSerdeContext(t){this.serdeContext=t}}class Rh{from;to;keys;constructor(t,n){this.from=t,this.to=n;let s=Object.keys(this.from),i=new Set(s);i.delete("__type"),this.keys=i}mark(t){this.keys.delete(t)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){let t=this.keys.values().next().value,n=this.from[t];this.to.$unknown=[t,n]}}}function YF(t,n,s){if(s?.source){let i=s.source;if(typeof n==="number"){if(n>Number.MAX_SAFE_INTEGER||n<Number.MIN_SAFE_INTEGER||i!==String(n))if(i.includes("."))return new hn(i,"bigDecimal");else return BigInt(i)}}return n}var CM=(t,n)=>dh(t,n).then((s)=>(n?.utf8Encoder??kM)(s)),bh=(t,n)=>CM(t,n).then((s)=>{if(s.length)try{return JSON.parse(s)}catch(i){if(i?.name==="SyntaxError")Object.defineProperty(i,"$responseBodyText",{value:s});throw i}return{}}),QF=async(t,n)=>{let s=await bh(t,n);return s.message=s.message??s.Message,s},PM=(t,n)=>Object.keys(t).find((s)=>s.toLowerCase()===n.toLowerCase()),gh=(t)=>{let n=t;if(typeof n==="number")n=n.toString();if(n.indexOf(",")>=0)n=n.split(",")[0];if(n.indexOf(":")>=0)n=n.split(":")[0];if(n.indexOf("#")>=0)n=n.split("#")[1];return n},KM=(t,n)=>{return jM(t,n,["header","code","type"])},VM=(t,n,s=!1)=>{return jM(t,n,s?["code","header","type"]:["type","code","header"])},jM=({headers:t},n,s)=>{while(s.length>0)switch(s.shift()){case"header":let r=PM(t??{},"x-amzn-errortype");if(r!==void 0)return gh(t[r]);break;case"code":let e=PM(n??{},"code");if(e&&n[e]!==void 0)return gh(n[e]);break;case"type":if(n?.__type!==void 0)return gh(n.__type);break}};class Th extends xn{settings;constructor(t){super();this.settings=t}async read(t,n){return this._read(t,typeof n==="string"?JSON.parse(n,YF):await bh(n,this.serdeContext))}readObject(t,n){return this._read(t,n)}_read(t,n){let s=n!==null&&typeof n==="object",i=ft.of(t);if(s){if(i.isStructSchema()){let e=n,f=i.isUnionSchema(),o={},c=void 0,{jsonName:h}=this.settings;if(h)c={};let u;if(f)u=new Rh(e,o);for(let[l,_]of i.structIterator()){let w=l;if(h)w=_.getMergedTraits().jsonName??w,c[w]=l;if(f)u.mark(w);if(e[w]!=null)o[l]=this._read(_,e[w])}if(f)u.writeUnknown();else if(typeof e.__type==="string")for(let l in e){let _=e[l],w=h?c[l]??l:l;if(!(w in o))o[w]=_}return o}if(Array.isArray(n)&&i.isListSchema()){let e=i.getValueSchema(),f=[];for(let o of n)f.push(this._read(e,o));return f}if(i.isMapSchema()){let e=i.getValueSchema(),f={};for(let o in n)f[o]=this._read(e,n[o]);return f}}if(i.isBlobSchema()&&typeof n==="string")return zM(n);let r=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof n==="string"&&r){if(r==="application/json"||r.endsWith("+json"))return XM.from(n);return n}if(i.isTimestampSchema()&&n!=null)switch(Xe(i,this.settings)){case 5:return PF(n);case 6:return HF(n);case 7:return FF(n);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",n),new Date(n)}if(i.isBigIntegerSchema()&&(typeof n==="number"||typeof n==="string"))return BigInt(n);if(i.isBigDecimalSchema()&&n!=null){if(n instanceof hn)return n;let e=n;if(e.type==="bigDecimal"&&"string"in e)return new hn(e.string,e.type);return new hn(String(n),"bigDecimal")}if(i.isNumericSchema()&&typeof n==="string"){switch(n){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return n}if(i.isDocumentSchema())if(s){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)e[f]=o;else e[f]=this._read(i,o)}return e}else return structuredClone(n);return n}}var NM=String.fromCharCode(925);class aM{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(t,n)=>{if(n instanceof hn){let s=`${NM+"nv"+this.counter++}_`+n.string;return this.values.set(`"${s}"`,n.string),s}if(typeof n==="bigint"){let s=n.toString(),i=`${NM+"b"+this.counter++}_`+s;return this.values.set(`"${i}"`,s),i}return n}}replaceInJson(t){if(this.stage===0)throw Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return t;for(let[n,s]of this.values)t=t.replace(n,s);return t}}class Sh extends xn{settings;buffer;useReplacer=!1;rootSchema;constructor(t){super();this.settings=t}write(t,n){this.rootSchema=ft.of(t),this.buffer=this._write(this.rootSchema,n)}flush(){let{rootSchema:t,useReplacer:n}=this;if(this.rootSchema=void 0,this.useReplacer=!1,t?.isStructSchema()||t?.isDocumentSchema()){if(!n)return JSON.stringify(this.buffer);let s=new aM;return s.replaceInJson(JSON.stringify(this.buffer,s.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(t,n){if(this.write(t,n),typeof this.buffer==="object")this.buffer.__type=ft.of(t).getName(!0)}_write(t,n,s){let i=n!==null&&typeof n==="object",r=ft.of(t);if(i){if(r.isStructSchema()){let e=n,f={},{jsonName:o}=this.settings,c=void 0;if(o)c={};let h=0;for(let[u,l]of r.structIterator()){let _=this._write(l,e[u],r);if(_!==void 0){let w=u;if(o)w=l.getMergedTraits().jsonName??u,c[u]=w;f[w]=_,h++}}if(r.isUnionSchema()&&h===0){let{$unknown:u}=e;if(Array.isArray(u)){let[l,_]=u;f[l]=this._write(15,_)}}else if(typeof e.__type==="string")for(let u in e){let l=e[u],_=o?c[u]??u:u;if(!(_ in f))f[_]=this._write(15,l)}return f}if(Array.isArray(n)&&r.isListSchema()){let e=r.getValueSchema(),f=[],o=!!r.getMergedTraits().sparse;for(let c of n)if(o||c!=null)f.push(this._write(e,c));return f}if(r.isMapSchema()){let e=r.getValueSchema(),f={},o=!!r.getMergedTraits().sparse;for(let c in n){let h=n[c];if(o||h!=null)f[c]=this._write(e,h)}return f}if(n instanceof Uint8Array&&(r.isBlobSchema()||r.isDocumentSchema())){if(r===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(n instanceof Date&&(r.isTimestampSchema()||r.isDocumentSchema()))switch(Xe(r,this.settings)){case 5:return n.toISOString().replace(".000Z","Z");case 6:return ze(n);case 7:return n.getTime()/1000;default:return console.warn("Missing timestamp format, using epoch seconds",n),n.getTime()/1000}if(n instanceof hn)this.useReplacer=!0}if(n===null&&s?.isStructSchema())return;if(r.isStringSchema()){if(typeof n>"u"&&r.isIdempotencyToken())return Eh();let e=r.getMergedTraits().mediaType;if(n!=null&&e){if(e==="application/json"||e.endsWith("+json"))return XM.from(n)}return n}if(typeof n==="number"&&r.isNumericSchema()){if(Math.abs(n)===1/0||isNaN(n))return String(n);return n}if(typeof n==="string"&&r.isBlobSchema()){if(r===this.rootSchema)return n;return(this.serdeContext?.base64Encoder??ke)(n)}if(typeof n==="bigint")this.useReplacer=!0;if(r.isDocumentSchema())if(i){let e=Array.isArray(n)?[]:{};for(let f in n){let o=n[f];if(o instanceof hn)this.useReplacer=!0,e[f]=o;else e[f]=this._write(r,o)}return e}else return structuredClone(n);return n}}class xe extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Sh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Th(this.settings);return t.setSerdeContext(this.serdeContext),t}}class qe extends mM{serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n});this.serviceTarget=s,this.codec=r??new xe({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new oi(this.awsQueryCompatible)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(!i.path.endsWith("/"))i.path+="/";if(i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${t.name}`,this.awsQueryCompatible)i.headers["x-amzn-query-mode"]="true";if(WM(t.input)==="unit"||!i.body)i.body="{}";return i}getPayloadCodec(){return this.codec}async handleError(t,n,s,i,r){let{awsQueryCompatible:e}=this;if(e)this.mixin.setQueryCompatError(i,s);let f=VM(s,i,e)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,f,this.options.defaultNamespace);let{errorSchema:o,errorMetadata:c}=await this.mixin.getErrorSchemaOrThrowBaseException(f,this.options.defaultNamespace,s,i,r,e?this.mixin.findQueryCompatibleError:void 0),h=ft.of(o),u=i.message??i.Message??"UnknownError",_=new(this.compositeErrorRegistry.getErrorCtor(o)??Error)({}),w={},A=this.codec.createDeserializer();for(let[M,d]of h.structIterator())if(i[M]!=null)w[M]=A.readObject(d,i[M]);if(e)this.mixin.queryCompatOutput(i,w);throw this.mixin.decorateServiceException(Object.assign(_,c,{$fault:h.getMergedTraits().error,message:u},w),i)}}class pM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_0"}getJsonRpcVersion(){return"1.0"}getDefaultContentType(){return"application/x-amz-json-1.0"}}class ZM extends qe{constructor({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r}){super({defaultNamespace:t,errorTypeRegistries:n,serviceTarget:s,awsQueryCompatible:i,jsonCodec:r})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}class vM extends YM{serializer;deserializer;codec;mixin=new oi;constructor({defaultNamespace:t,errorTypeRegistries:n}){super({defaultNamespace:t,errorTypeRegistries:n});let s={timestampFormat:{useTrait:!0,default:7},httpBindings:!0,jsonName:!0};this.codec=new xe(s),this.serializer=new QM(this.codec.createSerializer(),s),this.deserializer=new JM(this.codec.createDeserializer(),s)}getShapeId(){return"aws.protocols#restJson1"}getPayloadCodec(){return this.codec}setSerdeContext(t){this.codec.setSerdeContext(t),super.setSerdeContext(t)}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s),r=ft.of(t.input);if(!i.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)i.headers["content-type"]=e}if(i.body==null&&i.headers["content-type"]===this.getDefaultContentType())i.body="{}";return i}async deserializeResponse(t,n,s){let i=await super.deserializeResponse(t,n,s),r=ft.of(t.output);for(let[e,f]of r.structIterator())if(f.getMemberTraits().httpPayload&&!(e in i))i[e]=null;return i}async handleError(t,n,s,i,r){let e=KM(s,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r),c=ft.of(f),h=i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,i);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().jsonName??A;_[A]=w.readObject(M,i[d])}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}getDefaultContentType(){return"application/json"}}var JF=(t)=>{if(t==null)return;if(typeof t==="object"&&"__type"in t)delete t.__type;return NF(t)};class Ce extends xn{settings;stringDeserializer;constructor(t){super();this.settings=t,this.stringDeserializer=new BF(t)}setSerdeContext(t){this.serdeContext=t,this.stringDeserializer.setSerdeContext(t)}read(t,n,s){let i=ft.of(t),r=i.getMemberSchemas();if(i.isStructSchema()&&i.isMemberSchema()&&!!Object.values(r).find((c)=>{return!!c.getMemberTraits().eventPayload})){let c={},h=Object.keys(r)[0];if(r[h].isBlobSchema())c[h]=n;else c[h]=this.read(r[h],n);return c}let f=(this.serdeContext?.utf8Encoder??kM)(n),o=this.parseXml(f);return this.readSchema(t,s?o[s]:o)}readSchema(t,n){let s=ft.of(t);if(s.isUnitSchema())return;let i=s.getMergedTraits();if(s.isListSchema()&&!Array.isArray(n))return this.readSchema(s,[n]);if(n==null)return n;if(typeof n==="object"){let r=!!i.xmlFlattened;if(s.isListSchema()){let f=s.getValueSchema(),o=[],c=f.getMergedTraits().xmlName??"member",h=r?n:(n[0]??n)[c];if(h==null)return o;let u=Array.isArray(h)?h:[h];for(let l of u)o.push(this.readSchema(f,l));return o}let e={};if(s.isMapSchema()){let f=s.getKeySchema(),o=s.getValueSchema(),c;if(r)c=Array.isArray(n)?n:[n];else c=Array.isArray(n.entry)?n.entry:[n.entry];let h=f.getMergedTraits().xmlName??"key",u=o.getMergedTraits().xmlName??"value";for(let l of c){let _=l[h],w=l[u];e[_]=this.readSchema(o,w)}return e}if(s.isStructSchema()){let f=s.isUnionSchema(),o;if(f)o=new Rh(n,e);for(let[c,h]of s.structIterator()){let u=h.getMergedTraits(),l=!u.httpPayload?h.getMemberTraits().xmlName??c:u.xmlName??h.getName();if(f)o.mark(l);if(n[l]!=null)e[c]=this.readSchema(h,n[l])}if(f)o.writeUnknown();return e}if(s.isDocumentSchema())return n;throw Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${s.getName(!0)}`)}if(s.isListSchema())return[];if(s.isMapSchema()||s.isStructSchema())return{};return this.stringDeserializer.read(s,n)}parseXml(t){if(t.length){let n;try{n=xM(t)}catch(e){if(e&&typeof e==="object")Object.defineProperty(e,"$responseBodyText",{value:t});throw e}let s="#text",i=Object.keys(n)[0],r=n[i];if(r[s])r[i]=r[s],delete r[s];return DM(r)}return{}}}class $h extends xn{settings;buffer;constructor(t){super();this.settings=t}write(t,n,s=""){if(this.buffer===void 0)this.buffer="";let i=ft.of(t);if(s&&!s.endsWith("."))s+=".";if(i.isBlobSchema()){if(typeof n==="string"||n instanceof Uint8Array)this.writeKey(s),this.writeValue((this.serdeContext?.base64Encoder??ke)(n))}else if(i.isBooleanSchema()||i.isNumericSchema()||i.isStringSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n));else if(i.isIdempotencyToken())this.writeKey(s),this.writeValue(Eh())}else if(i.isBigIntegerSchema()){if(n!=null)this.writeKey(s),this.writeValue(String(n))}else if(i.isBigDecimalSchema()){if(n!=null)this.writeKey(s),this.writeValue(n instanceof hn?n.string:String(n))}else if(i.isTimestampSchema()){if(n instanceof Date)switch(this.writeKey(s),Xe(i,this.settings)){case 5:this.writeValue(n.toISOString().replace(".000Z","Z"));break;case 6:this.writeValue(ze(n));break;case 7:this.writeValue(String(n.getTime()/1000));break}}else if(i.isDocumentSchema())if(Array.isArray(n))this.write(79,n,s);else if(n instanceof Date)this.write(4,n,s);else if(n instanceof Uint8Array)this.write(21,n,s);else if(n&&typeof n==="object")this.write(143,n,s);else this.writeKey(s),this.writeValue(String(n));else if(i.isListSchema()){if(Array.isArray(n))if(n.length===0){if(this.settings.serializeEmptyLists)this.writeKey(s),this.writeValue("")}else{let r=i.getValueSchema(),e=this.settings.flattenLists||i.getMergedTraits().xmlFlattened,f=1;for(let o of n){if(o==null)continue;let c=r.getMergedTraits(),h=this.getKey("member",c.xmlName,c.ec2QueryName),u=e?`${s}${f}`:`${s}${h}.${f}`;this.write(r,o,u),++f}}}else if(i.isMapSchema()){if(n&&typeof n==="object"){let r=i.getKeySchema(),e=i.getValueSchema(),f=i.getMergedTraits().xmlFlattened,o=1;for(let c in n){let h=n[c];if(h==null)continue;let u=r.getMergedTraits(),l=this.getKey("key",u.xmlName,u.ec2QueryName),_=f?`${s}${o}.${l}`:`${s}entry.${o}.${l}`,w=e.getMergedTraits(),A=this.getKey("value",w.xmlName,w.ec2QueryName),M=f?`${s}${o}.${A}`:`${s}entry.${o}.${A}`;this.write(r,c,_),this.write(e,h,M),++o}}}else if(i.isStructSchema()){if(n&&typeof n==="object"){let r=!1;for(let[e,f]of i.structIterator()){if(n[e]==null&&!f.isIdempotencyToken())continue;let o=f.getMergedTraits(),c=this.getKey(e,o.xmlName,o.ec2QueryName,"struct"),h=`${s}${c}`;this.write(f,n[e],h),r=!0}if(!r&&i.isUnionSchema()){let{$unknown:e}=n;if(Array.isArray(e)){let[f,o]=e,c=`${s}${f}`;this.write(15,o,c)}}}}else if(i.isUnitSchema());else throw Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${i.getName(!0)}`)}flush(){if(this.buffer===void 0)throw Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer.");let t=this.buffer;return delete this.buffer,t}getKey(t,n,s,i){let{ec2:r,capitalizeKeys:e}=this.settings;if(r&&s)return s;let f=n??t;if(e&&i==="struct")return f[0].toUpperCase()+f.slice(1);return f}writeKey(t){if(t.endsWith("."))t=t.slice(0,t.length-1);this.buffer+=`&${FM(t)}=`}writeValue(t){this.buffer+=FM(t)}}class Uh extends mM{options;serializer;deserializer;mixin=new oi;constructor(t){super({defaultNamespace:t.defaultNamespace,errorTypeRegistries:t.errorTypeRegistries});this.options=t;let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!1,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace,serializeEmptyLists:!0};this.serializer=new $h(n),this.deserializer=new Ce(n)}getShapeId(){return"aws.protocols#awsQuery"}setSerdeContext(t){this.serializer.setSerdeContext(t),this.deserializer.setSerdeContext(t)}getPayloadCodec(){throw Error("AWSQuery protocol has no payload codec.")}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s);if(!i.path.endsWith("/"))i.path+="/";if(i.headers["content-type"]="application/x-www-form-urlencoded",WM(t.input)==="unit"||!i.body)i.body="";let r=t.name.split("#")[1]??t.name;if(i.body=`Action=${r}&Version=${this.options.version}`+i.body,i.body.endsWith("&"))i.body=i.body.slice(-1);return i}async deserializeResponse(t,n,s){let i=this.deserializer,r=ft.of(t.output),e={};if(s.statusCode>=300){let h=await dh(s.body,n);if(h.byteLength>0)Object.assign(e,await i.read(15,h));await this.handleError(t,n,s,e,this.deserializeMetadata(s))}for(let h in s.headers){let u=s.headers[h];delete s.headers[h],s.headers[h.toLowerCase()]=u}let f=t.name.split("#")[1]??t.name,o=r.isStructSchema()&&this.useNestedResult()?f+"Result":void 0,c=await dh(s.body,n);if(c.byteLength>0)Object.assign(e,await i.read(r,c,o));return e.$metadata=this.deserializeMetadata(s),e}useNestedResult(){return!0}async handleError(t,n,s,i,r){let e=this.loadQueryErrorCode(s,i)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace);let f=this.loadQueryError(i)??{},o=this.loadQueryErrorMessage(i);f.message=o,f.Error={Type:f.Type,Code:f.Code,Message:o};let{errorSchema:c,errorMetadata:h}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,f,r,this.mixin.findQueryCompatibleError),u=ft.of(c),_=new(this.compositeErrorRegistry.getErrorCtor(c)??Error)({}),w={Type:f.Error.Type,Code:f.Error.Code,Error:f.Error};for(let[A,M]of u.structIterator()){let d=M.getMergedTraits().xmlName??A,E=f[d]??i[d];w[A]=this.deserializer.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(_,h,{$fault:u.getMergedTraits().error,message:o},w),i)}loadQueryErrorCode(t,n){let s=(n.Errors?.[0]?.Error??n.Errors?.Error??n.Error)?.Code;if(s!==void 0)return s;if(t.statusCode==404)return"NotFound"}loadQueryError(t){return t.Errors?.[0]?.Error??t.Errors?.Error??t.Error}loadQueryErrorMessage(t){let n=this.loadQueryError(t);return n?.message??n?.Message??t.message??t.Message??"Unknown"}getDefaultContentType(){return"application/x-www-form-urlencoded"}}class t1 extends Uh{options;constructor(t){super(t);this.options=t;let n={capitalizeKeys:!0,flattenLists:!0,serializeEmptyLists:!1,ec2:!0};Object.assign(this.serializer.settings,n)}getShapeId(){return"aws.protocols#ec2Query"}useNestedResult(){return!1}}var n1=(t,n)=>CM(t,n).then((s)=>{if(s.length){let i;try{i=xM(s)}catch(o){if(o&&typeof o==="object")Object.defineProperty(o,"$responseBodyText",{value:s});throw o}let r="#text",e=Object.keys(i)[0],f=i[e];if(f[r])f[e]=f[r],delete f[r];return DM(f)}return{}}),kF=async(t,n)=>{let s=await n1(t,n);if(s.Error)s.Error.message=s.Error.message??s.Error.Message;return s},s1=(t,n)=>{if(n?.Error?.Code!==void 0)return n.Error.Code;if(n?.Code!==void 0)return n.Code;if(t.statusCode==404)return"NotFound"};class Lh extends xn{settings;stringBuffer;byteBuffer;buffer;constructor(t){super();this.settings=t}write(t,n){let s=ft.of(t);if(s.isStringSchema()&&typeof n==="string")this.stringBuffer=n;else if(s.isBlobSchema())this.byteBuffer="byteLength"in n?n:(this.serdeContext?.base64Decoder??zM)(n);else{this.buffer=this.writeStruct(s,n,void 0);let i=s.getMergedTraits();if(i.httpPayload&&!i.xmlName)this.buffer.withName(s.getName())}}flush(){if(this.byteBuffer!==void 0){let n=this.byteBuffer;return delete this.byteBuffer,n}if(this.stringBuffer!==void 0){let n=this.stringBuffer;return delete this.stringBuffer,n}let t=this.buffer;if(this.settings.xmlNamespace){if(!t?.attributes?.xmlns)t.addAttribute("xmlns",this.settings.xmlNamespace)}return delete this.buffer,t.toString()}writeStruct(t,n,s){let i=t.getMergedTraits(),r=t.isMemberSchema()&&!i.httpPayload?t.getMemberTraits().xmlName??t.getMemberName():i.xmlName??t.getName();if(!r||!t.isStructSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${t.getName(!0)}.`);let e=Ct.of(r),[f,o]=this.getXmlnsAttribute(t,s);for(let[h,u]of t.structIterator()){let l=n[h];if(l!=null||u.isIdempotencyToken()){if(u.getMergedTraits().xmlAttribute){e.addAttribute(u.getMergedTraits().xmlName??h,this.writeSimple(u,l));continue}if(u.isListSchema())this.writeList(u,l,e,o);else if(u.isMapSchema())this.writeMap(u,l,e,o);else if(u.isStructSchema())e.addChildNode(this.writeStruct(u,l,o));else{let _=Ct.of(u.getMergedTraits().xmlName??u.getMemberName());this.writeSimpleInto(u,l,_,o),e.addChildNode(_)}}}let{$unknown:c}=n;if(c&&t.isUnionSchema()&&Array.isArray(c)&&Object.keys(n).length===1){let[h,u]=c,l=Ct.of(h);if(typeof u!=="string")if(n instanceof Ct||n instanceof HM)e.addChildNode(n);else throw Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");this.writeSimpleInto(0,u,l,o),e.addChildNode(l)}if(o)e.addAttribute(f,o);return e}writeList(t,n,s,i){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${t.getName(!0)}`);let r=t.getMergedTraits(),e=t.getValueSchema(),f=e.getMergedTraits(),o=!!f.sparse,c=!!r.xmlFlattened,[h,u]=this.getXmlnsAttribute(t,i),l=(_,w)=>{if(e.isListSchema())this.writeList(e,Array.isArray(w)?w:[w],_,u);else if(e.isMapSchema())this.writeMap(e,w,_,u);else if(e.isStructSchema()){let A=this.writeStruct(e,w,u);_.addChildNode(A.withName(c?r.xmlName??t.getMemberName():f.xmlName??"member"))}else{let A=Ct.of(c?r.xmlName??t.getMemberName():f.xmlName??"member");this.writeSimpleInto(e,w,A,u),_.addChildNode(A)}};if(c){for(let _ of n)if(o||_!=null)l(s,_)}else{let _=Ct.of(r.xmlName??t.getMemberName());if(u)_.addAttribute(h,u);for(let w of n)if(o||w!=null)l(_,w);s.addChildNode(_)}}writeMap(t,n,s,i,r=!1){if(!t.isMemberSchema())throw Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${t.getName(!0)}`);let e=t.getMergedTraits(),f=t.getKeySchema(),c=f.getMergedTraits().xmlName??"key",h=t.getValueSchema(),u=h.getMergedTraits(),l=u.xmlName??"value",_=!!u.sparse,w=!!e.xmlFlattened,[A,M]=this.getXmlnsAttribute(t,i),d=(E,T,U)=>{let S=Ct.of(c,T),[y,D]=this.getXmlnsAttribute(f,M);if(D)S.addAttribute(y,D);E.addChildNode(S);let q=Ct.of(l);if(h.isListSchema())this.writeList(h,U,q,M);else if(h.isMapSchema())this.writeMap(h,U,q,M,!0);else if(h.isStructSchema())q=this.writeStruct(h,U,M);else this.writeSimpleInto(h,U,q,M);E.addChildNode(q)};if(w)for(let E in n){let T=n[E];if(_||T!=null){let U=Ct.of(e.xmlName??t.getMemberName());d(U,E,T),s.addChildNode(U)}}else{let E;if(!r){if(E=Ct.of(e.xmlName??t.getMemberName()),M)E.addAttribute(A,M);s.addChildNode(E)}for(let T in n){let U=n[T];if(_||U!=null){let S=Ct.of("entry");d(S,T,U),(r?s:E).addChildNode(S)}}}}writeSimple(t,n){if(n===null)throw Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");let s=ft.of(t),i=null;if(n&&typeof n==="object")if(s.isBlobSchema())i=(this.serdeContext?.base64Encoder??ke)(n);else if(s.isTimestampSchema()&&n instanceof Date)switch(Xe(s,this.settings)){case 5:i=n.toISOString().replace(".000Z","Z");break;case 6:i=ze(n);break;case 7:i=String(n.getTime()/1000);break;default:console.warn("Missing timestamp format, using http date",n),i=ze(n);break}else if(s.isBigDecimalSchema()&&n){if(n instanceof hn)return n.string;return String(n)}else if(s.isMapSchema()||s.isListSchema())throw Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead.");else throw Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${s.getName(!0)}`);if(s.isBooleanSchema()||s.isNumericSchema()||s.isBigIntegerSchema()||s.isBigDecimalSchema())i=String(n);if(s.isStringSchema())if(n===void 0&&s.isIdempotencyToken())i=Eh();else i=String(n);if(i===null)throw Error(`Unhandled schema-value pair ${s.getName(!0)}=${n}`);return i}writeSimpleInto(t,n,s,i){let r=this.writeSimple(t,n),e=ft.of(t),f=new HM(r),[o,c]=this.getXmlnsAttribute(e,i);if(c)s.addAttribute(o,c);s.addChildNode(f)}getXmlnsAttribute(t,n){let s=t.getMergedTraits(),[i,r]=s.xmlNamespace??[];if(r&&r!==n)return[i?`xmlns:${i}`:"xmlns",r];return[void 0,void 0]}}class Ih extends xn{settings;constructor(t){super();this.settings=t}createSerializer(){let t=new Lh(this.settings);return t.setSerdeContext(this.serdeContext),t}createDeserializer(){let t=new Ce(this.settings);return t.setSerdeContext(this.serdeContext),t}}class i1 extends YM{codec;serializer;deserializer;mixin=new oi;constructor(t){super(t);let n={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:t.xmlNamespace,serviceNamespace:t.defaultNamespace};this.codec=new Ih(n),this.serializer=new QM(this.codec.createSerializer(),n),this.deserializer=new JM(this.codec.createDeserializer(),n)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(t,n,s){let i=await super.serializeRequest(t,n,s),r=ft.of(t.input);if(!i.headers["content-type"]){let e=this.mixin.resolveRestContentType(this.getDefaultContentType(),r);if(e)i.headers["content-type"]=e}if(typeof i.body==="string"&&i.headers["content-type"]===this.getDefaultContentType()&&!i.body.startsWith("<?xml ")&&!this.hasUnstructuredPayloadBinding(r))i.body='<?xml version="1.0" encoding="UTF-8"?>'+i.body;return i}async deserializeResponse(t,n,s){return super.deserializeResponse(t,n,s)}async handleError(t,n,s,i,r){let e=s1(s,i)??"Unknown";if(this.mixin.compose(this.compositeErrorRegistry,e,this.options.defaultNamespace),i.Error&&typeof i.Error==="object"){for(let A of Object.keys(i.Error))if(i[A]=i.Error[A],A.toLowerCase()==="message")i.message=i.Error[A]}if(i.RequestId&&!r.requestId)r.requestId=i.RequestId;let{errorSchema:f,errorMetadata:o}=await this.mixin.getErrorSchemaOrThrowBaseException(e,this.options.defaultNamespace,s,i,r),c=ft.of(f),h=i.Error?.message??i.Error?.Message??i.message??i.Message??"UnknownError",l=new(this.compositeErrorRegistry.getErrorCtor(f)??Error)({});await this.deserializeHttpMessage(f,n,s,i);let _={},w=this.codec.createDeserializer();for(let[A,M]of c.structIterator()){let d=M.getMergedTraits().xmlName??A,E=i.Error?.[d]??i[d];_[A]=w.readSchema(M,E)}throw this.mixin.decorateServiceException(Object.assign(l,o,{$fault:c.getMergedTraits().error,message:h},_),i)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(t){for(let[,n]of t.structIterator())if(n.getMergedTraits().httpPayload)return!(n.isStructSchema()||n.isMapSchema()||n.isListSchema());return!1}}zF.AwsEc2QueryProtocol=t1;zF.AwsJson1_0Protocol=pM;zF.AwsJson1_1Protocol=ZM;zF.AwsJsonRpcProtocol=qe;zF.AwsQueryProtocol=Uh;zF.AwsRestJsonProtocol=vM;zF.AwsRestXmlProtocol=i1;zF.AwsSmithyRpcV2CborProtocol=qM;zF.JsonCodec=xe;zF.JsonShapeDeserializer=Th;zF.JsonShapeSerializer=Sh;zF.QueryShapeSerializer=$h;zF.XmlCodec=Ih;zF.XmlShapeDeserializer=Ce;zF.XmlShapeSerializer=Lh;zF._toBool=DF;zF._toNum=mF;zF._toStr=WF;zF.awsExpectUnion=JF;zF.loadJsonRpcErrorCode=VM;zF.loadRestJsonErrorCode=KM;zF.loadRestXmlErrorCode=s1;zF.parseJsonBody=bh;zF.parseJsonErrorBody=QF;zF.parseXmlBody=n1;zF.parseXmlErrorBody=kF});var Ph=Z((GN)=>{var{awsEndpointFunctions:MH,emitWarningIfUnsupportedVersion:gH,createDefaultUserAgentProvider:dH,NODE_APP_ID_CONFIG_OPTIONS:EH,getAwsRegionExtensionConfiguration:RH,resolveAwsRegionExtensionConfiguration:bH,resolveUserAgentConfig:TH,resolveHostHeaderConfig:SH,getUserAgentPlugin:$H,getHostHeaderPlugin:UH,getLoggerPlugin:LH,getRecursionDetectionPlugin:IH}=xt(),{NoAuthSigner:yH,getHttpAuthSchemeEndpointRuleSetPlugin:OH,DefaultIdentityProviderConfig:GH,getHttpSigningPlugin:BH}=kn(),{normalizeProvider:c1,getSmithyContext:FH,ServiceException:HH,NoOpLogger:PH,emitWarningIfUnsupportedVersion:NH,loadConfigsForDefaultMode:WH,getDefaultExtensionConfiguration:DH,resolveDefaultRuntimeConfig:mH,Client:h1,makeBuilder:YH,createAggregatedClient:QH}=Rn(),{Command:JH}=Rn();GN.$Command=JH;GN.__Client=h1;var{resolveDefaultsModeConfig:kH,loadConfig:As,NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS:zH,NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS:XH,NODE_REGION_CONFIG_OPTIONS:xH,NODE_REGION_CONFIG_FILE_OPTIONS:qH,resolveRegionConfig:CH}=St(),{BinaryDecisionDiagram:KH,EndpointCache:VH,decideEndpoint:jH,customEndpointFunctions:aH,resolveEndpointConfig:pH,getEndpointPlugin:ZH}=fs(),{parseUrl:vH,getHttpHandlerExtensionConfiguration:tP,resolveHttpHandlerRuntimeConfig:nP,getContentLengthPlugin:sP}=Ut(),{DEFAULT_RETRY_MODE:iP,NODE_RETRY_MODE_CONFIG_OPTIONS:rP,NODE_MAX_ATTEMPT_CONFIG_OPTIONS:eP,resolveRetryConfig:oP,getRetryPlugin:fP}=vi(),{TypeRegistry:u1,getSchemaSerdePlugin:cP}=Nn(),{resolveAwsSdkSigV4Config:hP,AwsSdkSigV4Signer:uP,NODE_AUTH_SCHEME_PREFERENCE_OPTIONS:lP}=jc(),{toUtf8:_P,fromUtf8:wP,toBase64:AP,fromBase64:MP,calculateBodyLength:gP}=$t(),{streamCollector:dP,NodeHttpHandler:EP}=Ye(),{AwsRestJsonProtocol:RP}=yh(),{Sha256:bP}=tc(),TP=async(t,n,s)=>{return{operation:FH(n).operation,region:await c1(t.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}};function SP(t){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"sso-oauth",region:t.region},propertiesExtractor:(n,s)=>({signingProperties:{config:n,context:s}})}}function $P(t){return{schemeId:"smithy.api#noAuth"}}var UP=(t)=>{let n=[];switch(t.operation){case"CreateToken":{n.push($P());break}default:n.push(SP(t))}return n},LP=(t)=>{let n=hP(t);return Object.assign(n,{authSchemePreference:c1(t.authSchemePreference??[])})},IP=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"sso-oauth"})},yP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},OP="3.997.32",GP={version:OP},_r="ref",Ms=-1,Ke=!0,r1="isSet",l1="PartitionResult",Ve="booleanEquals",Oh="getAttr",e1={[_r]:"Endpoint"},Gh={[_r]:l1},fi={},o1=[{[_r]:"Region"}],f1={conditions:[[r1,[e1]],[r1,o1],["aws.partition",o1,l1],[Ve,[{[_r]:"UseFIPS"},Ke]],[Ve,[{[_r]:"UseDualStack"},Ke]],[Ve,[{fn:Oh,argv:[Gh,"supportsDualStack"]},Ke]],[Ve,[{fn:Oh,argv:[Gh,"supportsFIPS"]},Ke]],["stringEquals",[{fn:Oh,argv:[Gh,"name"]},"aws-us-gov"]]],results:[[Ms],[Ms,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Ms,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[e1,fi],["https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",fi],[Ms,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://oidc.{Region}.amazonaws.com",fi],["https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}",fi],[Ms,"FIPS is enabled but this partition does not support FIPS"],["https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}",fi],[Ms,"DualStack is enabled but this partition does not support DualStack"],["https://oidc.{Region}.{PartitionResult#dnsSuffix}",fi],[Ms,"Invalid Configuration: Missing Region"]]},BP=2,Lt=1e8,FP=new Int32Array([-1,1,-1,0,13,3,1,4,Lt+12,2,5,Lt+12,3,8,6,4,7,Lt+11,5,Lt+9,Lt+10,4,11,9,6,10,Lt+8,7,Lt+6,Lt+7,5,12,Lt+5,6,Lt+4,Lt+5,3,Lt+1,14,4,Lt+2,Lt+3]),HP=KH.from(FP,BP,f1.conditions,f1.results),PP=new VH({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),NP=(t,n={})=>{return PP.get(t,()=>jH(HP,{endpointParams:t,logger:n.logger}))};aH.aws=MH;class Rt extends HH{constructor(t){super(t);Object.setPrototypeOf(this,Rt.prototype)}}class je extends Rt{name="AccessDeniedException";$fault="client";error;reason;error_description;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,je.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class ae extends Rt{name="AuthorizationPendingException";$fault="client";error;error_description;constructor(t){super({name:"AuthorizationPendingException",$fault:"client",...t});Object.setPrototypeOf(this,ae.prototype),this.error=t.error,this.error_description=t.error_description}}class pe extends Rt{name="ExpiredTokenException";$fault="client";error;error_description;constructor(t){super({name:"ExpiredTokenException",$fault:"client",...t});Object.setPrototypeOf(this,pe.prototype),this.error=t.error,this.error_description=t.error_description}}class Ze extends Rt{name="InternalServerException";$fault="server";error;error_description;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,Ze.prototype),this.error=t.error,this.error_description=t.error_description}}class ve extends Rt{name="InvalidClientException";$fault="client";error;error_description;constructor(t){super({name:"InvalidClientException",$fault:"client",...t});Object.setPrototypeOf(this,ve.prototype),this.error=t.error,this.error_description=t.error_description}}class to extends Rt{name="InvalidGrantException";$fault="client";error;error_description;constructor(t){super({name:"InvalidGrantException",$fault:"client",...t});Object.setPrototypeOf(this,to.prototype),this.error=t.error,this.error_description=t.error_description}}class no extends Rt{name="InvalidRequestException";$fault="client";error;reason;error_description;constructor(t){super({name:"InvalidRequestException",$fault:"client",...t});Object.setPrototypeOf(this,no.prototype),this.error=t.error,this.reason=t.reason,this.error_description=t.error_description}}class so extends Rt{name="InvalidScopeException";$fault="client";error;error_description;constructor(t){super({name:"InvalidScopeException",$fault:"client",...t});Object.setPrototypeOf(this,so.prototype),this.error=t.error,this.error_description=t.error_description}}class io extends Rt{name="SlowDownException";$fault="client";error;error_description;constructor(t){super({name:"SlowDownException",$fault:"client",...t});Object.setPrototypeOf(this,io.prototype),this.error=t.error,this.error_description=t.error_description}}class ro extends Rt{name="UnauthorizedClientException";$fault="client";error;error_description;constructor(t){super({name:"UnauthorizedClientException",$fault:"client",...t});Object.setPrototypeOf(this,ro.prototype),this.error=t.error,this.error_description=t.error_description}}class eo extends Rt{name="UnsupportedGrantTypeException";$fault="client";error;error_description;constructor(t){super({name:"UnsupportedGrantTypeException",$fault:"client",...t});Object.setPrototypeOf(this,eo.prototype),this.error=t.error,this.error_description=t.error_description}}var WP="AccessDeniedException",DP="AuthorizationPendingException",mP="AccessToken",YP="ClientSecret",QP="CreateToken",JP="CreateTokenRequest",kP="CreateTokenResponse",zP="CodeVerifier",XP="ExpiredTokenException",xP="InvalidClientException",qP="InvalidGrantException",CP="InvalidRequestException",KP="InternalServerException",VP="InvalidScopeException",jP="IdToken",aP="RefreshToken",pP="SlowDownException",ZP="UnauthorizedClientException",vP="UnsupportedGrantTypeException",tN="accessToken",un="client",nN="clientId",sN="clientSecret",iN="codeVerifier",rN="code",eN="deviceCode",et="error",oN="expiresIn",Kt="error_description",fN="grantType",cN="http",Vt="httpError",hN="idToken",_1="reason",w1="refreshToken",uN="redirectUri",A1="smithy.ts.sdk.synthetic.com.amazonaws.ssooidc",lN="scope",_N="server",wN="tokenType",ct="com.amazonaws.ssooidc",M1=u1.for(A1),g1=[-3,A1,"SSOOIDCServiceException",0,[],[]];M1.registerError(g1,Rt);var mt=u1.for(ct),d1=[-3,ct,WP,{[et]:un,[Vt]:400},[et,_1,Kt],[0,0,0]];mt.registerError(d1,je);var E1=[-3,ct,DP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(E1,ae);var R1=[-3,ct,XP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(R1,pe);var b1=[-3,ct,KP,{[et]:_N,[Vt]:500},[et,Kt],[0,0]];mt.registerError(b1,Ze);var T1=[-3,ct,xP,{[et]:un,[Vt]:401},[et,Kt],[0,0]];mt.registerError(T1,ve);var S1=[-3,ct,qP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(S1,to);var $1=[-3,ct,CP,{[et]:un,[Vt]:400},[et,_1,Kt],[0,0,0]];mt.registerError($1,no);var U1=[-3,ct,VP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(U1,so);var L1=[-3,ct,pP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(L1,io);var I1=[-3,ct,ZP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(I1,ro);var y1=[-3,ct,vP,{[et]:un,[Vt]:400},[et,Kt],[0,0]];mt.registerError(y1,eo);var O1=[M1,mt],AN=[0,ct,mP,8,0],MN=[0,ct,YP,8,0],gN=[0,ct,zP,8,0],dN=[0,ct,jP,8,0],G1=[0,ct,aP,8,0],B1=[3,ct,JP,0,[nN,sN,fN,eN,rN,w1,lN,uN,iN],[0,[()=>MN,0],0,0,0,[()=>G1,0],64,0,[()=>gN,0]],3],F1=[3,ct,kP,0,[tN,wN,oN,w1,hN],[[()=>AN,0],0,1,[()=>G1,0],[()=>dN,0]]],H1=[9,ct,QP,{[cN]:["POST","/token",200]},()=>B1,()=>F1],EN=(t)=>{return{apiVersion:"2019-06-10",base64Decoder:t?.base64Decoder??MP,base64Encoder:t?.base64Encoder??AP,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??NP,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??UP,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(n)=>n.getIdentityProvider("aws.auth#sigv4"),signer:new uP},{schemeId:"smithy.api#noAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new yH}],logger:t?.logger??new PH,protocol:t?.protocol??RP,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazonaws.ssooidc",errorTypeRegistries:O1,version:"2019-06-10",serviceTarget:"AWSSSOOIDCService"},serviceId:t?.serviceId??"SSO OIDC",sha256:t?.sha256??bP,urlParser:t?.urlParser??vH,utf8Decoder:t?.utf8Decoder??wP,utf8Encoder:t?.utf8Encoder??_P}},RN=(t)=>{NH(process.version);let n=kH(t),s=()=>n().then(WH),i=EN(t);gH(process.version);let r={profile:t?.profile,logger:i.logger};return{...i,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??As(lP,r),bodyLengthChecker:t?.bodyLengthChecker??gP,defaultUserAgentProvider:t?.defaultUserAgentProvider??dH({serviceId:i.serviceId,clientVersion:GP.version}),maxAttempts:t?.maxAttempts??As(eP,t),region:t?.region??As(xH,{...qH,...r}),requestHandler:EP.create(t?.requestHandler??s),retryMode:t?.retryMode??As({...rP,default:async()=>(await s()).retryMode||iP},t),streamCollector:t?.streamCollector??dP,useDualstackEndpoint:t?.useDualstackEndpoint??As(XH,r),useFipsEndpoint:t?.useFipsEndpoint??As(zH,r),userAgentAppId:t?.userAgentAppId??As(EH,r)}},bN=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,credentials:i}=t;return{setHttpAuthScheme(r){let e=n.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)n.push(r);else n.splice(e,1,r)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(r){s=r},httpAuthSchemeProvider(){return s},setCredentials(r){i=r},credentials(){return i}}},TN=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),credentials:t.credentials()}},SN=(t,n)=>{let s=Object.assign(RH(t),DH(t),tP(t),bN(t));return n.forEach((i)=>i.configure(s)),Object.assign(t,bH(s),mH(s),nP(s),TN(s))};class Bh extends h1{config;constructor(...[t]){let n=RN(t||{});super(n);this.initConfig=n;let s=IP(n),i=TH(s),r=oP(i),e=CH(r),f=SH(e),o=pH(f),c=LP(o),h=SN(c,t?.extensions||[]);this.config=h,this.middlewareStack.use(cP(this.config)),this.middlewareStack.use($H(this.config)),this.middlewareStack.use(fP(this.config)),this.middlewareStack.use(sP(this.config)),this.middlewareStack.use(UH(this.config)),this.middlewareStack.use(LH(this.config)),this.middlewareStack.use(IH(this.config)),this.middlewareStack.use(OH(this.config,{httpAuthSchemeParametersProvider:TP,identityProviderConfigProvider:async(u)=>new GH({"aws.auth#sigv4":u.credentials})})),this.middlewareStack.use(BH(this.config))}destroy(){super.destroy()}}var $N=YH(yP,"AWSSSOOIDCService","SSOOIDCClient",ZH),UN={},LN=(t,n,s,i)=>[];class Fh extends $N(UN,LN,"CreateToken",H1){}var IN={CreateTokenCommand:Fh};class Hh extends Bh{}QH(IN,Hh);var yN={KMS_ACCESS_DENIED:"KMS_AccessDeniedException"},ON={KMS_DISABLED_KEY:"KMS_DisabledException",KMS_INVALID_KEY_USAGE:"KMS_InvalidKeyUsageException",KMS_INVALID_STATE:"KMS_InvalidStateException",KMS_KEY_NOT_FOUND:"KMS_NotFoundException"};GN.AccessDeniedException=je;GN.AccessDeniedException$=d1;GN.AccessDeniedExceptionReason=yN;GN.AuthorizationPendingException=ae;GN.AuthorizationPendingException$=E1;GN.CreateToken$=H1;GN.CreateTokenCommand=Fh;GN.CreateTokenRequest$=B1;GN.CreateTokenResponse$=F1;GN.ExpiredTokenException=pe;GN.ExpiredTokenException$=R1;GN.InternalServerException=Ze;GN.InternalServerException$=b1;GN.InvalidClientException=ve;GN.InvalidClientException$=T1;GN.InvalidGrantException=to;GN.InvalidGrantException$=S1;GN.InvalidRequestException=no;GN.InvalidRequestException$=$1;GN.InvalidRequestExceptionReason=ON;GN.InvalidScopeException=so;GN.InvalidScopeException$=U1;GN.SSOOIDC=Hh;GN.SSOOIDCClient=Bh;GN.SSOOIDCServiceException=Rt;GN.SSOOIDCServiceException$=g1;GN.SlowDownException=io;GN.SlowDownException$=L1;GN.UnauthorizedClientException=ro;GN.UnauthorizedClientException$=I1;GN.UnsupportedGrantTypeException=eo;GN.UnsupportedGrantTypeException$=y1;GN.errorTypeRegistries=O1});import{existsSync as sR,readFileSync as iR}from"fs";import{homedir as rR}from"os";import{join as G0}from"path";var g={};Xd(g,{void:()=>yE,util:()=>x,unknown:()=>LE,union:()=>FE,undefined:()=>SE,tuple:()=>NE,transformer:()=>xE,symbol:()=>TE,string:()=>I0,strictObject:()=>BE,setErrorMap:()=>Cd,set:()=>mE,record:()=>WE,quotelessJson:()=>xd,promise:()=>XE,preprocess:()=>KE,pipeline:()=>VE,ostring:()=>jE,optional:()=>qE,onumber:()=>aE,oboolean:()=>pE,objectUtil:()=>Jo,object:()=>GE,number:()=>y0,nullable:()=>CE,null:()=>$E,never:()=>IE,nativeEnum:()=>zE,nan:()=>EE,map:()=>DE,makeIssue:()=>gi,literal:()=>JE,lazy:()=>QE,late:()=>gE,isValid:()=>yn,isDirty:()=>Sr,isAsync:()=>Ss,isAborted:()=>Tr,intersection:()=>PE,instanceof:()=>dE,getParsedType:()=>at,getErrorMap:()=>Ts,function:()=>YE,enum:()=>kE,effect:()=>xE,discriminatedUnion:()=>HE,defaultErrorMap:()=>An,datetimeRegex:()=>$0,date:()=>bE,custom:()=>L0,coerce:()=>ZE,boolean:()=>O0,bigint:()=>RE,array:()=>OE,any:()=>UE,addIssueToContext:()=>L,ZodVoid:()=>Ei,ZodUnknown:()=>On,ZodUnion:()=>Os,ZodUndefined:()=>Is,ZodType:()=>z,ZodTuple:()=>Zt,ZodTransformer:()=>zt,ZodSymbol:()=>di,ZodString:()=>Yt,ZodSet:()=>pn,ZodSchema:()=>z,ZodRecord:()=>Ri,ZodReadonly:()=>Ws,ZodPromise:()=>Zn,ZodPipeline:()=>Si,ZodParsedType:()=>$,ZodOptional:()=>Jt,ZodObject:()=>it,ZodNumber:()=>Gn,ZodNullable:()=>gn,ZodNull:()=>ys,ZodNever:()=>pt,ZodNativeEnum:()=>Hs,ZodNaN:()=>Ti,ZodMap:()=>bi,ZodLiteral:()=>Fs,ZodLazy:()=>Bs,ZodIssueCode:()=>b,ZodIntersection:()=>Gs,ZodFunction:()=>Us,ZodFirstPartyTypeKind:()=>N,ZodError:()=>bt,ZodEnum:()=>Fn,ZodEffects:()=>zt,ZodDiscriminatedUnion:()=>$r,ZodDefault:()=>Ps,ZodDate:()=>jn,ZodCatch:()=>Ns,ZodBranded:()=>Ur,ZodBoolean:()=>Ls,ZodBigInt:()=>Bn,ZodArray:()=>Qt,ZodAny:()=>an,Schema:()=>z,ParseStatus:()=>_t,OK:()=>gt,NEVER:()=>vE,INVALID:()=>P,EMPTY_PATH:()=>Kd,DIRTY:()=>Vn,BRAND:()=>ME});var x;(function(t){t.assertEqual=(r)=>{};function n(r){}t.assertIs=n;function s(r){throw Error()}t.assertNever=s,t.arrayToEnum=(r)=>{let e={};for(let f of r)e[f]=f;return e},t.getValidEnumValues=(r)=>{let e=t.objectKeys(r).filter((o)=>typeof r[r[o]]!=="number"),f={};for(let o of e)f[o]=r[o];return t.objectValues(f)},t.objectValues=(r)=>{return t.objectKeys(r).map(function(e){return r[e]})},t.objectKeys=typeof Object.keys==="function"?(r)=>Object.keys(r):(r)=>{let e=[];for(let f in r)if(Object.prototype.hasOwnProperty.call(r,f))e.push(f);return e},t.find=(r,e)=>{for(let f of r)if(e(f))return f;return},t.isInteger=typeof Number.isInteger==="function"?(r)=>Number.isInteger(r):(r)=>typeof r==="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,e=" | "){return r.map((f)=>typeof f==="string"?`'${f}'`:f).join(e)}t.joinValues=i,t.jsonStringifyReplacer=(r,e)=>{if(typeof e==="bigint")return e.toString();return e}})(x||(x={}));var Jo;(function(t){t.mergeShapes=(n,s)=>{return{...n,...s}}})(Jo||(Jo={}));var $=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=(t)=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":if(Array.isArray(t))return $.array;if(t===null)return $.null;if(t.then&&typeof t.then==="function"&&t.catch&&typeof t.catch==="function")return $.promise;if(typeof Map<"u"&&t instanceof Map)return $.map;if(typeof Set<"u"&&t instanceof Set)return $.set;if(typeof Date<"u"&&t instanceof Date)return $.date;return $.object;default:return $.unknown}};var b=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),xd=(t)=>{return JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:")};class bt extends Error{get errors(){return this.issues}constructor(t){super();this.issues=[],this.addIssue=(s)=>{this.issues=[...this.issues,s]},this.addIssues=(s=[])=>{this.issues=[...this.issues,...s]};let n=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,n);else this.__proto__=n;this.name="ZodError",this.issues=t}format(t){let n=t||function(r){return r.message},s={_errors:[]},i=(r)=>{for(let e of r.issues)if(e.code==="invalid_union")e.unionErrors.map(i);else if(e.code==="invalid_return_type")i(e.returnTypeError);else if(e.code==="invalid_arguments")i(e.argumentsError);else if(e.path.length===0)s._errors.push(n(e));else{let f=s,o=0;while(o<e.path.length){let c=e.path[o];if(o!==e.path.length-1)f[c]=f[c]||{_errors:[]};else f[c]=f[c]||{_errors:[]},f[c]._errors.push(n(e));f=f[c],o++}}};return i(this),s}static assert(t){if(!(t instanceof bt))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=(n)=>n.message){let n={},s=[];for(let i of this.issues)if(i.path.length>0){let r=i.path[0];n[r]=n[r]||[],n[r].push(t(i))}else s.push(t(i));return{formErrors:s,fieldErrors:n}}get formErrors(){return this.flatten()}}bt.create=(t)=>{return new bt(t)};var qd=(t,n)=>{let s;switch(t.code){case b.invalid_type:if(t.received===$.undefined)s="Required";else s=`Expected ${t.expected}, received ${t.received}`;break;case b.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,x.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:s=`Unrecognized key(s) in object: ${x.joinValues(t.keys,", ")}`;break;case b.invalid_union:s="Invalid input";break;case b.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${x.joinValues(t.options)}`;break;case b.invalid_enum_value:s=`Invalid enum value. Expected ${x.joinValues(t.options)}, received '${t.received}'`;break;case b.invalid_arguments:s="Invalid function arguments";break;case b.invalid_return_type:s="Invalid function return type";break;case b.invalid_date:s="Invalid date";break;case b.invalid_string:if(typeof t.validation==="object")if("includes"in t.validation){if(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position==="number")s=`${s} at one or more positions greater than or equal to ${t.validation.position}`}else if("startsWith"in t.validation)s=`Invalid input: must start with "${t.validation.startsWith}"`;else if("endsWith"in t.validation)s=`Invalid input: must end with "${t.validation.endsWith}"`;else x.assertNever(t.validation);else if(t.validation!=="regex")s=`Invalid ${t.validation}`;else s="Invalid";break;case b.too_small:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="bigint")s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`;else s="Invalid input";break;case b.too_big:if(t.type==="array")s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`;else if(t.type==="string")s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`;else if(t.type==="number")s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="bigint")s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`;else if(t.type==="date")s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`;else s="Invalid input";break;case b.custom:s="Invalid input";break;case b.invalid_intersection_types:s="Intersection results could not be merged";break;case b.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case b.not_finite:s="Number must be finite";break;default:s=n.defaultError,x.assertNever(t)}return{message:s}},An=qd;var E0=An;function Cd(t){E0=t}function Ts(){return E0}var gi=(t)=>{let{data:n,path:s,errorMaps:i,issueData:r}=t,e=[...s,...r.path||[]],f={...r,path:e};if(r.message!==void 0)return{...r,path:e,message:r.message};let o="",c=i.filter((h)=>!!h).slice().reverse();for(let h of c)o=h(f,{data:n,defaultError:o}).message;return{...r,path:e,message:o}},Kd=[];function L(t,n){let s=Ts(),i=gi({issueData:n,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===An?void 0:An].filter((r)=>!!r)});t.common.issues.push(i)}class _t{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(t,n){let s=[];for(let i of n){if(i.status==="aborted")return P;if(i.status==="dirty")t.dirty();s.push(i.value)}return{status:t.value,value:s}}static async mergeObjectAsync(t,n){let s=[];for(let i of n){let r=await i.key,e=await i.value;s.push({key:r,value:e})}return _t.mergeObjectSync(t,s)}static mergeObjectSync(t,n){let s={};for(let i of n){let{key:r,value:e}=i;if(r.status==="aborted")return P;if(e.status==="aborted")return P;if(r.status==="dirty")t.dirty();if(e.status==="dirty")t.dirty();if(r.value!=="__proto__"&&(typeof e.value<"u"||i.alwaysSet))s[r.value]=e.value}return{status:t.value,value:s}}}var P=Object.freeze({status:"aborted"}),Vn=(t)=>({status:"dirty",value:t}),gt=(t)=>({status:"valid",value:t}),Tr=(t)=>t.status==="aborted",Sr=(t)=>t.status==="dirty",yn=(t)=>t.status==="valid",Ss=(t)=>typeof Promise<"u"&&t instanceof Promise;var O;(function(t){t.errToObj=(n)=>typeof n==="string"?{message:n}:n||{},t.toString=(n)=>typeof n==="string"?n:n?.message})(O||(O={}));class kt{constructor(t,n,s,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=s,this._key=i}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var R0=(t,n)=>{if(yn(n))return{success:!0,data:n.value};else{if(!t.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let s=new bt(t.common.issues);return this._error=s,this._error}}}};function Q(t){if(!t)return{};let{errorMap:n,invalid_type_error:s,required_error:i,description:r}=t;if(n&&(s||i))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(n)return{errorMap:n,description:r};return{errorMap:(f,o)=>{let{message:c}=t;if(f.code==="invalid_enum_value")return{message:c??o.defaultError};if(typeof o.data>"u")return{message:c??i??o.defaultError};if(f.code!=="invalid_type")return{message:o.defaultError};return{message:c??s??o.defaultError}},description:r}}class z{get description(){return this._def.description}_getType(t){return at(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new _t,ctx:{common:t.parent.common,data:t.data,parsedType:at(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ss(n))throw Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let s=this.safeParse(t,n);if(s.success)return s.data;throw s.error}safeParse(t,n){let s={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},i=this._parseSync({data:t,path:s.path,parent:s});return R0(s,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)};if(!this["~standard"].async)try{let s=this._parseSync({data:t,path:[],parent:n});return yn(s)?{value:s.value}:{issues:n.common.issues}}catch(s){if(s?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then((s)=>yn(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(t,n){let s=await this.safeParseAsync(t,n);if(s.success)return s.data;throw s.error}async safeParseAsync(t,n){let s={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:at(t)},i=this._parse({data:t,path:s.path,parent:s}),r=await(Ss(i)?i:Promise.resolve(i));return R0(s,r)}refine(t,n){let s=(i)=>{if(typeof n==="string"||typeof n>"u")return{message:n};else if(typeof n==="function")return n(i);else return n};return this._refinement((i,r)=>{let e=t(i),f=()=>r.addIssue({code:b.custom,...s(i)});if(typeof Promise<"u"&&e instanceof Promise)return e.then((o)=>{if(!o)return f(),!1;else return!0});if(!e)return f(),!1;else return!0})}refinement(t,n){return this._refinement((s,i)=>{if(!t(s))return i.addIssue(typeof n==="function"?n(s,i):n),!1;else return!0})}_refinement(t){return new zt({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(n)=>this["~validate"](n)}}optional(){return Jt.create(this,this._def)}nullable(){return gn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Qt.create(this)}promise(){return Zn.create(this,this._def)}or(t){return Os.create([this,t],this._def)}and(t){return Gs.create(this,t,this._def)}transform(t){return new zt({...Q(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t==="function"?t:()=>t;return new Ps({...Q(this._def),innerType:this,defaultValue:n,typeName:N.ZodDefault})}brand(){return new Ur({typeName:N.ZodBranded,type:this,...Q(this._def)})}catch(t){let n=typeof t==="function"?t:()=>t;return new Ns({...Q(this._def),innerType:this,catchValue:n,typeName:N.ZodCatch})}describe(t){return new this.constructor({...this._def,description:t})}pipe(t){return Si.create(this,t)}readonly(){return Ws.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var Vd=/^c[^\s-]{8,}$/i,jd=/^[0-9a-z]+$/,ad=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pd=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Zd=/^[a-z0-9_-]{21}$/i,vd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tE=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,nE=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sE="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ko,iE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rE=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,eE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,oE=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fE=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cE=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T0="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",hE=new RegExp(`^${T0}$`);function S0(t){let n="[0-5]\\d";if(t.precision)n=`${n}\\.\\d{${t.precision}}`;else if(t.precision==null)n=`${n}(\\.\\d+)?`;let s=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${n})${s}`}function uE(t){return new RegExp(`^${S0(t)}$`)}function $0(t){let n=`${T0}T${S0(t)}`,s=[];if(s.push(t.local?"Z?":"Z"),t.offset)s.push("([+-]\\d{2}:?\\d{2})");return n=`${n}(${s.join("|")})`,new RegExp(`^${n}$`)}function lE(t,n){if((n==="v4"||!n)&&iE.test(t))return!0;if((n==="v6"||!n)&&eE.test(t))return!0;return!1}function _E(t,n){if(!vd.test(t))return!1;try{let[s]=t.split(".");if(!s)return!1;let i=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),r=JSON.parse(atob(i));if(typeof r!=="object"||r===null)return!1;if("typ"in r&&r?.typ!=="JWT")return!1;if(!r.alg)return!1;if(n&&r.alg!==n)return!1;return!0}catch{return!1}}function wE(t,n){if((n==="v4"||!n)&&rE.test(t))return!0;if((n==="v6"||!n)&&oE.test(t))return!0;return!1}class Yt extends z{_parse(t){if(this._def.coerce)t.data=String(t.data);if(this._getType(t)!==$.string){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.string,received:r.parsedType}),P}let s=new _t,i=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(t.data.length<r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="max"){if(t.data.length>r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),s.dirty()}else if(r.kind==="length"){let e=t.data.length>r.value,f=t.data.length<r.value;if(e||f){if(i=this._getOrReturnCtx(t,i),e)L(i,{code:b.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});else if(f)L(i,{code:b.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message});s.dirty()}}else if(r.kind==="email"){if(!nE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"email",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="emoji"){if(!ko)ko=new RegExp(sE,"u");if(!ko.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"emoji",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="uuid"){if(!pd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"uuid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="nanoid"){if(!Zd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"nanoid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cuid"){if(!Vd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"cuid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cuid2"){if(!jd.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"cuid2",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="ulid"){if(!ad.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"ulid",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),L(i,{validation:"url",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="regex"){if(r.regex.lastIndex=0,!r.regex.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"regex",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="trim")t.data=t.data.trim();else if(r.kind==="includes"){if(!t.data.includes(r.value,r.position))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),s.dirty()}else if(r.kind==="toLowerCase")t.data=t.data.toLowerCase();else if(r.kind==="toUpperCase")t.data=t.data.toUpperCase();else if(r.kind==="startsWith"){if(!t.data.startsWith(r.value))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{startsWith:r.value},message:r.message}),s.dirty()}else if(r.kind==="endsWith"){if(!t.data.endsWith(r.value))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:{endsWith:r.value},message:r.message}),s.dirty()}else if(r.kind==="datetime"){if(!$0(r).test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"datetime",message:r.message}),s.dirty()}else if(r.kind==="date"){if(!hE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"date",message:r.message}),s.dirty()}else if(r.kind==="time"){if(!uE(r).test(t.data))i=this._getOrReturnCtx(t,i),L(i,{code:b.invalid_string,validation:"time",message:r.message}),s.dirty()}else if(r.kind==="duration"){if(!tE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"duration",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="ip"){if(!lE(t.data,r.version))i=this._getOrReturnCtx(t,i),L(i,{validation:"ip",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="jwt"){if(!_E(t.data,r.alg))i=this._getOrReturnCtx(t,i),L(i,{validation:"jwt",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="cidr"){if(!wE(t.data,r.version))i=this._getOrReturnCtx(t,i),L(i,{validation:"cidr",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="base64"){if(!fE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"base64",code:b.invalid_string,message:r.message}),s.dirty()}else if(r.kind==="base64url"){if(!cE.test(t.data))i=this._getOrReturnCtx(t,i),L(i,{validation:"base64url",code:b.invalid_string,message:r.message}),s.dirty()}else x.assertNever(r);return{status:s.value,value:t.data}}_regex(t,n,s){return this.refinement((i)=>t.test(i),{validation:n,code:b.invalid_string,...O.errToObj(s)})}_addCheck(t){return new Yt({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...O.errToObj(t)})}url(t){return this._addCheck({kind:"url",...O.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...O.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...O.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...O.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...O.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...O.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...O.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...O.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...O.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...O.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...O.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...O.errToObj(t)})}datetime(t){if(typeof t==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t});return this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...O.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){if(typeof t==="string")return this._addCheck({kind:"time",precision:null,message:t});return this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...O.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...O.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...O.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...O.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...O.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...O.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...O.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...O.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...O.errToObj(n)})}nonempty(t){return this.min(1,O.errToObj(t))}trim(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Yt({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((t)=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find((t)=>t.kind==="date")}get isTime(){return!!this._def.checks.find((t)=>t.kind==="time")}get isDuration(){return!!this._def.checks.find((t)=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find((t)=>t.kind==="email")}get isURL(){return!!this._def.checks.find((t)=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find((t)=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find((t)=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((t)=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((t)=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((t)=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find((t)=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find((t)=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find((t)=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find((t)=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find((t)=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxLength(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Yt.create=(t)=>{return new Yt({checks:[],typeName:N.ZodString,coerce:t?.coerce??!1,...Q(t)})};function AE(t,n){let s=(t.toString().split(".")[1]||"").length,i=(n.toString().split(".")[1]||"").length,r=s>i?s:i,e=Number.parseInt(t.toFixed(r).replace(".","")),f=Number.parseInt(n.toFixed(r).replace(".",""));return e%f/10**r}class Gn extends z{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce)t.data=Number(t.data);if(this._getType(t)!==$.number){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.number,received:r.parsedType}),P}let s=void 0,i=new _t;for(let r of this._def.checks)if(r.kind==="int"){if(!x.isInteger(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.invalid_type,expected:"integer",received:"float",message:r.message}),i.dirty()}else if(r.kind==="min"){if(r.inclusive?t.data<r.value:t.data<=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="max"){if(r.inclusive?t.data>r.value:t.data>=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),i.dirty()}else if(r.kind==="multipleOf"){if(AE(t.data,r.value)!==0)s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()}else if(r.kind==="finite"){if(!Number.isFinite(t.data))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_finite,message:r.message}),i.dirty()}else x.assertNever(r);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,s,i){return new Gn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:O.toString(i)}]})}_addCheck(t){return new Gn({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:O.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:O.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:O.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:O.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}get isInt(){return!!this._def.checks.find((t)=>t.kind==="int"||t.kind==="multipleOf"&&x.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let s of this._def.checks)if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;else if(s.kind==="min"){if(n===null||s.value>n)n=s.value}else if(s.kind==="max"){if(t===null||s.value<t)t=s.value}return Number.isFinite(n)&&Number.isFinite(t)}}Gn.create=(t)=>{return new Gn({checks:[],typeName:N.ZodNumber,coerce:t?.coerce||!1,...Q(t)})};class Bn extends z{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==$.bigint)return this._getInvalidInput(t);let s=void 0,i=new _t;for(let r of this._def.checks)if(r.kind==="min"){if(r.inclusive?t.data<r.value:t.data<=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()}else if(r.kind==="max"){if(r.inclusive?t.data>r.value:t.data>=r.value)s=this._getOrReturnCtx(t,s),L(s,{code:b.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),i.dirty()}else if(r.kind==="multipleOf"){if(t.data%r.value!==BigInt(0))s=this._getOrReturnCtx(t,s),L(s,{code:b.not_multiple_of,multipleOf:r.value,message:r.message}),i.dirty()}else x.assertNever(r);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.bigint,received:n.parsedType}),P}gte(t,n){return this.setLimit("min",t,!0,O.toString(n))}gt(t,n){return this.setLimit("min",t,!1,O.toString(n))}lte(t,n){return this.setLimit("max",t,!0,O.toString(n))}lt(t,n){return this.setLimit("max",t,!1,O.toString(n))}setLimit(t,n,s,i){return new Bn({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:s,message:O.toString(i)}]})}_addCheck(t){return new Bn({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:O.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:O.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:O.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:O.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:O.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t}get maxValue(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t}}Bn.create=(t)=>{return new Bn({checks:[],typeName:N.ZodBigInt,coerce:t?.coerce??!1,...Q(t)})};class Ls extends z{_parse(t){if(this._def.coerce)t.data=Boolean(t.data);if(this._getType(t)!==$.boolean){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.boolean,received:s.parsedType}),P}return gt(t.data)}}Ls.create=(t)=>{return new Ls({typeName:N.ZodBoolean,coerce:t?.coerce||!1,...Q(t)})};class jn extends z{_parse(t){if(this._def.coerce)t.data=new Date(t.data);if(this._getType(t)!==$.date){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_type,expected:$.date,received:r.parsedType}),P}if(Number.isNaN(t.data.getTime())){let r=this._getOrReturnCtx(t);return L(r,{code:b.invalid_date}),P}let s=new _t,i=void 0;for(let r of this._def.checks)if(r.kind==="min"){if(t.data.getTime()<r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),s.dirty()}else if(r.kind==="max"){if(t.data.getTime()>r.value)i=this._getOrReturnCtx(t,i),L(i,{code:b.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),s.dirty()}else x.assertNever(r);return{status:s.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jn({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:O.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:O.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)if(n.kind==="min"){if(t===null||n.value>t)t=n.value}return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)if(n.kind==="max"){if(t===null||n.value<t)t=n.value}return t!=null?new Date(t):null}}jn.create=(t)=>{return new jn({checks:[],coerce:t?.coerce||!1,typeName:N.ZodDate,...Q(t)})};class di extends z{_parse(t){if(this._getType(t)!==$.symbol){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.symbol,received:s.parsedType}),P}return gt(t.data)}}di.create=(t)=>{return new di({typeName:N.ZodSymbol,...Q(t)})};class Is extends z{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.undefined,received:s.parsedType}),P}return gt(t.data)}}Is.create=(t)=>{return new Is({typeName:N.ZodUndefined,...Q(t)})};class ys extends z{_parse(t){if(this._getType(t)!==$.null){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.null,received:s.parsedType}),P}return gt(t.data)}}ys.create=(t)=>{return new ys({typeName:N.ZodNull,...Q(t)})};class an extends z{constructor(){super(...arguments);this._any=!0}_parse(t){return gt(t.data)}}an.create=(t)=>{return new an({typeName:N.ZodAny,...Q(t)})};class On extends z{constructor(){super(...arguments);this._unknown=!0}_parse(t){return gt(t.data)}}On.create=(t)=>{return new On({typeName:N.ZodUnknown,...Q(t)})};class pt extends z{_parse(t){let n=this._getOrReturnCtx(t);return L(n,{code:b.invalid_type,expected:$.never,received:n.parsedType}),P}}pt.create=(t)=>{return new pt({typeName:N.ZodNever,...Q(t)})};class Ei extends z{_parse(t){if(this._getType(t)!==$.undefined){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.void,received:s.parsedType}),P}return gt(t.data)}}Ei.create=(t)=>{return new Ei({typeName:N.ZodVoid,...Q(t)})};class Qt extends z{_parse(t){let{ctx:n,status:s}=this._processInputParams(t),i=this._def;if(n.parsedType!==$.array)return L(n,{code:b.invalid_type,expected:$.array,received:n.parsedType}),P;if(i.exactLength!==null){let e=n.data.length>i.exactLength.value,f=n.data.length<i.exactLength.value;if(e||f)L(n,{code:e?b.too_big:b.too_small,minimum:f?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),s.dirty()}if(i.minLength!==null){if(n.data.length<i.minLength.value)L(n,{code:b.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),s.dirty()}if(i.maxLength!==null){if(n.data.length>i.maxLength.value)L(n,{code:b.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),s.dirty()}if(n.common.async)return Promise.all([...n.data].map((e,f)=>{return i.type._parseAsync(new kt(n,e,n.path,f))})).then((e)=>{return _t.mergeArray(s,e)});let r=[...n.data].map((e,f)=>{return i.type._parseSync(new kt(n,e,n.path,f))});return _t.mergeArray(s,r)}get element(){return this._def.type}min(t,n){return new Qt({...this._def,minLength:{value:t,message:O.toString(n)}})}max(t,n){return new Qt({...this._def,maxLength:{value:t,message:O.toString(n)}})}length(t,n){return new Qt({...this._def,exactLength:{value:t,message:O.toString(n)}})}nonempty(t){return this.min(1,t)}}Qt.create=(t,n)=>{return new Qt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...Q(n)})};function $s(t){if(t instanceof it){let n={};for(let s in t.shape){let i=t.shape[s];n[s]=Jt.create($s(i))}return new it({...t._def,shape:()=>n})}else if(t instanceof Qt)return new Qt({...t._def,type:$s(t.element)});else if(t instanceof Jt)return Jt.create($s(t.unwrap()));else if(t instanceof gn)return gn.create($s(t.unwrap()));else if(t instanceof Zt)return Zt.create(t.items.map((n)=>$s(n)));else return t}class it extends z{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=x.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==$.object){let c=this._getOrReturnCtx(t);return L(c,{code:b.invalid_type,expected:$.object,received:c.parsedType}),P}let{status:s,ctx:i}=this._processInputParams(t),{shape:r,keys:e}=this._getCached(),f=[];if(!(this._def.catchall instanceof pt&&this._def.unknownKeys==="strip")){for(let c in i.data)if(!e.includes(c))f.push(c)}let o=[];for(let c of e){let h=r[c],u=i.data[c];o.push({key:{status:"valid",value:c},value:h._parse(new kt(i,u,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof pt){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of f)o.push({key:{status:"valid",value:h},value:{status:"valid",value:i.data[h]}});else if(c==="strict"){if(f.length>0)L(i,{code:b.unrecognized_keys,keys:f}),s.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of f){let u=i.data[h];o.push({key:{status:"valid",value:h},value:c._parse(new kt(i,u,i.path,h)),alwaysSet:h in i.data})}}if(i.common.async)return Promise.resolve().then(async()=>{let c=[];for(let h of o){let u=await h.key,l=await h.value;c.push({key:u,value:l,alwaysSet:h.alwaysSet})}return c}).then((c)=>{return _t.mergeObjectSync(s,c)});else return _t.mergeObjectSync(s,o)}get shape(){return this._def.shape()}strict(t){return O.errToObj,new it({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,s)=>{let i=this._def.errorMap?.(n,s).message??s.defaultError;if(n.code==="unrecognized_keys")return{message:O.errToObj(t).message??i};return{message:i}}}:{}})}strip(){return new it({...this._def,unknownKeys:"strip"})}passthrough(){return new it({...this._def,unknownKeys:"passthrough"})}extend(t){return new it({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new it({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:N.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new it({...this._def,catchall:t})}pick(t){let n={};for(let s of x.objectKeys(t))if(t[s]&&this.shape[s])n[s]=this.shape[s];return new it({...this._def,shape:()=>n})}omit(t){let n={};for(let s of x.objectKeys(this.shape))if(!t[s])n[s]=this.shape[s];return new it({...this._def,shape:()=>n})}deepPartial(){return $s(this)}partial(t){let n={};for(let s of x.objectKeys(this.shape)){let i=this.shape[s];if(t&&!t[s])n[s]=i;else n[s]=i.optional()}return new it({...this._def,shape:()=>n})}required(t){let n={};for(let s of x.objectKeys(this.shape))if(t&&!t[s])n[s]=this.shape[s];else{let r=this.shape[s];while(r instanceof Jt)r=r._def.innerType;n[s]=r}return new it({...this._def,shape:()=>n})}keyof(){return U0(x.objectKeys(this.shape))}}it.create=(t,n)=>{return new it({shape:()=>t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};it.strictCreate=(t,n)=>{return new it({shape:()=>t,unknownKeys:"strict",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};it.lazycreate=(t,n)=>{return new it({shape:t,unknownKeys:"strip",catchall:pt.create(),typeName:N.ZodObject,...Q(n)})};class Os extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=this._def.options;function i(r){for(let f of r)if(f.result.status==="valid")return f.result;for(let f of r)if(f.result.status==="dirty")return n.common.issues.push(...f.ctx.common.issues),f.result;let e=r.map((f)=>new bt(f.ctx.common.issues));return L(n,{code:b.invalid_union,unionErrors:e}),P}if(n.common.async)return Promise.all(s.map(async(r)=>{let e={...n,common:{...n.common,issues:[]},parent:null};return{result:await r._parseAsync({data:n.data,path:n.path,parent:e}),ctx:e}})).then(i);else{let r=void 0,e=[];for(let o of s){let c={...n,common:{...n.common,issues:[]},parent:null},h=o._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;else if(h.status==="dirty"&&!r)r={result:h,ctx:c};if(c.common.issues.length)e.push(c.common.issues)}if(r)return n.common.issues.push(...r.ctx.common.issues),r.result;let f=e.map((o)=>new bt(o));return L(n,{code:b.invalid_union,unionErrors:f}),P}}get options(){return this._def.options}}Os.create=(t,n)=>{return new Os({options:t,typeName:N.ZodUnion,...Q(n)})};var Mn=(t)=>{if(t instanceof Bs)return Mn(t.schema);else if(t instanceof zt)return Mn(t.innerType());else if(t instanceof Fs)return[t.value];else if(t instanceof Fn)return t.options;else if(t instanceof Hs)return x.objectValues(t.enum);else if(t instanceof Ps)return Mn(t._def.innerType);else if(t instanceof Is)return[void 0];else if(t instanceof ys)return[null];else if(t instanceof Jt)return[void 0,...Mn(t.unwrap())];else if(t instanceof gn)return[null,...Mn(t.unwrap())];else if(t instanceof Ur)return Mn(t.unwrap());else if(t instanceof Ws)return Mn(t.unwrap());else if(t instanceof Ns)return Mn(t._def.innerType);else return[]};class $r extends z{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.object)return L(n,{code:b.invalid_type,expected:$.object,received:n.parsedType}),P;let s=this.discriminator,i=n.data[s],r=this.optionsMap.get(i);if(!r)return L(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),P;if(n.common.async)return r._parseAsync({data:n.data,path:n.path,parent:n});else return r._parseSync({data:n.data,path:n.path,parent:n})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,s){let i=new Map;for(let r of n){let e=Mn(r.shape[t]);if(!e.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let f of e){if(i.has(f))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(f)}`);i.set(f,r)}}return new $r({typeName:N.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...Q(s)})}}function zo(t,n){let s=at(t),i=at(n);if(t===n)return{valid:!0,data:t};else if(s===$.object&&i===$.object){let r=x.objectKeys(n),e=x.objectKeys(t).filter((o)=>r.indexOf(o)!==-1),f={...t,...n};for(let o of e){let c=zo(t[o],n[o]);if(!c.valid)return{valid:!1};f[o]=c.data}return{valid:!0,data:f}}else if(s===$.array&&i===$.array){if(t.length!==n.length)return{valid:!1};let r=[];for(let e=0;e<t.length;e++){let f=t[e],o=n[e],c=zo(f,o);if(!c.valid)return{valid:!1};r.push(c.data)}return{valid:!0,data:r}}else if(s===$.date&&i===$.date&&+t===+n)return{valid:!0,data:t};else return{valid:!1}}class Gs extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t),i=(r,e)=>{if(Tr(r)||Tr(e))return P;let f=zo(r.value,e.value);if(!f.valid)return L(s,{code:b.invalid_intersection_types}),P;if(Sr(r)||Sr(e))n.dirty();return{status:n.value,value:f.data}};if(s.common.async)return Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([r,e])=>i(r,e));else return i(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Gs.create=(t,n,s)=>{return new Gs({left:t,right:n,typeName:N.ZodIntersection,...Q(s)})};class Zt extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.array)return L(s,{code:b.invalid_type,expected:$.array,received:s.parsedType}),P;if(s.data.length<this._def.items.length)return L(s,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;if(!this._def.rest&&s.data.length>this._def.items.length)L(s,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty();let r=[...s.data].map((e,f)=>{let o=this._def.items[f]||this._def.rest;if(!o)return null;return o._parse(new kt(s,e,s.path,f))}).filter((e)=>!!e);if(s.common.async)return Promise.all(r).then((e)=>{return _t.mergeArray(n,e)});else return _t.mergeArray(n,r)}get items(){return this._def.items}rest(t){return new Zt({...this._def,rest:t})}}Zt.create=(t,n)=>{if(!Array.isArray(t))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zt({items:t,typeName:N.ZodTuple,rest:null,...Q(n)})};class Ri extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.object)return L(s,{code:b.invalid_type,expected:$.object,received:s.parsedType}),P;let i=[],r=this._def.keyType,e=this._def.valueType;for(let f in s.data)i.push({key:r._parse(new kt(s,f,s.path,f)),value:e._parse(new kt(s,s.data[f],s.path,f)),alwaysSet:f in s.data});if(s.common.async)return _t.mergeObjectAsync(n,i);else return _t.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,s){if(n instanceof z)return new Ri({keyType:t,valueType:n,typeName:N.ZodRecord,...Q(s)});return new Ri({keyType:Yt.create(),valueType:t,typeName:N.ZodRecord,...Q(n)})}}class bi extends z{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.map)return L(s,{code:b.invalid_type,expected:$.map,received:s.parsedType}),P;let i=this._def.keyType,r=this._def.valueType,e=[...s.data.entries()].map(([f,o],c)=>{return{key:i._parse(new kt(s,f,s.path,[c,"key"])),value:r._parse(new kt(s,o,s.path,[c,"value"]))}});if(s.common.async){let f=new Map;return Promise.resolve().then(async()=>{for(let o of e){let c=await o.key,h=await o.value;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}})}else{let f=new Map;for(let o of e){let{key:c,value:h}=o;if(c.status==="aborted"||h.status==="aborted")return P;if(c.status==="dirty"||h.status==="dirty")n.dirty();f.set(c.value,h.value)}return{status:n.value,value:f}}}}bi.create=(t,n,s)=>{return new bi({valueType:n,keyType:t,typeName:N.ZodMap,...Q(s)})};class pn extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.parsedType!==$.set)return L(s,{code:b.invalid_type,expected:$.set,received:s.parsedType}),P;let i=this._def;if(i.minSize!==null){if(s.data.size<i.minSize.value)L(s,{code:b.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()}if(i.maxSize!==null){if(s.data.size>i.maxSize.value)L(s,{code:b.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty()}let r=this._def.valueType;function e(o){let c=new Set;for(let h of o){if(h.status==="aborted")return P;if(h.status==="dirty")n.dirty();c.add(h.value)}return{status:n.value,value:c}}let f=[...s.data.values()].map((o,c)=>r._parse(new kt(s,o,s.path,c)));if(s.common.async)return Promise.all(f).then((o)=>e(o));else return e(f)}min(t,n){return new pn({...this._def,minSize:{value:t,message:O.toString(n)}})}max(t,n){return new pn({...this._def,maxSize:{value:t,message:O.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}pn.create=(t,n)=>{return new pn({valueType:t,minSize:null,maxSize:null,typeName:N.ZodSet,...Q(n)})};class Us extends z{constructor(){super(...arguments);this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.function)return L(n,{code:b.invalid_type,expected:$.function,received:n.parsedType}),P;function s(f,o){return gi({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_arguments,argumentsError:o}})}function i(f,o){return gi({data:f,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ts(),An].filter((c)=>!!c),issueData:{code:b.invalid_return_type,returnTypeError:o}})}let r={errorMap:n.common.contextualErrorMap},e=n.data;if(this._def.returns instanceof Zn){let f=this;return gt(async function(...o){let c=new bt([]),h=await f._def.args.parseAsync(o,r).catch((_)=>{throw c.addIssue(s(o,_)),c}),u=await Reflect.apply(e,this,h);return await f._def.returns._def.type.parseAsync(u,r).catch((_)=>{throw c.addIssue(i(u,_)),c})})}else{let f=this;return gt(function(...o){let c=f._def.args.safeParse(o,r);if(!c.success)throw new bt([s(o,c.error)]);let h=Reflect.apply(e,this,c.data),u=f._def.returns.safeParse(h,r);if(!u.success)throw new bt([i(h,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Us({...this._def,args:Zt.create(t).rest(On.create())})}returns(t){return new Us({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,s){return new Us({args:t?t:Zt.create([]).rest(On.create()),returns:n||On.create(),typeName:N.ZodFunction,...Q(s)})}}class Bs extends z{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Bs.create=(t,n)=>{return new Bs({getter:t,typeName:N.ZodLazy,...Q(n)})};class Fs extends z{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return L(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:t.data}}get value(){return this._def.value}}Fs.create=(t,n)=>{return new Fs({value:t,typeName:N.ZodLiteral,...Q(n)})};function U0(t,n){return new Fn({values:t,typeName:N.ZodEnum,...Q(n)})}class Fn extends z{_parse(t){if(typeof t.data!=="string"){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{expected:x.joinValues(s),received:n.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),s=this._def.values;return L(n,{received:n.data,code:b.invalid_enum_value,options:s}),P}return gt(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return Fn.create(t,{...this._def,...n})}exclude(t,n=this._def){return Fn.create(this.options.filter((s)=>!t.includes(s)),{...this._def,...n})}}Fn.create=U0;class Hs extends z{_parse(t){let n=x.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(t);if(s.parsedType!==$.string&&s.parsedType!==$.number){let i=x.objectValues(n);return L(s,{expected:x.joinValues(i),received:s.parsedType,code:b.invalid_type}),P}if(!this._cache)this._cache=new Set(x.getValidEnumValues(this._def.values));if(!this._cache.has(t.data)){let i=x.objectValues(n);return L(s,{received:s.data,code:b.invalid_enum_value,options:i}),P}return gt(t.data)}get enum(){return this._def.values}}Hs.create=(t,n)=>{return new Hs({values:t,typeName:N.ZodNativeEnum,...Q(n)})};class Zn extends z{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==$.promise&&n.common.async===!1)return L(n,{code:b.invalid_type,expected:$.promise,received:n.parsedType}),P;let s=n.parsedType===$.promise?n.data:Promise.resolve(n.data);return gt(s.then((i)=>{return this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})}))}}Zn.create=(t,n)=>{return new Zn({type:t,typeName:N.ZodPromise,...Q(n)})};class zt extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:s}=this._processInputParams(t),i=this._def.effect||null,r={addIssue:(e)=>{if(L(s,e),e.fatal)n.abort();else n.dirty()},get path(){return s.path}};if(r.addIssue=r.addIssue.bind(r),i.type==="preprocess"){let e=i.transform(s.data,r);if(s.common.async)return Promise.resolve(e).then(async(f)=>{if(n.value==="aborted")return P;let o=await this._def.schema._parseAsync({data:f,path:s.path,parent:s});if(o.status==="aborted")return P;if(o.status==="dirty")return Vn(o.value);if(n.value==="dirty")return Vn(o.value);return o});else{if(n.value==="aborted")return P;let f=this._def.schema._parseSync({data:e,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")return Vn(f.value);if(n.value==="dirty")return Vn(f.value);return f}}if(i.type==="refinement"){let e=(f)=>{let o=i.refinement(f,r);if(s.common.async)return Promise.resolve(o);if(o instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return f};if(s.common.async===!1){let f=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value),{status:n.value,value:f.value}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((f)=>{if(f.status==="aborted")return P;if(f.status==="dirty")n.dirty();return e(f.value).then(()=>{return{status:n.value,value:f.value}})})}if(i.type==="transform")if(s.common.async===!1){let e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!yn(e))return P;let f=i.transform(e.value,r);if(f instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:f}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then((e)=>{if(!yn(e))return P;return Promise.resolve(i.transform(e.value,r)).then((f)=>({status:n.value,value:f}))});x.assertNever(i)}}zt.create=(t,n,s)=>{return new zt({schema:t,typeName:N.ZodEffects,effect:n,...Q(s)})};zt.createWithPreprocess=(t,n,s)=>{return new zt({schema:n,effect:{type:"preprocess",transform:t},typeName:N.ZodEffects,...Q(s)})};class Jt extends z{_parse(t){if(this._getType(t)===$.undefined)return gt(void 0);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Jt.create=(t,n)=>{return new Jt({innerType:t,typeName:N.ZodOptional,...Q(n)})};class gn extends z{_parse(t){if(this._getType(t)===$.null)return gt(null);return this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gn.create=(t,n)=>{return new gn({innerType:t,typeName:N.ZodNullable,...Q(n)})};class Ps extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;if(n.parsedType===$.undefined)s=this._def.defaultValue();return this._def.innerType._parse({data:s,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}Ps.create=(t,n)=>{return new Ps({innerType:t,typeName:N.ZodDefault,defaultValue:typeof n.default==="function"?n.default:()=>n.default,...Q(n)})};class Ns extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});if(Ss(i))return i.then((r)=>{return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}});else return{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new bt(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ns.create=(t,n)=>{return new Ns({innerType:t,typeName:N.ZodCatch,catchValue:typeof n.catch==="function"?n.catch:()=>n.catch,...Q(n)})};class Ti extends z{_parse(t){if(this._getType(t)!==$.nan){let s=this._getOrReturnCtx(t);return L(s,{code:b.invalid_type,expected:$.nan,received:s.parsedType}),P}return{status:"valid",value:t.data}}}Ti.create=(t)=>{return new Ti({typeName:N.ZodNaN,...Q(t)})};var ME=Symbol("zod_brand");class Ur extends z{_parse(t){let{ctx:n}=this._processInputParams(t),s=n.data;return this._def.type._parse({data:s,path:n.path,parent:n})}unwrap(){return this._def.type}}class Si extends z{_parse(t){let{status:n,ctx:s}=this._processInputParams(t);if(s.common.async)return(async()=>{let r=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});if(r.status==="aborted")return P;if(r.status==="dirty")return n.dirty(),Vn(r.value);else return this._def.out._parseAsync({data:r.value,path:s.path,parent:s})})();else{let i=this._def.in._parseSync({data:s.data,path:s.path,parent:s});if(i.status==="aborted")return P;if(i.status==="dirty")return n.dirty(),{status:"dirty",value:i.value};else return this._def.out._parseSync({data:i.value,path:s.path,parent:s})}}static create(t,n){return new Si({in:t,out:n,typeName:N.ZodPipeline})}}class Ws extends z{_parse(t){let n=this._def.innerType._parse(t),s=(i)=>{if(yn(i))i.value=Object.freeze(i.value);return i};return Ss(n)?n.then((i)=>s(i)):s(n)}unwrap(){return this._def.innerType}}Ws.create=(t,n)=>{return new Ws({innerType:t,typeName:N.ZodReadonly,...Q(n)})};function b0(t,n){let s=typeof t==="function"?t(n):typeof t==="string"?{message:t}:t;return typeof s==="string"?{message:s}:s}function L0(t,n={},s){if(t)return an.create().superRefine((i,r)=>{let e=t(i);if(e instanceof Promise)return e.then((f)=>{if(!f){let o=b0(n,i),c=o.fatal??s??!0;r.addIssue({code:"custom",...o,fatal:c})}});if(!e){let f=b0(n,i),o=f.fatal??s??!0;r.addIssue({code:"custom",...f,fatal:o})}return});return an.create()}var gE={object:it.lazycreate},N;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(N||(N={}));var dE=(t,n={message:`Input not instance of ${t.name}`})=>L0((s)=>s instanceof t,n),I0=Yt.create,y0=Gn.create,EE=Ti.create,RE=Bn.create,O0=Ls.create,bE=jn.create,TE=di.create,SE=Is.create,$E=ys.create,UE=an.create,LE=On.create,IE=pt.create,yE=Ei.create,OE=Qt.create,GE=it.create,BE=it.strictCreate,FE=Os.create,HE=$r.create,PE=Gs.create,NE=Zt.create,WE=Ri.create,DE=bi.create,mE=pn.create,YE=Us.create,QE=Bs.create,JE=Fs.create,kE=Fn.create,zE=Hs.create,XE=Zn.create,xE=zt.create,qE=Jt.create,CE=gn.create,KE=zt.createWithPreprocess,VE=Si.create,jE=()=>I0().optional(),aE=()=>y0().optional(),pE=()=>O0().optional(),ZE={string:(t)=>Yt.create({...t,coerce:!0}),number:(t)=>Gn.create({...t,coerce:!0}),boolean:(t)=>Ls.create({...t,coerce:!0}),bigint:(t)=>Bn.create({...t,coerce:!0}),date:(t)=>jn.create({...t,coerce:!0})};var vE=P;var Lr=g.enum(["low","medium","high","xhigh","max"]),vn=g.enum(["us-east-1","us-east-2","us-west-1","us-west-2","af-south-1","ap-east-1","ap-south-2","ap-southeast-3","ap-southeast-5","ap-southeast-4","ap-south-1","ap-southeast-6","ap-northeast-3","ap-northeast-2","ap-southeast-1","ap-southeast-2","ap-east-2","ap-southeast-7","ap-northeast-1","ca-central-1","ca-west-1","eu-central-1","eu-west-1","eu-west-2","eu-south-1","eu-west-3","eu-south-2","eu-north-1","eu-central-2","il-central-1","mx-central-1","me-south-1","me-central-1","sa-east-1"]);var tR=g.array(g.string()).transform((t)=>t.map((n)=>n.trim()).filter((n)=>n.length>0)).refine((t)=>t.length>0,{message:"api_keys must contain at least one non-empty key"}),nR=g.preprocess((t)=>typeof t==="string"&&t.trim().length===0?null:t,g.string().trim().refine((t)=>URL.canParse(t),{message:"proxy_url must be a valid URL"}).refine((t)=>{if(!URL.canParse(t))return!1;let n=new URL(t).protocol;return n==="http:"||n==="https:"},{message:"proxy_url must be http(s)"}).nullable()).default(null),Xo=g.object({host:g.string().default("127.0.0.1"),port:g.number().default(8787),api_keys:tR,proxy_url:nR,default_region:g.string().default("us-east-1"),account_selection_strategy:g.enum(["sticky","round-robin","lowest-usage"]).default("lowest-usage"),rate_limit_max_retries:g.number().default(3),rate_limit_retry_delay_ms:g.number().default(5000),max_request_iterations:g.number().default(20),request_timeout_ms:g.number().default(120000),stream_idle_timeout_ms:g.number().default(60000),max_request_body_bytes:g.number().default(10485760),token_expiry_buffer_ms:g.number().default(300000),effort:Lr.nullable().default(null),auto_effort_mapping:g.boolean().default(!0),log_level:g.string().default("info"),test_upstream_endpoint:g.string().url().optional()});class $i extends Error{constructor(t,n){super(t,n);this.name="ConfigLoadError"}}var eR=Xo.partial();function oR(t){let n=t.XDG_CONFIG_HOME??G0(rR(),".config");return G0(n,"kiro-provider","config.json")}function fR(t){if(!sR(t))return{};try{let n=JSON.parse(iR(t,"utf8"));return eR.parse(n)}catch(n){if(n instanceof g.ZodError)throw new $i(`Invalid configuration file ${t}: ${B0(n)}`,{cause:n});if(n instanceof Error)throw new $i(`Unable to read configuration file ${t}: ${n.message}`,{cause:n});throw n}}function cR(t){let n=t.trim().toLowerCase();if(n==="true"||n==="1")return!0;if(n==="false"||n==="0")return!1;return t}function hR(t){let n={},s={KIRO_PROVIDER_HOST:"host",KIRO_PROVIDER_DEFAULT_REGION:"default_region",KIRO_PROVIDER_ACCOUNT_SELECTION_STRATEGY:"account_selection_strategy",KIRO_PROVIDER_EFFORT:"effort",KIRO_PROVIDER_LOG_LEVEL:"log_level",KIRO_PROVIDER_TEST_UPSTREAM:"test_upstream_endpoint"};for(let[o,c]of Object.entries(s)){let h=t[o];if(h!==void 0)n[c]=h}let i={KIRO_PROVIDER_PORT:"port",KIRO_PROVIDER_RATE_LIMIT_MAX_RETRIES:"rate_limit_max_retries",KIRO_PROVIDER_RATE_LIMIT_RETRY_DELAY_MS:"rate_limit_retry_delay_ms",KIRO_PROVIDER_MAX_REQUEST_ITERATIONS:"max_request_iterations",KIRO_PROVIDER_REQUEST_TIMEOUT_MS:"request_timeout_ms",KIRO_PROVIDER_STREAM_IDLE_TIMEOUT_MS:"stream_idle_timeout_ms",KIRO_PROVIDER_MAX_REQUEST_BODY_BYTES:"max_request_body_bytes",KIRO_PROVIDER_TOKEN_EXPIRY_BUFFER_MS:"token_expiry_buffer_ms"};for(let[o,c]of Object.entries(i)){let h=t[o];if(h!==void 0)n[c]=Number(h)}let r=t.KIRO_PROVIDER_API_KEYS;if(r!==void 0)n.api_keys=r.split(",");let e=t.KIRO_PROVIDER_PROXY_URL;if(e!==void 0)n.proxy_url=e.trim();let f=t.KIRO_PROVIDER_AUTO_EFFORT_MAPPING;if(f!==void 0)n.auto_effort_mapping=cR(f);return n}function B0(t){return t.issues.map((n)=>`${n.path.length>0?n.path.join("."):"config"}: ${n.message}`).join(", ")}function F0(t={}){let n=t.env??process.env,s=t.configPath??oR(n);try{return Xo.parse({...fR(s),...hR(n),...t.overrides})}catch(i){if(i instanceof $i)throw i;if(i instanceof g.ZodError)throw new $i(`Invalid configuration: ${B0(i)}`,{cause:i});throw i}}function Ir(t){let n=t.split("|"),s=n[0]??"";if(n.length<2)return{refreshToken:s,authMethod:"desktop"};if(n.at(-1)==="idc")return{refreshToken:s,clientId:n[1],clientSecret:n[2],authMethod:"idc"};return{refreshToken:s,authMethod:"desktop"}}function H0(t,n=120000){if(!t.access||!t.expires)return!0;return Date.now()>=t.expires-n}function yr(t){if(t.authMethod==="idc"){if(!t.clientId||!t.clientSecret)throw Error("Missing credentials");return`${t.refreshToken}|${t.clientId}|${t.clientSecret}|idc`}return`${t.refreshToken}|desktop`}function uR(t){if(!t)return!1;return t.includes("Invalid refresh token")||t.includes("Invalid grant provided")||t.includes("invalid_grant")||t.includes("ExpiredTokenException")||t.includes("InvalidTokenException")||t.includes("ExpiredClientException")||t.includes("Client is expired")||t.includes("HTTP_401")||t.includes("HTTP_403")}function Or(t){if(!t)return!1;let n=t.toLowerCase();return n.includes("bearer token included in the request is invalid")||n.includes("access token has expired")||n.includes("access_token expired")||n.includes("the access token expired")}function xo(t){return uR(t)}var P0=4;class N0 extends Error{accountId;constructor(t){super(`Account ${t} changed too frequently to update`);this.accountId=t;this.name="AccountConcurrentUpdateError"}}function lR(t){throw TypeError(`Unsupported account selection strategy: ${String(t)}`)}function Ui(t){return{...t}}function _R(t){return{refresh:yr({refreshToken:t.refreshToken,authMethod:t.authMethod,...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.profileArn?{profileArn:t.profileArn}:{}}),access:t.accessToken,expires:t.expiresAt,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email?{email:t.email}:{},...t.profileArn?{profileArn:t.profileArn}:{}}}class qo{strategy;database;accounts;stickyId;roundRobinCursor=0;constructor(t,n,s){this.strategy=n;this.database=s;this.accounts=t.map(Ui)}getAccountCount(){return this.accounts.length}getAccounts(){return this.accounts.map(Ui)}getMinWaitTime(){let t=Date.now(),n=this.accounts.map(({rateLimitResetTime:s})=>s-t).filter((s)=>s>0);return n.length===0?0:Math.min(...n)}reconcileFromDb(t=this.database){let n=new Map(this.accounts.map((s)=>[s.id,s]));if(this.accounts=t.getAccounts().map((s)=>{let i=n.get(s.id);return i?.generation===s.generation?i:Ui(s)}),this.stickyId&&!this.accounts.some(({id:s})=>s===this.stickyId))this.stickyId=void 0;return this.getAccounts()}selectHealthyAccount(){let t=Date.now(),n=this.accounts.filter((i)=>this.isSelectable(i,t)).sort((i,r)=>i.id.localeCompare(r.id));if(n.length===0)return null;let s=this.selectCandidate(n);return this.patchAccount(s.id,(i)=>({...i,isHealthy:!0,unhealthyReason:void 0,recoveryTime:void 0,lastUsed:t,usedCount:(i.usedCount??0)+1}))??null}getCurrentOrNext(){return this.selectHealthyAccount()}markRateLimited(t,n){return this.patchAccount(t.id,(s)=>({...s,rateLimitResetTime:n}))}markUnhealthy(t,n,s){let i=Date.now();return this.patchAccount(t.id,(r)=>{if(xo(n))return{...r,failCount:10,isHealthy:!1,unhealthyReason:n,recoveryTime:void 0,lastUsed:i};let e=r.failCount+1;return{...r,failCount:e,isHealthy:e<10,unhealthyReason:n,recoveryTime:e>=10?s??i+3600000:void 0,lastUsed:i}})}updateFromAuth(t,n){let s=Ir(n.refresh);for(let i=0;i<P0;i+=1){let r=i===0?t:this.database.getById(t.id);if(!r||!this.isSameLogin(t,r)){this.reconcileFromDb();return}let e={...r,refreshToken:s.refreshToken,accessToken:n.access,expiresAt:n.expires};if(this.database.updateExistingAccounts([e])===1){let f={...e,generation:r.generation+1};return this.replaceAccount(f),Ui(f)}}this.reconcileFromDb();return}toAuthDetails(t){return _R(t)}isSelectable(t,n){if(xo(t.unhealthyReason))return!1;if(t.rateLimitResetTime>n)return!1;if(t.isHealthy||Or(t.unhealthyReason))return!0;return t.recoveryTime!==void 0&&t.recoveryTime<=n}isSameLogin(t,n){return n.refreshToken===t.refreshToken&&n.authMethod===t.authMethod&&n.clientId===t.clientId&&n.email===t.email&&n.startUrl===t.startUrl}selectCandidate(t){switch(this.strategy){case"sticky":{let s=t.find(({id:i})=>i===this.stickyId)??t[0];if(!s)throw RangeError("Candidate list cannot be empty");return this.stickyId=s.id,s}case"round-robin":{let n=t[this.roundRobinCursor%t.length];if(!n)throw RangeError("Candidate list cannot be empty");return this.roundRobinCursor+=1,n}case"lowest-usage":{let n=[...t].sort((s,i)=>(s.usedCount??0)-(i.usedCount??0)||(s.lastUsed??0)-(i.lastUsed??0)||s.id.localeCompare(i.id))[0];if(!n)throw RangeError("Candidate list cannot be empty");return n}default:return lR(this.strategy)}}patchAccount(t,n){for(let s=0;s<P0;s+=1){let i=this.database.getById(t);if(!i){this.accounts=this.accounts.filter((e)=>e.id!==t);return}let r=n(i);if(this.database.updateExistingAccounts([r])===1){let e={...r,generation:i.generation+1};return this.replaceAccount(e),Ui(e)}}throw this.reconcileFromDb(),new N0(t)}replaceAccount(t){let n=this.accounts.findIndex(({id:s})=>s===t.id);if(n===-1)this.accounts.push(t);else this.accounts[n]=t}}var j0=m(Vo(),1);import*as tn from"net";import*as Ii from"tls";import VR from"assert";import*as x0 from"net";import*as q0 from"http";import{Agent as KR}from"https";var vt=Symbol("AgentBaseInternalState");class jo extends q0.Agent{constructor(t){super(t);this[vt]={}}isSecureEndpoint(t){if(t){if(typeof t.secureEndpoint==="boolean")return t.secureEndpoint;if(typeof t.protocol==="string")return t.protocol==="https:"}let{stack:n}=Error();if(typeof n!=="string")return!1;return n.split(`
50
+ `).some((s)=>s.indexOf("(https.js:")!==-1||s.indexOf("node:https:")!==-1)}incrementSockets(t){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[t])this.sockets[t]=[];let n=new x0.Socket({writable:!1});return this.sockets[t].push(n),this.totalSocketCount++,n}decrementSockets(t,n){if(!this.sockets[t]||n===null)return;let s=this.sockets[t],i=s.indexOf(n);if(i!==-1){if(s.splice(i,1),this.totalSocketCount--,s.length===0)delete this.sockets[t]}}getName(t){if(this.isSecureEndpoint(t))return KR.prototype.getName.call(this,t);return super.getName(t)}createSocket(t,n,s){let i={...n,secureEndpoint:this.isSecureEndpoint(n)},r=this.getName(i),e=this.incrementSockets(r);Promise.resolve().then(()=>this.connect(t,i)).then((f)=>{if(this.decrementSockets(r,e),typeof f.addRequest==="function")try{return f.addRequest(t,i)}catch(o){return s(o)}this[vt].currentSocket=f,super.createSocket(t,n,s)},(f)=>{this.decrementSockets(r,e),s(f)})}createConnection(){let t=this[vt].currentSocket;if(this[vt].currentSocket=void 0,!t)throw Error("No socket was returned in the `connect()` function");return t}get defaultPort(){return this[vt].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(t){if(this[vt])this[vt].defaultPort=t}get protocol(){return this[vt].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(t){if(this[vt])this[vt].protocol=t}}import{URL as jR}from"url";var C0=m(Vo(),1),Pr=C0.default("https-proxy-agent:parse-proxy-response");function ao(t){return new Promise((n,s)=>{let i=0,r=[];function e(){let u=t.read();if(u)h(u);else t.once("readable",e)}function f(){t.removeListener("end",o),t.removeListener("error",c),t.removeListener("readable",e)}function o(){f(),Pr("onend"),s(Error("Proxy connection ended before receiving CONNECT response"))}function c(u){f(),Pr("onerror %o",u),s(u)}function h(u){r.push(u),i+=u.length;let l=Buffer.concat(r,i),_=l.indexOf(`\r
51
51
  \r
52
- `);if(l===-1){Pi("have not received end of HTTP headers yet..."),e();return}let w=_.slice(0,l).toString("ascii").split(`\r
53
- `),A=w.shift();if(!A)return t.destroy(),s(Error("No header received from proxy CONNECT response"));let M=A.split(" "),E=+M[1],d=M.slice(2).join(" "),T={};for(let U of w){if(!U)continue;let S=U.indexOf(":");if(S===-1)return t.destroy(),s(Error(`Invalid header from proxy CONNECT response: "${U}"`));let O=U.slice(0,S).toLowerCase(),D=U.slice(S+1).trimStart(),q=T[O];if(typeof q==="string")T[O]=[q,D];else if(Array.isArray(q))q.push(D);else T[O]=D}Pi("got proxy server response: %o %o",A,T),f(),n({connect:{statusCode:E,statusText:d,headers:T},buffered:_})}t.on("error",c),t.on("end",o),e()})}function K0(){return async({response:t,scheme:n})=>{if(n.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${n}"`);let s;try{s=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let r=t.headers["proxy-authenticate"]||"",i=Array.isArray(r)?r[0]:r,e=typeof i==="string"&&i.includes(" ")?i.split(" ").slice(1).join(" "):void 0,o=await(await s.initializeClient("HTTP@proxy",{mechOID:s.GSS_MECH_OID_SPNEGO})).step(e||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var ss=j0.default("https-proxy-agent"),Ni=(t)=>{if(t.servername===void 0&&t.host&&!tn.isIP(t.host))return{...t,servername:t.host};return t};class Wi extends jo{constructor(t,n){super(n);if(this.options={path:void 0},this.proxy=typeof t==="string"?new jR(t):t,this.proxyHeaders=n?.headers??{},ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href),n?.negotiate)this.onProxyAuth=K0();else if(n?.onProxyAuth)this.onProxyAuth=n.onProxyAuth;let s=(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"],...n?po(n,"headers","onProxyAuth","negotiate"):null,host:s,port:r}}async connect(t,n){let{proxy:s}=this;if(!n.host)throw TypeError('No "host" provided');let r;if(s.protocol==="https:")ss("Creating `tls.Socket`: %o",this.connectOpts),r=Ir.connect(Ni(this.connectOpts));else ss("Creating `net.Socket`: %o",this.connectOpts),r=tn.connect(this.connectOpts);let i=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},e=tn.isIPv6(n.host)?`[${n.host}]`:n.host,f=`CONNECT ${e}:${n.port} HTTP/1.1\r
54
- `;if(s.username||s.password){let _=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;i["Proxy-Authorization"]=`Basic ${Buffer.from(_).toString("base64")}`}if(i.Host=`${e}:${n.port}`,!i["Proxy-Connection"])i["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let _ of Object.keys(i))f+=`${_}: ${i[_]}\r
55
- `;let o=ao(r);r.write(`${f}\r
56
- `);let{connect:c,buffered:h}=await o;if(t.emit("proxyConnect",c),this.emit("proxyConnect",c,t),t.emit("proxy",{proxy:this.proxy.href,socket:r}),c.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ir.connect({...po(Ni(n),"host","path","port"),socket:r});return r}if(c.statusCode===407&&this.onProxyAuth){ss("Got 407 response, invoking onProxyAuth callback"),r.destroy();let _=c.headers["proxy-authenticate"]||"",l=Array.isArray(_)?_[0].split(/\s/)[0]:_.split(/\s/)[0],w=await this.onProxyAuth({response:c,scheme:l});return this._connectWithAuth(t,n,w.headers)}r.destroy();let u=new tn.Socket({writable:!1});return u.readable=!0,t.once("socket",(_)=>{ss("Replaying proxy buffer for failed request"),VR(_.listenerCount("data")>0),_.push(h),_.push(null)}),u}async _connectWithAuth(t,n,s){let{proxy:r}=this,i;if(r.protocol==="https:")i=Ir.connect(Ni(this.connectOpts));else i=tn.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=tn.isIPv6(n.host)?`[${n.host}]`:n.host,o=`CONNECT ${f}:${n.port} HTTP/1.1\r
57
- `;if(r.username||r.password){let u=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(u).toString("base64")}`}if(Object.assign(e,s),e.Host=`${f}:${n.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let u of Object.keys(e))o+=`${u}: ${e[u]}\r
58
- `;let c=ao(i);i.write(`${o}\r
59
- `);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ir.connect({...po(Ni(n),"host","path","port"),socket:i});return i}throw i.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Wi.protocols=["http","https"];function V0(t){setImmediate(()=>{t.resume()})}function po(t,...n){let s={},r;for(r in t)if(!n.includes(r))s[r]=t[r];return s}var a0=new Map;function Qs(t){return t.proxy_url||void 0}function p0(t){let n=a0.get(t);if(n!==void 0)return n;let s=new Wi(t,{keepAlive:!0,maxSockets:50});return a0.set(t,s),s}function Z0(t){return t===void 0?{}:{proxy:t}}var aR=vn.options;function v0(t){return aR.includes(t)}function Zo(t){if(!t||!v0(t))return"us-east-1";return t}function Or(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function tu(t){if(!t)return;let n=t.split(":");if(n.length<6)return;if(n[0]!=="arn")return;let s=n[3];if(typeof s!=="string"||!s)return;return v0(s)?s:void 0}var ot={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},yr={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},nu=Object.keys(yr),jm=new Set(Object.keys(yr).filter((t)=>t.includes("-1m")));var pR=200000,ZR={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function B(t){return ZR[t]??pR}var Gr={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class Hn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function vo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Di(t,n,s){let r=t[n];if(typeof r==="string"&&r)return r;let i=t[s];return typeof i==="string"&&i?i:void 0}function vR(t,n,s){let r=t[n];if(typeof r==="number")return r;let i=t[s];return typeof i==="number"?i:void 0}function tb(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!vo(s))return{message:t,code:`HTTP_${n}`};let r=Di(s,"message","error_description")??t,i=Di(s,"__type","error")??`HTTP_${n}`;return{message:r,code:i}}function su(t){let n=t.userInfo;if(!vo(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function ru(t,n,s){let r=Ii(t.refresh),i=t.authMethod==="idc",e=i?t.oidcRegion??t.region:t.region,f=Or(i?ot.REFRESH_IDC_URL:ot.REFRESH_URL,e);if(i&&(!r.clientId||!r.clientSecret))throw new Hn("Missing creds","MISSING_CREDENTIALS");let o=i?{refreshToken:r.refreshToken,clientId:r.clientId,clientSecret:r.clientSecret,grantType:"refresh_token"}:{refreshToken:r.refreshToken},c=i?`aws-sdk-js/${ot.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${ot.SDK_VERSION} m/E ${ot.USER_AGENT}`:`aws-sdk-js/3.0.0 ${ot.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":c,Connection:"close"},body:JSON.stringify(o),...n?{signal:n}:{},...Z0(s)});if(!h.ok){let w=tb(await h.text(),h.status);throw new Hn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!vo(u))throw new Hn("No access token","INVALID_RESPONSE");let _=Di(u,"access_token","accessToken");if(!_)throw new Hn("No access token","INVALID_RESPONSE");let l={refreshToken:Di(u,"refresh_token","refreshToken")??r.refreshToken,authMethod:t.authMethod,...r.clientId?{clientId:r.clientId}:{},...r.clientSecret?{clientSecret:r.clientSecret}:{}};return{refresh:Oi(l),access:_,expires:Date.now()+(vR(u,"expires_in","expiresIn")??3600)*1000,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.profileArn?{profileArn:t.profileArn}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email||su(u)?{email:t.email??su(u)}:{}}}catch(h){if(h instanceof Hn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new Hn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class Yi extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class tf{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(t,n,s){this.accountManager=t;this.tokenExpiryBufferMs=n;this.proxyUrl=s}async refreshIfNeeded(t,n,s){if(!H0(n,this.tokenExpiryBufferMs)){let r=this.accountManager.getAccounts().find(({id:i})=>i===t.id);if(!r)throw new Yi(t.id);return r}return this.startOrJoinRefresh(t,n,s)}async forceRefresh(t,n){return this.startOrJoinRefresh(t,this.accountManager.toAuthDetails(t),n)}startOrJoinRefresh(t,n,s){if(!("generation"in t)||typeof t.generation!=="number")throw new Yi(t.id);let r={...t,generation:t.generation},i=`${r.id}:${r.generation}`,e=this.inFlight.get(i);if(e)return e;let f=this.runRefresh(r,n,s).finally(()=>{if(this.inFlight.get(i)===f)this.inFlight.delete(i)});return this.inFlight.set(i,f),f}async runRefresh(t,n,s){let r=await ru(n,s,this.proxyUrl),i=this.accountManager.updateFromAuth(t,r);if(!i)throw new Yi(t.id);return i}}import{Database as nb}from"bun:sqlite";import{chmodSync as sb,existsSync as rb,mkdirSync as ib}from"fs";import{homedir as iu}from"os";import{dirname as eb,join as rf}from"path";function nf(t,n){return{id:t.id,email:t.email,auth_method:t.authMethod,region:t.region,oidc_region:t.oidcRegion??null,client_id:t.clientId??null,client_secret:t.clientSecret??null,profile_arn:t.profileArn??null,start_url:t.startUrl??null,refresh_token:t.refreshToken,access_token:t.accessToken,expires_at:t.expiresAt,rate_limit_reset:t.rateLimitResetTime,is_healthy:t.isHealthy?1:0,unhealthy_reason:t.unhealthyReason??null,recovery_time:t.recoveryTime??null,fail_count:t.failCount,last_used:t.lastUsed??0,used_count:t.usedCount??0,limit_count:t.limitCount??0,last_sync:t.lastSync??0,overage_count:t.overageCount??0,generation:n}}function mi(t){return{id:t.id,email:t.email,authMethod:t.auth_method,region:t.region,oidcRegion:t.oidc_region??void 0,clientId:t.client_id??void 0,clientSecret:t.client_secret??void 0,profileArn:t.profile_arn??void 0,startUrl:t.start_url??void 0,refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset,isHealthy:t.is_healthy===1,unhealthyReason:t.unhealthy_reason??void 0,recoveryTime:t.recovery_time??void 0,failCount:t.fail_count,lastUsed:t.last_used,usedCount:t.used_count,limitCount:t.limit_count,lastSync:t.last_sync,overageCount:t.overage_count,generation:t.generation}}function sf(t){return[t.id,t.email,t.auth_method,t.region??null,t.oidc_region??null,t.client_id??null,t.client_secret??null,t.profile_arn??null,t.start_url??null,t.refresh_token,t.access_token,t.expires_at,t.rate_limit_reset,t.is_healthy,t.unhealthy_reason??null,t.recovery_time??null,t.fail_count,t.last_used,t.used_count,t.limit_count,t.last_sync,t.overage_count,t.generation]}function ob(){let t=process.platform==="win32"?process.env.APPDATA??rf(iu(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??rf(iu(),".config");return rf(t,"kiro-provider","accounts.db")}var Pn=ob();class rs{db;path;constructor(t=Pn){if(this.path=t,t!==":memory:")ib(eb(t),{recursive:!0});this.db=new nb(t,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
52
+ `);if(_===-1){Pr("have not received end of HTTP headers yet..."),e();return}let w=l.slice(0,_).toString("ascii").split(`\r
53
+ `),A=w.shift();if(!A)return t.destroy(),s(Error("No header received from proxy CONNECT response"));let M=A.split(" "),d=+M[1],E=M.slice(2).join(" "),T={};for(let U of w){if(!U)continue;let S=U.indexOf(":");if(S===-1)return t.destroy(),s(Error(`Invalid header from proxy CONNECT response: "${U}"`));let y=U.slice(0,S).toLowerCase(),D=U.slice(S+1).trimStart(),q=T[y];if(typeof q==="string")T[y]=[q,D];else if(Array.isArray(q))q.push(D);else T[y]=D}Pr("got proxy server response: %o %o",A,T),f(),n({connect:{statusCode:d,statusText:E,headers:T},buffered:l})}t.on("error",c),t.on("end",o),e()})}function K0(){return async({response:t,scheme:n})=>{if(n.toLowerCase()!=="negotiate")throw Error(`Expected Negotiate scheme but got "${n}"`);let s;try{s=await import("kerberos")}catch{throw Error('The "kerberos" package is required for Negotiate proxy authentication. Install it with: npm install kerberos')}let i=t.headers["proxy-authenticate"]||"",r=Array.isArray(i)?i[0]:i,e=typeof r==="string"&&r.includes(" ")?r.split(" ").slice(1).join(" "):void 0,o=await(await s.initializeClient("HTTP@proxy",{mechOID:s.GSS_MECH_OID_SPNEGO})).step(e||"");if(!o)throw Error("Kerberos client.step() returned no token");return{headers:{"Proxy-Authorization":`Negotiate ${o}`}}}}var ss=j0.default("https-proxy-agent"),Nr=(t)=>{if(t.servername===void 0&&t.host&&!tn.isIP(t.host))return{...t,servername:t.host};return t};class Wr extends jo{constructor(t,n){super(n);if(this.options={path:void 0},this.proxy=typeof t==="string"?new jR(t):t,this.proxyHeaders=n?.headers??{},ss("Creating new HttpsProxyAgent instance: %o",this.proxy.href),n?.negotiate)this.onProxyAuth=K0();else if(n?.onProxyAuth)this.onProxyAuth=n.onProxyAuth;let s=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),i=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?po(n,"headers","onProxyAuth","negotiate"):null,host:s,port:i}}async connect(t,n){let{proxy:s}=this;if(!n.host)throw TypeError('No "host" provided');let i;if(s.protocol==="https:")ss("Creating `tls.Socket`: %o",this.connectOpts),i=Ii.connect(Nr(this.connectOpts));else ss("Creating `net.Socket`: %o",this.connectOpts),i=tn.connect(this.connectOpts);let r=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},e=tn.isIPv6(n.host)?`[${n.host}]`:n.host,f=`CONNECT ${e}:${n.port} HTTP/1.1\r
54
+ `;if(s.username||s.password){let l=`${decodeURIComponent(s.username)}:${decodeURIComponent(s.password)}`;r["Proxy-Authorization"]=`Basic ${Buffer.from(l).toString("base64")}`}if(r.Host=`${e}:${n.port}`,!r["Proxy-Connection"])r["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let l of Object.keys(r))f+=`${l}: ${r[l]}\r
55
+ `;let o=ao(i);i.write(`${f}\r
56
+ `);let{connect:c,buffered:h}=await o;if(t.emit("proxyConnect",c),this.emit("proxyConnect",c,t),t.emit("proxy",{proxy:this.proxy.href,socket:i}),c.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ii.connect({...po(Nr(n),"host","path","port"),socket:i});return i}if(c.statusCode===407&&this.onProxyAuth){ss("Got 407 response, invoking onProxyAuth callback"),i.destroy();let l=c.headers["proxy-authenticate"]||"",_=Array.isArray(l)?l[0].split(/\s/)[0]:l.split(/\s/)[0],w=await this.onProxyAuth({response:c,scheme:_});return this._connectWithAuth(t,n,w.headers)}i.destroy();let u=new tn.Socket({writable:!1});return u.readable=!0,t.once("socket",(l)=>{ss("Replaying proxy buffer for failed request"),VR(l.listenerCount("data")>0),l.push(h),l.push(null)}),u}async _connectWithAuth(t,n,s){let{proxy:i}=this,r;if(i.protocol==="https:")r=Ii.connect(Nr(this.connectOpts));else r=tn.connect(this.connectOpts);let e=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},f=tn.isIPv6(n.host)?`[${n.host}]`:n.host,o=`CONNECT ${f}:${n.port} HTTP/1.1\r
57
+ `;if(i.username||i.password){let u=`${decodeURIComponent(i.username)}:${decodeURIComponent(i.password)}`;e["Proxy-Authorization"]=`Basic ${Buffer.from(u).toString("base64")}`}if(Object.assign(e,s),e.Host=`${f}:${n.port}`,!e["Proxy-Connection"])e["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let u of Object.keys(e))o+=`${u}: ${e[u]}\r
58
+ `;let c=ao(r);r.write(`${o}\r
59
+ `);let{connect:h}=await c;if(t.emit("proxyConnect",h),this.emit("proxyConnect",h,t),h.statusCode===200){if(t.once("socket",V0),n.secureEndpoint)return ss("Upgrading socket connection to TLS"),Ii.connect({...po(Nr(n),"host","path","port"),socket:r});return r}throw r.destroy(),Error(`Proxy authentication failed with status ${h.statusCode} after retry`)}}Wr.protocols=["http","https"];function V0(t){setImmediate(()=>{t.resume()})}function po(t,...n){let s={},i;for(i in t)if(!n.includes(i))s[i]=t[i];return s}var a0=new Map;function Qs(t){return t.proxy_url||void 0}function p0(t){let n=a0.get(t);if(n!==void 0)return n;let s=new Wr(t,{keepAlive:!0,maxSockets:50});return a0.set(t,s),s}function Z0(t){return t===void 0?{}:{proxy:t}}var aR=vn.options;function v0(t){return aR.includes(t)}function Zo(t){if(!t||!v0(t))return"us-east-1";return t}function yi(t,n){let s=t.replace("{{region}}",n);try{return new URL(s),s}catch{throw Error(`Invalid URL generated: ${s}`)}}function tu(t){if(!t)return;let n=t.split(":");if(n.length<6)return;if(n[0]!=="arn")return;let s=n[3];if(typeof s!=="string"||!s)return;return v0(s)?s:void 0}var ot={REFRESH_URL:"https://prod.{{region}}.auth.desktop.kiro.dev/refreshToken",REFRESH_IDC_URL:"https://oidc.{{region}}.amazonaws.com/token",BASE_URL:"https://q.{{region}}.amazonaws.com/generateAssistantResponse",USAGE_LIMITS_URL:"https://q.{{region}}.amazonaws.com/getUsageLimits",DEFAULT_REGION:"us-east-1",AXIOS_TIMEOUT:120000,USER_AGENT:"KiroIDE",SDK_VERSION:"3.738.0",SDK_VERSION_USAGE:"3.0.0",CHAT_TRIGGER_TYPE_MANUAL:"MANUAL",ORIGIN_AI_EDITOR:"AI_EDITOR"},Oi={"claude-haiku-4-5":"claude-haiku-4.5","claude-haiku-4-5-thinking":"claude-haiku-4.5","claude-sonnet-4":"claude-sonnet-4","claude-sonnet-4-5":"claude-sonnet-4.5","claude-sonnet-4-5-thinking":"claude-sonnet-4.5","claude-sonnet-4-5-1m":"claude-sonnet-4.5-1m","claude-sonnet-4-5-1m-thinking":"claude-sonnet-4.5-1m","claude-sonnet-4-6":"claude-sonnet-4.6","claude-sonnet-4-6-thinking":"claude-sonnet-4.6","claude-sonnet-4-6-1m":"claude-sonnet-4.6-1m","claude-sonnet-4-6-1m-thinking":"claude-sonnet-4.6-1m","claude-sonnet-5":"claude-sonnet-5","claude-sonnet-5-thinking":"claude-sonnet-5","claude-opus-4-5":"claude-opus-4.5","claude-opus-4-5-thinking":"claude-opus-4.5","claude-opus-4-6":"claude-opus-4.6","claude-opus-4-6-thinking":"claude-opus-4.6","claude-opus-4-6-1m":"claude-opus-4.6-1m","claude-opus-4-6-1m-thinking":"claude-opus-4.6-1m","claude-opus-4-7":"claude-opus-4.7","claude-opus-4-7-thinking":"claude-opus-4.7","claude-opus-4-8":"claude-opus-4.8","claude-opus-4-8-thinking":"claude-opus-4.8",auto:"auto","deepseek-3.2":"deepseek-3.2","glm-5":"glm-5","minimax-m2.5":"minimax-m2.5","minimax-m2.1":"minimax-m2.1","qwen3-coder-next":"qwen3-coder-next","gpt-5.6-sol":"gpt-5.6-sol","gpt-5.6-terra":"gpt-5.6-terra","gpt-5.6-luna":"gpt-5.6-luna","claude-3-7-sonnet":"CLAUDE_3_7_SONNET_20250219_V1_0","nova-swe":"AGI_NOVA_SWE_V1_5","gpt-oss-120b":"OPENAI_GPT_OSS_120B_1_0","minimax-m2":"MINIMAX_MINIMAX_M2","kimi-k2-thinking":"MOONSHOT_KIMI_K2_THINKING"},nu=Object.keys(Oi),vY=new Set(Object.keys(Oi).filter((t)=>t.includes("-1m")));var pR=200000,ZR={auto:200000,"claude-haiku-4-5":200000,"claude-sonnet-4":200000,"claude-sonnet-4-5":200000,"claude-sonnet-4-5-1m":1e6,"claude-sonnet-4-6":1e6,"claude-sonnet-4-6-1m":1e6,"claude-sonnet-5":1e6,"claude-opus-4-5":200000,"claude-opus-4-6":1e6,"claude-opus-4-6-1m":1e6,"claude-opus-4-7":1e6,"claude-opus-4-8":1e6,"deepseek-3.2":128000,"glm-5":200000,"minimax-m2.5":200000,"minimax-m2.1":200000,"qwen3-coder-next":256000,"gpt-5.6-sol":272000,"gpt-5.6-terra":272000,"gpt-5.6-luna":272000};function B(t){return ZR[t]??pR}var Gi={ENDPOINT:"https://prod.{{region}}.auth.desktop.kiro.dev",SSO_OIDC_ENDPOINT:"https://oidc.{{region}}.amazonaws.com",BUILDER_ID_START_URL:"https://view.awsapps.com/start",USER_INFO_URL:"https://view.awsapps.com/api/user/info",SCOPES:["codewhisperer:completions","codewhisperer:analysis","codewhisperer:conversations","codewhisperer:transformations","codewhisperer:taskassist"]};class Hn extends Error{code;originalError;constructor(t,n,s){super(t);this.name="KiroTokenRefreshError",this.code=n,this.originalError=s}}function vo(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Dr(t,n,s){let i=t[n];if(typeof i==="string"&&i)return i;let r=t[s];return typeof r==="string"&&r?r:void 0}function vR(t,n,s){let i=t[n];if(typeof i==="number")return i;let r=t[s];return typeof r==="number"?r:void 0}function tb(t,n){let s;try{s=JSON.parse(t)}catch{return{message:t,code:`HTTP_${n}`}}if(!vo(s))return{message:t,code:`HTTP_${n}`};let i=Dr(s,"message","error_description")??t,r=Dr(s,"__type","error")??`HTTP_${n}`;return{message:i,code:r}}function su(t){let n=t.userInfo;if(!vo(n))return;let s=n.email;return typeof s==="string"?s:void 0}async function iu(t,n,s){let i=Ir(t.refresh),r=t.authMethod==="idc",e=r?t.oidcRegion??t.region:t.region,f=yi(r?ot.REFRESH_IDC_URL:ot.REFRESH_URL,e);if(r&&(!i.clientId||!i.clientSecret))throw new Hn("Missing creds","MISSING_CREDENTIALS");let o=r?{refreshToken:i.refreshToken,clientId:i.clientId,clientSecret:i.clientSecret,grantType:"refresh_token"}:{refreshToken:i.refreshToken},c=r?`aws-sdk-js/${ot.SDK_VERSION} ua/2.1 os/other lang/js md/browser#unknown_unknown api/sso-oidc#${ot.SDK_VERSION} m/E ${ot.USER_AGENT}`:`aws-sdk-js/3.0.0 ${ot.USER_AGENT}-0.1.0 os/macos lang/js md/nodejs/18.0.0`;try{let h=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","amz-sdk-request":"attempt=1; max=1","x-amzn-kiro-agent-mode":"vibe","user-agent":c,Connection:"close"},body:JSON.stringify(o),...n?{signal:n}:{},...Z0(s)});if(!h.ok){let w=tb(await h.text(),h.status);throw new Hn(`Refresh failed: ${w.message}`,w.code)}let u=await h.json();if(!vo(u))throw new Hn("No access token","INVALID_RESPONSE");let l=Dr(u,"access_token","accessToken");if(!l)throw new Hn("No access token","INVALID_RESPONSE");let _={refreshToken:Dr(u,"refresh_token","refreshToken")??i.refreshToken,authMethod:t.authMethod,...i.clientId?{clientId:i.clientId}:{},...i.clientSecret?{clientSecret:i.clientSecret}:{}};return{refresh:yr(_),access:l,expires:Date.now()+(vR(u,"expires_in","expiresIn")??3600)*1000,authMethod:t.authMethod,region:t.region,...t.oidcRegion?{oidcRegion:t.oidcRegion}:{},...t.profileArn?{profileArn:t.profileArn}:{},...t.clientId?{clientId:t.clientId}:{},...t.clientSecret?{clientSecret:t.clientSecret}:{},...t.email||su(u)?{email:t.email??su(u)}:{}}}catch(h){if(h instanceof Hn)throw h;if(h instanceof Error&&h.name==="AbortError")throw h;throw new Hn(`Token refresh failed: ${h instanceof Error?h.message:"Unknown error"}`,"NETWORK_ERROR",h instanceof Error?h:void 0)}}class mr extends Error{accountId;constructor(t){super(`Account ${t} is no longer available`);this.accountId=t;this.name="AccountUnavailableError"}}class tf{accountManager;tokenExpiryBufferMs;proxyUrl;inFlight=new Map;constructor(t,n,s){this.accountManager=t;this.tokenExpiryBufferMs=n;this.proxyUrl=s}async refreshIfNeeded(t,n,s){if(!H0(n,this.tokenExpiryBufferMs)){let i=this.accountManager.getAccounts().find(({id:r})=>r===t.id);if(!i)throw new mr(t.id);return i}return this.startOrJoinRefresh(t,n,s)}async forceRefresh(t,n){return this.startOrJoinRefresh(t,this.accountManager.toAuthDetails(t),n)}startOrJoinRefresh(t,n,s){if(!("generation"in t)||typeof t.generation!=="number")throw new mr(t.id);let i={...t,generation:t.generation},r=`${i.id}:${i.generation}`,e=this.inFlight.get(r);if(e)return e;let f=this.runRefresh(i,n,s).finally(()=>{if(this.inFlight.get(r)===f)this.inFlight.delete(r)});return this.inFlight.set(r,f),f}async runRefresh(t,n,s){let i=await iu(n,s,this.proxyUrl),r=this.accountManager.updateFromAuth(t,i);if(!r)throw new mr(t.id);return r}}import{Database as nb}from"bun:sqlite";import{chmodSync as sb,existsSync as ib,mkdirSync as rb}from"fs";import{homedir as ru}from"os";import{dirname as eb,join as rf}from"path";function nf(t,n){return{id:t.id,email:t.email,auth_method:t.authMethod,region:t.region,oidc_region:t.oidcRegion??null,client_id:t.clientId??null,client_secret:t.clientSecret??null,profile_arn:t.profileArn??null,start_url:t.startUrl??null,refresh_token:t.refreshToken,access_token:t.accessToken,expires_at:t.expiresAt,rate_limit_reset:t.rateLimitResetTime,is_healthy:t.isHealthy?1:0,unhealthy_reason:t.unhealthyReason??null,recovery_time:t.recoveryTime??null,fail_count:t.failCount,last_used:t.lastUsed??0,used_count:t.usedCount??0,limit_count:t.limitCount??0,last_sync:t.lastSync??0,overage_count:t.overageCount??0,generation:n}}function Yr(t){return{id:t.id,email:t.email,authMethod:t.auth_method,region:t.region,oidcRegion:t.oidc_region??void 0,clientId:t.client_id??void 0,clientSecret:t.client_secret??void 0,profileArn:t.profile_arn??void 0,startUrl:t.start_url??void 0,refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset,isHealthy:t.is_healthy===1,unhealthyReason:t.unhealthy_reason??void 0,recoveryTime:t.recovery_time??void 0,failCount:t.fail_count,lastUsed:t.last_used,usedCount:t.used_count,limitCount:t.limit_count,lastSync:t.last_sync,overageCount:t.overage_count,generation:t.generation}}function sf(t){return[t.id,t.email,t.auth_method,t.region??null,t.oidc_region??null,t.client_id??null,t.client_secret??null,t.profile_arn??null,t.start_url??null,t.refresh_token,t.access_token,t.expires_at,t.rate_limit_reset,t.is_healthy,t.unhealthy_reason??null,t.recovery_time??null,t.fail_count,t.last_used,t.used_count,t.limit_count,t.last_sync,t.overage_count,t.generation]}function ob(){let t=process.platform==="win32"?process.env.APPDATA??rf(ru(),"AppData","Roaming"):process.env.XDG_CONFIG_HOME??rf(ru(),".config");return rf(t,"kiro-provider","accounts.db")}var Pn=ob();class is{db;path;constructor(t=Pn){if(this.path=t,t!==":memory:")rb(eb(t),{recursive:!0});this.db=new nb(t,{create:!0,strict:!0}),this.tightenPermissions(),this.db.run("PRAGMA busy_timeout = 5000"),this.db.run("PRAGMA journal_mode = WAL"),this.withImmediateTransaction(()=>{if(this.db.run(`
60
60
  CREATE TABLE IF NOT EXISTS accounts (
61
61
  id TEXT PRIMARY KEY, email TEXT NOT NULL, auth_method TEXT NOT NULL,
62
62
  region TEXT NOT NULL, oidc_region TEXT, client_id TEXT, client_secret TEXT,
@@ -79,19 +79,19 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
79
79
  WHERE NOT EXISTS (
80
80
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
81
81
  )
82
- `).all().map(mi)}getById(t){let n=this.db.query(`
82
+ `).all().map(Yr)}getById(t){let n=this.db.query(`
83
83
  SELECT accounts.* FROM accounts
84
84
  WHERE accounts.id = ? AND NOT EXISTS (
85
85
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
86
86
  )
87
- `).get(t);return n===null?void 0:mi(n)}insertAccount(t){return this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t.id),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t.id),r=Math.max(n?.generation??0,s?.last_generation??0)+1,i=nf(t,r);return this.db.query(`
87
+ `).get(t);return n===null?void 0:Yr(n)}insertAccount(t){return this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t.id),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t.id),i=Math.max(n?.generation??0,s?.last_generation??0)+1,r=nf(t,i);return this.db.query(`
88
88
  INSERT OR REPLACE INTO accounts (
89
89
  id, email, auth_method, region, oidc_region, client_id, client_secret,
90
90
  profile_arn, start_url, refresh_token, access_token, expires_at,
91
91
  rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
92
92
  last_used, used_count, limit_count, last_sync, overage_count, generation
93
93
  ) VALUES (${Array.from({length:23},()=>"?").join(", ")})
94
- `).run(...sf(i)),this.clearRemovedAccountInternal(t.id),mi(i)})}updateExistingAccounts(t){return this.withImmediateTransaction(()=>{let n=0,s=this.db.query(`
94
+ `).run(...sf(r)),this.clearRemovedAccountInternal(t.id),Yr(r)})}updateExistingAccounts(t){return this.withImmediateTransaction(()=>{let n=0,s=this.db.query(`
95
95
  UPDATE accounts SET
96
96
  email = ?, auth_method = ?, region = ?, oidc_region = ?, client_id = ?,
97
97
  client_secret = ?, profile_arn = ?, start_url = ?, refresh_token = ?,
@@ -102,51 +102,52 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf
102
102
  WHERE id = ? AND generation = ? AND NOT EXISTS (
103
103
  SELECT 1 FROM removed_accounts WHERE removed_accounts.id = accounts.id
104
104
  )
105
- `);for(let r of t){let i=sf(nf(r,r.generation)),e=i.shift();i.pop(),n+=s.run(...i,e??r.id,r.generation).changes}return n})}removeAccount(t){this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t),r=n?.generation??s?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(t),this.db.query(`
105
+ `);for(let i of t){let r=sf(nf(i,i.generation)),e=r.shift();r.pop(),n+=s.run(...r,e??i.id,i.generation).changes}return n})}removeAccount(t){this.withImmediateTransaction(()=>{let n=this.db.query("SELECT generation FROM accounts WHERE id = ?").get(t),s=this.db.query("SELECT last_generation FROM removed_accounts WHERE id = ?").get(t),i=n?.generation??s?.last_generation??0;this.db.query("DELETE FROM accounts WHERE id = ?").run(t),this.db.query(`
106
106
  INSERT OR REPLACE INTO removed_accounts (id, removed_at, last_generation)
107
107
  VALUES (?, ?, ?)
108
- `).run(t,Date.now(),r)})}clearRemovedAccount(t){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(t))}close(){this.db.close()}clearRemovedAccountInternal(t){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(t)}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let n=t();return this.db.exec("COMMIT"),n}catch(n){throw this.db.exec("ROLLBACK"),n}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let t of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(rb(t))sb(t,384)}}function V(t,n,s,r){let i={message:n,type:s};if(r!==void 0)i.code=r;return new Response(JSON.stringify({error:i}),{status:t,headers:{"Content-Type":"application/json"}})}var eu="Bearer ";function ou(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:V(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(eu))return{ok:!1,response:V(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let r=s.slice(eu.length);if(!n.includes(r))return{ok:!1,response:V(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var Xn=Y(xt(),1);var ni=Y(xt(),1);var si=Y(xt(),1);var Un=Y(xt(),1);var Ht=Y(xt(),1);var p=Y(St(),1);var _r=Y(kn(),1),Tg=Y(Nn(),1);var Dc=Y(Me(),1);var ri=Y(Ut(),1);var Nt=Y(fs(),1);var v=Y(vr(),1);var z=Y(Rn(),1);var tr=Y(kn(),1);var vs=Y(Rn(),1);var AA=async(t,n,s)=>{return{operation:vs.getSmithyContext(n).operation}};function JG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:r,ignoreCache:i},e)=>({identityProperties:{profile:n,filepath:s,configFilepath:r,ignoreCache:i}})}}var MA=(t)=>{let n=[];switch(t.operation){default:n.push(JG(t))}return n},gA=(t)=>{let n=tr.memoizeIdentityProvider(t.token,tr.isIdentityExpired,tr.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:vs.normalizeProvider(t.authSchemePreference??[]),token:n})};var EA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},dA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var RA={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var Ag=Y(xt(),1),Mg=Y(jc(),1);var cr=Y(St(),1);var It=Y(St(),1);var iM=300000,sr="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var P1=async(t,n={},s)=>{let{SSOOIDCClient:r}=await Promise.resolve().then(() => Y(Ph(),1)),i=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new r(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:i("logger"),userAgentAppId:i("userAgentAppId")}))};var N1=async(t,n,s={},r)=>{let{CreateTokenCommand:i}=await Promise.resolve().then(() => Y(Ph(),1));return(await P1(n,s,r)).send(new i({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var W1=Y(St(),1);var Nh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new W1.TokenProviderError(`Token is expired. ${sr}`,!1)};var D1=Y(St(),1);var qn=(t,n,s=!1)=>{if(typeof n>"u")throw new D1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${sr}`,!1)};var Y1=Y(St(),1);import{promises as _W}from"fs";var{writeFile:lW}=_W,m1=(t,n)=>{let s=Y1.getSSOTokenFilepath(t),r=JSON.stringify(n,null,2);return lW(s,r)};var Q1=new Date(0),J1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await It.parseKnownFiles(t),r=It.getProfileName({profile:t.profile??n?.profile}),i=s[r];if(!i)throw new It.TokenProviderError(`Profile '${r}' could not be found in shared credentials file.`,!1);else if(!i.sso_session)throw new It.TokenProviderError(`Profile '${r}' is missing required property 'sso_session'.`);let e=i.sso_session,o=(await It.loadSsoSessionData(t))[e];if(!o)throw new It.TokenProviderError(`Sso session '${e}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new It.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await It.getSSOTokenFromFile(e)}catch(A){throw new It.TokenProviderError(`The SSO session token associated with profile=${r} was not found or is invalid. ${sr}`,!1)}qn("accessToken",u.accessToken),qn("expiresAt",u.expiresAt);let{accessToken:_,expiresAt:l}=u,w={token:_,expiration:new Date(l)};if(w.expiration.getTime()-Date.now()>iM)return w;if(Date.now()-Q1.getTime()<30000)return Nh(w),w;qn("clientId",u.clientId,!0),qn("clientSecret",u.clientSecret,!0),qn("refreshToken",u.refreshToken,!0);try{Q1.setTime(Date.now());let A=await N1(u,h,t,n);qn("accessToken",A.accessToken),qn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await m1(e,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(E){}return{token:A.accessToken,expiration:M}}catch(A){return Nh(w),w}};var Wh=(t={})=>cr.memoize(cr.chain(J1(t),async()=>{throw new cr.TokenProviderError("Could not load token from any providers",!1)}),(n)=>n.expiration!==void 0&&n.expiration.getTime()-Date.now()<300000,(n)=>n.expiration!==void 0);var _n=Y(xt(),1);var gg=Y(kn(),1);var oo=Y(Me(),1);var Dh=Y($t(),1);var Ln=Y(St(),1);var bo=Y(me(),1);var Yh=Y($t(),1);var mh=Y(St(),1);var ht=Y(vr(),1);var _g=Y(Oh(),1),lg=Y(kn(),1);var Qh=Y(Ut(),1);var hr=Y($t(),1);var gs=Y($t(),1);var dt=Y(fs(),1);var wi="ref",Es=-1,fo=!0,k1="isSet",q1="PartitionResult",co="booleanEquals",Jh="getAttr",X1={[wi]:"Endpoint"},kh={[wi]:q1},ur={},z1=[{[wi]:"Region"}],x1={conditions:[[k1,[X1]],[k1,z1],["aws.partition",z1,q1],[co,[{[wi]:"UseFIPS"},fo]],[co,[{[wi]:"UseDualStack"},fo]],[co,[{fn:Jh,argv:[kh,"supportsDualStack"]},fo]],[co,[{fn:Jh,argv:[kh,"supportsFIPS"]},fo]],["stringEquals",[{fn:Jh,argv:[kh,"name"]},"aws-us-gov"]]],results:[[Es],[Es,"Invalid Configuration: FIPS and custom endpoint are not supported"],[Es,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[X1,ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[Es,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",ur],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",ur],[Es,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ur],[Es,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ur],[Es,"Invalid Configuration: Missing Region"]]},wW=2,Ot=1e8,AW=new Int32Array([-1,1,-1,0,13,3,1,4,Ot+12,2,5,Ot+12,3,8,6,4,7,Ot+11,5,Ot+9,Ot+10,4,11,9,6,10,Ot+8,7,Ot+6,Ot+7,5,12,Ot+5,6,Ot+4,Ot+5,3,Ot+1,14,4,Ot+2,Ot+3]),C1=dt.BinaryDecisionDiagram.from(AW,wW,x1.conditions,x1.results);var MW=new dt.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),K1=(t,n={})=>{return MW.get(t,()=>dt.decideEndpoint(C1,{endpointParams:t,logger:n.logger}))};dt.customEndpointFunctions.aws=Ht.awsEndpointFunctions;var xh=Y(Nn(),1);class yt extends z.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,yt.prototype)}}class ho extends yt{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends yt{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class _o extends yt{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,_o.prototype),this.reason=t.reason}}class lo extends yt{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,lo.prototype),this.reason=t.reason}}class wo extends yt{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends yt{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype)}}class Mo extends yt{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,Mo.prototype)}}class go extends yt{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,go.prototype),this.reason=t.reason}}class Eo extends yt{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Eo.prototype),this.responseCode=t.responseCode}}var V1=xh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),gW=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];V1.registerError(gW,yt);var ln=xh.TypeRegistry.for("com.amazon.aws.codewhisperer"),EW=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];ln.registerError(EW,ho);var dW=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];ln.registerError(dW,uo);var RW=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];ln.registerError(RW,Eo);var j1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];ln.registerError(j1,_o);var bW=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];ln.registerError(bW,Ao);var TW=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];ln.registerError(TW,go);var SW=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];ln.registerError(SW,Mo);var $W=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];ln.registerError($W,lo);var UW=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];ln.registerError(UW,wo);var a1=[V1,ln];var qh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],F=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],LW=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Ro=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],j=[0,"com.amazon.aws.q","SensitiveString",8,0],IW=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],OW=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>F,0],[()=>F,0],[()=>F,0],[()=>F,0]],3],yW=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>F,0],0],1],GW=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>F,0],0,[()=>cg,0],()=>fg,[()=>p1,0],[()=>c7,0],()=>Ch,[()=>H7,0]],1];var Ch=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],BW=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>L7,[()=>F,0],[()=>F,0]],2],FW=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],HW=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>F,0]],1],PW=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>F,0]],1],NW=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>fg]],WW=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>F,0],0,0,0,[()=>F,0],[()=>F,0]]],DW=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],YW=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>hg,0],0,0,0,[()=>pD,0],0,0,0],2],mW=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>F,0],()=>Kh],2],QW=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>mW,0],[()=>F,0]],2],JW=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>G7,0]],3],kW=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>F,0],[()=>F,0],[()=>y7,0],[()=>t7,0]]],XW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],zW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>F,0]]],Xh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],xW=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>F,0],[()=>F,0]]],qW=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],CW=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],KW=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>tg,0],()=>I7,[()=>r7,0],2,[()=>h7,0]]],VW=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>F,0],[()=>F,0]]],jW=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>F,0],[()=>n7,0],1]],p1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>F,0],0],1],aW=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>p1,0]]],pW=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>F,0]]],ZW=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>B7,0]],2],vW=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>S7,0]]],tD=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],nD=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],sD=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>SD]],rD=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],zh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Z1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Kh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>zh,()=>zh],2],iD=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>F,0],21,[()=>F,0]]],eD=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>F,0],[()=>F,0]],1],oD=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>v1]],fD=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og,0],1],cD=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>F,0],0,[()=>F,0]],3],hD=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>F,0],[()=>F,0],1,[()=>F,0],[()=>F,0]],1],uD=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>i7,0]],1],v1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],_D=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],lD=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>cg,0]]],tg=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og],1],wD=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>tg,0],()=>Kh,[()=>F,0],0,[()=>F,0],[()=>F,0],[()=>HW,0],64,[()=>ZD,0],[()=>F,0]],5],AD=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>qh,0]]],ng=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>e7,0],0,[()=>Ro,0]],2],MD=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>ng,0]]],gD=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>AD,0],[()=>Ro,0],[()=>LW,0]],2],ED=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Ro,0],[()=>qh,0]],3],dD=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Ro,0],[()=>F,0],2],2];var RD=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>F,0],[()=>bD,0],0,0,[()=>s7,0],[()=>vD,0],0,()=>Ch,()=>FW],1],bD=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>KW,0],[()=>uD,0],[()=>pW,0],[()=>jW,0],[()=>OW,0],[()=>O7,0],[()=>WW,0],()=>TD,[()=>aD,0],[()=>o7,0],[()=>f7,0]]],TD=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var SD=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var $D=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>YW,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],UD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>U7,16]],2];var LD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>w7,0]],1],Vh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>jD,0],[()=>WD,0]]],jh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>u7,0]],2],ID=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>Ai,0]]],OD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>l7,0],2],1],yD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>j,0],[()=>j,0]],2],GD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>j,0],[()=>_7,0],2,2],2],BD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>j,0],[()=>j,0],[()=>j,0]],2],sg=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>FD,0]]],FD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>j,0],[()=>j,0]],2],HD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],4],PD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>Ai,0],[()=>jh,0],[()=>sg,0],[()=>rg,0],[()=>eg,0],[()=>CD,0],()=>VD,[()=>kD,0],[()=>YD,0],[()=>ah,0],[()=>ig,0],[()=>Vh,0],[()=>OD,0],[()=>HD,0]]],ND=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>PD,0],0],1],WD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>BD,0]]],rg=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>A7,0]],1],DD=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>eg,0]]],ah=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],6],ig=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>M7,0],[()=>Vh,0]],1],YD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>j,0],[()=>g7,0],[()=>Vh,0]],2],mD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>Ai,0],[()=>jh,0],[()=>ah,0],[()=>ig,0]]],eg=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>j,0],[()=>E7,0]],3],QD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>Ai,0]]],JD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>j,0]],1],kD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>d7,0]],1],XD=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>j,0],[()=>$7,0],[()=>xD,0],2,2,[()=>zD,0]],2],zD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>j,0]]],xD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>j,0],0],1],qD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>Ai,0],[()=>sg,0],[()=>jh,0],[()=>rg,0]]],CD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>KD,0],[()=>b7,0],[()=>R7,0]],2],KD=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>j,0],[()=>j,0]],2],VD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],Ai=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>j,0]],1],jD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>j,0],[()=>j,0]],2];var aD=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>IW,0]],pD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>hg,0]],ZD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>QW,0]];var vD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>JW,0]],t7=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>zW,0]],og=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>qW],n7=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>VW,0]],s7=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>ZW,0]],fg=[1,"com.amazon.aws.codewhisperer","References",0,()=>oD],r7=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>fD,0]],i7=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>hD,0]],cg=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>_D,0]],e7=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>N7,0]],o7=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>ng,0]],f7=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>P7,0]],c7=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>ED,0]],h7=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>F,0]],u7=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>ID,0]],_7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>yD,0]],l7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>GD,0]],w7=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>ND,0]],A7=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>DD,0]],M7=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>ah,0]],g7=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>mD,0]],E7=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>QD,0]],d7=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>JD,0]],R7=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>XD,0]],b7=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>qD,0]],T7=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>F7],S7=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>T7,0]],$7=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>j,0]],hg=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>RD,0],[()=>GW,0]]],U7=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>nD,[()=>yW,0],[()=>iD,0],()=>CW,()=>NW,[()=>lD,0],[()=>aW,0],[()=>PW,0],[()=>vW,0],[()=>LD,0],[()=>dD,0],[()=>MD,0],()=>sD,()=>rD,()=>DW,[()=>BW,0],[()=>kW,0],()=>tD,[()=>j1,0]]],L7=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>v1]],I7=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>zh,()=>Kh]],O7=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>wD,0],[()=>cD,0]]],y7=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>Xh,()=>Xh,()=>Xh,()=>XW,[()=>xW,0]]],G7=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var B7=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],F7=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],H7=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>eD,0],21]];var P7=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>gD,0],()=>Ch]],N7=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>F,0],[()=>qh,0]]];var ug=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>$D,()=>UD];var wg=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hr.fromBase64,base64Encoder:t?.base64Encoder??hr.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??K1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??MA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new lg.HttpBearerAuthSigner}],logger:t?.logger??new z.NoOpLogger,protocol:t?.protocol??_g.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:a1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Qh.parseUrl,utf8Decoder:t?.utf8Decoder??gs.fromUtf8,utf8Encoder:t?.utf8Encoder??gs.toUtf8}};var Eg=(t)=>{z.emitWarningIfUnsupportedVersion(process.version);let n=mh.resolveDefaultsModeConfig(t),s=()=>n().then(z.loadConfigsForDefaultMode),r=wg(t);Ag.emitWarningIfUnsupportedVersion(process.version);let i={profile:t?.profile,logger:r.logger};return{...r,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Ln.loadConfig(Mg.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,i),bodyLengthChecker:t?.bodyLengthChecker??Yh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??_n.createDefaultUserAgentProvider({serviceId:r.serviceId,clientVersion:RA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??oo.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await Wh(f)(f)}),signer:new gg.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Ln.loadConfig(v.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Ln.loadConfig(p.NODE_REGION_CONFIG_OPTIONS,{...p.NODE_REGION_CONFIG_FILE_OPTIONS,...i}),requestHandler:bo.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Ln.loadConfig({...v.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ht.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Dh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??bo.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ln.loadConfig(p.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,i),useFipsEndpoint:t?.useFipsEndpoint??Ln.loadConfig(p.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,i),userAgentAppId:t?.userAgentAppId??Ln.loadConfig(_n.NODE_APP_ID_CONFIG_OPTIONS,i)}};var Pt=Y(xt(),1);var Gt=Y(Ut(),1);var dg=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:r}=t;return{setHttpAuthScheme(i){let e=n.findIndex((f)=>f.schemeId===i.schemeId);if(e===-1)n.push(i);else n.splice(e,1,i)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(i){s=i},httpAuthSchemeProvider(){return s},setToken(i){r=i},token(){return r}}},Rg=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var bg=(t,n)=>{let s=Object.assign(Pt.getAwsRegionExtensionConfiguration(t),z.getDefaultExtensionConfiguration(t),Gt.getHttpHandlerExtensionConfiguration(t),dg(t));return n.forEach((r)=>r.configure(s)),Object.assign(t,Pt.resolveAwsRegionExtensionConfiguration(s),z.resolveDefaultRuntimeConfig(s),Gt.resolveHttpHandlerRuntimeConfig(s),Rg(s))};class ph extends z.Client{config;constructor(...[t]){let n=Eg(t||{});super(n);this.initConfig=n;let s=EA(n),r=Un.resolveUserAgentConfig(s),i=v.resolveRetryConfig(r),e=p.resolveRegionConfig(i),f=Xn.resolveHostHeaderConfig(e),o=Nt.resolveEndpointConfig(f),c=Ht.resolveDefaultAwsRegionalEndpointsConfig(o),h=Dc.resolveEventStreamSerdeConfig(c),u=gA(h),_=bg(u,t?.extensions||[]);this.config=_,this.middlewareStack.use(Tg.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Un.getUserAgentPlugin(this.config)),this.middlewareStack.use(v.getRetryPlugin(this.config)),this.middlewareStack.use(ri.getContentLengthPlugin(this.config)),this.middlewareStack.use(Xn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(ni.getLoggerPlugin(this.config)),this.middlewareStack.use(si.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(_r.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:AA,identityProviderConfigProvider:async(l)=>new _r.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":l.token})})),this.middlewareStack.use(_r.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class Zh extends z.Command.classBuilder().ep(dA).m(function(t,n,s,r){return[Nt.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(ug).build(){}function Sg(t){let n=yr[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${nu.join(", ")}`);return n}var $g=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Ug=["low","medium","high","xhigh","max"];function To(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if($g.has(r))return{wireId:Sg(r),effort:n}}}return{wireId:Sg(t),effort:void 0}}function W7(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let r=t.slice(0,-s.length);if($g.has(r))return r}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(yr[n])return n}return t}function Lg(t){return B(W7(t))}var D7=["low","medium","high","xhigh","max"];function Y7(t){return typeof t==="string"&&D7.some((n)=>n===t)}var Ig=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Og=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...Ig]),m7=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.5","claude-sonnet-4.5-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...Og]);function So(t){return m7.has(t)}function Q7(t){return Og.has(t)}function yg(t,n){if(Ig.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function J7(t,n){if(!So(t))return;if(n==="xhigh"&&!Q7(t))return"max";return n}function k7(t,n){if(!So(n))return;let s;if(t<=1e4)s="low";else if(t<=20000)s="medium";else if(t<=28000)s="high";else s="max";return s}function Gg(t){let n;if(So(t.model))n={wireId:t.model,effort:void 0};else try{n=To(t.model)}catch(r){if(r instanceof Error&&r.message.startsWith("Unsupported model:"))return;throw r}if(!So(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let r of s)if(Y7(r))return J7(n.wireId,r);if(!t.think)return;if(t.autoEffortMapping??!0)return k7(t.budget,n.wireId);return"medium"}import{randomUUID as K7}from"crypto";function Mi(t){return typeof t==="object"&&t!==null}function X7(t){let n=atob(t),s=new Uint8Array(n.length);for(let r=0;r<n.length;r++)s[r]=n.charCodeAt(r);return s}function z7(t){let n=[];for(let s of t){if(!Mi(s)||s.type!=="image"||!Mi(s.source))continue;let r=s.source;if(r.type!=="base64"||typeof r.data!=="string")continue;n.push({mediaType:typeof r.media_type==="string"?r.media_type:"image/jpeg",data:r.data})}return n}function x7(t){let n=[];for(let s of t){if(!Mi(s)||s.type!=="image_url"||!Mi(s.image_url))continue;let r=s.image_url.url;if(typeof r!=="string"||!r.startsWith("data:"))continue;let[i="",e]=r.split(",",2);if(!e)continue;let f=i.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:e})}return n}function $o(t){if(!Array.isArray(t))return[];return[...z7(t),...x7(t)]}function Uo(t){let n=[],s=0;for(let r of t){if(n.length>=4)break;if(s+r.data.length>3750000)break;n.push(r),s+=r.data.length}return{images:n.map((r)=>({format:r.mediaType.split("/")[1]||"png",source:{bytes:X7(r.data)}})),omitted:t.length-n.length}}function Lo(t){let n=[];for(let s of t){if(!Mi(s))continue;if(typeof s.text==="string")n.push(s.text);else if(s.type==="text"&&s.text)n.push(String(s.text))}return n.join("")}function vh(t){return typeof t==="object"&&t!==null}function Bg(t,n){for(let s of t){if(s.role!=="assistant")continue;if(s.tool_calls){for(let r of s.tool_calls)if(r.id===n)return r}if(Array.isArray(s.content)){for(let r of s.content)if(vh(r)&&r.type==="tool_use"&&r.id===n)return r}}return null}function Fg(t){let n=[];for(let s of t){if(n.length===0){n.push({...s});continue}let r=n[n.length-1];if(!r||s.role!==r.role){n.push({...s});continue}if(Array.isArray(r.content)&&Array.isArray(s.content))r.content.push(...s.content);else if(typeof r.content==="string"&&typeof s.content==="string")r.content+=`
109
- ${s.content}`;else if(Array.isArray(r.content)&&typeof s.content==="string")r.content.push({type:"text",text:s.content});else if(typeof r.content==="string"&&Array.isArray(s.content))r.content=[{type:"text",text:r.content},...s.content];if(s.tool_calls){if(!r.tool_calls)r.tool_calls=[];r.tool_calls.push(...s.tool_calls)}if(s.role==="tool"){if(!r.tool_results)r.tool_results=[{content:r.content,tool_call_id:r.tool_call_id}];r.tool_results.push({content:s.content,tool_call_id:s.tool_call_id})}}return n}function Bt(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(!vh(t))return"";if(typeof t.content==="string")return t.content;if(Array.isArray(t.content))return t.content.filter((n)=>vh(n)&&n.type==="text").map((n)=>typeof n.text==="string"?n.text:"").join("");return typeof t.text==="string"?t.text:""}function Hg(t){return t.map((n)=>({toolSpecification:{name:n.name||n.function?.name,description:(n.description||n.function?.description||"").substring(0,9216),inputSchema:{json:n.input_schema||n.function?.parameters||{}}}}))}function gi(t){let n=[],s=new Set;for(let r of t)if(!s.has(r.toolUseId))s.add(r.toolUseId),n.push(r);return n}function Pg(t){return typeof t==="object"&&t!==null}function q7(t){let n=t.function?.arguments;return{input:typeof n==="string"?JSON.parse(n):n,name:t.function?.name??"",toolUseId:t.id??""}}function C7(t){if(t.length<4)return t;let n=[],s=0;while(s<t.length){let r=t[s];if(r?.assistantResponseMessage?.toolUses&&s+1<t.length&&t[s+1]?.userInputMessage?.userInputMessageContext?.toolResults){let i=s,e=s;while(e<t.length){let o=t[e],c=e+1<t.length?t[e+1]:void 0;if(!o?.assistantResponseMessage?.toolUses||!c?.userInputMessage?.userInputMessageContext?.toolResults)break;e+=2}let f=(e-i)/2;for(let o=i;o<e;o+=2){let c=t[o],h=t[o+1];if(!c||!h)continue;if(f>1&&o!==i){let u=c.assistantResponseMessage?.content.match(/^<thinking>[\s\S]*?<\/thinking>/)?.[0];n.push({assistantResponseMessage:{content:u?`${u}
108
+ `).run(t,Date.now(),i)})}clearRemovedAccount(t){this.withImmediateTransaction(()=>this.clearRemovedAccountInternal(t))}close(){this.db.close()}clearRemovedAccountInternal(t){this.db.query("DELETE FROM removed_accounts WHERE id = ?").run(t)}withImmediateTransaction(t){this.db.exec("BEGIN IMMEDIATE");try{let n=t();return this.db.exec("COMMIT"),n}catch(n){throw this.db.exec("ROLLBACK"),n}finally{this.tightenPermissions()}}tightenPermissions(){if(this.path===":memory:")return;for(let t of[this.path,`${this.path}-wal`,`${this.path}-shm`])if(ib(t))sb(t,384)}}function V(t,n,s,i){let r={message:n,type:s};if(i!==void 0)r.code=i;return new Response(JSON.stringify({error:r}),{status:t,headers:{"Content-Type":"application/json"}})}var eu="Bearer ";function ou(t,n){let s=t.headers.get("Authorization");if(s===null)return{ok:!1,response:V(401,"Missing Authorization header.","authentication_error","missing_api_key")};if(!s.startsWith(eu))return{ok:!1,response:V(401,"Authorization header must use the Bearer scheme.","authentication_error","invalid_api_key")};let i=s.slice(eu.length);if(!n.includes(i))return{ok:!1,response:V(401,"Incorrect API key provided.","authentication_error","invalid_api_key")};return{ok:!0}}var zn=m(xt(),1);var nr=m(xt(),1);var sr=m(xt(),1);var Un=m(xt(),1);var Ht=m(xt(),1);var p=m(St(),1);var li=m(kn(),1),Tg=m(Nn(),1);var Dc=m(Me(),1);var ir=m(Ut(),1);var Nt=m(fs(),1);var v=m(vi(),1);var X=m(Rn(),1);var ti=m(kn(),1);var vs=m(Rn(),1);var AA=async(t,n,s)=>{return{operation:vs.getSmithyContext(n).operation}};function JG(t){return{schemeId:"smithy.api#httpBearerAuth",propertiesExtractor:({profile:n,filepath:s,configFilepath:i,ignoreCache:r},e)=>({identityProperties:{profile:n,filepath:s,configFilepath:i,ignoreCache:r}})}}var MA=(t)=>{let n=[];switch(t.operation){default:n.push(JG(t))}return n},gA=(t)=>{let n=ti.memoizeIdentityProvider(t.token,ti.isIdentityExpired,ti.doesIdentityRequireRefresh);return Object.assign(t,{authSchemePreference:vs.normalizeProvider(t.authSchemePreference??[]),token:n})};var dA=(t)=>{return Object.assign(t,{useDualstackEndpoint:t.useDualstackEndpoint??!1,useFipsEndpoint:t.useFipsEndpoint??!1,defaultSigningName:"amazoncodewhispererstreamingservice"})},EA={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var RA={name:"@aws/codewhisperer-streaming-client",description:"@aws/codewhisperer-streaming-client",version:"1.0.45",scripts:{build:"concurrently 'npm:build:cjs' 'npm:build:es' 'npm:build:types'","build:cjs":"tsc -p tsconfig.cjs.json","build:es":"tsc -p tsconfig.es.json","build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo",prepack:"npm run clean && npm run build"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{tslib:"^2.6.2","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.974.7","@aws-sdk/middleware-host-header":"^3.972.10","@aws-sdk/middleware-logger":"^3.972.10","@aws-sdk/middleware-recursion-detection":"^3.972.11","@aws-sdk/middleware-user-agent":"^3.972.37","@aws-sdk/region-config-resolver":"^3.972.13","@aws-sdk/token-providers":"^3.1040.0","@aws-sdk/types":"^3.973.8","@aws-sdk/util-endpoints":"^3.996.8","@aws-sdk/util-user-agent-browser":"^3.972.10","@aws-sdk/util-user-agent-node":"^3.973.23","@smithy/config-resolver":"^4.4.17","@smithy/core":"^3.23.17","@smithy/eventstream-serde-browser":"^4.2.14","@smithy/eventstream-serde-config-resolver":"^4.3.14","@smithy/eventstream-serde-node":"^4.2.14","@smithy/fetch-http-handler":"^5.3.17","@smithy/hash-node":"^4.2.14","@smithy/invalid-dependency":"^4.2.14","@smithy/middleware-content-length":"^4.2.14","@smithy/middleware-endpoint":"^4.4.32","@smithy/middleware-retry":"^4.5.7","@smithy/middleware-serde":"^4.2.20","@smithy/middleware-stack":"^4.2.14","@smithy/node-config-provider":"^4.3.14","@smithy/node-http-handler":"^4.6.1","@smithy/protocol-http":"^5.3.14","@smithy/smithy-client":"^4.12.13","@smithy/types":"^4.14.1","@smithy/url-parser":"^4.2.14","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.49","@smithy/util-defaults-mode-node":"^4.2.54","@smithy/util-endpoints":"^3.4.2","@smithy/util-middleware":"^4.2.14","@smithy/util-retry":"^4.3.6","@smithy/util-utf8":"^4.2.2"},devDependencies:{"@tsconfig/node20":"20.1.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3","@types/node":"^20.14.8"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},license:"Apache-2.0"};var Ag=m(xt(),1),Mg=m(jc(),1);var ci=m(St(),1);var It=m(St(),1);var rM=300000,si="To refresh this SSO session run 'aws sso login' with the corresponding profile.";var P1=async(t,n={},s)=>{let{SSOOIDCClient:i}=await Promise.resolve().then(() => m(Ph(),1)),r=(f)=>n.clientConfig?.[f]??n.parentClientConfig?.[f]??s?.[f];return new i(Object.assign({},n.clientConfig??{},{region:t??n.clientConfig?.region,logger:r("logger"),userAgentAppId:r("userAgentAppId")}))};var N1=async(t,n,s={},i)=>{let{CreateTokenCommand:r}=await Promise.resolve().then(() => m(Ph(),1));return(await P1(n,s,i)).send(new r({clientId:t.clientId,clientSecret:t.clientSecret,refreshToken:t.refreshToken,grantType:"refresh_token"}))};var W1=m(St(),1);var Nh=(t)=>{if(t.expiration&&t.expiration.getTime()<Date.now())throw new W1.TokenProviderError(`Token is expired. ${si}`,!1)};var D1=m(St(),1);var qn=(t,n,s=!1)=>{if(typeof n>"u")throw new D1.TokenProviderError(`Value not present for '${t}' in SSO Token${s?". Cannot refresh":""}. ${si}`,!1)};var m1=m(St(),1);import{promises as lW}from"fs";var{writeFile:_W}=lW,Y1=(t,n)=>{let s=m1.getSSOTokenFilepath(t),i=JSON.stringify(n,null,2);return _W(s,i)};var Q1=new Date(0),J1=(t={})=>async({callerClientConfig:n}={})=>{t.logger?.debug("@aws-sdk/token-providers - fromSso");let s=await It.parseKnownFiles(t),i=It.getProfileName({profile:t.profile??n?.profile}),r=s[i];if(!r)throw new It.TokenProviderError(`Profile '${i}' could not be found in shared credentials file.`,!1);else if(!r.sso_session)throw new It.TokenProviderError(`Profile '${i}' is missing required property 'sso_session'.`);let e=r.sso_session,o=(await It.loadSsoSessionData(t))[e];if(!o)throw new It.TokenProviderError(`Sso session '${e}' could not be found in shared credentials file.`,!1);for(let A of["sso_start_url","sso_region"])if(!o[A])throw new It.TokenProviderError(`Sso session '${e}' is missing required property '${A}'.`,!1);let{sso_start_url:c,sso_region:h}=o,u;try{u=await It.getSSOTokenFromFile(e)}catch(A){throw new It.TokenProviderError(`The SSO session token associated with profile=${i} was not found or is invalid. ${si}`,!1)}qn("accessToken",u.accessToken),qn("expiresAt",u.expiresAt);let{accessToken:l,expiresAt:_}=u,w={token:l,expiration:new Date(_)};if(w.expiration.getTime()-Date.now()>rM)return w;if(Date.now()-Q1.getTime()<30000)return Nh(w),w;qn("clientId",u.clientId,!0),qn("clientSecret",u.clientSecret,!0),qn("refreshToken",u.refreshToken,!0);try{Q1.setTime(Date.now());let A=await N1(u,h,t,n);qn("accessToken",A.accessToken),qn("expiresIn",A.expiresIn);let M=new Date(Date.now()+A.expiresIn*1000);try{await Y1(e,{...u,accessToken:A.accessToken,expiresAt:M.toISOString(),refreshToken:A.refreshToken})}catch(d){}return{token:A.accessToken,expiration:M}}catch(A){return Nh(w),w}};var Wh=(t={})=>ci.memoize(ci.chain(J1(t),async()=>{throw new ci.TokenProviderError("Could not load token from any providers",!1)}),(n)=>n.expiration!==void 0&&n.expiration.getTime()-Date.now()<300000,(n)=>n.expiration!==void 0);var ln=m(xt(),1);var gg=m(kn(),1);var oo=m(Me(),1);var Dh=m($t(),1);var Ln=m(St(),1);var bo=m(Ye(),1);var mh=m($t(),1);var Yh=m(St(),1);var ht=m(vi(),1);var lg=m(yh(),1),_g=m(kn(),1);var Qh=m(Ut(),1);var hi=m($t(),1);var gs=m($t(),1);var Et=m(fs(),1);var wr="ref",ds=-1,fo=!0,k1="isSet",q1="PartitionResult",co="booleanEquals",Jh="getAttr",z1={[wr]:"Endpoint"},kh={[wr]:q1},ui={},X1=[{[wr]:"Region"}],x1={conditions:[[k1,[z1]],[k1,X1],["aws.partition",X1,q1],[co,[{[wr]:"UseFIPS"},fo]],[co,[{[wr]:"UseDualStack"},fo]],[co,[{fn:Jh,argv:[kh,"supportsDualStack"]},fo]],[co,[{fn:Jh,argv:[kh,"supportsFIPS"]},fo]],["stringEquals",[{fn:Jh,argv:[kh,"name"]},"aws-us-gov"]]],results:[[ds],[ds,"Invalid Configuration: FIPS and custom endpoint are not supported"],[ds,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[z1,ui],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",ui],[ds,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://amazoncodewhispererstreamingservice.{Region}.amazonaws.com",ui],["https://amazoncodewhispererstreamingservice-fips.{Region}.{PartitionResult#dnsSuffix}",ui],[ds,"FIPS is enabled but this partition does not support FIPS"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dualStackDnsSuffix}",ui],[ds,"DualStack is enabled but this partition does not support DualStack"],["https://amazoncodewhispererstreamingservice.{Region}.{PartitionResult#dnsSuffix}",ui],[ds,"Invalid Configuration: Missing Region"]]},wW=2,yt=1e8,AW=new Int32Array([-1,1,-1,0,13,3,1,4,yt+12,2,5,yt+12,3,8,6,4,7,yt+11,5,yt+9,yt+10,4,11,9,6,10,yt+8,7,yt+6,yt+7,5,12,yt+5,6,yt+4,yt+5,3,yt+1,14,4,yt+2,yt+3]),C1=Et.BinaryDecisionDiagram.from(AW,wW,x1.conditions,x1.results);var MW=new Et.EndpointCache({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),K1=(t,n={})=>{return MW.get(t,()=>Et.decideEndpoint(C1,{endpointParams:t,logger:n.logger}))};Et.customEndpointFunctions.aws=Ht.awsEndpointFunctions;var xh=m(Nn(),1);class Ot extends X.ServiceException{constructor(t){super(t);Object.setPrototypeOf(this,Ot.prototype)}}class ho extends Ot{name="AccessDeniedException";$fault="client";reason;constructor(t){super({name:"AccessDeniedException",$fault:"client",...t});Object.setPrototypeOf(this,ho.prototype),this.reason=t.reason}}class uo extends Ot{name="ConflictException";$fault="client";reason;constructor(t){super({name:"ConflictException",$fault:"client",...t});Object.setPrototypeOf(this,uo.prototype),this.reason=t.reason}}class lo extends Ot{name="InternalServerException";$fault="server";$retryable={};reason;constructor(t){super({name:"InternalServerException",$fault:"server",...t});Object.setPrototypeOf(this,lo.prototype),this.reason=t.reason}}class _o extends Ot{name="ThrottlingException";$fault="client";$retryable={throttling:!0};reason;constructor(t){super({name:"ThrottlingException",$fault:"client",...t});Object.setPrototypeOf(this,_o.prototype),this.reason=t.reason}}class wo extends Ot{name="ValidationException";$fault="client";reason;constructor(t){super({name:"ValidationException",$fault:"client",...t});Object.setPrototypeOf(this,wo.prototype),this.reason=t.reason}}class Ao extends Ot{name="ResourceNotFoundException";$fault="client";constructor(t){super({name:"ResourceNotFoundException",$fault:"client",...t});Object.setPrototypeOf(this,Ao.prototype)}}class Mo extends Ot{name="ServiceUnavailableException";$fault="server";constructor(t){super({name:"ServiceUnavailableException",$fault:"server",...t});Object.setPrototypeOf(this,Mo.prototype)}}class go extends Ot{name="ServiceQuotaExceededException";$fault="client";reason;constructor(t){super({name:"ServiceQuotaExceededException",$fault:"client",...t});Object.setPrototypeOf(this,go.prototype),this.reason=t.reason}}class Eo extends Ot{name="DryRunOperationException";$fault="client";responseCode;constructor(t){super({name:"DryRunOperationException",$fault:"client",...t});Object.setPrototypeOf(this,Eo.prototype),this.responseCode=t.responseCode}}var V1=xh.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming"),gW=[-3,"smithy.ts.sdk.synthetic.com.amazon.aws.codewhisperer.streaming","CodeWhispererStreamingServiceException",0,[],[]];V1.registerError(gW,Ot);var _n=xh.TypeRegistry.for("com.amazon.aws.codewhisperer"),dW=[-3,"com.amazon.aws.codewhisperer","AccessDeniedException",{["error"]:"client",["httpError"]:403},["message","reason"],[0,0],1];_n.registerError(dW,ho);var EW=[-3,"com.amazon.aws.codewhisperer","ConflictException",{["error"]:"client",["httpError"]:409},["message","reason"],[0,0],1];_n.registerError(EW,uo);var RW=[-3,"com.amazon.aws.codewhisperer","DryRunOperationException",{["error"]:"client"},["message","responseCode"],[0,[1,32]]];_n.registerError(RW,Eo);var j1=[-3,"com.amazon.aws.codewhisperer","InternalServerException",{["error"]:"server",["httpError"]:500},["message","reason"],[0,0],1];_n.registerError(j1,lo);var bW=[-3,"com.amazon.aws.codewhisperer","ResourceNotFoundException",{["error"]:"client",["httpError"]:404},["message"],[0],1];_n.registerError(bW,Ao);var TW=[-3,"com.amazon.aws.codewhisperer","ServiceQuotaExceededException",{["error"]:"client",["httpError"]:402},["message","reason"],[0,0],1];_n.registerError(TW,go);var SW=[-3,"com.amazon.aws.codewhisperer","ServiceUnavailableException",{["error"]:"server",["httpError"]:503},["message"],[0],1];_n.registerError(SW,Mo);var $W=[-3,"com.amazon.aws.codewhisperer","ThrottlingException",{["error"]:"client",["httpError"]:429},["message","reason"],[0,0],1];_n.registerError($W,_o);var UW=[-3,"com.amazon.aws.codewhisperer","ValidationException",{["error"]:"client",["httpError"]:400},["message","reason"],[0,0],1];_n.registerError(UW,wo);var a1=[V1,_n];var qh=[0,"com.amazon.aws.codewhisperer","SensitiveDocument",8,15],F=[0,"com.amazon.aws.codewhisperer","SensitiveString",8,0],LW=[0,"com.amazon.aws.codewhisperer","ToolDescription",8,0],Ro=[0,"com.amazon.aws.codewhisperer","ToolName",8,0],j=[0,"com.amazon.aws.q","SensitiveString",8,0],IW=[3,"com.amazon.aws.codewhisperer","AdditionalContentEntry",0,["name","description","innerContext"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],yW=[3,"com.amazon.aws.codewhisperer","AppStudioState",0,["namespace","propertyName","propertyContext","propertyValue"],[[()=>F,0],[()=>F,0],[()=>F,0],[()=>F,0]],3],OW=[3,"com.amazon.aws.codewhisperer","AssistantResponseEvent",0,["content","modelId"],[[()=>F,0],0],1],GW=[3,"com.amazon.aws.codewhisperer","AssistantResponseMessage",0,["content","messageId","supplementaryWebLinks","references","followupPrompt","toolUses","cachePoint","reasoningContent"],[[()=>F,0],0,[()=>cg,0],()=>fg,[()=>p1,0],[()=>c7,0],()=>Ch,[()=>H7,0]],1];var Ch=[3,"com.amazon.aws.codewhisperer","CachePoint",0,["type"],[0],1],BW=[3,"com.amazon.aws.codewhisperer","CitationEvent",0,["target","citationLink","citationText"],[()=>L7,[()=>F,0],[()=>F,0]],2],FW=[3,"com.amazon.aws.codewhisperer","ClientCacheConfig",0,["useClientCachingOnly"],[2]],HW=[3,"com.amazon.aws.codewhisperer","CodeDescription",0,["href"],[[()=>F,0]],1],PW=[3,"com.amazon.aws.codewhisperer","CodeEvent",0,["content"],[[()=>F,0]],1],NW=[3,"com.amazon.aws.codewhisperer","CodeReferenceEvent",0,["references"],[()=>fg]],WW=[3,"com.amazon.aws.codewhisperer","ConsoleState",0,["region","consoleUrl","serviceId","serviceConsolePage","serviceSubconsolePage","taskName","uxErrorMessage"],[0,[()=>F,0],0,0,0,[()=>F,0],[()=>F,0]]],DW=[3,"com.amazon.aws.codewhisperer","ContextUsageEvent",0,["contextUsagePercentage"],[1]],mW=[3,"com.amazon.aws.codewhisperer","ConversationState",0,["currentMessage","chatTriggerType","conversationId","workspaceId","history","customizationArn","agentContinuationId","agentTaskType"],[[()=>hg,0],0,0,0,[()=>pD,0],0,0,0],2],YW=[3,"com.amazon.aws.codewhisperer","DiagnosticLocation",0,["uri","range"],[[()=>F,0],()=>Kh],2],QW=[3,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformation",0,["location","message"],[[()=>YW,0],[()=>F,0]],2],JW=[3,"com.amazon.aws.codewhisperer","DocumentBlock",0,["name","format","source"],[0,0,[()=>G7,0]],3],kW=[3,"com.amazon.aws.codewhisperer","DocumentCitationEvent",0,["source","title","location","sourceContent"],[[()=>F,0],[()=>F,0],[()=>O7,0],[()=>t7,0]]],zW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSearchResultSpan",0,["searchResultIndex","start","end"],[1,1,1]],XW=[3,"com.amazon.aws.codewhisperer","DocumentCitationSourceContent",0,["text"],[[()=>F,0]]],zh=[3,"com.amazon.aws.codewhisperer","DocumentCitationSpan",0,["documentIndex","start","end"],[1,1,1]],xW=[3,"com.amazon.aws.codewhisperer","DocumentCitationWebLocation",0,["url","domain"],[[()=>F,0],[()=>F,0]]],qW=[3,"com.amazon.aws.codewhisperer","DocumentSymbol",0,["name","type","source"],[0,0,0],2],CW=[3,"com.amazon.aws.codewhisperer","DryRunSucceedEvent",0,[],[]],KW=[3,"com.amazon.aws.codewhisperer","EditorState",0,["document","cursorState","relevantDocuments","useRelevantDocuments","workspaceFolders"],[[()=>tg,0],()=>I7,[()=>i7,0],2,[()=>h7,0]]],VW=[3,"com.amazon.aws.codewhisperer","EnvironmentVariable",0,["key","value"],[[()=>F,0],[()=>F,0]]],jW=[3,"com.amazon.aws.codewhisperer","EnvState",0,["operatingSystem","currentWorkingDirectory","environmentVariables","timezoneOffset"],[0,[()=>F,0],[()=>n7,0],1]],p1=[3,"com.amazon.aws.codewhisperer","FollowupPrompt",0,["content","userIntent"],[[()=>F,0],0],1],aW=[3,"com.amazon.aws.codewhisperer","FollowupPromptEvent",0,["followupPrompt"],[[()=>p1,0]]],pW=[3,"com.amazon.aws.codewhisperer","GitState",0,["status"],[[()=>F,0]]],ZW=[3,"com.amazon.aws.codewhisperer","ImageBlock",0,["format","source"],[0,[()=>B7,0]],2],vW=[3,"com.amazon.aws.codewhisperer","IntentsEvent",0,["intents"],[[()=>S7,0]]],tD=[3,"com.amazon.aws.codewhisperer","InvalidStateEvent",0,["reason","message"],[0,0],2],nD=[3,"com.amazon.aws.codewhisperer","MessageMetadataEvent",0,["conversationId","utteranceId"],[0,0]],sD=[3,"com.amazon.aws.codewhisperer","MetadataEvent",0,["tokenUsage"],[()=>SD]],iD=[3,"com.amazon.aws.codewhisperer","MeteringEvent",0,["usage","unit","unitPlural"],[1,0,0]],Xh=[3,"com.amazon.aws.codewhisperer","Position",0,["line","character"],[1,1],2],Z1=[3,"com.amazon.aws.codewhisperer","ProgrammingLanguage",0,["languageName"],[0],1],Kh=[3,"com.amazon.aws.codewhisperer","Range",0,["start","end"],[()=>Xh,()=>Xh],2],rD=[3,"com.amazon.aws.codewhisperer","ReasoningContentEvent",8,["text","redactedContent","signature"],[[()=>F,0],21,[()=>F,0]]],eD=[3,"com.amazon.aws.codewhisperer","ReasoningText",8,["text","signature"],[[()=>F,0],[()=>F,0]],1],oD=[3,"com.amazon.aws.codewhisperer","Reference",0,["licenseName","repository","url","recommendationContentSpan"],[0,0,0,()=>v1]],fD=[3,"com.amazon.aws.codewhisperer","RelevantTextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols","type"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og,0],1],cD=[3,"com.amazon.aws.codewhisperer","RuntimeDiagnostic",0,["source","severity","message"],[[()=>F,0],0,[()=>F,0]],3],hD=[3,"com.amazon.aws.codewhisperer","ShellHistoryEntry",0,["command","directory","exitCode","stdout","stderr"],[[()=>F,0],[()=>F,0],1,[()=>F,0],[()=>F,0]],1],uD=[3,"com.amazon.aws.codewhisperer","ShellState",0,["shellName","shellHistory"],[0,[()=>r7,0]],1],v1=[3,"com.amazon.aws.codewhisperer","Span",0,["start","end"],[1,1]],lD=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLink",0,["url","title","snippet"],[[()=>F,0],[()=>F,0],[()=>F,0]],2],_D=[3,"com.amazon.aws.codewhisperer","SupplementaryWebLinksEvent",0,["supplementaryWebLinks"],[[()=>cg,0]]],tg=[3,"com.amazon.aws.codewhisperer","TextDocument",0,["relativeFilePath","programmingLanguage","text","documentSymbols"],[[()=>F,0],()=>Z1,[()=>F,0],()=>og],1],wD=[3,"com.amazon.aws.codewhisperer","TextDocumentDiagnostic",0,["document","range","source","severity","message","code","codeDescription","tags","relatedInformation","data"],[[()=>tg,0],()=>Kh,[()=>F,0],0,[()=>F,0],[()=>F,0],[()=>HW,0],64,[()=>ZD,0],[()=>F,0]],5],AD=[3,"com.amazon.aws.codewhisperer","ToolInputSchema",0,["json"],[[()=>qh,0]]],ng=[3,"com.amazon.aws.codewhisperer","ToolResult",0,["toolUseId","content","status","toolName"],[0,[()=>e7,0],0,[()=>Ro,0]],2],MD=[3,"com.amazon.aws.codewhisperer","ToolResultEvent",0,["toolResult"],[[()=>ng,0]]],gD=[3,"com.amazon.aws.codewhisperer","ToolSpecification",0,["inputSchema","name","description"],[[()=>AD,0],[()=>Ro,0],[()=>LW,0]],2],dD=[3,"com.amazon.aws.codewhisperer","ToolUse",0,["toolUseId","name","input"],[0,[()=>Ro,0],[()=>qh,0]],3],ED=[3,"com.amazon.aws.codewhisperer","ToolUseEvent",0,["toolUseId","name","input","stop"],[0,[()=>Ro,0],[()=>F,0],2],2];var RD=[3,"com.amazon.aws.codewhisperer","UserInputMessage",0,["content","userInputMessageContext","userIntent","origin","images","documents","modelId","cachePoint","clientCacheConfig"],[[()=>F,0],[()=>bD,0],0,0,[()=>s7,0],[()=>vD,0],0,()=>Ch,()=>FW],1],bD=[3,"com.amazon.aws.codewhisperer","UserInputMessageContext",0,["editorState","shellState","gitState","envState","appStudioContext","diagnostic","consoleState","userSettings","additionalContext","toolResults","tools"],[[()=>KW,0],[()=>uD,0],[()=>pW,0],[()=>jW,0],[()=>yW,0],[()=>y7,0],[()=>WW,0],()=>TD,[()=>aD,0],[()=>o7,0],[()=>f7,0]]],TD=[3,"com.amazon.aws.codewhisperer","UserSettings",0,["hasConsentedToCrossRegionCalls"],[2]];var SD=[3,"com.amazon.aws.codewhisperer.internal","TokenUsage",0,["uncachedInputTokens","outputTokens","totalTokens","cacheReadInputTokens","cacheWriteInputTokens","contextUsagePercentage","normalizedTokenUsage"],[1,1,1,1,1,1,1],3];var $D=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseRequest",0,["conversationState","profileArn","agentMode","additionalModelRequestFields"],[[()=>mW,0],0,[0,{["httpHeader"]:"x-amzn-kiro-agent-mode"}],15],1],UD=[3,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponseResponse",0,["conversationId","generateAssistantResponseResponse"],[[0,{["httpHeader"]:"x-amzn-codewhisperer-conversation-id"}],[()=>U7,16]],2];var LD=[3,"com.amazon.aws.q","InteractionComponentsEvent",0,["interactionComponentEntries"],[[()=>w7,0]],1],Vh=[3,"com.amazon.aws.q.interactioncomponents","Action",0,["webLink","moduleLink"],[[()=>jD,0],[()=>WD,0]]],jh=[3,"com.amazon.aws.q.interactioncomponents","Alert",0,["type","content"],[0,[()=>u7,0]],2],ID=[3,"com.amazon.aws.q.interactioncomponents","AlertComponent",0,["text"],[[()=>Ar,0]]],yD=[3,"com.amazon.aws.q.interactioncomponents","Clarification",0,["questions","dismissible"],[[()=>_7,0],2],1],OD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOption",0,["label","value"],[[()=>j,0],[()=>j,0]],2],GD=[3,"com.amazon.aws.q.interactioncomponents","ClarificationQuestion",0,["question","options","allowCustom","skippable"],[[()=>j,0],[()=>l7,0],2,2],2],BD=[3,"com.amazon.aws.q.interactioncomponents","CloudWatchTroubleshootingLink",0,["label","investigationPayload","defaultText"],[[()=>j,0],[()=>j,0],[()=>j,0]],2],sg=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdate",0,["transition"],[[()=>FD,0]]],FD=[3,"com.amazon.aws.q.interactioncomponents","InfrastructureUpdateTransition",0,["currentState","nextState"],[[()=>j,0],[()=>j,0]],2],HD=[3,"com.amazon.aws.q.interactioncomponents","InlineArtifact",0,["dsl","summary","title","artifactLabel"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],4],PD=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponent",0,["text","alert","infrastructureUpdate","progress","step","taskDetails","taskReference","suggestions","section","resource","resourceList","action","clarification","inlineArtifact"],[[()=>Ar,0],[()=>jh,0],[()=>sg,0],[()=>ig,0],[()=>eg,0],[()=>CD,0],()=>VD,[()=>kD,0],[()=>mD,0],[()=>ah,0],[()=>rg,0],[()=>Vh,0],[()=>yD,0],[()=>HD,0]]],ND=[3,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntry",0,["interactionComponent","interactionComponentId"],[[()=>PD,0],0],1],WD=[3,"com.amazon.aws.q.interactioncomponents","ModuleLink",0,["cloudWatchTroubleshootingLink"],[[()=>BD,0]]],ig=[3,"com.amazon.aws.q.interactioncomponents","Progress",0,["content"],[[()=>A7,0]],1],DD=[3,"com.amazon.aws.q.interactioncomponents","ProgressComponent",0,["step"],[[()=>eg,0]]],ah=[3,"com.amazon.aws.q.interactioncomponents","Resource",0,["title","link","description","type","ARN","resourceJsonString"],[[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0],[()=>j,0]],6],rg=[3,"com.amazon.aws.q.interactioncomponents","ResourceList",0,["items","action"],[[()=>M7,0],[()=>Vh,0]],1],mD=[3,"com.amazon.aws.q.interactioncomponents","Section",0,["title","content","action"],[[()=>j,0],[()=>g7,0],[()=>Vh,0]],2],YD=[3,"com.amazon.aws.q.interactioncomponents","SectionComponent",0,["text","alert","resource","resourceList"],[[()=>Ar,0],[()=>jh,0],[()=>ah,0],[()=>rg,0]]],eg=[3,"com.amazon.aws.q.interactioncomponents","Step",0,["id","state","label","content"],[1,0,[()=>j,0],[()=>d7,0]],3],QD=[3,"com.amazon.aws.q.interactioncomponents","StepComponent",0,["text"],[[()=>Ar,0]]],JD=[3,"com.amazon.aws.q.interactioncomponents","Suggestion",0,["value"],[[()=>j,0]],1],kD=[3,"com.amazon.aws.q.interactioncomponents","Suggestions",0,["items"],[[()=>E7,0]],1],zD=[3,"com.amazon.aws.q.interactioncomponents","TaskAction",0,["label","payload","note","primary","disabled","confirmation"],[[()=>j,0],[()=>$7,0],[()=>xD,0],2,2,[()=>XD,0]],2],XD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionConfirmation",0,["content"],[[()=>j,0]]],xD=[3,"com.amazon.aws.q.interactioncomponents","TaskActionNote",0,["content","type"],[[()=>j,0],0],1],qD=[3,"com.amazon.aws.q.interactioncomponents","TaskComponent",0,["text","infrastructureUpdate","alert","progress"],[[()=>Ar,0],[()=>sg,0],[()=>jh,0],[()=>ig,0]]],CD=[3,"com.amazon.aws.q.interactioncomponents","TaskDetails",0,["overview","content","actions"],[[()=>KD,0],[()=>b7,0],[()=>R7,0]],2],KD=[3,"com.amazon.aws.q.interactioncomponents","TaskOverview",0,["label","description"],[[()=>j,0],[()=>j,0]],2],VD=[3,"com.amazon.aws.q.interactioncomponents","TaskReference",0,["taskId"],[0],1],Ar=[3,"com.amazon.aws.q.interactioncomponents","Text",0,["content"],[[()=>j,0]],1],jD=[3,"com.amazon.aws.q.interactioncomponents","WebLink",0,["label","url"],[[()=>j,0],[()=>j,0]],2];var aD=[1,"com.amazon.aws.codewhisperer","AdditionalContentList",0,[()=>IW,0]],pD=[1,"com.amazon.aws.codewhisperer","ChatHistory",0,[()=>hg,0]],ZD=[1,"com.amazon.aws.codewhisperer","DiagnosticRelatedInformationList",0,[()=>QW,0]];var vD=[1,"com.amazon.aws.codewhisperer","DocumentBlocks",0,[()=>JW,0]],t7=[1,"com.amazon.aws.codewhisperer","DocumentCitationSourceContents",0,[()=>XW,0]],og=[1,"com.amazon.aws.codewhisperer","DocumentSymbols",0,()=>qW],n7=[1,"com.amazon.aws.codewhisperer","EnvironmentVariables",0,[()=>VW,0]],s7=[1,"com.amazon.aws.codewhisperer","ImageBlocks",0,[()=>ZW,0]],fg=[1,"com.amazon.aws.codewhisperer","References",0,()=>oD],i7=[1,"com.amazon.aws.codewhisperer","RelevantDocumentList",0,[()=>fD,0]],r7=[1,"com.amazon.aws.codewhisperer","ShellHistory",0,[()=>hD,0]],cg=[1,"com.amazon.aws.codewhisperer","SupplementaryWebLinks",0,[()=>lD,0]],e7=[1,"com.amazon.aws.codewhisperer","ToolResultContent",0,[()=>N7,0]],o7=[1,"com.amazon.aws.codewhisperer","ToolResults",0,[()=>ng,0]],f7=[1,"com.amazon.aws.codewhisperer","Tools",0,[()=>P7,0]],c7=[1,"com.amazon.aws.codewhisperer","ToolUses",0,[()=>dD,0]],h7=[1,"com.amazon.aws.codewhisperer","WorkspaceFolderList",0,[()=>F,0]],u7=[1,"com.amazon.aws.q.interactioncomponents","AlertComponentList",0,[()=>ID,0]],l7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationAnswerOptionsList",0,[()=>OD,0]],_7=[1,"com.amazon.aws.q.interactioncomponents","ClarificationQuestionList",0,[()=>GD,0]],w7=[1,"com.amazon.aws.q.interactioncomponents","InteractionComponentEntryList",0,[()=>ND,0]],A7=[1,"com.amazon.aws.q.interactioncomponents","ProgressComponentList",0,[()=>DD,0]],M7=[1,"com.amazon.aws.q.interactioncomponents","Resources",0,[()=>ah,0]],g7=[1,"com.amazon.aws.q.interactioncomponents","SectionComponentList",0,[()=>YD,0]],d7=[1,"com.amazon.aws.q.interactioncomponents","StepComponentList",0,[()=>QD,0]],E7=[1,"com.amazon.aws.q.interactioncomponents","SuggestionList",0,[()=>JD,0]],R7=[1,"com.amazon.aws.q.interactioncomponents","TaskActionList",0,[()=>zD,0]],b7=[1,"com.amazon.aws.q.interactioncomponents","TaskComponentList",0,[()=>qD,0]],T7=[2,"com.amazon.aws.codewhisperer","IntentData",8,0,()=>F7],S7=[2,"com.amazon.aws.codewhisperer","IntentMap",0,[0,0],[()=>T7,0]],$7=[2,"com.amazon.aws.q.interactioncomponents","TaskActionPayload",0,[0,0],[()=>j,0]],hg=[4,"com.amazon.aws.codewhisperer","ChatMessage",0,["userInputMessage","assistantResponseMessage"],[[()=>RD,0],[()=>GW,0]]],U7=[4,"com.amazon.aws.codewhisperer","ChatResponseStream",{["streaming"]:1},["messageMetadataEvent","assistantResponseEvent","reasoningContentEvent","dryRunSucceedEvent","codeReferenceEvent","supplementaryWebLinksEvent","followupPromptEvent","codeEvent","intentsEvent","interactionComponentsEvent","toolUseEvent","toolResultEvent","metadataEvent","meteringEvent","contextUsageEvent","citationEvent","documentCitationEvent","invalidStateEvent","error"],[()=>nD,[()=>OW,0],[()=>rD,0],()=>CW,()=>NW,[()=>_D,0],[()=>aW,0],[()=>PW,0],[()=>vW,0],[()=>LD,0],[()=>ED,0],[()=>MD,0],()=>sD,()=>iD,()=>DW,[()=>BW,0],[()=>kW,0],()=>tD,[()=>j1,0]]],L7=[4,"com.amazon.aws.codewhisperer","CitationTarget",0,["location","range"],[1,()=>v1]],I7=[4,"com.amazon.aws.codewhisperer","CursorState",0,["position","range"],[()=>Xh,()=>Kh]],y7=[4,"com.amazon.aws.codewhisperer","Diagnostic",0,["textDocumentDiagnostic","runtimeDiagnostic"],[[()=>wD,0],[()=>cD,0]]],O7=[4,"com.amazon.aws.codewhisperer","DocumentCitationLocation",0,["documentPage","documentChar","documentChunk","searchResult","web"],[()=>zh,()=>zh,()=>zh,()=>zW,[()=>xW,0]]],G7=[4,"com.amazon.aws.codewhisperer","DocumentSource",8,["bytes"],[21]];var B7=[4,"com.amazon.aws.codewhisperer","ImageSource",8,["bytes"],[21]],F7=[4,"com.amazon.aws.codewhisperer","IntentDataType",0,["string"],[0]],H7=[4,"com.amazon.aws.codewhisperer","ReasoningContent",8,["reasoningText","redactedContent"],[[()=>eD,0],21]];var P7=[4,"com.amazon.aws.codewhisperer","Tool",0,["toolSpecification","cachePoint"],[[()=>gD,0],()=>Ch]],N7=[4,"com.amazon.aws.codewhisperer","ToolResultContentBlock",0,["text","json"],[[()=>F,0],[()=>qh,0]]];var ug=[9,"com.amazon.aws.codewhisperer.streaming","GenerateAssistantResponse",{["http"]:["POST","/generateAssistantResponse",200]},()=>$D,()=>UD];var wg=(t)=>{return{apiVersion:"2023-11-27",base64Decoder:t?.base64Decoder??hi.fromBase64,base64Encoder:t?.base64Encoder??hi.toBase64,disableHostPrefix:t?.disableHostPrefix??!1,endpointProvider:t?.endpointProvider??K1,extensions:t?.extensions??[],httpAuthSchemeProvider:t?.httpAuthSchemeProvider??MA,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(n)=>n.getIdentityProvider("smithy.api#httpBearerAuth"),signer:new _g.HttpBearerAuthSigner}],logger:t?.logger??new X.NoOpLogger,protocol:t?.protocol??lg.AwsRestJsonProtocol,protocolSettings:t?.protocolSettings??{defaultNamespace:"com.amazon.aws.codewhisperer.streaming",errorTypeRegistries:a1,version:"2023-11-27",serviceTarget:"AmazonCodeWhispererStreamingService"},serviceId:t?.serviceId??"CodeWhispererStreaming",urlParser:t?.urlParser??Qh.parseUrl,utf8Decoder:t?.utf8Decoder??gs.fromUtf8,utf8Encoder:t?.utf8Encoder??gs.toUtf8}};var dg=(t)=>{X.emitWarningIfUnsupportedVersion(process.version);let n=Yh.resolveDefaultsModeConfig(t),s=()=>n().then(X.loadConfigsForDefaultMode),i=wg(t);Ag.emitWarningIfUnsupportedVersion(process.version);let r={profile:t?.profile,logger:i.logger};return{...i,...t,runtime:"node",defaultsMode:n,authSchemePreference:t?.authSchemePreference??Ln.loadConfig(Mg.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,r),bodyLengthChecker:t?.bodyLengthChecker??mh.calculateBodyLength,defaultUserAgentProvider:t?.defaultUserAgentProvider??ln.createDefaultUserAgentProvider({serviceId:i.serviceId,clientVersion:RA.version}),eventStreamSerdeProvider:t?.eventStreamSerdeProvider??oo.eventStreamSerdeProvider,httpAuthSchemes:t?.httpAuthSchemes??[{schemeId:"smithy.api#httpBearerAuth",identityProvider:(e)=>e.getIdentityProvider("smithy.api#httpBearerAuth")||(async(f)=>{return await Wh(f)(f)}),signer:new gg.HttpBearerAuthSigner}],maxAttempts:t?.maxAttempts??Ln.loadConfig(v.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,t),region:t?.region??Ln.loadConfig(p.NODE_REGION_CONFIG_OPTIONS,{...p.NODE_REGION_CONFIG_FILE_OPTIONS,...r}),requestHandler:bo.NodeHttpHandler.create(t?.requestHandler??s),retryMode:t?.retryMode??Ln.loadConfig({...v.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await s()).retryMode||ht.DEFAULT_RETRY_MODE},t),sha256:t?.sha256??Dh.Hash.bind(null,"sha256"),streamCollector:t?.streamCollector??bo.streamCollector,useDualstackEndpoint:t?.useDualstackEndpoint??Ln.loadConfig(p.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,r),useFipsEndpoint:t?.useFipsEndpoint??Ln.loadConfig(p.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,r),userAgentAppId:t?.userAgentAppId??Ln.loadConfig(ln.NODE_APP_ID_CONFIG_OPTIONS,r)}};var Pt=m(xt(),1);var Gt=m(Ut(),1);var Eg=(t)=>{let{httpAuthSchemes:n,httpAuthSchemeProvider:s,token:i}=t;return{setHttpAuthScheme(r){let e=n.findIndex((f)=>f.schemeId===r.schemeId);if(e===-1)n.push(r);else n.splice(e,1,r)},httpAuthSchemes(){return n},setHttpAuthSchemeProvider(r){s=r},httpAuthSchemeProvider(){return s},setToken(r){i=r},token(){return i}}},Rg=(t)=>{return{httpAuthSchemes:t.httpAuthSchemes(),httpAuthSchemeProvider:t.httpAuthSchemeProvider(),token:t.token()}};var bg=(t,n)=>{let s=Object.assign(Pt.getAwsRegionExtensionConfiguration(t),X.getDefaultExtensionConfiguration(t),Gt.getHttpHandlerExtensionConfiguration(t),Eg(t));return n.forEach((i)=>i.configure(s)),Object.assign(t,Pt.resolveAwsRegionExtensionConfiguration(s),X.resolveDefaultRuntimeConfig(s),Gt.resolveHttpHandlerRuntimeConfig(s),Rg(s))};class ph extends X.Client{config;constructor(...[t]){let n=dg(t||{});super(n);this.initConfig=n;let s=dA(n),i=Un.resolveUserAgentConfig(s),r=v.resolveRetryConfig(i),e=p.resolveRegionConfig(r),f=zn.resolveHostHeaderConfig(e),o=Nt.resolveEndpointConfig(f),c=Ht.resolveDefaultAwsRegionalEndpointsConfig(o),h=Dc.resolveEventStreamSerdeConfig(c),u=gA(h),l=bg(u,t?.extensions||[]);this.config=l,this.middlewareStack.use(Tg.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(Un.getUserAgentPlugin(this.config)),this.middlewareStack.use(v.getRetryPlugin(this.config)),this.middlewareStack.use(ir.getContentLengthPlugin(this.config)),this.middlewareStack.use(zn.getHostHeaderPlugin(this.config)),this.middlewareStack.use(nr.getLoggerPlugin(this.config)),this.middlewareStack.use(sr.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(li.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:AA,identityProviderConfigProvider:async(_)=>new li.DefaultIdentityProviderConfig({"smithy.api#httpBearerAuth":_.token})})),this.middlewareStack.use(li.getHttpSigningPlugin(this.config))}destroy(){super.destroy()}}class Zh extends X.Command.classBuilder().ep(EA).m(function(t,n,s,i){return[Nt.getEndpointPlugin(s,t.getEndpointParameterInstructions())]}).s("AmazonCodeWhispererStreamingService","GenerateAssistantResponse",{eventStream:{output:!0}}).n("CodeWhispererStreamingClient","GenerateAssistantResponseCommand").sc(ug).build(){}function Sg(t){let n=Oi[t];if(!n)throw Error(`Unsupported model: ${t}. Supported models: ${nu.join(", ")}`);return n}var $g=new Set(["claude-opus-4-8","claude-opus-4-7","claude-sonnet-5","claude-sonnet-4-6","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),Ug=["low","medium","high","xhigh","max"];function To(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let i=t.slice(0,-s.length);if($g.has(i))return{wireId:Sg(i),effort:n}}}return{wireId:Sg(t),effort:void 0}}function W7(t){for(let n of Ug){let s=`-${n}`;if(t.endsWith(s)){let i=t.slice(0,-s.length);if($g.has(i))return i}}if(t.endsWith("-thinking")){let n=t.slice(0,-9);if(Oi[n])return n}return t}function Lg(t){return B(W7(t))}var D7=["low","medium","high","xhigh","max"];function m7(t){return typeof t==="string"&&D7.some((n)=>n===t)}var Ig=new Set(["gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"]),yg=new Set(["claude-opus-4.7","claude-opus-4.8","claude-sonnet-5",...Ig]),Y7=new Set(["claude-opus-4.5","claude-opus-4.6","claude-opus-4.6-1m","claude-sonnet-4.5","claude-sonnet-4.5-1m","claude-sonnet-4.6","claude-sonnet-4.6-1m",...yg]);function So(t){return Y7.has(t)}function Q7(t){return yg.has(t)}function Og(t,n){if(Ig.has(t))return{reasoning:{effort:n}};return{output_config:{effort:n}}}function J7(t,n){if(!So(t))return;if(n==="xhigh"&&!Q7(t))return"max";return n}function k7(t,n){if(!So(n))return;let s;if(t<=1e4)s="low";else if(t<=20000)s="medium";else if(t<=28000)s="high";else s="max";return s}function Gg(t){let n;if(So(t.model))n={wireId:t.model,effort:void 0};else try{n=To(t.model)}catch(i){if(i instanceof Error&&i.message.startsWith("Unsupported model:"))return;throw i}if(!So(n.wireId))return;let s=[n.effort,t.reasoningEffort,t.configEffort];for(let i of s)if(m7(i))return J7(n.wireId,i);if(!t.think)return;if(t.autoEffortMapping??!0)return k7(t.budget,n.wireId);return"medium"}import{randomUUID as K7}from"crypto";function Mr(t){return typeof t==="object"&&t!==null}function z7(t){let n=atob(t),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s}function X7(t){let n=[];for(let s of t){if(!Mr(s)||s.type!=="image"||!Mr(s.source))continue;let i=s.source;if(i.type!=="base64"||typeof i.data!=="string")continue;n.push({mediaType:typeof i.media_type==="string"?i.media_type:"image/jpeg",data:i.data})}return n}function x7(t){let n=[];for(let s of t){if(!Mr(s)||s.type!=="image_url"||!Mr(s.image_url))continue;let i=s.image_url.url;if(typeof i!=="string"||!i.startsWith("data:"))continue;let[r="",e]=i.split(",",2);if(!e)continue;let f=r.split(";")[0]?.replace("data:","");n.push({mediaType:f||"image/jpeg",data:e})}return n}function $o(t){if(!Array.isArray(t))return[];return[...X7(t),...x7(t)]}function Uo(t){let n=[],s=0;for(let i of t){if(n.length>=4)break;if(s+i.data.length>3750000)break;n.push(i),s+=i.data.length}return{images:n.map((i)=>({format:i.mediaType.split("/")[1]||"png",source:{bytes:z7(i.data)}})),omitted:t.length-n.length}}function Lo(t){let n=[];for(let s of t){if(!Mr(s))continue;if(typeof s.text==="string")n.push(s.text);else if(s.type==="text"&&s.text)n.push(String(s.text))}return n.join("")}function vh(t){return typeof t==="object"&&t!==null}function Bg(t,n){for(let s of t){if(s.role!=="assistant")continue;if(s.tool_calls){for(let i of s.tool_calls)if(i.id===n)return i}if(Array.isArray(s.content)){for(let i of s.content)if(vh(i)&&i.type==="tool_use"&&i.id===n)return i}}return null}function Fg(t){let n=[];for(let s of t){if(n.length===0){n.push({...s});continue}let i=n[n.length-1];if(!i||s.role!==i.role){n.push({...s});continue}if(Array.isArray(i.content)&&Array.isArray(s.content))i.content.push(...s.content);else if(typeof i.content==="string"&&typeof s.content==="string")i.content+=`
109
+ ${s.content}`;else if(Array.isArray(i.content)&&typeof s.content==="string")i.content.push({type:"text",text:s.content});else if(typeof i.content==="string"&&Array.isArray(s.content))i.content=[{type:"text",text:i.content},...s.content];if(s.tool_calls){if(!i.tool_calls)i.tool_calls=[];i.tool_calls.push(...s.tool_calls)}if(s.role==="tool"){if(!i.tool_results)i.tool_results=[{content:i.content,tool_call_id:i.tool_call_id}];i.tool_results.push({content:s.content,tool_call_id:s.tool_call_id})}}return n}function Bt(t){if(t===null||t===void 0)return"";if(typeof t==="string")return t;if(!vh(t))return"";if(typeof t.content==="string")return t.content;if(Array.isArray(t.content))return t.content.filter((n)=>vh(n)&&n.type==="text").map((n)=>typeof n.text==="string"?n.text:"").join("");return typeof t.text==="string"?t.text:""}function Hg(t){return t.map((n)=>({toolSpecification:{name:n.name||n.function?.name,description:(n.description||n.function?.description||"").substring(0,9216),inputSchema:{json:n.input_schema||n.function?.parameters||{}}}}))}function gr(t){let n=[],s=new Set;for(let i of t)if(!s.has(i.toolUseId))s.add(i.toolUseId),n.push(i);return n}function Pg(t){return typeof t==="object"&&t!==null}function q7(t){let n=t.function?.arguments;return{input:typeof n==="string"?JSON.parse(n):n,name:t.function?.name??"",toolUseId:t.id??""}}function C7(t){if(t.length<4)return t;let n=[],s=0;while(s<t.length){let i=t[s];if(i?.assistantResponseMessage?.toolUses&&s+1<t.length&&t[s+1]?.userInputMessage?.userInputMessageContext?.toolResults){let r=s,e=s;while(e<t.length){let o=t[e],c=e+1<t.length?t[e+1]:void 0;if(!o?.assistantResponseMessage?.toolUses||!c?.userInputMessage?.userInputMessageContext?.toolResults)break;e+=2}let f=(e-r)/2;for(let o=r;o<e;o+=2){let c=t[o],h=t[o+1];if(!c||!h)continue;if(f>1&&o!==r){let u=c.assistantResponseMessage?.content.match(/^<thinking>[\s\S]*?<\/thinking>/)?.[0];n.push({assistantResponseMessage:{content:u?`${u}
110
110
 
111
- [system: tool calling continues]`:"[system: tool calling continues]",toolUses:c.assistantResponseMessage?.toolUses}})}else n.push(c);n.push(h)}s=e}else{if(r)n.push(r);s++}}return n}function Ng(t,n){let s=[];for(let r=0;r<t.length-1;r++){let i=t[r];if(!i)continue;if(i.role==="user"){let h={content:"",modelId:n,origin:ot.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(i.content)){h.content=Lo(i.content);for(let l of i.content){if(!Pg(l)||l.type!=="tool_result"||typeof l.tool_use_id!=="string")continue;u.push({content:[{text:Bt(l.content??l)}],status:"success",toolUseId:l.tool_use_id})}let _=$o(i.content);if(_.length>0){let l=Uo(_);if(h.images=l.images,l.omitted>0)h.content+=`
111
+ [system: tool calling continues]`:"[system: tool calling continues]",toolUses:c.assistantResponseMessage?.toolUses}})}else n.push(c);n.push(h)}s=e}else{if(i)n.push(i);s++}}return n}function Ng(t,n){let s=[];for(let i=0;i<t.length-1;i++){let r=t[i];if(!r)continue;if(r.role==="user"){let h={content:"",modelId:n,origin:ot.ORIGIN_AI_EDITOR},u=[];if(Array.isArray(r.content)){h.content=Lo(r.content);for(let _ of r.content){if(!Pg(_)||_.type!=="tool_result"||typeof _.tool_use_id!=="string")continue;u.push({content:[{text:Bt(_.content??_)}],status:"success",toolUseId:_.tool_use_id})}let l=$o(r.content);if(l.length>0){let _=Uo(l);if(h.images=_.images,_.omitted>0)h.content+=`
112
112
 
113
- [${l.omitted} image(s) omitted due to API limits]`}}else h.content=Bt(i);if(u.length>0)h.userInputMessageContext={toolResults:gi(u)};if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:h});continue}if(i.role==="tool"){let h=[];if(i.tool_results)for(let u of i.tool_results){if(!u.tool_call_id)continue;h.push({content:[{text:Bt(u)}],status:"success",toolUseId:u.tool_call_id})}else if(i.tool_call_id)h.push({content:[{text:Bt(i)}],status:"success",toolUseId:i.tool_call_id});if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:{content:"Tool results provided.",modelId:n,origin:ot.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:gi(h)}}});continue}if(i.role!=="assistant")continue;let e={content:""},f=[],o="";if(Array.isArray(i.content))for(let h of i.content){if(!Pg(h))continue;if(h.type==="text")e.content+=typeof h.text==="string"?h.text:"";else if(h.type==="thinking")o+=typeof h.thinking==="string"?h.thinking:typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else e.content=Bt(i);if(i.tool_calls)for(let h of i.tool_calls)f.push(q7(h));if(o){let h=o.replaceAll("</thinking>","<\\/thinking>");e.content=e.content?`<thinking>${h}</thinking>
113
+ [${_.omitted} image(s) omitted due to API limits]`}}else h.content=Bt(r);if(u.length>0)h.userInputMessageContext={toolResults:gr(u)};if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:h});continue}if(r.role==="tool"){let h=[];if(r.tool_results)for(let u of r.tool_results){if(!u.tool_call_id)continue;h.push({content:[{text:Bt(u)}],status:"success",toolUseId:u.tool_call_id})}else if(r.tool_call_id)h.push({content:[{text:Bt(r)}],status:"success",toolUseId:r.tool_call_id});if(s[s.length-1]?.userInputMessage)s.push({assistantResponseMessage:{content:"[system: conversation continues]"}});s.push({userInputMessage:{content:"Tool results provided.",modelId:n,origin:ot.ORIGIN_AI_EDITOR,userInputMessageContext:{toolResults:gr(h)}}});continue}if(r.role!=="assistant")continue;let e={content:""},f=[],o="";if(Array.isArray(r.content))for(let h of r.content){if(!Pg(h))continue;if(h.type==="text")e.content+=typeof h.text==="string"?h.text:"";else if(h.type==="thinking")o+=typeof h.thinking==="string"?h.thinking:typeof h.text==="string"?h.text:"";else if(h.type==="tool_use"&&typeof h.id==="string"&&typeof h.name==="string")f.push({input:h.input,name:h.name,toolUseId:h.id})}else e.content=Bt(r);if(r.tool_calls)for(let h of r.tool_calls)f.push(q7(h));if(o){let h=o.replaceAll("</thinking>","<\\/thinking>");e.content=e.content?`<thinking>${h}</thinking>
114
114
 
115
115
  ${e.content}`:`<thinking>${h}</thinking>`}if(f.length>0)e.toolUses=f;if(!e.content&&!e.toolUses)continue;let c=s[s.length-1]?.assistantResponseMessage;if(c){if(e.content)c.content=c.content?`${c.content}
116
116
 
117
- ${e.content}`:e.content;if(e.toolUses)c.toolUses=[...c.toolUses??[],...e.toolUses]}else s.push({assistantResponseMessage:e})}return C7(s)}function Wg(t,n,s){if(!n)return t;let r=t.find((i)=>i.userInputMessage);if(r?.userInputMessage)r.userInputMessage.content=`${n}
117
+ ${e.content}`:e.content;if(e.toolUses)c.toolUses=[...c.toolUses??[],...e.toolUses]}else s.push({assistantResponseMessage:e})}return C7(s)}function Wg(t,n,s){if(!n)return t;let i=t.find((r)=>r.userInputMessage);if(i?.userInputMessage)i.userInputMessage.content=`${n}
118
118
 
119
- ${r.userInputMessage.content||""}`;else t.unshift({userInputMessage:{content:n,modelId:s,origin:ot.ORIGIN_AI_EDITOR}});return t}function Dg(t){return t.some((n)=>Boolean(n.assistantResponseMessage?.toolUses)||Boolean(n.userInputMessage?.userInputMessageContext?.toolResults))}function Yg(t){let n=new Set;for(let s of t)for(let r of s.assistantResponseMessage?.toolUses??[])if(r.name)n.add(r.name);return n}function wn(t){return typeof t==="object"&&t!==null}function V7(t){return wn(t)}function j7(t){return wn(t)}function a7(t){let n=typeof t==="string"?JSON.parse(t):t;if(!wn(n))return{messages:[],tools:[],system:""};return{messages:Array.isArray(n.messages)?n.messages.filter(V7):[],tools:Array.isArray(n.tools)?n.tools.filter(j7):[],system:typeof n.system==="string"?n.system:""}}function p7(t){if(Array.isArray(t))return"array";if(t===null)return"string";let n=typeof t;return n==="number"||n==="boolean"||n==="string"||n==="object"?n:"string"}function Z7(t,n){let s=n?.find((e)=>e.name===t&&wn(e.input)),r={};if(s&&wn(s.input))for(let[e,f]of Object.entries(s.input))r[e]={type:p7(f)};let i=Object.keys(r).length>0?{type:"object",properties:r}:{type:"object"};return{toolSpecification:{name:t,description:`Tool ${t}`,inputSchema:{json:i}}}}function v7(t,n){let s={content:""},r=[],i="";if(Array.isArray(n.content))for(let e of n.content){if(!wn(e))continue;if(e.type==="text"&&typeof e.text==="string")s.content+=e.text;else if(e.type==="thinking")i+=typeof e.thinking==="string"?e.thinking:typeof e.text==="string"?e.text:"";else if(e.type==="tool_use"&&typeof e.id==="string"&&typeof e.name==="string")r.push({input:e.input,name:e.name,toolUseId:e.id})}else s.content=Bt(n);for(let e of n.tool_calls??[]){if(typeof e.id!=="string"||typeof e.function?.name!=="string")continue;let f=e.function.arguments;r.push({input:typeof f==="string"?JSON.parse(f):f,name:e.function.name,toolUseId:e.id})}if(i){let e=i.replaceAll("</thinking>","<\\/thinking>");s.content=s.content?`<thinking>${e}</thinking>
119
+ ${i.userInputMessage.content||""}`;else t.unshift({userInputMessage:{content:n,modelId:s,origin:ot.ORIGIN_AI_EDITOR}});return t}function Dg(t){return t.some((n)=>Boolean(n.assistantResponseMessage?.toolUses)||Boolean(n.userInputMessage?.userInputMessageContext?.toolResults))}function mg(t){let n=new Set;for(let s of t)for(let i of s.assistantResponseMessage?.toolUses??[])if(i.name)n.add(i.name);return n}function wn(t){return typeof t==="object"&&t!==null}function V7(t){return wn(t)}function j7(t){return wn(t)}function a7(t){let n=typeof t==="string"?JSON.parse(t):t;if(!wn(n))return{messages:[],tools:[],system:""};return{messages:Array.isArray(n.messages)?n.messages.filter(V7):[],tools:Array.isArray(n.tools)?n.tools.filter(j7):[],system:typeof n.system==="string"?n.system:""}}function p7(t){if(Array.isArray(t))return"array";if(t===null)return"string";let n=typeof t;return n==="number"||n==="boolean"||n==="string"||n==="object"?n:"string"}function Z7(t,n){let s=n?.find((e)=>e.name===t&&wn(e.input)),i={};if(s&&wn(s.input))for(let[e,f]of Object.entries(s.input))i[e]={type:p7(f)};let r=Object.keys(i).length>0?{type:"object",properties:i}:{type:"object"};return{toolSpecification:{name:t,description:`Tool ${t}`,inputSchema:{json:r}}}}function v7(t,n){let s={content:""},i=[],r="";if(Array.isArray(n.content))for(let e of n.content){if(!wn(e))continue;if(e.type==="text"&&typeof e.text==="string")s.content+=e.text;else if(e.type==="thinking")r+=typeof e.thinking==="string"?e.thinking:typeof e.text==="string"?e.text:"";else if(e.type==="tool_use"&&typeof e.id==="string"&&typeof e.name==="string")i.push({input:e.input,name:e.name,toolUseId:e.id})}else s.content=Bt(n);for(let e of n.tool_calls??[]){if(typeof e.id!=="string"||typeof e.function?.name!=="string")continue;let f=e.function.arguments;i.push({input:typeof f==="string"?JSON.parse(f):f,name:e.function.name,toolUseId:e.id})}if(r){let e=r.replaceAll("</thinking>","<\\/thinking>");s.content=s.content?`<thinking>${e}</thinking>
120
120
 
121
- ${s.content}`:`<thinking>${e}</thinking>`}if(r.length>0)s.toolUses=r;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function t9(t){let n="",s=[],r=[];if(t.role==="tool"){let i=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let e of i){if(typeof e.tool_call_id!=="string")continue;s.push({content:[{text:Bt(e)}],status:"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(t.content)){n=Lo(t.content);for(let e of t.content){if(!wn(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;s.push({content:[{text:Bt(e.content??e)}],status:"success",toolUseId:e.tool_use_id})}let i=Uo($o(t.content));if(r.push(...i.images),i.omitted>0)n+=`
121
+ ${s.content}`:`<thinking>${e}</thinking>`}if(i.length>0)s.toolUses=i;if(s.content||s.toolUses)t.push({assistantResponseMessage:s})}function t9(t){let n="",s=[],i=[];if(t.role==="tool"){let r=t.tool_results??[{content:t.content,tool_call_id:t.tool_call_id}];for(let e of r){if(typeof e.tool_call_id!=="string")continue;s.push({content:[{text:Bt(e)}],status:"success",toolUseId:e.tool_call_id})}}else if(Array.isArray(t.content)){n=Lo(t.content);for(let e of t.content){if(!wn(e)||e.type!=="tool_result"||typeof e.tool_use_id!=="string")continue;s.push({content:[{text:Bt(e.content??e)}],status:"success",toolUseId:e.tool_use_id})}let r=Uo($o(t.content));if(i.push(...r.images),r.omitted>0)n+=`
122
122
 
123
- [${i.omitted} image(s) omitted due to API limits]`}else n=Bt(t);if(!n)n=s.length>0?"Tool results provided.":"[system: conversation continues]";return{content:n,toolResults:s,images:r}}function n9(t,n){let s=Bg(t,n.toolUseId);if(!wn(s))return;let r=wn(s.function)?s.function:void 0,i=typeof s.name==="string"?s.name:typeof r?.name==="string"?r.name:"tool",e=s.input??r?.arguments;return{name:i,toolUseId:n.toolUseId,input:typeof e==="string"?JSON.parse(e):e??{}}}function mg(t,n,s,r=!1,i=20000){let e=a7(t);if(e.messages.length===0)throw Error("No messages");let{wireId:f,effort:o}=To(n),c=e.messages.filter((R)=>R.role==="system"),h=Fg(e.messages.filter((R)=>R.role!=="system")),u=e.system,_=c.map(Bt).join(`
123
+ [${r.omitted} image(s) omitted due to API limits]`}else n=Bt(t);if(!n)n=s.length>0?"Tool results provided.":"[system: conversation continues]";return{content:n,toolResults:s,images:i}}function n9(t,n){let s=Bg(t,n.toolUseId);if(!wn(s))return;let i=wn(s.function)?s.function:void 0,r=typeof s.name==="string"?s.name:typeof i?.name==="string"?i.name:"tool",e=s.input??i?.arguments;return{name:r,toolUseId:n.toolUseId,input:typeof e==="string"?JSON.parse(e):e??{}}}function Yg(t,n,s,i=!1,r=20000){let e=a7(t);if(e.messages.length===0)throw Error("No messages");let{wireId:f,effort:o}=To(n),c=e.messages.filter((R)=>R.role==="system"),h=Fg(e.messages.filter((R)=>R.role!=="system")),u=e.system,l=c.map(Bt).join(`
124
124
 
125
- `);if(_)u=u?`${u}
125
+ `);if(l)u=u?`${u}
126
126
 
127
- ${_}`:_;if(r&&!u.includes("<thinking_mode>")){let R=`<thinking_mode>enabled</thinking_mode><max_thinking_length>${i}</max_thinking_length>`;u=u?`${R}
128
- ${u}`:R}let l=h.at(-1);if(l?.role==="assistant"&&Bt(l)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Ng(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((R)=>wn(R)&&R.type==="tool_result")),E=h.at(-2);if(M&&E?.role==="assistant"&&A.at(-1)?.userInputMessage){let R=Bt(E);if(R)A.push({assistantResponseMessage:{content:R}})}A=Wg(A,u,f);let d="[system: conversation continues]",T=[],U=[];if(w.role==="assistant")v7(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let R=t9(w);d=R.content,T=R.toolResults,U=R.images}let S=A.flatMap((R)=>R.assistantResponseMessage?.toolUses??[]),O=new Set(S.map((R)=>R.toolUseId)),D=[],q=[];for(let R of T)if(O.has(R.toolUseId))D.push(R);else{let W=n9(e.messages,R);if(W)q.push({call:W,result:R});else d+=`
127
+ ${l}`:l;if(i&&!u.includes("<thinking_mode>")){let R=`<thinking_mode>enabled</thinking_mode><max_thinking_length>${r}</max_thinking_length>`;u=u?`${R}
128
+ ${u}`:R}let _=h.at(-1);if(_?.role==="assistant"&&Bt(_)==="{")h.pop();let w=h.at(-1);if(!w)throw Error("Empty");let A=Ng(h,f),M=w.role==="user"&&!(Array.isArray(w.content)&&w.content.some((R)=>wn(R)&&R.type==="tool_result")),d=h.at(-2);if(M&&d?.role==="assistant"&&A.at(-1)?.userInputMessage){let R=Bt(d);if(R)A.push({assistantResponseMessage:{content:R}})}A=Wg(A,u,f);let E="[system: conversation continues]",T=[],U=[];if(w.role==="assistant")v7(A,w);else{if(A.at(-1)&&!A.at(-1)?.assistantResponseMessage)A.push({assistantResponseMessage:{content:"[system: conversation continues]"}});let R=t9(w);E=R.content,T=R.toolResults,U=R.images}let S=A.flatMap((R)=>R.assistantResponseMessage?.toolUses??[]),y=new Set(S.map((R)=>R.toolUseId)),D=[],q=[];for(let R of T)if(y.has(R.toolUseId))D.push(R);else{let W=n9(e.messages,R);if(W)q.push({call:W,result:R});else E+=`
129
129
 
130
130
  [Output for tool call ${R.toolUseId}]:
131
- ${R.content[0]?.text??""}`}if(q.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:ot.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:q.map(({call:R})=>R)}}),D.push(...q.map(({result:R})=>R))}let tt={content:d,modelId:f,origin:ot.ORIGIN_AI_EDITOR};if(U.length>0)tt.images=U;let J=Hg(e.tools).filter((R)=>typeof R.toolSpecification.name==="string").map((R)=>({toolSpecification:{...R.toolSpecification,name:R.toolSpecification.name??""}}));if(D.length>0||J.length>0){if(tt.userInputMessageContext={},D.length>0)tt.userInputMessageContext.toolResults=gi(D);if(J.length>0)tt.userInputMessageContext.tools=J}if(Dg(A)){let R=tt.userInputMessageContext?.tools??[],W=new Set(R.map((st)=>st.toolSpecification.name)),k=[...Yg(A)].filter((st)=>!W.has(st));if(k.length>0)tt.userInputMessageContext??={},tt.userInputMessageContext.tools=[...R,...k.map((st)=>Z7(st,S))]}let G=K7(),K={conversationState:{chatTriggerType:ot.CHAT_TRIGGER_TYPE_MANUAL,conversationId:G,currentMessage:{userInputMessage:tt},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:K,resolved:f,convId:G}:{request:K,resolved:f,convId:G,variantEffort:o}}function s9(t){let n=typeof t==="string"?JSON.parse(t):t;if(typeof n!=="object"||n===null||!("reasoning_effort"in n))return;let s=n.reasoning_effort;return typeof s==="string"||s===null?s:void 0}function Qg(t,n,s,r=!1,i=20000,e){let{request:f,resolved:o,convId:c}=mg(t,n,s,r,i),h=Gg({model:n,think:r,budget:i,reasoningEffort:s9(t),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:tu(s.profileArn)??s.region,...h?{effort:h}:{}}}function Jg(t){return Math.ceil(t.length/4)}async function Io(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((r,i)=>{let e=()=>r({kind:"aborted"});n.addEventListener("abort",e,{once:!0}),s.then((f)=>{n.removeEventListener("abort",e),r({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",e),i(f)})})}function Ei(t,n){if(!n?.name||!n.toolUseId)return;let s=t.get(n.toolUseId);if(s){s.input+=n.input??"";return}t.set(n.toolUseId,{toolUseId:n.toolUseId,name:n.name,input:n.input??""})}function kg(t){let n=[],s=0;for(let r of t.values()){let i=r.input;try{i=JSON.stringify(JSON.parse(r.input))}catch{i=r.input}n.push({type:"content_block_start",index:s,content_block:{type:"tool_use",id:r.toolUseId,name:r.name,input:{}}},{type:"content_block_delta",index:s,delta:{type:"input_json_delta",partial_json:i}},{type:"content_block_stop",index:s}),s+=1}return n}function Oo(t,n){let s=n.metadataEvent?.tokenUsage;if(s)t.outputTokens=s.outputTokens??t.outputTokens,t.totalTokens=s.totalTokens??t.totalTokens,t.inputTokens=s.inputTokens??(s.uncachedInputTokens===void 0?t.inputTokens:s.uncachedInputTokens+(s.cacheReadInputTokens??0)+(s.cacheWriteInputTokens??0));t.contextUsagePercentage=n.contextUsageEvent?.contextUsagePercentage??n.metadataEvent?.contextUsagePercentage??s?.contextUsagePercentage??t.contextUsagePercentage}function yo(t,n,s){let r=t.outputTokens??Jg(n),i=t.inputTokens;if(i===void 0&&t.totalTokens!==void 0)i=Math.max(0,t.totalTokens-r);if(i===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let e=Math.round(Lg(s)*t.contextUsagePercentage/100);i=Math.max(0,e-r)}return{inputTokens:i??0,outputTokens:r}}class Xg extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function zg(t,n,s,r){let i=t.generateAssistantResponseResponse;if(!i)throw new Xg;let e=i[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,_=!1;try{while(!0){let A=await Io(e,r);if(A.kind==="aborted"){if(e.return)await e.return();_=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;Oo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",Ei(f,M.toolUseEvent)}}finally{if(!u&&!_&&e.return)await e.return()}let l=yo(o,c,n),w={role:"assistant",content:c,...h?{reasoning_content:h}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:s,object:"chat.completion",created:Math.floor(Date.now()/1000),model:n,choices:[{index:0,message:w,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:l.inputTokens,completion_tokens:l.outputTokens,total_tokens:l.inputTokens+l.outputTokens}}}var r9=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],i9=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function t0(t,n){let s=t[n];return typeof s==="string"?s:void 0}function e9(t){let n=t.$metadata;if(!Go(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function o9(t){let n=t.$response;if(!Go(n))return;let s=n.headers;if(!Go(s))return;let r={};for(let[i,e]of Object.entries(s))if(typeof e==="string")r[i]=e;else if(typeof e==="number")r[i]=String(e);return Object.keys(r).length>0?r:void 0}function n0(t){if(!Go(t))return{message:t instanceof Error?t.message:String(t)};let n=e9(t),s=t0(t,"message")??String(t),r=t0(t,"name"),i=t0(t,"reason"),e=o9(t);return{message:s,...n!==void 0?{status:n}:{},...r!==void 0?{code:r}:{},...i!==void 0?{reason:i}:{},...e!==void 0?{headers:e}:{}}}function f9(t){let n=Object.entries(t??{}).find(([r])=>r.toLowerCase()==="retry-after"),s=Number.parseInt(n?.[1]??"60",10);return Number.isFinite(s)&&s>=0?s*1000:60000}function c9(t){return r9.some((n)=>n.test(t))}function xg(t,n){if(t.reason==="INVALID_MODEL_ID"){let s=t.status??400;return{action:"fail",status:s,terminalStatus:s}}if(t.reason==="TEMPORARILY_SUSPENDED")return n.accountCount>1?{action:"switch",...t.status!==void 0?{status:t.status}:{}}:{action:"fail",...t.status!==void 0?{status:t.status}:{},terminalStatus:t.status??403};switch(t.status){case 400:return{action:"fail",status:400,terminalStatus:c9(t.message)?413:400};case 401:return n.retryCount<n.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(yi(t.message)){if(!n.forcedRefreshAccountIds.has(n.accountId))return n.forcedRefreshAccountIds.add(n.accountId),{action:"refresh-then-retry",status:403};return n.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(n.accountCount>1)return{action:"switch",status:403};return n.retryCount<n.maxRetries?{action:"retry",status:403,retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let s=f9(t.headers);return n.accountCount>1?{action:"switch",status:429,retryAfterMs:s}:{action:"retry",status:429,retryAfterMs:s}}case 500:return n.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,n.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(i9.test(t.message))return n.retryCount<n.maxRetries?{action:"retry",retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:t.status,terminalStatus:t.status}}}var qg=Promise.resolve();function In(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function lr(t,n){if(n.aborted)return Promise.reject(In(n));return new Promise((s,r)=>{let i=()=>r(In(n));n.addEventListener("abort",i,{once:!0}),t.then((e)=>{n.removeEventListener("abort",i),s(e)},(e)=>{n.removeEventListener("abort",i),r(e)})})}function Cg(t,n){if(t<=0)return Promise.resolve();return lr(Bun.sleep(t),n)}async function Kg(t){let n=qg,s,r=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let i=s;qg=n.catch(()=>{return}).then(()=>r);try{await lr(n,t)}catch(f){throw i(),f}let e=!1;return()=>{if(e)return;e=!0,i()}}function Vg(t,n){if(t)return{signal:t,dispose:()=>{return}};let s=new AbortController,r=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),n);return{signal:s.signal,dispose:()=>clearTimeout(r)}}var di="<\uFF5CDSML\uFF5Cfunction_calls";function s0(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function h9(t){let n=[],s=/```[\s\S]*?```/g;for(let e=s.exec(t);e!==null;e=s.exec(t))n.push([e.index,e.index+e[0].length]);let r=(e)=>n.some(([f,o])=>e>=f&&e<o),i=/`[^`\n]+`/g;for(let e=i.exec(t);e!==null;e=i.exec(t))if(!r(e.index))n.push([e.index,e.index+e[0].length]);return n}function ds(t,n,s){return s.some(([r,i])=>t<i&&n>r)}function u9(t){let n={},s=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let r=s.exec(t);r!==null;r=s.exec(t)){let i=r[1];if(i===void 0)continue;let e=r[2]??"";try{n[i]=JSON.parse(e)}catch{n[i]=e}}return n}function jg(t,n){return{toolUseId:s0(),name:t,input:u9(n)}}function _9(t,n,s){let r=[],i=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=i.exec(t);f!==null;f=i.exec(t)){let o=f.index,c=o+f[0].length;if(ds(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let _=h.exec(f[0]);_!==null;_=h.exec(f[0])){let l=_[1];if(l)u.push(jg(l,_[2]??""))}if(u.length===0)continue;r.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||ds(o,c,n)||ds(o,c,s))continue;r.push({start:o,end:c,toolCalls:[jg(h,f[2]??"")]}),s.push([o,c])}return r}function l9(t,n,s){let r=[],i=0;for(;;){let e=t.indexOf(di,i);if(e===-1)break;let f=t.slice(e+di.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?e+di.length+o.index+o[0].length:t.length;if(i=c,ds(e,c,n)||ds(e,c,s))continue;let h=t.slice(e,c),u=[],_=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),l=/(\{[\s\S]*\})/.exec(h);if(_?.[1]&&l?.[1])try{u.push({toolUseId:s0(),name:_[1],input:JSON.parse(l[1])})}catch{}r.push({start:e,end:c,toolCalls:u}),s.push([e,c])}return r}function w9(t,n,s){let r=[],i=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=i.exec(t);e!==null;e=i.exec(t)){let f=e.index,o=f+e[0].length,c=e[1],h=e[2];if(!c||!h||ds(f,o,n)||ds(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}r.push({start:f,end:o,toolCalls:[{toolUseId:s0(),name:c,input:u}]}),s.push([f,o])}return r}function ag(t){if(!t)return{toolCalls:[],cleanedText:t};let n=h9(t),s=[],r=[..._9(t,n,s),...l9(t,n,s),...w9(t,n,s)];if(r.length===0)return{toolCalls:[],cleanedText:t};r.sort((o,c)=>o.start-c.start);let i=[],e="",f=0;for(let o of r){if(o.start<f)continue;e+=t.slice(f,o.start),f=o.end,i.push(...o.toolCalls)}return e+=t.slice(f),{toolCalls:i,cleanedText:e}}var r0=["<function_calls","<invoke name=",di],A9=Math.max(...r0.map((t)=>t.length));function pg(t){let n=-1;for(let s of r0){let r=t.indexOf(s);if(r!==-1&&(n===-1||r<n))n=r}return n}function M9(t){let n=Math.min(t.length,A9-1);for(let s=n;s>0;s--){let r=t.slice(t.length-s);for(let i of r0)if(i.length>s&&i.startsWith(r))return s}return 0}class i0{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&pg(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let r=pg(this.accumulated);n=r===-1?this.accumulated.length:r}else n=this.accumulated.length-M9(this.accumulated);if(n<=this.emitted)return"";let s=this.accumulated.slice(this.emitted,n);return this.emitted=n,s}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:t,cleanedText:n}=ag(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function e0(t,n,s){let r=[];if(t.type==="content_block_delta"){if(t.delta?.type==="text_delta")r.push({index:0,delta:{content:t.delta.text??""},finish_reason:null});else if(t.delta?.type==="thinking_delta"){if(t.delta.thinking)r.push({index:0,delta:{reasoning_content:t.delta.thinking},finish_reason:null})}else if(t.delta?.type==="input_json_delta")r.push({index:0,delta:{tool_calls:[{index:t.index,function:{arguments:t.delta.partial_json??""}}]},finish_reason:null})}else if(t.type==="content_block_start"&&t.content_block?.type==="tool_use")r.push({index:0,delta:{tool_calls:[{index:t.index,id:t.content_block.id,type:"function",function:{name:t.content_block.name,arguments:""}}]},finish_reason:null});else if(t.type==="message_delta")r.push({index:0,delta:{},finish_reason:t.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(r.length===0)return null;let i={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:r};if(t.type!=="message_delta")return i;let e=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...i,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function o0(t,n){let s=/```[\s\S]*?```/g,r=[],i=s.exec(t);while(i!==null)r.push([i.index,i.index+i[0].length]),i=s.exec(t);let e=t.indexOf(n,0);while(e!==-1){if(!r.some(([o,c])=>e>=o&&e<c))return e;e=t.indexOf(n,e+n.length)}return-1}function Zg(t,n){if(t==="thinking"){if(n.thinkingBlockIndex!==null)return[];let r=n.nextBlockIndex++;return n.thinkingBlockIndex=r,[{type:"content_block_start",index:r,content_block:{type:"thinking",thinking:""}}]}if(n.textBlockIndex!==null)return[];let s=n.nextBlockIndex++;return n.textBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"text",text:""}}]}function Rs(t,n){if(t===null||n.stoppedBlocks.has(t))return[];return n.stoppedBlocks.add(t),[{type:"content_block_stop",index:t}]}function Cn(t,n){if(!t)return[];let s=Zg("text",n),r=n.textBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"text_delta",text:t}}),s}function Kn(t,n){let s=Zg("thinking",n),r=n.thinkingBlockIndex;if(r===null)return s;return s.push({type:"content_block_delta",index:r,delta:{type:"thinking_delta",thinking:t}}),s}var Bo="<thinking>",Fo="</thinking>";function vg(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let i=o0(n.buffer,Bo);if(i!==-1){let f=n.buffer.slice(0,i);s.push(...Cn(f,n)),n.buffer=n.buffer.slice(i+Bo.length),n.inThinking=!0;continue}let e=Math.max(0,n.buffer.length-Bo.length);if(e>0)s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}if(n.inThinking){let i=o0(n.buffer,Fo);if(i!==-1){if(s.push(...Kn(n.buffer.slice(0,i),n)),n.buffer=n.buffer.slice(i+Fo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Kn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
131
+ ${R.content[0]?.text??""}`}if(q.length>0){if(!A.at(-1)||A.at(-1)?.assistantResponseMessage)A.push({userInputMessage:{content:"Running tools...",modelId:f,origin:ot.ORIGIN_AI_EDITOR}});A.push({assistantResponseMessage:{content:"I will execute the following tools.",toolUses:q.map(({call:R})=>R)}}),D.push(...q.map(({result:R})=>R))}let tt={content:E,modelId:f,origin:ot.ORIGIN_AI_EDITOR};if(U.length>0)tt.images=U;let J=Hg(e.tools).filter((R)=>typeof R.toolSpecification.name==="string").map((R)=>({toolSpecification:{...R.toolSpecification,name:R.toolSpecification.name??""}}));if(D.length>0||J.length>0){if(tt.userInputMessageContext={},D.length>0)tt.userInputMessageContext.toolResults=gr(D);if(J.length>0)tt.userInputMessageContext.tools=J}if(Dg(A)){let R=tt.userInputMessageContext?.tools??[],W=new Set(R.map((st)=>st.toolSpecification.name)),k=[...mg(A)].filter((st)=>!W.has(st));if(k.length>0)tt.userInputMessageContext??={},tt.userInputMessageContext.tools=[...R,...k.map((st)=>Z7(st,S))]}let G=K7(),K={conversationState:{chatTriggerType:ot.CHAT_TRIGGER_TYPE_MANUAL,conversationId:G,currentMessage:{userInputMessage:tt},...A.length>0?{history:A}:{}},...s.profileArn?{profileArn:s.profileArn}:{}};return o===void 0?{request:K,resolved:f,convId:G}:{request:K,resolved:f,convId:G,variantEffort:o}}function s9(t){let n=typeof t==="string"?JSON.parse(t):t;if(typeof n!=="object"||n===null||!("reasoning_effort"in n))return;let s=n.reasoning_effort;return typeof s==="string"||s===null?s:void 0}function Qg(t,n,s,i=!1,r=20000,e){let{request:f,resolved:o,convId:c}=Yg(t,n,s,i,r),h=Gg({model:n,think:i,budget:r,reasoningEffort:s9(t),configEffort:e?.effort,autoEffortMapping:e?.autoEffortMapping});return{conversationState:f.conversationState,...f.profileArn?{profileArn:f.profileArn}:{},streaming:!0,effectiveModel:o,conversationId:c,region:tu(s.profileArn)??s.region,...h?{effort:h}:{}}}function Jg(t){return Math.ceil(t.length/4)}async function Io(t,n){if(n?.aborted)return{kind:"aborted"};let s=t.next();if(!n)return{kind:"event",result:await s};return new Promise((i,r)=>{let e=()=>i({kind:"aborted"});n.addEventListener("abort",e,{once:!0}),s.then((f)=>{n.removeEventListener("abort",e),i({kind:"event",result:f})},(f)=>{n.removeEventListener("abort",e),r(f)})})}function dr(t,n){if(!n?.name||!n.toolUseId)return;let s=t.get(n.toolUseId);if(s){s.input+=n.input??"";return}t.set(n.toolUseId,{toolUseId:n.toolUseId,name:n.name,input:n.input??""})}function kg(t){let n=[],s=0;for(let i of t.values()){let r=i.input;try{r=JSON.stringify(JSON.parse(i.input))}catch{r=i.input}n.push({type:"content_block_start",index:s,content_block:{type:"tool_use",id:i.toolUseId,name:i.name,input:{}}},{type:"content_block_delta",index:s,delta:{type:"input_json_delta",partial_json:r}},{type:"content_block_stop",index:s}),s+=1}return n}function yo(t,n){let s=n.metadataEvent?.tokenUsage;if(s)t.outputTokens=s.outputTokens??t.outputTokens,t.totalTokens=s.totalTokens??t.totalTokens,t.inputTokens=s.inputTokens??(s.uncachedInputTokens===void 0?t.inputTokens:s.uncachedInputTokens+(s.cacheReadInputTokens??0)+(s.cacheWriteInputTokens??0));t.contextUsagePercentage=n.contextUsageEvent?.contextUsagePercentage??n.metadataEvent?.contextUsagePercentage??s?.contextUsagePercentage??t.contextUsagePercentage}function Oo(t,n,s){let i=t.outputTokens??Jg(n),r=t.inputTokens;if(r===void 0&&t.totalTokens!==void 0)r=Math.max(0,t.totalTokens-i);if(r===void 0&&t.contextUsagePercentage!==void 0&&t.contextUsagePercentage>0){let e=Math.round(Lg(s)*t.contextUsagePercentage/100);r=Math.max(0,e-i)}return{inputTokens:r??0,outputTokens:i}}class zg extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function Xg(t,n,s,i){let r=t.generateAssistantResponseResponse;if(!r)throw new zg;let e=r[Symbol.asyncIterator](),f=new Map,o={},c="",h="",u=!1,l=!1;try{while(!0){let A=await Io(e,i);if(A.kind==="aborted"){if(e.return)await e.return();l=!0;break}if(A.result.done){u=!0;break}let M=A.result.value;yo(o,M),h+=M.reasoningContentEvent?.text??"",c+=M.assistantResponseEvent?.content??"",dr(f,M.toolUseEvent)}}finally{if(!u&&!l&&e.return)await e.return()}let _=Oo(o,c,n),w={role:"assistant",content:c,...h?{reasoning_content:h}:{},...f.size>0?{tool_calls:Array.from(f.values(),(A)=>({id:A.toolUseId,type:"function",function:{name:A.name,arguments:A.input}}))}:{}};return{id:s,object:"chat.completion",created:Math.floor(Date.now()/1000),model:n,choices:[{index:0,message:w,finish_reason:f.size>0?"tool_calls":"stop"}],usage:{prompt_tokens:_.inputTokens,completion_tokens:_.outputTokens,total_tokens:_.inputTokens+_.outputTokens}}}var i9=[/input is too long/i,/CONTENT_LENGTH_EXCEEDS_THRESHOLD/i],r9=/econnreset|etimedout|enotfound|network|fetch failed|socket/i;function Go(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function t0(t,n){let s=t[n];return typeof s==="string"?s:void 0}function e9(t){let n=t.$metadata;if(!Go(n))return;let s=n.httpStatusCode;return typeof s==="number"?s:void 0}function o9(t){let n=t.$response;if(!Go(n))return;let s=n.headers;if(!Go(s))return;let i={};for(let[r,e]of Object.entries(s))if(typeof e==="string")i[r]=e;else if(typeof e==="number")i[r]=String(e);return Object.keys(i).length>0?i:void 0}function n0(t){if(!Go(t))return{message:t instanceof Error?t.message:String(t)};let n=e9(t),s=t0(t,"message")??String(t),i=t0(t,"name"),r=t0(t,"reason"),e=o9(t);return{message:s,...n!==void 0?{status:n}:{},...i!==void 0?{code:i}:{},...r!==void 0?{reason:r}:{},...e!==void 0?{headers:e}:{}}}function f9(t){let n=Object.entries(t??{}).find(([i])=>i.toLowerCase()==="retry-after"),s=Number.parseInt(n?.[1]??"60",10);return Number.isFinite(s)&&s>=0?s*1000:60000}function c9(t){return i9.some((n)=>n.test(t))}function xg(t,n){if(t.reason==="INVALID_MODEL_ID"){let s=t.status??400;return{action:"fail",status:s,terminalStatus:s}}if(t.reason==="TEMPORARILY_SUSPENDED")return n.accountCount>1?{action:"switch",...t.status!==void 0?{status:t.status}:{}}:{action:"fail",...t.status!==void 0?{status:t.status}:{},terminalStatus:t.status??403};switch(t.status){case 400:return{action:"fail",status:400,terminalStatus:c9(t.message)?413:400};case 401:return n.retryCount<n.maxRetries?{action:"retry",status:401}:{action:"fail",status:401,terminalStatus:401};case 402:return{action:"fail",status:402,terminalStatus:402};case 403:if(Or(t.message)){if(!n.forcedRefreshAccountIds.has(n.accountId))return n.forcedRefreshAccountIds.add(n.accountId),{action:"refresh-then-retry",status:403};return n.accountCount>1?{action:"switch",status:403}:{action:"fail",status:403,terminalStatus:403}}if(n.accountCount>1)return{action:"switch",status:403};return n.retryCount<n.maxRetries?{action:"retry",status:403,retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",status:403,terminalStatus:403};case 429:{let s=f9(t.headers);return n.accountCount>1?{action:"switch",status:429,retryAfterMs:s}:{action:"retry",status:429,retryAfterMs:s}}case 500:return n.serverErrorCount<5?{action:"retry",status:500,retryAfterMs:1000*2**Math.max(0,n.serverErrorCount-1)}:{action:"switch",status:500};case void 0:if(r9.test(t.message))return n.retryCount<n.maxRetries?{action:"retry",retryAfterMs:n.retryDelayMs*2**n.retryCount}:{action:"fail",terminalStatus:500};return{action:"fail",terminalStatus:500};default:return{action:"fail",status:t.status,terminalStatus:t.status}}}var qg=Promise.resolve();function In(t){return t.reason instanceof Error?t.reason:new DOMException("The request was aborted","AbortError")}function _i(t,n){if(n.aborted)return Promise.reject(In(n));return new Promise((s,i)=>{let r=()=>i(In(n));n.addEventListener("abort",r,{once:!0}),t.then((e)=>{n.removeEventListener("abort",r),s(e)},(e)=>{n.removeEventListener("abort",r),i(e)})})}function Cg(t,n){if(t<=0)return Promise.resolve();return _i(Bun.sleep(t),n)}async function Kg(t){let n=qg,s,i=new Promise((f)=>{s=f});if(!s)throw TypeError("Queue release was not initialized");let r=s;qg=n.catch(()=>{return}).then(()=>i);try{await _i(n,t)}catch(f){throw r(),f}let e=!1;return()=>{if(e)return;e=!0,r()}}function Vg(t,n){if(t)return{signal:t,dispose:()=>{return}};let s=new AbortController,i=setTimeout(()=>s.abort(new DOMException("Request deadline exceeded","TimeoutError")),n);return{signal:s.signal,dispose:()=>clearTimeout(i)}}var Er="<\uFF5CDSML\uFF5Cfunction_calls";function s0(){return`tool_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}function h9(t){let n=[],s=/```[\s\S]*?```/g;for(let e=s.exec(t);e!==null;e=s.exec(t))n.push([e.index,e.index+e[0].length]);let i=(e)=>n.some(([f,o])=>e>=f&&e<o),r=/`[^`\n]+`/g;for(let e=r.exec(t);e!==null;e=r.exec(t))if(!i(e.index))n.push([e.index,e.index+e[0].length]);return n}function Es(t,n,s){return s.some(([i,r])=>t<r&&n>i)}function u9(t){let n={},s=/<parameter\s+name="([^"]+)"\s*>([\s\S]*?)<\/parameter>/g;for(let i=s.exec(t);i!==null;i=s.exec(t)){let r=i[1];if(r===void 0)continue;let e=i[2]??"";try{n[r]=JSON.parse(e)}catch{n[r]=e}}return n}function jg(t,n){return{toolUseId:s0(),name:t,input:u9(n)}}function l9(t,n,s){let i=[],r=/<function_calls>[\s\S]*?<\/function_calls>/g;for(let f=r.exec(t);f!==null;f=r.exec(t)){let o=f.index,c=o+f[0].length;if(Es(o,c,n))continue;let h=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g,u=[];for(let l=h.exec(f[0]);l!==null;l=h.exec(f[0])){let _=l[1];if(_)u.push(jg(_,l[2]??""))}if(u.length===0)continue;i.push({start:o,end:c,toolCalls:u}),s.push([o,c])}let e=/<invoke\s+name="([^"]+)"\s*>([\s\S]*?)<\/invoke>/g;for(let f=e.exec(t);f!==null;f=e.exec(t)){let o=f.index,c=o+f[0].length,h=f[1];if(!h||Es(o,c,n)||Es(o,c,s))continue;i.push({start:o,end:c,toolCalls:[jg(h,f[2]??"")]}),s.push([o,c])}return i}function _9(t,n,s){let i=[],r=0;for(;;){let e=t.indexOf(Er,r);if(e===-1)break;let f=t.slice(e+Er.length),o=/<\uFF5C[^>]*?end[^>]*?>|<\/\uFF5CDSML[^>]*?>/.exec(f),c=o!==null?e+Er.length+o.index+o[0].length:t.length;if(r=c,Es(e,c,n)||Es(e,c,s))continue;let h=t.slice(e,c),u=[],l=/name["\uFF5C=:\s]+["']?([A-Za-z0-9_]+)/.exec(h),_=/(\{[\s\S]*\})/.exec(h);if(l?.[1]&&_?.[1])try{u.push({toolUseId:s0(),name:l[1],input:JSON.parse(_[1])})}catch{}i.push({start:e,end:c,toolCalls:u}),s.push([e,c])}return i}function w9(t,n,s){let i=[],r=/\[Called\s+(\w+)\s+with\s+args:\s*(\{[^}]*(?:\{[^}]*\}[^}]*)*\})\]/gs;for(let e=r.exec(t);e!==null;e=r.exec(t)){let f=e.index,o=f+e[0].length,c=e[1],h=e[2];if(!c||!h||Es(f,o,n)||Es(f,o,s))continue;let u;try{u=JSON.parse(h)}catch{continue}i.push({start:f,end:o,toolCalls:[{toolUseId:s0(),name:c,input:u}]}),s.push([f,o])}return i}function ag(t){if(!t)return{toolCalls:[],cleanedText:t};let n=h9(t),s=[],i=[...l9(t,n,s),..._9(t,n,s),...w9(t,n,s)];if(i.length===0)return{toolCalls:[],cleanedText:t};i.sort((o,c)=>o.start-c.start);let r=[],e="",f=0;for(let o of i){if(o.start<f)continue;e+=t.slice(f,o.start),f=o.end,r.push(...o.toolCalls)}return e+=t.slice(f),{toolCalls:r,cleanedText:e}}var i0=["<function_calls","<invoke name=",Er],A9=Math.max(...i0.map((t)=>t.length));function pg(t){let n=-1;for(let s of i0){let i=t.indexOf(s);if(i!==-1&&(n===-1||i<n))n=i}return n}function M9(t){let n=Math.min(t.length,A9-1);for(let s=n;s>0;s--){let i=t.slice(t.length-s);for(let r of i0)if(r.length>s&&r.startsWith(i))return s}return 0}class r0{accumulated="";emitted=0;markerSeen=!1;push(t){if(!t)return"";if(this.accumulated+=t,!this.markerSeen&&pg(this.accumulated)!==-1)this.markerSeen=!0;let n;if(this.markerSeen){let i=pg(this.accumulated);n=i===-1?this.accumulated.length:i}else n=this.accumulated.length-M9(this.accumulated);if(n<=this.emitted)return"";let s=this.accumulated.slice(this.emitted,n);return this.emitted=n,s}get suppressing(){return this.markerSeen}finalize(){let{toolCalls:t,cleanedText:n}=ag(this.accumulated),s=n.length>this.emitted?n.slice(this.emitted):"";return{toolCalls:t,remainderText:s}}}function e0(t,n,s){let i=[];if(t.type==="content_block_delta"){if(t.delta?.type==="text_delta")i.push({index:0,delta:{content:t.delta.text??""},finish_reason:null});else if(t.delta?.type==="thinking_delta"){if(t.delta.thinking)i.push({index:0,delta:{reasoning_content:t.delta.thinking},finish_reason:null})}else if(t.delta?.type==="input_json_delta")i.push({index:0,delta:{tool_calls:[{index:t.index,function:{arguments:t.delta.partial_json??""}}]},finish_reason:null})}else if(t.type==="content_block_start"&&t.content_block?.type==="tool_use")i.push({index:0,delta:{tool_calls:[{index:t.index,id:t.content_block.id,type:"function",function:{name:t.content_block.name,arguments:""}}]},finish_reason:null});else if(t.type==="message_delta")i.push({index:0,delta:{},finish_reason:t.delta?.stop_reason==="tool_use"?"tool_calls":"stop"});else return null;if(i.length===0)return null;let r={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:s,choices:i};if(t.type!=="message_delta")return r;let e=t.usage?.input_tokens??0,f=t.usage?.output_tokens??0;return{...r,usage:{prompt_tokens:e,completion_tokens:f,total_tokens:e+f}}}function o0(t,n){let s=/```[\s\S]*?```/g,i=[],r=s.exec(t);while(r!==null)i.push([r.index,r.index+r[0].length]),r=s.exec(t);let e=t.indexOf(n,0);while(e!==-1){if(!i.some(([o,c])=>e>=o&&e<c))return e;e=t.indexOf(n,e+n.length)}return-1}function Zg(t,n){if(t==="thinking"){if(n.thinkingBlockIndex!==null)return[];let i=n.nextBlockIndex++;return n.thinkingBlockIndex=i,[{type:"content_block_start",index:i,content_block:{type:"thinking",thinking:""}}]}if(n.textBlockIndex!==null)return[];let s=n.nextBlockIndex++;return n.textBlockIndex=s,[{type:"content_block_start",index:s,content_block:{type:"text",text:""}}]}function Rs(t,n){if(t===null||n.stoppedBlocks.has(t))return[];return n.stoppedBlocks.add(t),[{type:"content_block_stop",index:t}]}function Cn(t,n){if(!t)return[];let s=Zg("text",n),i=n.textBlockIndex;if(i===null)return s;return s.push({type:"content_block_delta",index:i,delta:{type:"text_delta",text:t}}),s}function Kn(t,n){let s=Zg("thinking",n),i=n.thinkingBlockIndex;if(i===null)return s;return s.push({type:"content_block_delta",index:i,delta:{type:"thinking_delta",thinking:t}}),s}var Bo="<thinking>",Fo="</thinking>";function vg(t,n){n.buffer+=t;let s=[];while(n.buffer.length>0){if(!n.inThinking&&!n.thinkingExtracted){let r=o0(n.buffer,Bo);if(r!==-1){let f=n.buffer.slice(0,r);s.push(...Cn(f,n)),n.buffer=n.buffer.slice(r+Bo.length),n.inThinking=!0;continue}let e=Math.max(0,n.buffer.length-Bo.length);if(e>0)s.push(...Cn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}if(n.inThinking){let r=o0(n.buffer,Fo);if(r!==-1){if(s.push(...Kn(n.buffer.slice(0,r),n)),n.buffer=n.buffer.slice(r+Fo.length),n.inThinking=!1,n.thinkingExtracted=!0,s.push(...Kn("",n)),s.push(...Rs(n.thinkingBlockIndex,n)),n.buffer.startsWith(`
132
132
 
133
- `))n.buffer=n.buffer.slice(2);continue}let e=Math.max(0,n.buffer.length-Fo.length);if(e>0)s.push(...Kn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}let r=n.buffer;n.buffer="",s.push(...Cn(r,n))}return s}function tE(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return Cn(n,t);return[...Kn(n,t),...Kn("",t),...Rs(t.thinkingBlockIndex,t)]}class nE extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*sE(t,n,s,r){let i=t.generateAssistantResponseResponse;if(!i)throw new nE;let e={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new i0,o=new Map,c={},h=i[Symbol.asyncIterator](),u="",_=!1,l=!1,w=!1,A=!1,M=(S,O=!1)=>{if(O&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let D=f.push(S.delta.text??"");if(!D)return null;return e0({...S,delta:{...S.delta,text:D}},s,n)}return e0(S,s,n)};try{while(!0){let S=await Io(h,r);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let O=S.result.value;Oo(c,O);let D=O.reasoningContentEvent?.text;if(D){if(l)e.thinkingBlockIndex=null,l=!1;_=!0;for(let tt of Kn(D,e)){let J=M(tt);if(J)yield J}continue}let q=O.assistantResponseEvent?.content;if(q){if(u+=q,_&&!l){for(let J of Rs(e.thinkingBlockIndex,e)){let G=M(J);if(G)yield G}l=!0}let tt=_?Cn(q,e):vg(q,e);for(let J of tt){let G=M(J,!0);if(G)yield G}continue}if(O.toolUseEvent)Ei(o,O.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(_&&!l)for(let S of Rs(e.thinkingBlockIndex,e)){let O=M(S);if(O)yield O}for(let S of tE(e)){let O=M(S,S.delta?.type==="text_delta");if(O)yield O}let{toolCalls:E,remainderText:d}=f.finalize();for(let S of Cn(d,e)){let O=M(S);if(O)yield O}for(let S of Rs(e.textBlockIndex,e)){let O=M(S);if(O)yield O}for(let S of E)Ei(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of kg(o)){let O=M(S);if(O)yield O}let T=yo(c,u,n),U=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:T.inputTokens,output_tokens:T.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(U)yield U;M({type:"message_stop"})}class rE extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function iE(t,n,s,r){let i=new AbortController,e=AbortSignal.any([n,i.signal]),f=sE(t.sdkResponse,t.model,t.conversationId,e)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},_=()=>{if(c)return;c=!0,r()},l=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((E,d)=>{let T=()=>{u(),d(In(e))};if(A=()=>e.removeEventListener("abort",T),e.addEventListener("abort",T,{once:!0}),h=setTimeout(()=>{h=void 0,d(new rE(s))},s),e.aborted)T()})]);if(e.aborted)throw In(e);if(M.done){w.close(),_();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
134
- `))}catch(M){if(u(),A?.(),i.signal.aborted)return;let E=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});i.abort(E),w.error(E);try{await l()}finally{_()}}finally{u(),A?.()}},async cancel(){u(),i.abort();try{await l()}catch{return}finally{_()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var oE=Y(me(),1);var eE=new Map,g9=3;function Ho(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function E9(t){let n=t.conversationState;if(!Ho(n))return;let s=n.currentMessage;if(!Ho(s))return;let r=s.userInputMessage;if(!Ho(r))return;let i=r.modelId;return typeof i==="string"?i:void 0}function d9(t,n,s,r){let i=r?(()=>{let e=p0(r);return new oE.NodeHttpHandler({httpAgent:e,httpsAgent:e})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:g9,retryMode:"standard",customUserAgent:[[ot.USER_AGENT]],...i?{requestHandler:i}:{}}}function fE(t,n,s,r,i){let e=r??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,e,i??null]),o=eE.get(f);if(o?.token===t.access)return o.client;let c=new ph(d9(t,n,e,i));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest)u.request.headers["x-amzn-kiro-agent-mode"]="vibe";return h(u)},{step:"build",name:"addKiroHeaders"}),s)c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest&&typeof u.request.body==="string")try{let _=JSON.parse(u.request.body);if(Ho(_)){let l=E9(_);if(l)_.additionalModelRequestFields=yg(l,s),u.request.body=JSON.stringify(_)}}catch(_){if(!(_ instanceof SyntaxError))throw _}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return eE.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function R9(t){if(!bs(t))return!1;let n=t.conversationState;return bs(n)&&typeof n.conversationId==="string"&&bs(n.currentMessage)&&typeof n.chatTriggerType==="string"}function b9(t,n){let s=typeof t==="string"?JSON.parse(t):t;if(!bs(s))return{think:n.endsWith("-thinking"),budget:20000};let r=s.providerOptions,i=bs(r)?r.thinkingConfig:void 0,e=s.thinkingConfig,f=bs(i)?i:bs(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function T9(t,n,s){return V(t,n,"upstream_error",s)}async function S9(t,n){let{think:s,budget:r}=b9(t.body,t.model),i=new Set,e=new Map,f=0,o=0;while(!0){if(n.aborted)throw In(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:V(500,`Exceeded max iterations (${t.config.max_request_iterations})`,"request_error","max_request_iterations")};t.accountManager.reconcileFromDb();let c=t.accountManager.selectHealthyAccount();if(!c)return{kind:"response",response:V(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await lr(t.tokenRefresher.refreshIfNeeded(c,h,n),n),_=t.accountManager.toAuthDetails(u),l=Li.safeParse(t.config.effort),w=Qg(t.body,t.model,_,s,r,{autoEffortMapping:t.config.auto_effort_mapping,...l.success?{effort:l.data}:{}}),M=(t.makeClient??fE)(_,w.region,w.effort,t.config.test_upstream_endpoint,Qs(t.config)),E={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!R9(E))throw TypeError("Transformed request is not a valid SDK command input");let d=new Zh(E);try{let T=await lr(M.send(d,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:T,model:t.model,conversationId:w.conversationId};let U=await zg(T,t.model,w.conversationId,n);if(n.aborted)throw In(n);return{kind:"response",response:Response.json(U,{headers:{"Content-Type":"application/json"}})}}catch(T){if(n.aborted)throw In(n);let U=n0(T),S=U.status===500?(e.get(u.id)??0)+1:0;if(U.status===500)e.set(u.id,S);let O=xg(U,{accountId:u.id,accountCount:t.accountManager.getAccountCount(),retryCount:f,maxRetries:t.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:t.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:i});switch(O.action){case"refresh-then-retry":await lr(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Cg(O.retryAfterMs??0,n);continue;case"switch":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);else t.accountManager.markRateLimited(u,Date.now()+(O.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);return{kind:"response",response:T9(O.terminalStatus??O.status??500,U.message,U.code)}}}}}async function Po(t){let n=Vg(t.deadlineSignal,t.config.request_timeout_ms),s,r=!1;try{s=await Kg(n.signal);let i=await S9(t,n.signal);if(i.kind==="response")return i.response;let e=s;return s=void 0,r=!0,iE(i,n.signal,t.config.stream_idle_timeout_ms,()=>{e(),n.dispose()})}catch(i){if(n.signal.aborted)return V(504,"Request deadline exceeded","timeout_error","request_timeout");let e=n0(i);return V(500,e.message,"internal_error",e.code)}finally{if(!r)s?.(),n.dispose()}}var Ri=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ut=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),a=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),cE=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),hE=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:B("auto"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:B("claude-sonnet-4"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:B("claude-sonnet-4-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:B("claude-haiku-4-5"),outputLimit:64000,modalities:ut},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:B("claude-opus-4-5"),outputLimit:64000,modalities:a},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:B("claude-opus-4-6"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:B("deepseek-3.2"),outputLimit:64000,modalities:Ri},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:B("glm-5"),outputLimit:64000,modalities:Ri},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:B("minimax-m2.5"),outputLimit:64000,modalities:Ri},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:B("minimax-m2.1"),outputLimit:64000,modalities:Ri},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:B("qwen3-coder-next"),outputLimit:64000,modalities:Ri},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut}]);var f0=g.record(g.unknown()),$9=new Set(cE),U9=g.object({type:g.literal("text"),text:g.string()}).passthrough(),L9=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),I9=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),O9=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),y9=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),G9=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),B9=g.discriminatedUnion("type",[U9,L9,I9,O9,y9,G9]),No=g.union([g.string(),g.array(B9)]);function uE(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var F9=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(uE,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),H9=g.object({role:g.literal("system"),content:No}).passthrough(),P9=g.object({role:g.literal("user"),content:No}).passthrough(),N9=g.object({role:g.literal("assistant"),content:No.nullable().optional(),tool_calls:g.array(F9).min(1).optional()}).passthrough().refine((t)=>t.content!==null&&t.content!==void 0?!0:t.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),W9=g.object({role:g.literal("tool"),content:No,tool_call_id:g.string().min(1)}).passthrough(),D9=g.union([H9,P9,N9,W9]),Y9=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:f0.optional()}).passthrough()}).passthrough(),m9=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:f0.optional()}).passthrough(),Q9=g.object({model:g.string().refine((t)=>$9.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(D9).min(1),tools:g.array(g.union([Y9,m9])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),J9=g.object({type:g.literal("input_text"),text:g.string()}).passthrough(),k9=g.object({type:g.literal("output_text"),text:g.string()}).passthrough(),X9=g.object({type:g.literal("input_image"),image_url:g.string()}).passthrough(),z9=new Set(["input_text","output_text","input_image"]),x9=g.object({type:g.string()}).passthrough().refine((t)=>!z9.has(t.type),{message:"known content parts must have a valid payload"}),q9=g.union([J9,k9,X9,x9]),C9=g.object({type:g.literal("message"),role:g.enum(["system","user","assistant"]),content:g.array(q9)}).passthrough(),K9=g.object({type:g.literal("function_call"),call_id:g.string().min(1),name:g.string().min(1),arguments:g.string().refine(uE,"function arguments must contain valid JSON")}).passthrough(),V9=g.object({type:g.literal("function_call_output"),call_id:g.string().min(1),output:g.string()}).passthrough(),j9=g.object({type:g.literal("summary_text"),text:g.string()}).passthrough(),a9=g.object({type:g.literal("reasoning_text"),reasoning_text:g.string()}).passthrough(),p9=g.object({type:g.literal("reasoning"),summary:g.array(j9).optional(),content:g.array(a9).optional(),encrypted_content:g.string().optional()}).passthrough(),Z9=new Set(["message","function_call","function_call_output","reasoning"]),v9=g.object({type:g.string()}).passthrough().refine((t)=>!Z9.has(t.type),{message:"known input items must have a valid payload"}),tY=g.union([C9,K9,V9,p9,v9]),nY=g.object({type:g.literal("function"),name:g.string().min(1),description:g.string().optional(),parameters:f0.optional(),strict:g.boolean().optional()}).passthrough(),sY=g.object({effort:g.enum(["none","minimal","low","medium","high","xhigh"]).optional(),summary:g.unknown().optional()}).passthrough(),rY=g.object({model:g.string(),input:g.union([g.string(),g.array(tY)]),instructions:g.string().optional(),stream:g.boolean().default(!1),tools:g.array(nY).optional(),tool_choice:g.literal("auto").optional(),parallel_tool_calls:g.boolean().optional(),reasoning:sY.nullable().optional(),include:g.array(g.string()).optional(),store:g.boolean().optional(),text:g.unknown().optional(),service_tier:g.unknown().optional(),prompt_cache_key:g.string().optional(),client_metadata:g.unknown().optional(),previous_response_id:g.string().optional()}).passthrough();function Wo(t){let n=Q9.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}function _E(t){let n=rY.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((r)=>{return`${r.path.length>0?r.path.join("."):"request"}: ${r.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class h0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function c0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function iY(t,n,s){let r=t.body?.getReader();if(!r)return{ok:!0,text:""};let i=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=c0(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw c0(s.combined);let _=await Promise.race([r.read(),o]);if(s.combined.aborted)throw c0(s.combined);if(_.done)break;if(e+=_.value.byteLength,e>n)throw new h0(n);i.push(_.value)}let h=new Uint8Array(e),u=0;for(let _ of i)h.set(_,u),u+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof h0)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function eY(t,n){let s=t.body;if(!s)return t;let r=s.getReader(),i=new TextDecoder,e=new TextEncoder,f="",o=!1,c=!1,h=()=>{if(c)return;c=!0,n()};return new Response(new ReadableStream({async pull(u){try{while(!0){let _=f.indexOf(`
135
- `);if(_>=0){let A=f.slice(0,_).trimEnd();if(f=f.slice(_+1),A.length>0){u.enqueue(e.encode(`data: ${A}
133
+ `))n.buffer=n.buffer.slice(2);continue}let e=Math.max(0,n.buffer.length-Fo.length);if(e>0)s.push(...Kn(n.buffer.slice(0,e),n)),n.buffer=n.buffer.slice(e);break}let i=n.buffer;n.buffer="",s.push(...Cn(i,n))}return s}function td(t){if(!t.buffer)return[];let n=t.buffer;if(t.buffer="",!t.inThinking)return Cn(n,t);return[...Kn(n,t),...Kn("",t),...Rs(t.thinkingBlockIndex,t)]}class nd extends Error{name="MissingSdkEventStreamError";constructor(){super("SDK response has no event stream")}}async function*sd(t,n,s,i){let r=t.generateAssistantResponseResponse;if(!r)throw new nd;let e={thinkingRequested:!0,buffer:"",inThinking:!1,thinkingExtracted:!1,thinkingBlockIndex:null,textBlockIndex:null,nextBlockIndex:0,stoppedBlocks:new Set},f=new r0,o=new Map,c={},h=r[Symbol.asyncIterator](),u="",l=!1,_=!1,w=!1,A=!1,M=(S,y=!1)=>{if(y&&S.type==="content_block_delta"&&S.delta?.type==="text_delta"){let D=f.push(S.delta.text??"");if(!D)return null;return e0({...S,delta:{...S.delta,text:D}},s,n)}return e0(S,s,n)};try{while(!0){let S=await Io(h,i);if(S.kind==="aborted"){if(h.return)await h.return();A=!0;return}if(S.result.done){w=!0;break}let y=S.result.value;yo(c,y);let D=y.reasoningContentEvent?.text;if(D){if(_)e.thinkingBlockIndex=null,_=!1;l=!0;for(let tt of Kn(D,e)){let J=M(tt);if(J)yield J}continue}let q=y.assistantResponseEvent?.content;if(q){if(u+=q,l&&!_){for(let J of Rs(e.thinkingBlockIndex,e)){let G=M(J);if(G)yield G}_=!0}let tt=l?Cn(q,e):vg(q,e);for(let J of tt){let G=M(J,!0);if(G)yield G}continue}if(y.toolUseEvent)dr(o,y.toolUseEvent)}}finally{if(!w&&!A&&h.return)await h.return()}if(l&&!_)for(let S of Rs(e.thinkingBlockIndex,e)){let y=M(S);if(y)yield y}for(let S of td(e)){let y=M(S,S.delta?.type==="text_delta");if(y)yield y}let{toolCalls:d,remainderText:E}=f.finalize();for(let S of Cn(E,e)){let y=M(S);if(y)yield y}for(let S of Rs(e.textBlockIndex,e)){let y=M(S);if(y)yield y}for(let S of d)dr(o,{toolUseId:S.toolUseId,name:S.name,input:typeof S.input==="string"?S.input:JSON.stringify(S.input),stop:!0});for(let S of kg(o)){let y=M(S);if(y)yield y}let T=Oo(c,u,n),U=M({type:"message_delta",delta:{type:"message_delta",stop_reason:o.size>0?"tool_use":"end_turn"},usage:{input_tokens:T.inputTokens,output_tokens:T.outputTokens,cache_creation_input_tokens:0,cache_read_input_tokens:0}});if(U)yield U;M({type:"message_stop"})}class id extends Error{timeoutMs;name="StreamIdleTimeoutError";constructor(t){super(`SDK stream idle timeout after ${t}ms`);this.timeoutMs=t}}function rd(t,n,s,i){let r=new AbortController,e=AbortSignal.any([n,r.signal]),f=sd(t.sdkResponse,t.model,t.conversationId,e)[Symbol.asyncIterator](),o=new TextEncoder,c=!1,h,u=()=>{if(h===void 0)return;clearTimeout(h),h=void 0},l=()=>{if(c)return;c=!0,i()},_=async()=>{await f.return?.(void 0)};return new Response(new ReadableStream({async pull(w){let A;try{let M=await Promise.race([f.next(),new Promise((d,E)=>{let T=()=>{u(),E(In(e))};if(A=()=>e.removeEventListener("abort",T),e.addEventListener("abort",T,{once:!0}),h=setTimeout(()=>{h=void 0,E(new id(s))},s),e.aborted)T()})]);if(e.aborted)throw In(e);if(M.done){w.close(),l();return}w.enqueue(o.encode(`${JSON.stringify(M.value)}
134
+ `))}catch(M){if(u(),A?.(),r.signal.aborted)return;let d=M instanceof Error?M:TypeError("SDK stream failed with a non-Error reason",{cause:M});r.abort(d),w.error(d);try{await _()}finally{l()}}finally{u(),A?.()}},async cancel(){u(),r.abort();try{await _()}catch{return}finally{l()}}}),{headers:{"Content-Type":"application/x-ndjson; charset=utf-8"}})}var od=m(Ye(),1);var ed=new Map,g9=3;function Ho(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function d9(t){let n=t.conversationState;if(!Ho(n))return;let s=n.currentMessage;if(!Ho(s))return;let i=s.userInputMessage;if(!Ho(i))return;let r=i.modelId;return typeof r==="string"?r:void 0}function E9(t,n,s,i){let r=i?(()=>{let e=p0(i);return new od.NodeHttpHandler({httpAgent:e,httpsAgent:e})})():void 0;return{region:n,endpoint:s,token:()=>Promise.resolve({token:t.access}),maxAttempts:g9,retryMode:"standard",customUserAgent:[[ot.USER_AGENT]],...r?{requestHandler:r}:{}}}function fd(t,n,s,i,r){let e=i??`https://q.${n}.amazonaws.com`,f=JSON.stringify([n,t.email??null,s??null,e,r??null]),o=ed.get(f);if(o?.token===t.access)return o.client;let c=new ph(E9(t,n,e,r));if(c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest)u.request.headers["x-amzn-kiro-agent-mode"]="vibe";return h(u)},{step:"build",name:"addKiroHeaders"}),s)c.middlewareStack.add((h)=>async(u)=>{if(u.request instanceof Gt.HttpRequest&&typeof u.request.body==="string")try{let l=JSON.parse(u.request.body);if(Ho(l)){let _=d9(l);if(_)l.additionalModelRequestFields=Og(_,s),u.request.body=JSON.stringify(l)}}catch(l){if(!(l instanceof SyntaxError))throw l}return h(u)},{step:"build",name:"addEffortConfig",priority:"high"});return ed.set(f,{client:c,token:t.access}),c}function bs(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function R9(t){if(!bs(t))return!1;let n=t.conversationState;return bs(n)&&typeof n.conversationId==="string"&&bs(n.currentMessage)&&typeof n.chatTriggerType==="string"}function b9(t,n){let s=typeof t==="string"?JSON.parse(t):t;if(!bs(s))return{think:n.endsWith("-thinking"),budget:20000};let i=s.providerOptions,r=bs(i)?i.thinkingConfig:void 0,e=s.thinkingConfig,f=bs(r)?r:bs(e)?e:void 0,o=f?.thinkingBudget??f?.budget_tokens;return{think:n.endsWith("-thinking")||f!==void 0,budget:typeof o==="number"?o:20000}}function T9(t,n,s){return V(t,n,"upstream_error",s)}async function S9(t,n){let{think:s,budget:i}=b9(t.body,t.model),r=new Set,e=new Map,f=0,o=0;while(!0){if(n.aborted)throw In(n);if(o+=1,o>t.config.max_request_iterations)return{kind:"response",response:V(500,`Exceeded max iterations (${t.config.max_request_iterations})`,"request_error","max_request_iterations")};t.accountManager.reconcileFromDb();let c=t.accountManager.selectHealthyAccount();if(!c)return{kind:"response",response:V(503,"All accounts are unhealthy or rate-limited","service_unavailable","no_healthy_accounts")};let h=t.accountManager.toAuthDetails(c),u=await _i(t.tokenRefresher.refreshIfNeeded(c,h,n),n),l=t.accountManager.toAuthDetails(u),_=Lr.safeParse(t.config.effort),w=Qg(t.body,t.model,l,s,i,{autoEffortMapping:t.config.auto_effort_mapping,..._.success?{effort:_.data}:{}}),M=(t.makeClient??fd)(l,w.region,w.effort,t.config.test_upstream_endpoint,Qs(t.config)),d={conversationState:w.conversationState,...w.profileArn?{profileArn:w.profileArn}:{}};if(!R9(d))throw TypeError("Transformed request is not a valid SDK command input");let E=new Zh(d);try{let T=await _i(M.send(E,{abortSignal:n}),n);if(t.stream)return{kind:"stream",sdkResponse:T,model:t.model,conversationId:w.conversationId};let U=await Xg(T,t.model,w.conversationId,n);if(n.aborted)throw In(n);return{kind:"response",response:Response.json(U,{headers:{"Content-Type":"application/json"}})}}catch(T){if(n.aborted)throw In(n);let U=n0(T),S=U.status===500?(e.get(u.id)??0)+1:0;if(U.status===500)e.set(u.id,S);let y=xg(U,{accountId:u.id,accountCount:t.accountManager.getAccountCount(),retryCount:f,maxRetries:t.config.rate_limit_max_retries,serverErrorCount:S,retryDelayMs:t.config.rate_limit_retry_delay_ms,forcedRefreshAccountIds:r});switch(y.action){case"refresh-then-retry":await _i(t.tokenRefresher.forceRefresh(u,n),n);continue;case"retry":f+=1,await Cg(y.retryAfterMs??0,n);continue;case"switch":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);else t.accountManager.markRateLimited(u,Date.now()+(y.retryAfterMs??t.config.rate_limit_retry_delay_ms));continue;case"fail":if(U.reason==="TEMPORARILY_SUSPENDED")t.accountManager.markUnhealthy(u,`InvalidTokenException: Account Suspended: ${U.message}`);return{kind:"response",response:T9(y.terminalStatus??y.status??500,U.message,U.code)}}}}}async function Po(t){let n=Vg(t.deadlineSignal,t.config.request_timeout_ms),s,i=!1;try{s=await Kg(n.signal);let r=await S9(t,n.signal);if(r.kind==="response")return r.response;let e=s;return s=void 0,i=!0,rd(r,n.signal,t.config.stream_idle_timeout_ms,()=>{e(),n.dispose()})}catch(r){if(n.signal.aborted)return V(504,"Request deadline exceeded","timeout_error","request_timeout");let e=n0(r);return V(500,e.message,"internal_error",e.code)}finally{if(!i)s?.(),n.dispose()}}var Rr=Object.freeze({input:Object.freeze(["text"]),output:Object.freeze(["text"])}),ut=Object.freeze({input:Object.freeze(["text","image"]),output:Object.freeze(["text"])}),a=Object.freeze({input:Object.freeze(["text","image","pdf"]),output:Object.freeze(["text"])}),cd=Object.freeze(["auto","claude-sonnet-4","claude-sonnet-4-5","claude-sonnet-4-6","claude-sonnet-4-6-low","claude-sonnet-4-6-medium","claude-sonnet-4-6-high","claude-sonnet-4-6-max","claude-sonnet-5","claude-sonnet-5-low","claude-sonnet-5-medium","claude-sonnet-5-high","claude-sonnet-5-xhigh","claude-sonnet-5-max","claude-haiku-4-5","claude-opus-4-5","claude-opus-4-6","claude-opus-4-7","claude-opus-4-7-low","claude-opus-4-7-medium","claude-opus-4-7-high","claude-opus-4-7-xhigh","claude-opus-4-7-max","claude-opus-4-8","claude-opus-4-8-low","claude-opus-4-8-medium","claude-opus-4-8-high","claude-opus-4-8-xhigh","claude-opus-4-8-max","claude-opus-4-8-thinking","deepseek-3.2","glm-5","minimax-m2.5","minimax-m2.1","qwen3-coder-next","gpt-5.6-sol","gpt-5.6-sol-low","gpt-5.6-sol-medium","gpt-5.6-sol-high","gpt-5.6-sol-xhigh","gpt-5.6-sol-max","gpt-5.6-terra","gpt-5.6-terra-low","gpt-5.6-terra-medium","gpt-5.6-terra-high","gpt-5.6-terra-xhigh","gpt-5.6-terra-max","gpt-5.6-luna","gpt-5.6-luna-low","gpt-5.6-luna-medium","gpt-5.6-luna-high","gpt-5.6-luna-xhigh","gpt-5.6-luna-max"]),hd=Object.freeze([{id:"auto",wireId:"auto",name:"Auto (1.0x)",contextLimit:B("auto"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4",wireId:"claude-sonnet-4",name:"Claude Sonnet 4.0 (1.3x)",contextLimit:B("claude-sonnet-4"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-5",wireId:"claude-sonnet-4.5",name:"Claude Sonnet 4.5 (1.3x)",contextLimit:B("claude-sonnet-4-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-low",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (low) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-medium",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (medium) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-high",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (high) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-4-6-max",wireId:"claude-sonnet-4.6",name:"Claude Sonnet 4.6 (max) (1.3x)",contextLimit:B("claude-sonnet-4-6"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-low",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (low) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-medium",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (medium) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-high",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (high) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-xhigh",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (xhigh) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-sonnet-5-max",wireId:"claude-sonnet-5",name:"Claude Sonnet 5 (max) (1.3x)",contextLimit:B("claude-sonnet-5"),outputLimit:64000,modalities:a},{id:"claude-haiku-4-5",wireId:"claude-haiku-4.5",name:"Claude Haiku 4.5 (0.4x)",contextLimit:B("claude-haiku-4-5"),outputLimit:64000,modalities:ut},{id:"claude-opus-4-5",wireId:"claude-opus-4.5",name:"Claude Opus 4.5 (2.2x)",contextLimit:B("claude-opus-4-5"),outputLimit:64000,modalities:a},{id:"claude-opus-4-6",wireId:"claude-opus-4.6",name:"Claude Opus 4.6 (2.2x)",contextLimit:B("claude-opus-4-6"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-low",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (low) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-medium",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (medium) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-high",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (high) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-xhigh",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-7-max",wireId:"claude-opus-4.7",name:"Claude Opus 4.7 (max) (2.2x)",contextLimit:B("claude-opus-4-7"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-low",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (low) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-medium",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (medium) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-high",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (high) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-xhigh",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (xhigh) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-max",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 (max) (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"claude-opus-4-8-thinking",wireId:"claude-opus-4.8",name:"Claude Opus 4.8 Thinking (2.2x)",contextLimit:B("claude-opus-4-8"),outputLimit:64000,modalities:a},{id:"deepseek-3.2",wireId:"deepseek-3.2",name:"DeepSeek 3.2 (0.25x)",contextLimit:B("deepseek-3.2"),outputLimit:64000,modalities:Rr},{id:"glm-5",wireId:"glm-5",name:"GLM-5 (0.5x)",contextLimit:B("glm-5"),outputLimit:64000,modalities:Rr},{id:"minimax-m2.5",wireId:"minimax-m2.5",name:"MiniMax M2.5 (0.25x)",contextLimit:B("minimax-m2.5"),outputLimit:64000,modalities:Rr},{id:"minimax-m2.1",wireId:"minimax-m2.1",name:"MiniMax M2.1 (0.15x)",contextLimit:B("minimax-m2.1"),outputLimit:64000,modalities:Rr},{id:"qwen3-coder-next",wireId:"qwen3-coder-next",name:"Qwen3 Coder Next (0.05x)",contextLimit:B("qwen3-coder-next"),outputLimit:64000,modalities:Rr},{id:"gpt-5.6-sol",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-low",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (low) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-medium",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (medium) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-high",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (high) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-xhigh",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (xhigh) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-sol-max",wireId:"gpt-5.6-sol",name:"GPT 5.6 Sol (max) (2.4x)",contextLimit:B("gpt-5.6-sol"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-low",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (low) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-medium",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (medium) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-high",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (high) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-xhigh",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (xhigh) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-terra-max",wireId:"gpt-5.6-terra",name:"GPT 5.6 Terra (max) (1.2x)",contextLimit:B("gpt-5.6-terra"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-low",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (low)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-medium",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (medium)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-high",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (high)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-xhigh",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (xhigh)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut},{id:"gpt-5.6-luna-max",wireId:"gpt-5.6-luna",name:"GPT 5.6 Luna (max)",contextLimit:B("gpt-5.6-luna"),outputLimit:64000,modalities:ut}]);var f0=g.record(g.unknown()),$9=new Set(cd),U9=g.object({type:g.literal("text"),text:g.string()}).passthrough(),L9=g.object({type:g.literal("image_url"),image_url:g.object({url:g.string(),detail:g.string().optional()}).passthrough()}).passthrough(),I9=g.object({type:g.literal("image"),source:g.object({type:g.string(),data:g.string(),media_type:g.string().optional()}).passthrough()}).passthrough(),y9=g.object({type:g.literal("tool_result"),tool_use_id:g.string().min(1),content:g.unknown()}).passthrough(),O9=g.object({type:g.literal("tool_use"),id:g.string().min(1),name:g.string().min(1),input:g.unknown()}).passthrough(),G9=g.object({type:g.literal("thinking"),thinking:g.string().optional(),text:g.string().optional()}).passthrough(),B9=g.discriminatedUnion("type",[U9,L9,I9,y9,O9,G9]),No=g.union([g.string(),g.array(B9)]);function ud(t){try{return JSON.parse(t),!0}catch(n){if(n instanceof SyntaxError)return!1;throw n}}var F9=g.object({id:g.string().min(1),type:g.literal("function"),function:g.object({name:g.string().min(1),arguments:g.string().refine(ud,"function arguments must contain valid JSON")}).passthrough()}).passthrough(),H9=g.object({role:g.literal("system"),content:No}).passthrough(),P9=g.object({role:g.literal("user"),content:No}).passthrough(),N9=g.object({role:g.literal("assistant"),content:No.nullable().optional(),tool_calls:g.array(F9).min(1).optional()}).passthrough().refine((t)=>t.content!==null&&t.content!==void 0?!0:t.tool_calls!==void 0,{message:"assistant message requires content or tool_calls"}),W9=g.object({role:g.literal("tool"),content:No,tool_call_id:g.string().min(1)}).passthrough(),D9=g.union([H9,P9,N9,W9]),m9=g.object({type:g.literal("function"),function:g.object({name:g.string().min(1),description:g.string().optional(),parameters:f0.optional()}).passthrough()}).passthrough(),Y9=g.object({name:g.string().min(1),description:g.string().optional(),input_schema:f0.optional()}).passthrough(),Q9=g.object({model:g.string().refine((t)=>$9.has(t),{message:"model is not supported"}),stream:g.boolean().default(!1),messages:g.array(D9).min(1),tools:g.array(g.union([m9,Y9])).optional(),reasoning_effort:g.enum(["low","medium","high","xhigh","max"]).optional()}).passthrough(),J9=g.object({type:g.literal("input_text"),text:g.string()}).passthrough(),k9=g.object({type:g.literal("output_text"),text:g.string()}).passthrough(),z9=g.object({type:g.literal("input_image"),image_url:g.string()}).passthrough(),X9=new Set(["input_text","output_text","input_image"]),x9=g.object({type:g.string()}).passthrough().refine((t)=>!X9.has(t.type),{message:"known content parts must have a valid payload"}),q9=g.union([J9,k9,z9,x9]),C9=g.object({type:g.literal("message"),role:g.enum(["system","developer","user","assistant"]),content:g.array(q9)}).passthrough(),K9=g.object({type:g.literal("function_call"),call_id:g.string().min(1),name:g.string().min(1),arguments:g.string().refine(ud,"function arguments must contain valid JSON")}).passthrough(),V9=g.object({type:g.literal("function_call_output"),call_id:g.string().min(1),output:g.union([g.string(),g.array(g.object({type:g.string(),text:g.string().optional()}).passthrough())])}).passthrough(),j9=g.object({type:g.literal("additional_tools"),role:g.string().optional(),tools:g.array(g.object({type:g.string()}).passthrough())}).passthrough(),a9=g.object({type:g.literal("summary_text"),text:g.string()}).passthrough(),p9=g.object({type:g.literal("reasoning_text"),reasoning_text:g.string()}).passthrough(),Z9=g.object({type:g.literal("reasoning"),summary:g.array(a9).optional(),content:g.array(p9).optional(),encrypted_content:g.string().optional()}).passthrough(),v9=new Set(["message","function_call","function_call_output","additional_tools","reasoning"]),tm=g.object({type:g.string()}).passthrough().refine((t)=>!v9.has(t.type),{message:"known input items must have a valid payload"}),nm=g.union([C9,K9,V9,j9,Z9,tm]),sm=g.object({type:g.literal("function"),name:g.string().min(1),description:g.string().optional(),parameters:f0.optional(),strict:g.boolean().optional()}).passthrough(),im=g.object({effort:g.enum(["none","minimal","low","medium","high","xhigh"]).optional(),summary:g.unknown().optional()}).passthrough(),rm=g.object({model:g.string(),input:g.union([g.string(),g.array(nm)]),instructions:g.string().optional(),stream:g.boolean().default(!1),tools:g.array(sm).optional(),tool_choice:g.literal("auto").optional(),parallel_tool_calls:g.boolean().optional(),reasoning:im.nullable().optional(),include:g.array(g.string()).optional(),store:g.boolean().optional(),text:g.unknown().optional(),service_tier:g.unknown().optional(),prompt_cache_key:g.string().optional(),client_metadata:g.unknown().optional(),previous_response_id:g.string().optional()}).passthrough();function Wo(t){let n=Q9.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((i)=>{return`${i.path.length>0?i.path.join("."):"request"}: ${i.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}function ld(t){let n=rm.safeParse(t);if(n.success)return{ok:!0,value:n.data};let s=n.error.issues.map((i)=>{return`${i.path.length>0?i.path.join("."):"request"}: ${i.message}`}).join(", ");return{ok:!1,response:V(400,`Invalid request: ${s}`,"invalid_request_error","invalid_request")}}class h0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function c0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function em(t,n,s){let i=t.body?.getReader();if(!i)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=c0(s.combined);f?.(h),i.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw c0(s.combined);let l=await Promise.race([i.read(),o]);if(s.combined.aborted)throw c0(s.combined);if(l.done)break;if(e+=l.value.byteLength,e>n)throw new h0(n);r.push(l.value)}let h=new Uint8Array(e),u=0;for(let l of r)h.set(l,u),u+=l.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof h0)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function om(t,n){let s=t.body;if(!s)return t;let i=s.getReader(),r=new TextDecoder,e=new TextEncoder,f="",o=!1,c=!1,h=()=>{if(c)return;c=!0,n()};return new Response(new ReadableStream({async pull(u){try{while(!0){let l=f.indexOf(`
135
+ `);if(l>=0){let A=f.slice(0,l).trimEnd();if(f=f.slice(l+1),A.length>0){u.enqueue(e.encode(`data: ${A}
136
136
 
137
- `));return}continue}let l=await r.read();if(!l.done){f+=i.decode(l.value,{stream:!0});continue}f+=i.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(e.encode(`data: ${w}
137
+ `));return}continue}let _=await i.read();if(!_.done){f+=r.decode(_.value,{stream:!0});continue}f+=r.decode();let w=f.trim();if(f="",w.length>0){u.enqueue(e.encode(`data: ${w}
138
138
 
139
139
  `));return}if(!o){o=!0,u.enqueue(e.encode(`data: [DONE]
140
140
 
141
- `));return}u.close(),h();return}}catch{let _=JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}});u.enqueue(e.encode(`data: ${_}
141
+ `));return}u.close(),h();return}}catch{let l=JSON.stringify({error:{message:"Upstream stream error",type:"upstream_error"}});u.enqueue(e.encode(`data: ${l}
142
142
 
143
- `)),u.close(),h()}},cancel(u){r.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function lE(t,n,s){let r=new AbortController,i=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([r.signal,t.signal]),f={combined:e,deadline:r.signal,client:t.signal},o=await iY(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(i),o.response;let c;try{c=JSON.parse(o.text)}catch(l){if(clearTimeout(i),!(l instanceof SyntaxError))throw l;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Wo(c);if(!h.ok)return clearTimeout(i),h.response;let u=await Po({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return clearTimeout(i),V(499,"Client closed request","request_aborted","client_disconnected");let _=u.headers.get("Content-Type")??"";if(!h.value.stream||_.includes("application/json"))return clearTimeout(i),u;if(!_.includes("application/x-ndjson"))return clearTimeout(i),V(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return eY(u,()=>clearTimeout(i))}function wE(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var oY=1700000000;function AE(){let t=hE.map((n)=>({id:n.id,object:"model",created:oY,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}import{randomUUID as l0}from"crypto";function fY(t){return t.type==="message"}function cY(t){return t.type==="function_call"}function hY(t){return t.type==="function_call_output"}function uY(t){return t.type==="reasoning"}function _Y(t,n){let s=[];for(let r of t){if((r.type==="input_text"||r.type==="output_text")&&"text"in r&&typeof r.text==="string"){s.push({type:"text",text:r.text});continue}if(r.type==="input_image"&&"image_url"in r&&typeof r.image_url==="string"){s.push({type:"image_url",image_url:{url:r.image_url}});continue}n.count++}return s}function lY(t){return[...(t.summary??[]).map((n)=>n.text),...(t.content??[]).map((n)=>n.reasoning_text)].filter((n)=>n.length>0).join(`
144
- `)}function wY(t){if(t==="minimal")return"low";if(t==="low"||t==="medium"||t==="high"||t==="xhigh")return t;return}function u0(t){return{type:"thinking",thinking:t}}function ME(t){let n=[],s={count:0},r=0,i=!1,e="";if(t.instructions&&t.instructions.length>0)n.push({role:"system",content:t.instructions});if(typeof t.input==="string")n.push({role:"user",content:t.input}),i=!0;else{let c=()=>{if(!e)return;n.push({role:"assistant",content:[u0(e)]}),e="",i=!0};for(let h of t.input){if(uY(h)){let u=lY(h);if(u)e=e?`${e}
145
- ${u}`:u;continue}if(cY(h)){n.push({role:"assistant",...e?{content:[u0(e)]}:{},tool_calls:[{id:h.call_id,type:"function",function:{name:h.name,arguments:h.arguments}}]}),e="",i=!0;continue}if(fY(h)){if(h.role!=="assistant")c();let u=_Y(h.content,s);if(h.role==="assistant")n.push({role:"assistant",content:e?[u0(e),...u]:u}),e="",i=!0;else if(n.push({role:h.role,content:u}),h.role==="user")i=!0;continue}if(hY(h)){c(),n.push({role:"tool",tool_call_id:h.call_id,content:h.output}),i=!0;continue}c(),r++}c()}if(s.count,!i)return{ok:!1,code:"empty_input"};let f=wY(t.reasoning?.effort);return{ok:!0,body:{model:t.model,stream:t.stream,messages:n,...t.tools?{tools:t.tools.map((c)=>({type:"function",function:{name:c.name,...c.description!==void 0?{description:c.description}:{},...c.parameters!==void 0?{parameters:c.parameters}:{}}}))}:{},...t.tool_choice!==void 0?{tool_choice:t.tool_choice}:{},...f!==void 0?{reasoning_effort:f}:{}}}}import{randomUUID as Yo}from"crypto";function gE(t){return{type:"response.created",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"in_progress",model:t.model,output:[]}}}function _0(t){return{type:"response.output_item.added",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function EE(t){return{type:"response.output_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,content_index:t.contentIndex,delta:t.delta}}function dE(t){return{type:"response.reasoning_summary_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,delta:t.delta}}function RE(t){return{type:"response.reasoning_summary_text.done",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,text:t.text}}function Do(t){return{type:"response.output_item.done",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function bE(t){return{type:"response.completed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"completed",model:t.model,output:t.output,usage:t.usage}}}function TE(t){return{type:"response.failed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"failed",model:t.model,error:t.error}}}function SE(t){return`event: ${t.type}
143
+ `)),u.close(),h()}},cancel(u){i.cancel(u).catch(()=>{return}),h()}}),{status:t.status,headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache",Connection:"keep-alive"}})}async function _d(t,n,s){let i=new AbortController,r=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([i.signal,t.signal]),f={combined:e,deadline:i.signal,client:t.signal},o=await em(t,n.max_request_body_bytes,f);if(!o.ok)return clearTimeout(r),o.response;let c;try{c=JSON.parse(o.text)}catch(_){if(clearTimeout(r),!(_ instanceof SyntaxError))throw _;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let h=Wo(c);if(!h.ok)return clearTimeout(r),h.response;let u=await Po({body:h.value,model:h.value.model,stream:h.value.stream,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!i.signal.aborted)return clearTimeout(r),V(499,"Client closed request","request_aborted","client_disconnected");let l=u.headers.get("Content-Type")??"";if(!h.value.stream||l.includes("application/json"))return clearTimeout(r),u;if(!l.includes("application/x-ndjson"))return clearTimeout(r),V(500,"Pipeline returned an unsupported streaming response","internal_error","invalid_pipeline_response");return om(u,()=>clearTimeout(r))}function wd(){return new Response(JSON.stringify({status:"ok"}),{status:200,headers:{"Content-Type":"application/json"}})}var fm=1700000000;function Ad(){let t=hd.map((n)=>({id:n.id,object:"model",created:fm,owned_by:"kiro",name:n.name,context_limit:n.contextLimit,output_limit:n.outputLimit,modalities:n.modalities}));return new Response(JSON.stringify({object:"list",data:t}),{status:200,headers:{"Content-Type":"application/json"}})}import{randomUUID as _0}from"crypto";function cm(t){return t.type==="message"}function hm(t){return t.type==="function_call"}function um(t){return t.type==="function_call_output"}function lm(t){return t.type==="additional_tools"}function _m(t){return t.type==="reasoning"}function wm(t,n){let s=[];for(let i of t){if((i.type==="input_text"||i.type==="output_text")&&"text"in i&&typeof i.text==="string"){s.push({type:"text",text:i.text});continue}if(i.type==="input_image"&&"image_url"in i&&typeof i.image_url==="string"){s.push({type:"image_url",image_url:{url:i.image_url}});continue}n.count++}return s}function Am(t){return[...(t.summary??[]).map((n)=>n.text),...(t.content??[]).map((n)=>n.reasoning_text)].filter((n)=>n.length>0).join(`
144
+ `)}function Mm(t){if(t==="minimal")return"low";if(t==="low"||t==="medium"||t==="high"||t==="xhigh")return t;return}function u0(t){return{type:"thinking",thinking:t}}function gm(t){if(typeof t==="string")return t;return t.flatMap((n)=>n.text===void 0?[]:[n.text]).join(`
145
+ `)}function dm(t){return{type:"function",function:{name:t.name,...t.description!==void 0?{description:t.description}:{},...t.parameters!==void 0?{parameters:t.parameters}:{}}}}function Md(t){let n=[],s=(t.tools??[]).map(dm),i=new Set(s.map((l)=>l.function.name)),r={count:0},e=0,f=0,o=!1,c="";if(t.instructions&&t.instructions.length>0)n.push({role:"system",content:t.instructions});if(typeof t.input==="string")n.push({role:"user",content:t.input}),o=!0;else{let l=()=>{if(!c)return;n.push({role:"assistant",content:[u0(c)]}),c="",o=!0};for(let _ of t.input){if(_m(_)){let w=Am(_);if(w)c=c?`${c}
146
+ ${w}`:w;continue}if(hm(_)){n.push({role:"assistant",...c?{content:[u0(c)]}:{},tool_calls:[{id:_.call_id,type:"function",function:{name:_.name,arguments:_.arguments}}]}),c="",o=!0;continue}if(cm(_)){if(_.role!=="assistant")l();let w=wm(_.content,r);if(_.role==="assistant")n.push({role:"assistant",content:c?[u0(c),...w]:w}),c="",o=!0;else if(n.push({role:_.role==="developer"?"system":_.role,content:w}),_.role==="user")o=!0;continue}if(um(_)){l(),n.push({role:"tool",tool_call_id:_.call_id,content:gm(_.output)}),o=!0;continue}if(lm(_)){for(let w of _.tools){if(w.type!=="function"||typeof w.name!=="string"||w.name.length===0||typeof w.parameters!=="object"||w.parameters===null||Array.isArray(w.parameters)||i.has(w.name)){f++;continue}s.push({type:"function",function:{name:w.name,...typeof w.description==="string"?{description:w.description}:{},parameters:Object.fromEntries(Object.entries(w.parameters))}}),i.add(w.name)}continue}l(),e++}l()}if(r.count,!o)return{ok:!1,code:"empty_input"};let h=Mm(t.reasoning?.effort);return{ok:!0,body:{model:t.model,stream:t.stream,messages:n,...s.length>0||t.tools!==void 0?{tools:s}:{},...t.tool_choice!==void 0?{tool_choice:t.tool_choice}:{},...h!==void 0?{reasoning_effort:h}:{}}}}import{randomUUID as mo}from"crypto";function gd(t){return{type:"response.created",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"in_progress",model:t.model,output:[]}}}function l0(t){return{type:"response.output_item.added",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function dd(t){return{type:"response.output_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,content_index:t.contentIndex,delta:t.delta}}function Ed(t){return{type:"response.reasoning_summary_text.delta",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,delta:t.delta}}function Rd(t){return{type:"response.reasoning_summary_text.done",sequence_number:t.sequenceNumber,item_id:t.itemId,output_index:t.outputIndex,summary_index:t.summaryIndex,text:t.text}}function Do(t){return{type:"response.output_item.done",sequence_number:t.sequenceNumber,output_index:t.outputIndex,item:t.item}}function bd(t){return{type:"response.completed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"completed",model:t.model,output:t.output,usage:t.usage}}}function Td(t){return{type:"response.failed",sequence_number:t.sequenceNumber,response:{id:t.responseId,object:"response",status:"failed",model:t.model,error:t.error}}}function Sd(t){return`event: ${t.type}
146
147
  data: ${JSON.stringify(t)}
147
148
 
148
- `}function wr(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function AY(t){if(!wr(t)||typeof t.index!=="number"||!wr(t.function))return;let n=t.id,s=t.function.name,r=t.function.arguments;if(n!==void 0&&typeof n!=="string"||s!==void 0&&typeof s!=="string"||typeof r!=="string")return;return{index:t.index,id:n,name:s,arguments:r}}function MY(t){if(!wr(t))return;let n=["content","reasoning_content","tool_calls"].filter((r)=>t[r]!==void 0);if(n.length===0)return{kind:"empty"};if(n.length!==1)return;if(typeof t.content==="string")return{kind:"text",text:t.content};if(typeof t.reasoning_content==="string")return{kind:"reasoning",text:t.reasoning_content};if(!Array.isArray(t.tool_calls))return;let s=[];for(let r of t.tool_calls){let i=AY(r);if(!i)return;s.push(i)}return{kind:"tool_calls",calls:s}}function gY(t){if(!wr(t))return;if(typeof t.prompt_tokens!=="number"||typeof t.completion_tokens!=="number"||typeof t.total_tokens!=="number")return;return{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,total_tokens:t.total_tokens}}function $E(t){let n;try{n=JSON.parse(t)}catch(f){if(f instanceof SyntaxError)return;throw f}if(!wr(n)||n.object!=="chat.completion.chunk"||!Array.isArray(n.choices))return;let s=n.choices[0];if(!wr(s))return;let r=MY(s.delta),i=s.finish_reason;if(!r||i!==null&&i!=="stop"&&i!=="tool_calls")return;let e=n.usage===void 0?void 0:gY(n.usage);if(n.usage!==void 0&&!e)return;return{delta:r,finishReason:i,usage:e}}function UE(t,n){let r=(t.body??new ReadableStream({start:(G)=>G.close()})).getReader(),i=new TextDecoder,e=new TextEncoder,f=`resp_${Yo()}`,o=`msg_${Yo()}`,c=new Map,h=new Map,u="",_="",l,w,A=0,M=0,E=!1,d=!1,T=!1,U=()=>{if(T)return;T=!0,n.finalize()},S=(G,K)=>{G.enqueue(e.encode(SE(K(M)))),M+=1},O=async(G)=>{await r.cancel(G).catch(()=>{return})},D=async(G,K)=>{if(d)return;d=!0,S(G,(R)=>TE({responseId:f,model:n.model,error:{code:"upstream_error",message:K},sequenceNumber:R})),await O(),U(),G.close()},q=(G)=>{if(!w)return;let K={id:w.id,type:"reasoning",summary:[{type:"summary_text",text:w.text}]};S(G,(R)=>RE({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,text:w?.text??"",sequenceNumber:R})),S(G,(R)=>Do({item:K,outputIndex:w?.outputIndex??0,sequenceNumber:R})),h.set(w.outputIndex,K),w=void 0},tt=(G,K)=>{switch(K.kind){case"empty":return;case"reasoning":{if(!w)w={id:`rs_${Yo()}`,outputIndex:A,text:""},A+=1,S(G,(R)=>_0({item:{id:w?.id??"",type:"reasoning",summary:[]},outputIndex:w?.outputIndex??0,sequenceNumber:R}));w.text+=K.text,S(G,(R)=>dE({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,delta:K.text,sequenceNumber:R}));return}case"text":{if(q(G),l===void 0)l=A,A+=1,S(G,(R)=>_0({item:{id:o,type:"message",role:"assistant",content:[]},outputIndex:l??0,sequenceNumber:R}));_+=K.text,S(G,(R)=>EE({itemId:o,outputIndex:l??0,contentIndex:0,delta:K.text,sequenceNumber:R}));return}case"tool_calls":q(G);for(let R of K.calls){let W=c.get(R.index)??{itemId:`fc_${Yo()}`,id:"",name:"",arguments:""};if(W.id.length===0&&R.id!==void 0)W.id=R.id;if(W.name.length===0&&R.name!==void 0)W.name=R.name;W.arguments+=R.arguments,c.set(R.index,W)}return}},J=async(G,K)=>{if([...c.values()].some((k)=>k.id.length===0||k.name.length===0)){await D(G,"Malformed upstream tool call");return}if(q(G),l!==void 0){let k={id:o,type:"message",role:"assistant",content:[{type:"output_text",text:_}]};S(G,(st)=>Do({item:k,outputIndex:l??0,sequenceNumber:st})),h.set(l,k)}for(let[,k]of[...c.entries()].sort(([st],[bi])=>st-bi)){let st=A;A+=1;let bi={id:k.itemId,type:"function_call",call_id:k.id,name:k.name,arguments:k.arguments};S(G,(PE)=>Do({item:bi,outputIndex:st,sequenceNumber:PE})),h.set(st,bi)}let W=[...h.entries()].sort(([k],[st])=>k-st).map(([,k])=>k);E=!0,d=!0,S(G,(k)=>bE({responseId:f,model:n.model,output:W,usage:K,sequenceNumber:k})),await O(),U(),G.close()};return new Response(new ReadableStream({start(G){S(G,(K)=>gE({responseId:f,model:n.model,sequenceNumber:K}))},async pull(G){try{while(!d){let K=u.indexOf(`
149
- `);if(K>=0){let k=u.slice(0,K).trimEnd();if(u=u.slice(K+1),k.length===0)continue;let st=$E(k);if(!st){await D(G,"Malformed upstream stream");return}if(tt(G,st.delta),st.finishReason!==null){if(!st.usage){await D(G,"Terminal upstream chunk omitted usage");return}await J(G,st.usage);return}if(st.delta.kind!=="tool_calls"&&st.delta.kind!=="empty")return;continue}let R=await r.read();if(!R.done){u+=i.decode(R.value,{stream:!0});continue}u+=i.decode();let W=u.trim();if(u="",W.length>0){let k=$E(W);if(!k){await D(G,"Malformed upstream stream");return}if(tt(G,k.delta),k.finishReason!==null&&k.usage){await J(G,k.usage);return}}if(!E)await D(G,"Upstream stream ended before completion");return}}catch{await D(G,"Upstream stream error")}finally{if(d)U()}},async cancel(G){d=!0,await O(G),U()}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class A0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function w0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function EY(t,n,s){let r=t.body?.getReader();if(!r)return{ok:!0,text:""};let i=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=w0(s.combined);f?.(h),r.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw w0(s.combined);let _=await Promise.race([r.read(),o]);if(s.combined.aborted)throw w0(s.combined);if(_.done)break;if(e+=_.value.byteLength,e>n)throw new A0(n);i.push(_.value)}let h=new Uint8Array(e),u=0;for(let _ of i)h.set(_,u),u+=_.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof A0)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return r.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function Ar(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function dY(t){if(!Ar(t)||!Array.isArray(t.choices)||!Ar(t.usage))return;let n=t.choices[0];if(!Ar(n)||!Ar(n.message))return;let s=n.message;if(typeof s.content!=="string")return;let r=s.reasoning_content;if(r!==void 0&&typeof r!=="string")return;let i=[];if(s.tool_calls!==void 0){if(!Array.isArray(s.tool_calls))return;for(let e of s.tool_calls){if(!Ar(e)||typeof e.id!=="string"||!Ar(e.function)||typeof e.function.name!=="string"||typeof e.function.arguments!=="string")return;i.push({id:e.id,name:e.function.name,arguments:e.function.arguments})}}if(typeof t.usage.prompt_tokens!=="number"||typeof t.usage.completion_tokens!=="number"||typeof t.usage.total_tokens!=="number")return;return{message:{content:s.content,reasoningContent:r,toolCalls:i},usage:{input_tokens:t.usage.prompt_tokens,output_tokens:t.usage.completion_tokens,total_tokens:t.usage.total_tokens}}}function RY(t,n){let s=[];if(t.message.reasoningContent){let i={id:`rs_${l0()}`,type:"reasoning",summary:[{type:"summary_text",text:t.message.reasoningContent}]};s.push(i)}let r={id:`msg_${l0()}`,type:"message",role:"assistant",content:[{type:"output_text",text:t.message.content}]};s.push(r);for(let i of t.message.toolCalls){let e={type:"function_call",call_id:i.id,name:i.name,arguments:i.arguments};s.push(e)}return Response.json({id:`resp_${l0()}`,object:"response",status:"completed",model:n,output:s,usage:t.usage})}async function LE(t,n,s){let r=new AbortController,i=setTimeout(()=>r.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([r.signal,t.signal]),f=await EY(t,n.max_request_body_bytes,{combined:e,deadline:r.signal,client:t.signal});if(!f.ok)return clearTimeout(i),f.response;let o;try{o=JSON.parse(f.text)}catch(A){if(clearTimeout(i),!(A instanceof SyntaxError))throw A;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let c=_E(o);if(!c.ok)return clearTimeout(i),c.response;let h=ME(c.value);if(!h.ok)return clearTimeout(i),V(400,"input produced no messages","invalid_request_error","empty_input");let u=Wo(h.body);if(!u.ok)return clearTimeout(i),u.response;let _=c.value.stream,l=await(s.runPipeline??Po)({body:u.value,model:u.value.model,stream:_,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!r.signal.aborted)return await l.body?.cancel().catch(()=>{return}),clearTimeout(i),V(499,"Client closed request","request_aborted","client_disconnected");let w=l.headers.get("Content-Type")??"";if(_&&w.includes("application/x-ndjson"))return UE(l,{model:u.value.model,finalize:()=>clearTimeout(i)});if(w.includes("application/json")){if(clearTimeout(i),_||!l.ok)return l;let A=await l.json(),M=dY(A);if(M)return RY(M,u.value.model);return V(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return await l.body?.cancel().catch(()=>{return}),clearTimeout(i),V(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}function bY(t,n){return async(s)=>{let r=ou(s,t.api_keys);if(!r.ok)return r.response;let i=new URL(s.url);try{if(s.method==="POST"&&i.pathname==="/v1/chat/completions")return await lE(s,t,n);if(s.method==="POST"&&i.pathname==="/v1/responses")return await LE(s,t,n);if(s.method==="GET"&&i.pathname==="/v1/models")return AE();if(s.method==="GET"&&i.pathname==="/health")return wE();return V(404,"Route not found","invalid_request_error","not_found")}catch(e){let f=e instanceof Error?e.message:"Internal server error";return V(500,f,"internal_error","internal_error")}}}function TY(t,n={}){let s=n.createDatabase?.()??new rs,r=new qo(s.getAccounts(),t.account_selection_strategy,s),i=Qs(t),e=n.createTokenRefresher?n.createTokenRefresher(r,t.token_expiry_buffer_ms,i):new tf(r,t.token_expiry_buffer_ms,i);return{accountManager:r,tokenRefresher:e}}function IE(t){return Bun.serve({hostname:t.host,port:t.port,fetch:bY(t,TY(t))})}import{parseArgs as M0}from"util";var mo=`Usage: kiro-provider <command> [options]
149
+ `}function wi(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Em(t){if(!wi(t)||typeof t.index!=="number"||!wi(t.function))return;let n=t.id,s=t.function.name,i=t.function.arguments;if(n!==void 0&&typeof n!=="string"||s!==void 0&&typeof s!=="string"||typeof i!=="string")return;return{index:t.index,id:n,name:s,arguments:i}}function Rm(t){if(!wi(t))return;let n=["content","reasoning_content","tool_calls"].filter((i)=>t[i]!==void 0);if(n.length===0)return{kind:"empty"};if(n.length!==1)return;if(typeof t.content==="string")return{kind:"text",text:t.content};if(typeof t.reasoning_content==="string")return{kind:"reasoning",text:t.reasoning_content};if(!Array.isArray(t.tool_calls))return;let s=[];for(let i of t.tool_calls){let r=Em(i);if(!r)return;s.push(r)}return{kind:"tool_calls",calls:s}}function bm(t){if(!wi(t))return;if(typeof t.prompt_tokens!=="number"||typeof t.completion_tokens!=="number"||typeof t.total_tokens!=="number")return;return{input_tokens:t.prompt_tokens,output_tokens:t.completion_tokens,total_tokens:t.total_tokens}}function $d(t){let n;try{n=JSON.parse(t)}catch(f){if(f instanceof SyntaxError)return;throw f}if(!wi(n)||n.object!=="chat.completion.chunk"||!Array.isArray(n.choices))return;let s=n.choices[0];if(!wi(s))return;let i=Rm(s.delta),r=s.finish_reason;if(!i||r!==null&&r!=="stop"&&r!=="tool_calls")return;let e=n.usage===void 0?void 0:bm(n.usage);if(n.usage!==void 0&&!e)return;return{delta:i,finishReason:r,usage:e}}function Ud(t,n){let i=(t.body??new ReadableStream({start:(G)=>G.close()})).getReader(),r=new TextDecoder,e=new TextEncoder,f=`resp_${mo()}`,o=`msg_${mo()}`,c=new Map,h=new Map,u="",l="",_,w,A=0,M=0,d=!1,E=!1,T=!1,U=()=>{if(T)return;T=!0,n.finalize()},S=(G,K)=>{G.enqueue(e.encode(Sd(K(M)))),M+=1},y=async(G)=>{await i.cancel(G).catch(()=>{return})},D=async(G,K)=>{if(E)return;E=!0,S(G,(R)=>Td({responseId:f,model:n.model,error:{code:"upstream_error",message:K},sequenceNumber:R})),await y(),U(),G.close()},q=(G)=>{if(!w)return;let K={id:w.id,type:"reasoning",summary:[{type:"summary_text",text:w.text}]};S(G,(R)=>Rd({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,text:w?.text??"",sequenceNumber:R})),S(G,(R)=>Do({item:K,outputIndex:w?.outputIndex??0,sequenceNumber:R})),h.set(w.outputIndex,K),w=void 0},tt=(G,K)=>{switch(K.kind){case"empty":return;case"reasoning":{if(!w)w={id:`rs_${mo()}`,outputIndex:A,text:""},A+=1,S(G,(R)=>l0({item:{id:w?.id??"",type:"reasoning",summary:[]},outputIndex:w?.outputIndex??0,sequenceNumber:R}));w.text+=K.text,S(G,(R)=>Ed({itemId:w?.id??"",outputIndex:w?.outputIndex??0,summaryIndex:0,delta:K.text,sequenceNumber:R}));return}case"text":{if(q(G),_===void 0)_=A,A+=1,S(G,(R)=>l0({item:{id:o,type:"message",role:"assistant",content:[]},outputIndex:_??0,sequenceNumber:R}));l+=K.text,S(G,(R)=>dd({itemId:o,outputIndex:_??0,contentIndex:0,delta:K.text,sequenceNumber:R}));return}case"tool_calls":q(G);for(let R of K.calls){let W=c.get(R.index)??{itemId:`fc_${mo()}`,id:"",name:"",arguments:""};if(W.id.length===0&&R.id!==void 0)W.id=R.id;if(W.name.length===0&&R.name!==void 0)W.name=R.name;W.arguments+=R.arguments,c.set(R.index,W)}return}},J=async(G,K)=>{if([...c.values()].some((k)=>k.id.length===0||k.name.length===0)){await D(G,"Malformed upstream tool call");return}if(q(G),_!==void 0){let k={id:o,type:"message",role:"assistant",content:[{type:"output_text",text:l}]};S(G,(st)=>Do({item:k,outputIndex:_??0,sequenceNumber:st})),h.set(_,k)}for(let[,k]of[...c.entries()].sort(([st],[br])=>st-br)){let st=A;A+=1;let br={id:k.itemId,type:"function_call",call_id:k.id,name:k.name,arguments:k.arguments};S(G,(Pd)=>Do({item:br,outputIndex:st,sequenceNumber:Pd})),h.set(st,br)}let W=[...h.entries()].sort(([k],[st])=>k-st).map(([,k])=>k);d=!0,E=!0,S(G,(k)=>bd({responseId:f,model:n.model,output:W,usage:K,sequenceNumber:k})),await y(),U(),G.close()};return new Response(new ReadableStream({start(G){S(G,(K)=>gd({responseId:f,model:n.model,sequenceNumber:K}))},async pull(G){try{while(!E){let K=u.indexOf(`
150
+ `);if(K>=0){let k=u.slice(0,K).trimEnd();if(u=u.slice(K+1),k.length===0)continue;let st=$d(k);if(!st){await D(G,"Malformed upstream stream");return}if(tt(G,st.delta),st.finishReason!==null){if(!st.usage){await D(G,"Terminal upstream chunk omitted usage");return}await J(G,st.usage);return}if(st.delta.kind!=="tool_calls"&&st.delta.kind!=="empty")return;continue}let R=await i.read();if(!R.done){u+=r.decode(R.value,{stream:!0});continue}u+=r.decode();let W=u.trim();if(u="",W.length>0){let k=$d(W);if(!k){await D(G,"Malformed upstream stream");return}if(tt(G,k.delta),k.finishReason!==null&&k.usage){await J(G,k.usage);return}}if(!d)await D(G,"Upstream stream ended before completion");return}}catch{await D(G,"Upstream stream error")}finally{if(E)U()}},async cancel(G){E=!0,await y(G),U()}}),{headers:{"Cache-Control":"no-cache","Content-Type":"text/event-stream; charset=utf-8"}})}class A0 extends Error{limit;name="RequestBodyTooLargeError";constructor(t){super(`Request body exceeds the ${t} byte limit`);this.limit=t}}function w0(t){return t.reason instanceof Error?t.reason:new DOMException("Request deadline exceeded","TimeoutError")}async function Tm(t,n,s){let i=t.body?.getReader();if(!i)return{ok:!0,text:""};let r=[],e=0,f,o=new Promise((h,u)=>{f=u}),c=()=>{let h=w0(s.combined);f?.(h),i.cancel(h)};s.combined.addEventListener("abort",c,{once:!0});try{while(!0){if(s.combined.aborted)throw w0(s.combined);let l=await Promise.race([i.read(),o]);if(s.combined.aborted)throw w0(s.combined);if(l.done)break;if(e+=l.value.byteLength,e>n)throw new A0(n);r.push(l.value)}let h=new Uint8Array(e),u=0;for(let l of r)h.set(l,u),u+=l.byteLength;return{ok:!0,text:new TextDecoder().decode(h)}}catch(h){if(h instanceof A0)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(413,h.message,"invalid_request_error","request_too_large")};if(s.deadline.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(504,"Request deadline exceeded","timeout_error","request_timeout")};if(s.client.aborted)return i.cancel(h).catch(()=>{return}),{ok:!1,response:V(499,"Client closed request","request_aborted","client_disconnected")};throw h}finally{s.combined.removeEventListener("abort",c)}}function Ai(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function Sm(t){if(!Ai(t)||!Array.isArray(t.choices)||!Ai(t.usage))return;let n=t.choices[0];if(!Ai(n)||!Ai(n.message))return;let s=n.message;if(typeof s.content!=="string")return;let i=s.reasoning_content;if(i!==void 0&&typeof i!=="string")return;let r=[];if(s.tool_calls!==void 0){if(!Array.isArray(s.tool_calls))return;for(let e of s.tool_calls){if(!Ai(e)||typeof e.id!=="string"||!Ai(e.function)||typeof e.function.name!=="string"||typeof e.function.arguments!=="string")return;r.push({id:e.id,name:e.function.name,arguments:e.function.arguments})}}if(typeof t.usage.prompt_tokens!=="number"||typeof t.usage.completion_tokens!=="number"||typeof t.usage.total_tokens!=="number")return;return{message:{content:s.content,reasoningContent:i,toolCalls:r},usage:{input_tokens:t.usage.prompt_tokens,output_tokens:t.usage.completion_tokens,total_tokens:t.usage.total_tokens}}}function $m(t,n){let s=[];if(t.message.reasoningContent){let r={id:`rs_${_0()}`,type:"reasoning",summary:[{type:"summary_text",text:t.message.reasoningContent}]};s.push(r)}let i={id:`msg_${_0()}`,type:"message",role:"assistant",content:[{type:"output_text",text:t.message.content}]};s.push(i);for(let r of t.message.toolCalls){let e={type:"function_call",call_id:r.id,name:r.name,arguments:r.arguments};s.push(e)}return Response.json({id:`resp_${_0()}`,object:"response",status:"completed",model:n,output:s,usage:t.usage})}async function Ld(t,n,s){let i=new AbortController,r=setTimeout(()=>i.abort(new DOMException("Request deadline exceeded","TimeoutError")),n.request_timeout_ms),e=AbortSignal.any([i.signal,t.signal]),f=await Tm(t,n.max_request_body_bytes,{combined:e,deadline:i.signal,client:t.signal});if(!f.ok)return clearTimeout(r),f.response;let o;try{o=JSON.parse(f.text)}catch(A){if(clearTimeout(r),!(A instanceof SyntaxError))throw A;return V(400,"Request body must contain valid JSON","invalid_request_error","invalid_json")}let c=ld(o);if(!c.ok)return clearTimeout(r),c.response;let h=Md(c.value);if(!h.ok)return clearTimeout(r),V(400,"input produced no messages","invalid_request_error","empty_input");let u=Wo(h.body);if(!u.ok)return clearTimeout(r),u.response;let l=c.value.stream,_=await(s.runPipeline??Po)({body:u.value,model:u.value.model,stream:l,config:n,accountManager:s.accountManager,tokenRefresher:s.tokenRefresher,deadlineSignal:e,...s.makeClient?{makeClient:s.makeClient}:{}});if(t.signal.aborted&&!i.signal.aborted)return await _.body?.cancel().catch(()=>{return}),clearTimeout(r),V(499,"Client closed request","request_aborted","client_disconnected");let w=_.headers.get("Content-Type")??"";if(l&&w.includes("application/x-ndjson"))return Ud(_,{model:u.value.model,finalize:()=>clearTimeout(r)});if(w.includes("application/json")){if(clearTimeout(r),l||!_.ok)return _;let A=await _.json(),M=Sm(A);if(M)return $m(M,u.value.model);return V(500,"Pipeline returned an invalid non-streaming response","internal_error","invalid_pipeline_response")}return await _.body?.cancel().catch(()=>{return}),clearTimeout(r),V(500,"Pipeline returned an unsupported response","internal_error","invalid_pipeline_response")}function Um(t,n){return async(s)=>{let i=ou(s,t.api_keys);if(!i.ok)return i.response;let r=new URL(s.url);try{if(s.method==="POST"&&r.pathname==="/v1/chat/completions")return await _d(s,t,n);if(s.method==="POST"&&r.pathname==="/v1/responses")return await Ld(s,t,n);if(s.method==="GET"&&r.pathname==="/v1/models")return Ad();if(s.method==="GET"&&r.pathname==="/health")return wd();return V(404,"Route not found","invalid_request_error","not_found")}catch(e){let f=e instanceof Error?e.message:"Internal server error";return V(500,f,"internal_error","internal_error")}}}function Lm(t,n={}){let s=n.createDatabase?.()??new is,i=new qo(s.getAccounts(),t.account_selection_strategy,s),r=Qs(t),e=n.createTokenRefresher?n.createTokenRefresher(i,t.token_expiry_buffer_ms,r):new tf(i,t.token_expiry_buffer_ms,r);return{accountManager:i,tokenRefresher:e}}function Id(t){return Bun.serve({hostname:t.host,port:t.port,fetch:Um(t,Lm(t))})}import{parseArgs as M0}from"util";var Yo=`Usage: kiro-provider <command> [options]
150
151
 
151
152
  Commands:
152
153
  serve [--config <path>] [--host <host>] [--port <port>] [--proxy <url>]
@@ -161,10 +162,10 @@ Commands:
161
162
  Remove an account and write a tombstone.
162
163
 
163
164
  Options:
164
- -h, --help Show this help.`;class Mr extends Error{constructor(t){super(t);this.name="CliUsageError"}}function SY(t){let n=M0({args:[...t],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};let s=n.values.port===void 0?void 0:Number(n.values.port);if(s!==void 0&&(!Number.isInteger(s)||s<1||s>65535))throw new Mr(`Invalid port: ${n.values.port}`);return{kind:"serve",...n.values.config?{configPath:n.values.config}:{},...n.values.host?{host:n.values.host}:{},...s!==void 0?{port:s}:{},...n.values.proxy!==void 0?{proxy:n.values.proxy}:{}}}function $Y(t){let n=M0({args:[...t],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...n.values.config?{configPath:n.values.config}:{},...n.values["start-url"]?{startUrl:n.values["start-url"]}:{},...n.values.region?{region:n.values.region}:{}}}function UY(t){let n=M0({args:[...t],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};return{kind:"accounts-import",...n.values.from?{from:n.values.from}:{},...n.values.config?{configPath:n.values.config}:{}}}function LY(t){let n=t[0];switch(n){case"list":if(t.length!==1)throw new Mr("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return UY(t.slice(1));case"remove":{let s=t[1];if(!s||t.length!==2)throw new Mr("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:s}}default:throw new Mr(n===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${n}`)}}function g0(t){let n=t[0];switch(n){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return SY(t.slice(1));case"login":return $Y(t.slice(1));case"accounts":return LY(t.slice(1));default:throw new Mr(`Unknown command: ${n}`)}}import{Database as IY}from"bun:sqlite";import{homedir as OY}from"os";import{join as OE}from"path";var yY=g.object({id:g.string().min(1),email:g.string().min(1),auth_method:g.string(),region:g.string(),oidc_region:g.string().nullable(),client_id:g.string().nullable(),client_secret:g.string().nullable(),profile_arn:g.string().nullable(),start_url:g.string().nullable(),refresh_token:g.string(),access_token:g.string(),expires_at:g.number(),rate_limit_reset:g.number().nullable(),is_healthy:g.number().nullable(),unhealthy_reason:g.string().nullable(),recovery_time:g.number().nullable(),fail_count:g.number().nullable(),last_used:g.number().nullable(),used_count:g.number().nullable(),limit_count:g.number().nullable(),last_sync:g.number().nullable(),overage_count:g.number().nullable()});function GY(t=process.env){let n=t.XDG_CONFIG_HOME??OE(OY(),".config");return OE(n,"opencode","kiro.db")}function jt(t){return t===null||t===""?void 0:t}function BY(t){if(!t.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!t.access_token)return{kind:"skipped",reason:"missing access token"};let n=vn.safeParse(t.region);if(!n.success)return{kind:"skipped",reason:"missing or unsupported region"};if(t.auth_method!=="idc"&&t.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(t.auth_method==="idc"&&(!t.client_id||!t.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let s=jt(t.oidc_region),r=s===void 0?void 0:vn.safeParse(s);if(r!==void 0&&!r.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:t.id,email:t.email,authMethod:t.auth_method,region:n.data,...r?.success?{oidcRegion:r.data}:{},...jt(t.client_id)?{clientId:jt(t.client_id)}:{},...jt(t.client_secret)?{clientSecret:jt(t.client_secret)}:{},...jt(t.profile_arn)?{profileArn:jt(t.profile_arn)}:{},...jt(t.start_url)?{startUrl:jt(t.start_url)}:{},refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset??0,isHealthy:t.is_healthy!==0,...jt(t.unhealthy_reason)?{unhealthyReason:jt(t.unhealthy_reason)}:{},...t.recovery_time===null?{}:{recoveryTime:t.recovery_time},failCount:t.fail_count??0,lastUsed:t.last_used??0,usedCount:t.used_count??0,limitCount:t.limit_count??0,lastSync:t.last_sync??0,overageCount:t.overage_count??0}}}function yE(t,n){let s=t.from??GY(),r=new IY(s,{readonly:!0,strict:!0}),i=0,e=0;try{let o=r.query(`SELECT
165
+ -h, --help Show this help.`;class Mi extends Error{constructor(t){super(t);this.name="CliUsageError"}}function Im(t){let n=M0({args:[...t],options:{config:{type:"string"},host:{type:"string"},port:{type:"string"},proxy:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};let s=n.values.port===void 0?void 0:Number(n.values.port);if(s!==void 0&&(!Number.isInteger(s)||s<1||s>65535))throw new Mi(`Invalid port: ${n.values.port}`);return{kind:"serve",...n.values.config?{configPath:n.values.config}:{},...n.values.host?{host:n.values.host}:{},...s!==void 0?{port:s}:{},...n.values.proxy!==void 0?{proxy:n.values.proxy}:{}}}function ym(t){let n=M0({args:[...t],options:{config:{type:"string"},"start-url":{type:"string"},region:{type:"string"}},strict:!0,allowPositionals:!1});return{kind:"login",...n.values.config?{configPath:n.values.config}:{},...n.values["start-url"]?{startUrl:n.values["start-url"]}:{},...n.values.region?{region:n.values.region}:{}}}function Om(t){let n=M0({args:[...t],options:{from:{type:"string"},config:{type:"string"},help:{type:"boolean",short:"h"}},strict:!0,allowPositionals:!1});if(n.values.help)return{kind:"help"};return{kind:"accounts-import",...n.values.from?{from:n.values.from}:{},...n.values.config?{configPath:n.values.config}:{}}}function Gm(t){let n=t[0];switch(n){case"list":if(t.length!==1)throw new Mi("accounts list takes no arguments");return{kind:"accounts-list"};case"import":return Om(t.slice(1));case"remove":{let s=t[1];if(!s||t.length!==2)throw new Mi("accounts remove requires exactly one <id|email>");return{kind:"accounts-remove",identifier:s}}default:throw new Mi(n===void 0?"accounts requires list, import, or remove":`Unknown accounts command: ${n}`)}}function g0(t){let n=t[0];switch(n){case void 0:case"--help":case"-h":return{kind:"help"};case"serve":return Im(t.slice(1));case"login":return ym(t.slice(1));case"accounts":return Gm(t.slice(1));default:throw new Mi(`Unknown command: ${n}`)}}import{Database as Bm}from"bun:sqlite";import{homedir as Fm}from"os";import{join as yd}from"path";var Hm=g.object({id:g.string().min(1),email:g.string().min(1),auth_method:g.string(),region:g.string(),oidc_region:g.string().nullable(),client_id:g.string().nullable(),client_secret:g.string().nullable(),profile_arn:g.string().nullable(),start_url:g.string().nullable(),refresh_token:g.string(),access_token:g.string(),expires_at:g.number(),rate_limit_reset:g.number().nullable(),is_healthy:g.number().nullable(),unhealthy_reason:g.string().nullable(),recovery_time:g.number().nullable(),fail_count:g.number().nullable(),last_used:g.number().nullable(),used_count:g.number().nullable(),limit_count:g.number().nullable(),last_sync:g.number().nullable(),overage_count:g.number().nullable()});function Pm(t=process.env){let n=t.XDG_CONFIG_HOME??yd(Fm(),".config");return yd(n,"opencode","kiro.db")}function jt(t){return t===null||t===""?void 0:t}function Nm(t){if(!t.refresh_token)return{kind:"skipped",reason:"missing refresh token"};if(!t.access_token)return{kind:"skipped",reason:"missing access token"};let n=vn.safeParse(t.region);if(!n.success)return{kind:"skipped",reason:"missing or unsupported region"};if(t.auth_method!=="idc"&&t.auth_method!=="desktop")return{kind:"skipped",reason:"unsupported auth method"};if(t.auth_method==="idc"&&(!t.client_id||!t.client_secret))return{kind:"skipped",reason:"IDC client credentials missing"};let s=jt(t.oidc_region),i=s===void 0?void 0:vn.safeParse(s);if(i!==void 0&&!i.success)return{kind:"skipped",reason:"unsupported OIDC region"};return{kind:"usable",account:{id:t.id,email:t.email,authMethod:t.auth_method,region:n.data,...i?.success?{oidcRegion:i.data}:{},...jt(t.client_id)?{clientId:jt(t.client_id)}:{},...jt(t.client_secret)?{clientSecret:jt(t.client_secret)}:{},...jt(t.profile_arn)?{profileArn:jt(t.profile_arn)}:{},...jt(t.start_url)?{startUrl:jt(t.start_url)}:{},refreshToken:t.refresh_token,accessToken:t.access_token,expiresAt:t.expires_at,rateLimitResetTime:t.rate_limit_reset??0,isHealthy:t.is_healthy!==0,...jt(t.unhealthy_reason)?{unhealthyReason:jt(t.unhealthy_reason)}:{},...t.recovery_time===null?{}:{recoveryTime:t.recovery_time},failCount:t.fail_count??0,lastUsed:t.last_used??0,usedCount:t.used_count??0,limitCount:t.limit_count??0,lastSync:t.last_sync??0,overageCount:t.overage_count??0}}}function Od(t,n){let s=t.from??Pm(),i=new Bm(s,{readonly:!0,strict:!0}),r=0,e=0;try{let o=i.query(`SELECT
165
166
  id, email, auth_method, region, oidc_region, client_id, client_secret,
166
167
  profile_arn, start_url, refresh_token, access_token, expires_at,
167
168
  rate_limit_reset, is_healthy, unhealthy_reason, recovery_time, fail_count,
168
169
  last_used, used_count, limit_count, last_sync, overage_count
169
- FROM accounts`).all();for(let c of o){let h=yY.safeParse(c);if(!h.success){e+=1,n.stdout("Skipped malformed source account row");continue}let u=BY(h.data);if(u.kind==="skipped"){e+=1,n.stdout(`Skipped ${h.data.email}: ${u.reason}`);continue}n.database.insertAccount(u.account),i+=1,n.stdout(`Imported ${u.account.email} ${u.account.authMethod} ${u.account.region}`)}}finally{r.close()}let f=n.database.getAccounts().length;return n.stdout(`Imported ${i}, skipped ${e}, total in DB now ${f}`),{imported:i,skipped:e,total:f}}import{createHash as NY}from"crypto";var FY=g.object({clientId:g.string().min(1),clientSecret:g.string().min(1)}),HY=g.object({verificationUri:g.string().min(1),verificationUriComplete:g.string().min(1),userCode:g.string().min(1),deviceCode:g.string().min(1),interval:g.number().positive().default(5),expiresIn:g.number().positive().default(600)}),PY=g.object({error:g.string().optional(),error_description:g.string().optional(),access_token:g.string().optional(),accessToken:g.string().optional(),refresh_token:g.string().optional(),refreshToken:g.string().optional(),expires_in:g.number().optional(),expiresIn:g.number().optional()}).passthrough();class Ft extends Error{constructor(t,n){super(t,n);this.name="KiroIDCError"}}async function E0(t){try{return await t.text()}catch(n){if(n instanceof Error)return"";throw n}}async function GE(t,n,s){let r=Zo(t),i=Or(Gr.SSO_OIDC_ENDPOINT,r),e=n??Gr.BUILDER_ID_START_URL,f=await fetch(`${i}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Gr.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...s?{proxy:s}:{}});if(!f.ok)throw new Ft(`Client registration failed: ${f.status} ${await E0(f)}`);let o=FY.safeParse(await f.json());if(!o.success)throw new Ft("Client registration response missing clientId or clientSecret",{cause:o.error});let c=await fetch(`${i}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:e}),...s?{proxy:s}:{}});if(!c.ok)throw new Ft(`Device authorization failed: ${c.status} ${await E0(c)}`);let h=HY.safeParse(await c.json());if(!h.success)throw new Ft("Device authorization response missing required fields",{cause:h.error});return{verificationUrl:h.data.verificationUri,verificationUriComplete:h.data.verificationUriComplete,userCode:h.data.userCode,deviceCode:h.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:h.data.interval,expiresIn:h.data.expiresIn,region:r,startUrl:e}}async function BE(t,n,s,r,i,e,f=(c)=>new Promise((h)=>setTimeout(h,c)),o){if(!t||!n||!s)throw new Ft("Missing required parameters for token polling");let c=Zo(e),h=Or(Gr.SSO_OIDC_ENDPOINT,c),u=Math.floor(i/r),_=r*1000;for(let l=1;l<=u;l+=1){await f(_);let w=await fetch(`${h}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:t,clientSecret:n,deviceCode:s,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await E0(w),M={};if(A)try{M=JSON.parse(A)}catch(S){throw new Ft(`Token polling failed: invalid JSON response (HTTP ${w.status}): ${A.slice(0,300)}`,{cause:S})}let E=PY.safeParse(M);if(!E.success)throw new Ft(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:E.error});let d=E.data;switch(d.error){case void 0:break;case"authorization_pending":continue;case"slow_down":_+=5000;continue;case"expired_token":throw new Ft("Device code has expired. Please restart the authorization process.");case"access_denied":throw new Ft("Authorization was denied by the user.");default:throw new Ft(`Token polling failed: ${d.error} - ${d.error_description??""}`)}let T=d.access_token??d.accessToken,U=d.refresh_token??d.refreshToken;if(T&&U)return{refreshToken:U,accessToken:T,expiresAt:Date.now()+(d.expires_in??d.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:t,clientSecret:n,region:c,authMethod:"idc"};if(!w.ok)throw new Ft(`Token request failed with status: ${w.status} ${A?`(${A.slice(0,200)})`:""}`);throw new Ft(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new Ft("Token polling timed out. Authorization may have expired.")}function WY(t){if(t===void 0||t.trim()==="")return;let n=new URL(t.trim());return n.hash="",n.search="",n.pathname=`${n.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,n.toString()}function DY(t,n){return NY("sha256").update(`${t}:idc:${n}:`).digest("hex")}async function FE(t,n={},s={}){let r=s.authorize??GE,i=s.poll??BE,e=s.stdout??console.log,f=WY(n.startUrl),o=vn.parse(n.region??t.default_region),c=Qs(t),h=await r(o,f,c);e(`Open this URL to sign in:
170
- ${h.verificationUriComplete}`);let u=await i(h.clientId,h.clientSecret,h.deviceCode,h.interval,h.expiresIn,o,void 0,c),_={id:DY(u.email,u.clientId),email:u.email,authMethod:"idc",region:o,oidcRegion:o,clientId:u.clientId,clientSecret:u.clientSecret,...f?{startUrl:f}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},l=s.openDb?.(Pn)??new rs(Pn);try{l.insertAccount(_)}finally{l.close()}e(`Login successful: ${_.email}`)}function YY(t){let n=t.isHealthy?"healthy":"unhealthy";return`${t.email} ${t.region} ${n} generation=${t.generation} used=${t.usedCount??0}/${t.limitCount??0}`}var mY={loadConfig:F0,startServer:IE,runLogin:FE,runImportAccounts:yE,openDb:(t)=>new rs(t),stdout:console.log,stderr:console.error};async function QY(t,n){switch(t.kind){case"help":return n.stdout(mo),0;case"serve":{let s={...t.host?{host:t.host}:{},...t.port!==void 0?{port:t.port}:{},...t.proxy!==void 0?{proxy_url:t.proxy}:{}},r=n.loadConfig({...t.configPath?{configPath:t.configPath}:{},overrides:s});if(r.test_upstream_endpoint)n.stderr(`WARNING: test_upstream_endpoint is set (${r.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let i=n.startServer(r);return n.stdout(`Listening on http://${i.hostname??r.host}:${i.port??r.port}`),0}case"login":{let s=n.loadConfig({...t.configPath?{configPath:t.configPath}:{}});return await n.runLogin(s,{...t.startUrl?{startUrl:t.startUrl}:{},...t.region?{region:t.region}:{}}),0}case"accounts-list":{let s=n.openDb(Pn);try{for(let r of s.getAccounts())n.stdout(YY(r))}finally{s.close()}return 0}case"accounts-import":{let s=n.openDb(Pn);try{n.runImportAccounts({...t.from?{from:t.from}:{}},{database:s,stdout:n.stdout})}finally{s.close()}return 0}case"accounts-remove":{let s=n.openDb(Pn);try{let r=s.getAccounts().find((i)=>i.id===t.identifier||i.email===t.identifier);if(!r)return n.stderr(`Account not found: ${t.identifier}`),1;s.removeAccount(r.id),n.stdout(`Removed account ${r.email}`)}finally{s.close()}return 0}}}async function HE(t=process.argv.slice(2),n=mY){let s;try{s=g0(t)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),n.stderr(mo),1}try{return await QY(s,n)}catch(r){return n.stderr(r instanceof Error?r.message:String(r)),1}}process.exitCode=await HE();
170
+ FROM accounts`).all();for(let c of o){let h=Hm.safeParse(c);if(!h.success){e+=1,n.stdout("Skipped malformed source account row");continue}let u=Nm(h.data);if(u.kind==="skipped"){e+=1,n.stdout(`Skipped ${h.data.email}: ${u.reason}`);continue}n.database.insertAccount(u.account),r+=1,n.stdout(`Imported ${u.account.email} ${u.account.authMethod} ${u.account.region}`)}}finally{i.close()}let f=n.database.getAccounts().length;return n.stdout(`Imported ${r}, skipped ${e}, total in DB now ${f}`),{imported:r,skipped:e,total:f}}import{createHash as Ym}from"crypto";var Wm=g.object({clientId:g.string().min(1),clientSecret:g.string().min(1)}),Dm=g.object({verificationUri:g.string().min(1),verificationUriComplete:g.string().min(1),userCode:g.string().min(1),deviceCode:g.string().min(1),interval:g.number().positive().default(5),expiresIn:g.number().positive().default(600)}),mm=g.object({error:g.string().optional(),error_description:g.string().optional(),access_token:g.string().optional(),accessToken:g.string().optional(),refresh_token:g.string().optional(),refreshToken:g.string().optional(),expires_in:g.number().optional(),expiresIn:g.number().optional()}).passthrough();class Ft extends Error{constructor(t,n){super(t,n);this.name="KiroIDCError"}}async function d0(t){try{return await t.text()}catch(n){if(n instanceof Error)return"";throw n}}async function Gd(t,n,s){let i=Zo(t),r=yi(Gi.SSO_OIDC_ENDPOINT,i),e=n??Gi.BUILDER_ID_START_URL,f=await fetch(`${r}/client/register`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientName:"Kiro IDE",clientType:"public",scopes:Gi.SCOPES,grantTypes:["urn:ietf:params:oauth:grant-type:device_code","refresh_token"]}),...s?{proxy:s}:{}});if(!f.ok)throw new Ft(`Client registration failed: ${f.status} ${await d0(f)}`);let o=Wm.safeParse(await f.json());if(!o.success)throw new Ft("Client registration response missing clientId or clientSecret",{cause:o.error});let c=await fetch(`${r}/device_authorization`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:o.data.clientId,clientSecret:o.data.clientSecret,startUrl:e}),...s?{proxy:s}:{}});if(!c.ok)throw new Ft(`Device authorization failed: ${c.status} ${await d0(c)}`);let h=Dm.safeParse(await c.json());if(!h.success)throw new Ft("Device authorization response missing required fields",{cause:h.error});return{verificationUrl:h.data.verificationUri,verificationUriComplete:h.data.verificationUriComplete,userCode:h.data.userCode,deviceCode:h.data.deviceCode,clientId:o.data.clientId,clientSecret:o.data.clientSecret,interval:h.data.interval,expiresIn:h.data.expiresIn,region:i,startUrl:e}}async function Bd(t,n,s,i,r,e,f=(c)=>new Promise((h)=>setTimeout(h,c)),o){if(!t||!n||!s)throw new Ft("Missing required parameters for token polling");let c=Zo(e),h=yi(Gi.SSO_OIDC_ENDPOINT,c),u=Math.floor(r/i),l=i*1000;for(let _=1;_<=u;_+=1){await f(l);let w=await fetch(`${h}/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":ot.USER_AGENT},body:JSON.stringify({clientId:t,clientSecret:n,deviceCode:s,grantType:"urn:ietf:params:oauth:grant-type:device_code"}),...o?{proxy:o}:{}}),A=await d0(w),M={};if(A)try{M=JSON.parse(A)}catch(S){throw new Ft(`Token polling failed: invalid JSON response (HTTP ${w.status}): ${A.slice(0,300)}`,{cause:S})}let d=mm.safeParse(M);if(!d.success)throw new Ft(`Token polling failed: invalid response (HTTP ${w.status})`,{cause:d.error});let E=d.data;switch(E.error){case void 0:break;case"authorization_pending":continue;case"slow_down":l+=5000;continue;case"expired_token":throw new Ft("Device code has expired. Please restart the authorization process.");case"access_denied":throw new Ft("Authorization was denied by the user.");default:throw new Ft(`Token polling failed: ${E.error} - ${E.error_description??""}`)}let T=E.access_token??E.accessToken,U=E.refresh_token??E.refreshToken;if(T&&U)return{refreshToken:U,accessToken:T,expiresAt:Date.now()+(E.expires_in??E.expiresIn??3600)*1000,email:"builder-id@aws.amazon.com",clientId:t,clientSecret:n,region:c,authMethod:"idc"};if(!w.ok)throw new Ft(`Token request failed with status: ${w.status} ${A?`(${A.slice(0,200)})`:""}`);throw new Ft(`Token polling failed: missing tokens in response: ${A?A.slice(0,300):"[empty]"}`)}throw new Ft("Token polling timed out. Authorization may have expired.")}function Qm(t){if(t===void 0||t.trim()==="")return;let n=new URL(t.trim());return n.hash="",n.search="",n.pathname=`${n.pathname.replace(/\/start\/?$/,"").replace(/\/+$/,"")}/start`,n.toString()}function Jm(t,n){return Ym("sha256").update(`${t}:idc:${n}:`).digest("hex")}async function Fd(t,n={},s={}){let i=s.authorize??Gd,r=s.poll??Bd,e=s.stdout??console.log,f=Qm(n.startUrl),o=vn.parse(n.region??t.default_region),c=Qs(t),h=await i(o,f,c);e(`Open this URL to sign in:
171
+ ${h.verificationUriComplete}`);let u=await r(h.clientId,h.clientSecret,h.deviceCode,h.interval,h.expiresIn,o,void 0,c),l={id:Jm(u.email,u.clientId),email:u.email,authMethod:"idc",region:o,oidcRegion:o,clientId:u.clientId,clientSecret:u.clientSecret,...f?{startUrl:f}:{},refreshToken:u.refreshToken,accessToken:u.accessToken,expiresAt:u.expiresAt,rateLimitResetTime:0,isHealthy:!0,failCount:0,usedCount:0,limitCount:0},_=s.openDb?.(Pn)??new is(Pn);try{_.insertAccount(l)}finally{_.close()}e(`Login successful: ${l.email}`)}function km(t){let n=t.isHealthy?"healthy":"unhealthy";return`${t.email} ${t.region} ${n} generation=${t.generation} used=${t.usedCount??0}/${t.limitCount??0}`}var zm={loadConfig:F0,startServer:Id,runLogin:Fd,runImportAccounts:Od,openDb:(t)=>new is(t),stdout:console.log,stderr:console.error};async function Xm(t,n){switch(t.kind){case"help":return n.stdout(Yo),0;case"serve":{let s={...t.host?{host:t.host}:{},...t.port!==void 0?{port:t.port}:{},...t.proxy!==void 0?{proxy_url:t.proxy}:{}},i=n.loadConfig({...t.configPath?{configPath:t.configPath}:{},overrides:s});if(i.test_upstream_endpoint)n.stderr(`WARNING: test_upstream_endpoint is set (${i.test_upstream_endpoint}); routing upstream to a NON-production endpoint. Unset it for normal use.`);let r=n.startServer(i);return n.stdout(`Listening on http://${r.hostname??i.host}:${r.port??i.port}`),0}case"login":{let s=n.loadConfig({...t.configPath?{configPath:t.configPath}:{}});return await n.runLogin(s,{...t.startUrl?{startUrl:t.startUrl}:{},...t.region?{region:t.region}:{}}),0}case"accounts-list":{let s=n.openDb(Pn);try{for(let i of s.getAccounts())n.stdout(km(i))}finally{s.close()}return 0}case"accounts-import":{let s=n.openDb(Pn);try{n.runImportAccounts({...t.from?{from:t.from}:{}},{database:s,stdout:n.stdout})}finally{s.close()}return 0}case"accounts-remove":{let s=n.openDb(Pn);try{let i=s.getAccounts().find((r)=>r.id===t.identifier||r.email===t.identifier);if(!i)return n.stderr(`Account not found: ${t.identifier}`),1;s.removeAccount(i.id),n.stdout(`Removed account ${i.email}`)}finally{s.close()}return 0}}}async function Hd(t=process.argv.slice(2),n=zm){let s;try{s=g0(t)}catch(i){return n.stderr(i instanceof Error?i.message:String(i)),n.stderr(Yo),1}try{return await Xm(s,n)}catch(i){return n.stderr(i instanceof Error?i.message:String(i)),1}}process.exitCode=await Hd();