@caeliq/llms 1.0.63 → 1.0.64

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.
@@ -1,4 +1,4 @@
1
- var rD=Object.create;var Pp=Object.defineProperty;var oD=Object.getOwnPropertyDescriptor;var sD=Object.getOwnPropertyNames;var iD=Object.getPrototypeOf,aD=Object.prototype.hasOwnProperty;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Br=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var G=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},tC=(t,e)=>{for(var n in e)Pp(t,n,{get:e[n],enumerable:!0})},cD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sD(e))!aD.call(t,o)&&o!==n&&Pp(t,o,{get:()=>e[o],enumerable:!(r=oD(e,o))||r.enumerable});return t};var nr=(t,e,n)=>(n=t!=null?rD(iD(t)):{},cD(e||!t||!t.__esModule?Pp(n,"default",{value:t,enumerable:!0}):n,t));var Fi=G(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.AddressError=void 0;var Ip=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};bc.AddressError=Ip});var wc=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.isInSubnet=uD;yn.isHostInSubnet=nC;yn.isCorrect=lD;yn.prefixLengthFromMask=dD;yn.assertByteArray=fD;yn.numberToPaddedHex=rC;yn.stringToPaddedHex=pD;yn.testBit=hD;var Cc=Fi();function uD(t){return this.subnetMask<t.subnetMask?!1:nC.call(this,t)}function nC(t){return this.mask(t.subnetMask)===t.mask()}function lD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function dD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new Cc.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new Cc.AddressError("Invalid subnet mask.");return r}function fD(t,e,n,r){if(t.length!==e)throw new Cc.AddressError(`${n} addresses require exactly ${e} bytes`);for(let o=0;o<t.length;o++)if(!Number.isInteger(t[o])||t[o]<r||t[o]>255)throw new Cc.AddressError(`All bytes must be integers between ${r} and 255`)}function rC(t){return t.toString(16).padStart(2,"0")}function pD(t){return rC(parseInt(t,10))}function hD(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var Fp=G(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.RE_SUBNET_STRING=_n.RE_ADDRESS=_n.GROUPS=_n.BITS=void 0;_n.BITS=32;_n.GROUPS=4;_n.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;_n.RE_SUBNET_STRING=/\/\d{1,2}$/});var Np=G(Cn=>{"use strict";var gD=Cn&&Cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),mD=Cn&&Cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),oC=Cn&&Cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&gD(e,t,n);return mD(e,t),e};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.Address4=void 0;var bn=oC(wc()),nt=oC(Fp()),rr=Fi(),yD=bn.isCorrect(nt.BITS),Lt=class t{constructor(e){this.addressMinusSuffix="",this.groups=nt.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=yD,this.isInSubnet=bn.isInSubnet,this.isHostInSubnet=bn.isHostInSubnet,this.address=e;let n=nt.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>nt.BITS)throw new rr.AddressError("Invalid subnet mask.");e=e.replace(nt.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let n=e.split(".");if(n.some(r=>/^0\d/.test(r)))throw new rr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(nt.RE_ADDRESS))throw new rr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=bn.prefixLengthFromMask(new t(n).bigInt(),nt.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(nt.BITS))-BigInt(1),s=r^o,i=bn.prefixLengthFromMask(s,nt.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==nt.GROUPS)throw new rr.AddressError("Wildcard pattern must have 4 octets");let r=-1;for(let a=0;a<n.length;a++)if(n[a]==="*")r===-1&&(r=a);else if(r!==-1)throw new rr.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let o=r===-1?0:n.length-r,s=n.map(a=>a==="*"?"0":a),i=nt.BITS-o*8;return new t(`${s.join(".")}/${i}`)}static fromHex(e){let n=e.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(n))throw new rr.AddressError("IPv4 hex must be exactly 8 hex digits");let r=[];for(let o=0;o<8;o+=2)r.push(parseInt(n.slice(o,o+2),16));return new t(r.join("."))}static fromInteger(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new rr.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromArpa(e){let r=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(r)}toHex(){return this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<nt.GROUPS;n+=2)e.push(`${bn.stringToPaddedHex(this.parsedAddress[n])}${bn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(nt.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(nt.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(nt.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(nt.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new rr.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromByteArray(e){return bn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new rr.AddressError("IPv4 addresses require exactly 4 bytes");let n=e.join(".");return new t(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}reverseForm(e){e||(e={});let n=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?n:`${n}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(_D)}isPrivate(){return bD.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(CD)}isLinkLocal(){return this.isHostInSubnet(wD)}isUnspecified(){return this.isHostInSubnet(kD)}isBroadcast(){return this.isHostInSubnet(SD)}isCGNAT(){return this.isHostInSubnet(AD)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(nt.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(nt.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};Cn.Address4=Lt;var _D=new Lt("224.0.0.0/4"),bD=[new Lt("10.0.0.0/8"),new Lt("172.16.0.0/12"),new Lt("192.168.0.0/16")],CD=new Lt("127.0.0.0/8"),wD=new Lt("169.254.0.0/16"),kD=new Lt("0.0.0.0/32"),SD=new Lt("255.255.255.255/32"),AD=new Lt("100.64.0.0/10")});var Mp=G(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.RE_URL_WITH_PORT=We.RE_URL=We.RE_ZONE_STRING=We.RE_SUBNET_STRING=We.RE_BAD_ADDRESS=We.RE_BAD_CHARACTERS=We.TYPES=We.SCOPES=We.GROUPS=We.BITS=void 0;We.BITS=128;We.GROUPS=8;We.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};We.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};We.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;We.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;We.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;We.RE_ZONE_STRING=/%.*$/;We.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;We.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var Bp=G(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.escapeHtml=kc;lo.spanAllZeroes=sC;lo.spanAll=ED;lo.spanLeadingZeroes=vD;lo.simpleGroup=TD;function kc(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sC(t){return kc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function ED(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${kc(r)} position-${o+e}">${sC(r)}</span>`).join("")}function iC(t){return kc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function vD(t){return t.split(":").map(n=>iC(n)).join(":")}function TD(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${iC(r)}</span>`)}});var aC=G(kt=>{"use strict";var xD=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),RD=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),DD=kt&&kt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&xD(e,t,n);return RD(e,t),e};Object.defineProperty(kt,"__esModule",{value:!0});kt.ADDRESS_BOUNDARY=void 0;kt.groupPossibilities=Ac;kt.padGroup=Sc;kt.simpleRegularExpression=PD;kt.possibleElisions=ID;var OD=DD(Mp());function Ac(t){return`(${t.join("|")})`}function Sc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}kt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function PD(t){let e=[];t.forEach((r,o)=>{parseInt(r,16)===0&&e.push(o)});let n=e.map(r=>t.map((o,s)=>{if(s===r){let i=s===0||s===OD.GROUPS-1?":":"";return Ac([Sc(o),i])}return Sc(o)}).join(":"));return n.push(t.map(Sc).join(":")),Ac(n)}function ID(t,e,n){let r=e?"":":",o=n?"":":",s=[];!e&&!n&&s.push("::"),e&&n&&s.push(""),(n&&!e||!n&&e)&&s.push(":"),s.push(`${r}(:0{1,4}){1,${t-1}}`),s.push(`(0{1,4}:){1,${t-1}}${o}`),s.push(`(0{1,4}:){${t-1}}0{1,4}`);for(let i=1;i<t-1;i++)for(let a=1;a<t-i;a++)s.push(`(0{1,4}:){${a}}:(0{1,4}:){${t-a-i-1}}0{1,4}`);return Ac(s)}});var dC=G(Sn=>{"use strict";var FD=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ND=Sn&&Sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Tc=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&FD(e,t,n);return ND(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.Address6=void 0;var ho=Tc(wc()),Up=Tc(Fp()),xe=Tc(Mp()),fo=Tc(Bp()),wn=Np(),po=aC(),ct=Fi(),Ec=wc(),MD=ho.isCorrect(xe.BITS);function vc(t){if(!t)throw new Error("Assertion failed.")}function BD(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function UD(t){return t=t.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),t=t.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),t}function jD(t,e){let n=[],r=[],o;for(o=0;o<t.length;o++)o<e[0]?n.push(t[o]):o>e[1]&&r.push(t[o]);return n.concat(["compact"]).concat(r)}function cC(t){return parseInt(t,16).toString(16).padStart(4,"0")}function uC(t){return t&255}var kn=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=ho.isInSubnet,this.isHostInSubnet=ho.isHostInSubnet,this.isCorrect=MD,n===void 0?this.groups=xe.GROUPS:this.groups=n,this.address=e;let r=xe.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>xe.BITS)throw new ct.AddressError("Invalid subnet mask.");e=e.replace(xe.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new ct.AddressError("Invalid subnet mask.");let o=xe.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(xe.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){if(e<BigInt(0)||e>(BigInt(1)<<BigInt(xe.BITS))-BigInt(1))throw new ct.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let n=e.toString(16).padStart(32,"0"),r=[];for(let o=0;o<xe.GROUPS;o++)r.push(n.slice(o*4,(o+1)*4));return new t(r.join(":"))}static fromURL(e){var n;let r,o=null,s,i,a=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(a.indexOf("[")!==-1&&a.indexOf("]:")!==-1){if(i="failed to parse address with port",s=xe.RE_URL_WITH_PORT.exec(a),s===null)return{error:i,address:null,port:null};r=s[1],o=s[2]}else{if(i="failed to parse address from URL",s=xe.RE_URL.exec(a),s===null)return{error:i,address:null,port:null};r=(n=s[1])!==null&&n!==void 0?n:s[2]}o?(o=parseInt(o,10),(o<0||o>65535)&&(o=null)):o=null;let u;try{u=new t(r)}catch{return{error:i,address:null,port:null}}return{address:u,port:o}}static fromAddressAndMask(e,n){let r=ho.prefixLengthFromMask(new t(n).bigInt(),xe.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(xe.BITS))-BigInt(1),s=r^o,i=ho.prefixLengthFromMask(s,xe.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new ct.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new ct.AddressError("Wildcard pattern cannot contain more than one '::'");let r;if(n.length===2){let u=n[0]===""?[]:n[0].split(":"),d=n[1]===""?[]:n[1].split(":"),f=xe.GROUPS-u.length-d.length;if(f<1)throw new ct.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==xe.GROUPS)throw new ct.AddressError("Wildcard pattern must have 8 groups");let o=-1;for(let u=0;u<r.length;u++)if(r[u]==="*")o===-1&&(o=u);else if(o!==-1)throw new ct.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let s=o===-1?0:r.length-o,i=r.map(u=>u==="*"?"0":u),a=xe.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new wn.Address4(e),r=xe.BITS-(Up.BITS-n.subnetMask);return new t(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(e){let n=e.replace(/(\.ip6\.arpa)?\.$/,""),r=7;if(n.length!==63)throw new ct.AddressError("Invalid 'ip6.arpa' form.");let o=n.split(".").reverse();for(let s=r;s>0;s--){let i=s*4;o.splice(i,0,":")}return n=o.join(""),new t(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let n=xe.BITS-this.subnetMask,r=Math.abs(e-xe.BITS),o=n-r;return o<0?"0":BD((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(xe.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(xe.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(xe.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(xe.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?xe.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":e==="Link-local unicast"||e==="Loopback"?"Link local":e==="Unspecified"?"Unknown":"Global"}getType(){for(let e=0;e<lC.length;e++){let n=lC[e];if(this.isHostInSubnet(n[0]))return n[1]}return"Global unicast"}getBits(e,n){return BigInt(`0b${this.getBitsBase2(e,n)}`)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}getBitsBase16(e,n){let r=n-e;if(r%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,n).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,xe.BITS)}reverseForm(e){e||(e={});let n=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,n).reverse().join(".");return n>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,n=[],r=0,o=[];for(e=0;e<this.parsedAddress.length;e++){let a=parseInt(this.parsedAddress[e],16);a===0&&r++,a!==0&&r>0&&(r>1&&o.push([e-r,e-1]),r=0)}r>1&&o.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);let s=o.map(a=>a[1]-a[0]+1);if(o.length>0){let a=s.indexOf(Math.max(...s));n=jD(this.parsedAddress,o[a])}else n=this.parsedAddress;for(e=0;e<n.length;e++)n[e]!=="compact"&&(n[e]=parseInt(n[e],16).toString(16));let i=n.join(":");return i=i.replace(/^compact$/,"::"),i=i.replace(/(^compact)|(compact$)/,":"),i=i.replace(/compact/,""),i}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(xe.BITS,"0")),this._binaryZeroPad}parse4in6(e){if(e.indexOf(".")===-1)return e;let n=e.split(":"),r=n.slice(-1)[0],o=r.split(".");if(o.length===Up.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(UD).join("."),a=n.slice(0,-1).map(fo.escapeHtml).join(":"),u=n.length>1?":":"";throw new ct.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(Up.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new wn.Address4(`${this.parsedAddress4}${i}`),this.v4=!0,n[n.length-1]=this.address4.toGroup6(),e=n.join(":")}return e}parse(e){e=this.parse4in6(e);let n=e.match(xe.RE_BAD_CHARACTERS);if(n)throw new ct.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(xe.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(xe.RE_BAD_ADDRESS);if(r)throw new ct.AddressError(`Address failed regex: ${r.join("")}`,e.replace(xe.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let o=[],s=e.split("::");if(s.length===2){let i=s[0].split(":"),a=s[1].split(":");i.length===1&&i[0]===""&&(i=[]),a.length===1&&a[0]===""&&(a=[]);let u=this.groups-(i.length+a.length);if(!u)throw new ct.AddressError("Error parsing groups");this.elidedGroups=u,this.elisionBegin=i.length,this.elisionEnd=i.length+this.elidedGroups,o=o.concat(i);for(let d=0;d<u;d++)o.push("0");o=o.concat(a)}else if(s.length===1)o=e.split(":"),this.elidedGroups=0;else throw new ct.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new ct.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(cC).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(cC).join("")}`)}to4(){let e=this.binaryZeroPad().split(""),n=BigInt(`0b${e.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let r=this.subnetMask-96,o=[];for(let s=0;s<8;s+=2)o.push(parseInt(n.slice(s,s+2),16));return new wn.Address4(`${o.join(".")}/${r}`)}return wn.Address4.fromHex(n)}to4in6(){let e=this.to4(),r=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),o="";return/:$/.test(r)||(o=":"),r+o+e.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),r=(this.getBits(80,96)^BigInt("0xffff")).toString(),o=wn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=wn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Ec.testBit)(a,15),d=(0,Ec.testBit)(a,14),f=(0,Ec.testBit)(a,8),p=(0,Ec.testBit)(a,9),h=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:o.address,client4:i.address,flags:a,coneNat:u,microsoft:{reserved:d,universalLocal:p,groupIndividual:f,nonce:h},udpPort:r}}inspect6to4(){let e=this.getBitsBase16(0,16),n=wn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:n.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}static fromAddress4Nat64(e,n="64:ff9b::/96"){let r=new wn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let i=o.binaryZeroPad(),a=r.binaryZeroPad(),u;if(s===96)u=i.slice(0,96)+a;else{let p=64-s;u=[i.slice(0,s),a.slice(0,p),"00000000",a.slice(p),"0".repeat(56-(32-p))].join("")}let d=BigInt(`0b${u}`).toString(16).padStart(32,"0"),f=[];for(let p=0;p<8;p++)f.push(d.slice(p*4,(p+1)*4));return new t(f.join(":"))}toAddress4Nat64(e="64:ff9b::/96"){let n=new t(e),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(n))return null;let o=this.binaryZeroPad(),s;if(r===96)s=o.slice(96,128);else{let a=64-r;s=o.slice(r,r+a)+o.slice(72,72+(32-a))}let i=[];for(let a=0;a<4;a++)i.push(parseInt(s.slice(a*8,(a+1)*8),2).toString());return new wn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(xe.BITS/4,"0"),n=[];for(let r=0,o=e.length;r<o;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(uC)}static fromByteArray(e){return ho.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(uC))}static fromUnsignedByteArray(e){ho.assertByteArray(e,16,"IPv6",0);let n=BigInt("256"),r=BigInt("0"),o=BigInt("1");for(let s=e.length-1;s>=0;s--)r+=o*BigInt(e[s].toString(10)),o*=n;return t.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let n=this.getType();return n==="Multicast"||n.startsWith("Multicast ")}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(zD)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(WD)?this.to4():null}isTeredo(){return this.isHostInSubnet(LD)}is6to4(){return this.isHostInSubnet($D)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(qD)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()==="Unspecified"}isDocumentation(){return this.isHostInSubnet(HD)}href(e){return e===void 0?e="":e=`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),e.className===void 0&&(e.className=""),e.prefix===void 0&&(e.prefix="/#address="),e.v4===void 0&&(e.v4=!1);let n=this.correctForm;e.v4&&(n=this.to4in6);let r=n.call(this),o=fo.escapeHtml(`${e.prefix}${r}`),s=fo.escapeHtml(r);if(e.className){let i=fo.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return fo.simpleGroup(this.addressMinusSuffix).join(":");vc(typeof this.elidedGroups=="number"),vc(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...fo.simpleGroup(n)):e.push("");let o=["hover-group"];for(let s=this.elisionBegin;s<this.elisionBegin+this.elidedGroups;s++)o.push(`group-${s}`);return e.push(`<span class="${o.join(" ")}"></span>`),r.length?e.push(...fo.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(vc(this.address4 instanceof wn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let n=[],r=new t(this.correctForm());if(r.elidedGroups===0)n.push((0,po.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===xe.GROUPS)n.push((0,po.possibleElisions)(xe.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,po.simpleRegularExpression)(o[0].split(":"))),vc(typeof r.elidedGroups=="number"),n.push((0,po.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,po.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",po.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",po.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Sn.Address6=kn;var lC=Object.keys(xe.TYPES).map(t=>[new kn(t),xe.TYPES[t]]),LD=new kn("2001::/32"),$D=new kn("2002::/16"),qD=new kn("fc00::/7"),HD=new kn("2001:db8::/32"),zD=new kn("::ffff:0:0/96"),WD=new kn("64:ff9b::/96")});var fC=G(ft=>{"use strict";var GD=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),JD=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),KD=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&GD(e,t,n);return JD(e,t),e};Object.defineProperty(ft,"__esModule",{value:!0});ft.v6=ft.AddressError=ft.Address6=ft.Address4=void 0;var VD=Np();Object.defineProperty(ft,"Address4",{enumerable:!0,get:function(){return VD.Address4}});var YD=dC();Object.defineProperty(ft,"Address6",{enumerable:!0,get:function(){return YD.Address6}});var XD=Fi();Object.defineProperty(ft,"AddressError",{enumerable:!0,get:function(){return XD.AddressError}});var QD=KD(Bp());ft.v6={helpers:QD}});var hC=G((pH,jp)=>{"use strict";var ZD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,eO=/(\w*(\.\w*)*)\..*/;jp.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,pC(r.stack)}};function pC(t){let e=t.match(ZD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(eO)[1]:"anonymous"}jp.exports.extractPluginName=pC});var mC=G((hH,gC)=>{"use strict";gC.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var $p=G((gH,xc)=>{"use strict";var tO=hC(),nO=mC(),rO=0;function Lp(t,e={}){let n=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(n=!0,e.name=tO(t)+"-auto-"+rO++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let r=nO(e.name);return!n&&!t[r]&&(t[r]=t),t}xc.exports=Lp;xc.exports.default=Lp;xc.exports.fastifyPlugin=Lp});var yC=G(Hp=>{var oO=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,Rc=1e3,Dc=Rc*60,Oc=Dc*60,Mi=Oc*24,qp=Mi*365.25;function sO(t){var e,n=t.toLowerCase().match(oO);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*Rc:n[4]!=null?e*Dc:n[5]!=null?e*Oc:n[6]!=null?e*Mi:n[7]!=null?e*Mi*7:n[8]!=null?e*qp:e}function Ni(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function iO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<Rc?t+(e?" ms":"ms"):r<Dc?Ni(r/Rc,n,"second",e):r<Oc?Ni(r/Dc,n,"minute",e):r<Mi?Ni(r/Oc,n,"hour",e):r<qp?Ni(r/Mi,n,"day",e):Ni(r/qp,n,"year",e)}Hp.format=iO;Hp.parse=sO});var bC=G(An=>{"use strict";function Nc(t,e){if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("Invalid max value");if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("Invalid ttl value")}var zp=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},Pc=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function Wp(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var Ic=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:Wp()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=Wp()}getStatistics(){return this.records}},Gp=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},Bi=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function _C(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var Jp=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=_C(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new Ic,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=Wp()),e[this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){Date.now()>=this.archiveAfter&&(this.collectionStart=new Date,this.currentTimeStamp=_C(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},Fc=class extends Bi{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Jp(r,s!==void 0?s:24,o)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,n){super.set(e,n),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){let e=this.size>0;super.evict(),e&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,n=!1){let r=this.items[e]!==void 0;super.delete(e),r&&!n&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(n),n.value||(this.hitStatistics.addFalsyHit(),(n.value===void 0||n.value===null||n.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),n.value}this.hitStatistics.addMiss()}};An.Fifo=Pc;An.FifoMap=zp;An.FifoObject=Pc;An.HitStatisticsRecord=Ic;An.Lru=Bi;An.LruHitStatistics=Fc;An.LruMap=Gp;An.LruObject=Bi;An.LruObjectHitStatistics=Fc});var wC=G((_H,CC)=>{"use strict";var{LruMap:aO}=bC();function Ui(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new aO(n)}Ui.prototype.incr=function(t,e,n,r){let o=Date.now(),s=this.lru.get(t);if(!s)s={current:1,ttl:n,iterationStartMs:o};else if(s.iterationStartMs+n<=o)s.current=1,s.ttl=n,s.iterationStartMs=o;else if(++s.current,this.continueExceeding&&s.current>r)s.ttl=n,s.iterationStartMs=o;else if(this.exponentialBackoff&&s.current>r){let i=s.current-r-1,a=n*2**i;s.ttl=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER,s.iterationStartMs=o}else s.ttl=n-(o-s.iterationStartMs);this.lru.set(t,s),e(null,s)};Ui.prototype.read=function(t,e,n,r){let o=Date.now(),s=this.lru.get(t);if(!s||s.iterationStartMs+n<=o){e(null,{current:0,ttl:0});return}let i=n-(o-s.iterationStartMs);e(null,{current:s.current,ttl:i})};Ui.prototype.child=function(t){return new Ui(t.continueExceeding,t.exponentialBackoff,t.cache)};CC.exports=Ui});var SC=G((bH,kC)=>{"use strict";var cO=`
1
+ var oD=Object.create;var Op=Object.defineProperty;var sD=Object.getOwnPropertyDescriptor;var iD=Object.getOwnPropertyNames;var aD=Object.getPrototypeOf,cD=Object.prototype.hasOwnProperty;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Br=(t,e,n)=>()=>{if(n)throw n[0];try{return t&&(e=t(t=0)),e}catch(r){throw n=[r],r}};var G=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}},tC=(t,e)=>{for(var n in e)Op(t,n,{get:e[n],enumerable:!0})},uD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of iD(e))!cD.call(t,o)&&o!==n&&Op(t,o,{get:()=>e[o],enumerable:!(r=sD(e,o))||r.enumerable});return t};var nr=(t,e,n)=>(n=t!=null?oD(aD(t)):{},uD(e||!t||!t.__esModule?Op(n,"default",{value:t,enumerable:!0}):n,t));var Fi=G(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.AddressError=void 0;var Pp=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};bc.AddressError=Pp});var wc=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.isInSubnet=lD;yn.isHostInSubnet=nC;yn.isCorrect=dD;yn.prefixLengthFromMask=fD;yn.assertByteArray=pD;yn.numberToPaddedHex=rC;yn.stringToPaddedHex=hD;yn.testBit=gD;var Cc=Fi();function lD(t){return this.subnetMask<t.subnetMask?!1:nC.call(this,t)}function nC(t){return this.mask(t.subnetMask)===t.mask()}function dD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function fD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new Cc.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new Cc.AddressError("Invalid subnet mask.");return r}function pD(t,e,n,r){if(t.length!==e)throw new Cc.AddressError(`${n} addresses require exactly ${e} bytes`);for(let o=0;o<t.length;o++)if(!Number.isInteger(t[o])||t[o]<r||t[o]>255)throw new Cc.AddressError(`All bytes must be integers between ${r} and 255`)}function rC(t){return t.toString(16).padStart(2,"0")}function hD(t){return rC(parseInt(t,10))}function gD(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var Ip=G(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.RE_SUBNET_STRING=_n.RE_ADDRESS=_n.GROUPS=_n.BITS=void 0;_n.BITS=32;_n.GROUPS=4;_n.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;_n.RE_SUBNET_STRING=/\/\d{1,2}$/});var Fp=G(Cn=>{"use strict";var mD=Cn&&Cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),yD=Cn&&Cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),oC=Cn&&Cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&mD(e,t,n);return yD(e,t),e};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.Address4=void 0;var bn=oC(wc()),nt=oC(Ip()),rr=Fi(),_D=bn.isCorrect(nt.BITS),Lt=class t{constructor(e){this.addressMinusSuffix="",this.groups=nt.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=_D,this.isInSubnet=bn.isInSubnet,this.isHostInSubnet=bn.isHostInSubnet,this.address=e;let n=nt.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>nt.BITS)throw new rr.AddressError("Invalid subnet mask.");e=e.replace(nt.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let n=e.split(".");if(n.some(r=>/^0\d/.test(r)))throw new rr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(nt.RE_ADDRESS))throw new rr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=bn.prefixLengthFromMask(new t(n).bigInt(),nt.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(nt.BITS))-BigInt(1),s=r^o,i=bn.prefixLengthFromMask(s,nt.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==nt.GROUPS)throw new rr.AddressError("Wildcard pattern must have 4 octets");let r=-1;for(let a=0;a<n.length;a++)if(n[a]==="*")r===-1&&(r=a);else if(r!==-1)throw new rr.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let o=r===-1?0:n.length-r,s=n.map(a=>a==="*"?"0":a),i=nt.BITS-o*8;return new t(`${s.join(".")}/${i}`)}static fromHex(e){let n=e.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(n))throw new rr.AddressError("IPv4 hex must be exactly 8 hex digits");let r=[];for(let o=0;o<8;o+=2)r.push(parseInt(n.slice(o,o+2),16));return new t(r.join("."))}static fromInteger(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new rr.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromArpa(e){let r=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(r)}toHex(){return this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<nt.GROUPS;n+=2)e.push(`${bn.stringToPaddedHex(this.parsedAddress[n])}${bn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(nt.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(nt.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(nt.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(nt.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new rr.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromByteArray(e){return bn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new rr.AddressError("IPv4 addresses require exactly 4 bytes");let n=e.join(".");return new t(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}reverseForm(e){e||(e={});let n=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?n:`${n}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(bD)}isPrivate(){return CD.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(wD)}isLinkLocal(){return this.isHostInSubnet(kD)}isUnspecified(){return this.isHostInSubnet(SD)}isBroadcast(){return this.isHostInSubnet(AD)}isCGNAT(){return this.isHostInSubnet(ED)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(nt.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(nt.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};Cn.Address4=Lt;var bD=new Lt("224.0.0.0/4"),CD=[new Lt("10.0.0.0/8"),new Lt("172.16.0.0/12"),new Lt("192.168.0.0/16")],wD=new Lt("127.0.0.0/8"),kD=new Lt("169.254.0.0/16"),SD=new Lt("0.0.0.0/32"),AD=new Lt("255.255.255.255/32"),ED=new Lt("100.64.0.0/10")});var Np=G(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.RE_URL_WITH_PORT=We.RE_URL=We.RE_ZONE_STRING=We.RE_SUBNET_STRING=We.RE_BAD_ADDRESS=We.RE_BAD_CHARACTERS=We.TYPES=We.SCOPES=We.GROUPS=We.BITS=void 0;We.BITS=128;We.GROUPS=8;We.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};We.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};We.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;We.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;We.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;We.RE_ZONE_STRING=/%.*$/;We.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;We.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var Mp=G(lo=>{"use strict";Object.defineProperty(lo,"__esModule",{value:!0});lo.escapeHtml=kc;lo.spanAllZeroes=sC;lo.spanAll=vD;lo.spanLeadingZeroes=TD;lo.simpleGroup=xD;function kc(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sC(t){return kc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function vD(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${kc(r)} position-${o+e}">${sC(r)}</span>`).join("")}function iC(t){return kc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function TD(t){return t.split(":").map(n=>iC(n)).join(":")}function xD(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${iC(r)}</span>`)}});var aC=G(kt=>{"use strict";var RD=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DD=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),OD=kt&&kt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&RD(e,t,n);return DD(e,t),e};Object.defineProperty(kt,"__esModule",{value:!0});kt.ADDRESS_BOUNDARY=void 0;kt.groupPossibilities=Ac;kt.padGroup=Sc;kt.simpleRegularExpression=ID;kt.possibleElisions=FD;var PD=OD(Np());function Ac(t){return`(${t.join("|")})`}function Sc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}kt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function ID(t){let e=[];t.forEach((r,o)=>{parseInt(r,16)===0&&e.push(o)});let n=e.map(r=>t.map((o,s)=>{if(s===r){let i=s===0||s===PD.GROUPS-1?":":"";return Ac([Sc(o),i])}return Sc(o)}).join(":"));return n.push(t.map(Sc).join(":")),Ac(n)}function FD(t,e,n){let r=e?"":":",o=n?"":":",s=[];!e&&!n&&s.push("::"),e&&n&&s.push(""),(n&&!e||!n&&e)&&s.push(":"),s.push(`${r}(:0{1,4}){1,${t-1}}`),s.push(`(0{1,4}:){1,${t-1}}${o}`),s.push(`(0{1,4}:){${t-1}}0{1,4}`);for(let i=1;i<t-1;i++)for(let a=1;a<t-i;a++)s.push(`(0{1,4}:){${a}}:(0{1,4}:){${t-a-i-1}}0{1,4}`);return Ac(s)}});var dC=G(Sn=>{"use strict";var ND=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),MD=Sn&&Sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Tc=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&ND(e,t,n);return MD(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.Address6=void 0;var ho=Tc(wc()),Bp=Tc(Ip()),xe=Tc(Np()),fo=Tc(Mp()),wn=Fp(),po=aC(),ct=Fi(),Ec=wc(),BD=ho.isCorrect(xe.BITS);function vc(t){if(!t)throw new Error("Assertion failed.")}function jD(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function UD(t){return t=t.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2'),t=t.replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2'),t}function LD(t,e){let n=[],r=[],o;for(o=0;o<t.length;o++)o<e[0]?n.push(t[o]):o>e[1]&&r.push(t[o]);return n.concat(["compact"]).concat(r)}function cC(t){return parseInt(t,16).toString(16).padStart(4,"0")}function uC(t){return t&255}var kn=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=ho.isInSubnet,this.isHostInSubnet=ho.isHostInSubnet,this.isCorrect=BD,n===void 0?this.groups=xe.GROUPS:this.groups=n,this.address=e;let r=xe.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>xe.BITS)throw new ct.AddressError("Invalid subnet mask.");e=e.replace(xe.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new ct.AddressError("Invalid subnet mask.");let o=xe.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(xe.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){if(e<BigInt(0)||e>(BigInt(1)<<BigInt(xe.BITS))-BigInt(1))throw new ct.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let n=e.toString(16).padStart(32,"0"),r=[];for(let o=0;o<xe.GROUPS;o++)r.push(n.slice(o*4,(o+1)*4));return new t(r.join(":"))}static fromURL(e){var n;let r,o=null,s,i,a=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(a.indexOf("[")!==-1&&a.indexOf("]:")!==-1){if(i="failed to parse address with port",s=xe.RE_URL_WITH_PORT.exec(a),s===null)return{error:i,address:null,port:null};r=s[1],o=s[2]}else{if(i="failed to parse address from URL",s=xe.RE_URL.exec(a),s===null)return{error:i,address:null,port:null};r=(n=s[1])!==null&&n!==void 0?n:s[2]}o?(o=parseInt(o,10),(o<0||o>65535)&&(o=null)):o=null;let u;try{u=new t(r)}catch{return{error:i,address:null,port:null}}return{address:u,port:o}}static fromAddressAndMask(e,n){let r=ho.prefixLengthFromMask(new t(n).bigInt(),xe.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(xe.BITS))-BigInt(1),s=r^o,i=ho.prefixLengthFromMask(s,xe.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new ct.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new ct.AddressError("Wildcard pattern cannot contain more than one '::'");let r;if(n.length===2){let u=n[0]===""?[]:n[0].split(":"),d=n[1]===""?[]:n[1].split(":"),f=xe.GROUPS-u.length-d.length;if(f<1)throw new ct.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==xe.GROUPS)throw new ct.AddressError("Wildcard pattern must have 8 groups");let o=-1;for(let u=0;u<r.length;u++)if(r[u]==="*")o===-1&&(o=u);else if(o!==-1)throw new ct.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let s=o===-1?0:r.length-o,i=r.map(u=>u==="*"?"0":u),a=xe.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new wn.Address4(e),r=xe.BITS-(Bp.BITS-n.subnetMask);return new t(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(e){let n=e.replace(/(\.ip6\.arpa)?\.$/,""),r=7;if(n.length!==63)throw new ct.AddressError("Invalid 'ip6.arpa' form.");let o=n.split(".").reverse();for(let s=r;s>0;s--){let i=s*4;o.splice(i,0,":")}return n=o.join(""),new t(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let n=xe.BITS-this.subnetMask,r=Math.abs(e-xe.BITS),o=n-r;return o<0?"0":jD((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(xe.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(xe.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(xe.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(xe.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?xe.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":e==="Link-local unicast"||e==="Loopback"?"Link local":e==="Unspecified"?"Unknown":"Global"}getType(){for(let e=0;e<lC.length;e++){let n=lC[e];if(this.isHostInSubnet(n[0]))return n[1]}return"Global unicast"}getBits(e,n){return BigInt(`0b${this.getBitsBase2(e,n)}`)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}getBitsBase16(e,n){let r=n-e;if(r%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,n).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,xe.BITS)}reverseForm(e){e||(e={});let n=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,n).reverse().join(".");return n>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,n=[],r=0,o=[];for(e=0;e<this.parsedAddress.length;e++){let a=parseInt(this.parsedAddress[e],16);a===0&&r++,a!==0&&r>0&&(r>1&&o.push([e-r,e-1]),r=0)}r>1&&o.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);let s=o.map(a=>a[1]-a[0]+1);if(o.length>0){let a=s.indexOf(Math.max(...s));n=LD(this.parsedAddress,o[a])}else n=this.parsedAddress;for(e=0;e<n.length;e++)n[e]!=="compact"&&(n[e]=parseInt(n[e],16).toString(16));let i=n.join(":");return i=i.replace(/^compact$/,"::"),i=i.replace(/(^compact)|(compact$)/,":"),i=i.replace(/compact/,""),i}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(xe.BITS,"0")),this._binaryZeroPad}parse4in6(e){if(e.indexOf(".")===-1)return e;let n=e.split(":"),r=n.slice(-1)[0],o=r.split(".");if(o.length===Bp.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(UD).join("."),a=n.slice(0,-1).map(fo.escapeHtml).join(":"),u=n.length>1?":":"";throw new ct.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(Bp.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new wn.Address4(`${this.parsedAddress4}${i}`),this.v4=!0,n[n.length-1]=this.address4.toGroup6(),e=n.join(":")}return e}parse(e){e=this.parse4in6(e);let n=e.match(xe.RE_BAD_CHARACTERS);if(n)throw new ct.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(xe.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(xe.RE_BAD_ADDRESS);if(r)throw new ct.AddressError(`Address failed regex: ${r.join("")}`,e.replace(xe.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let o=[],s=e.split("::");if(s.length===2){let i=s[0].split(":"),a=s[1].split(":");i.length===1&&i[0]===""&&(i=[]),a.length===1&&a[0]===""&&(a=[]);let u=this.groups-(i.length+a.length);if(!u)throw new ct.AddressError("Error parsing groups");this.elidedGroups=u,this.elisionBegin=i.length,this.elisionEnd=i.length+this.elidedGroups,o=o.concat(i);for(let d=0;d<u;d++)o.push("0");o=o.concat(a)}else if(s.length===1)o=e.split(":"),this.elidedGroups=0;else throw new ct.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new ct.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(cC).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(cC).join("")}`)}to4(){let e=this.binaryZeroPad().split(""),n=BigInt(`0b${e.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let r=this.subnetMask-96,o=[];for(let s=0;s<8;s+=2)o.push(parseInt(n.slice(s,s+2),16));return new wn.Address4(`${o.join(".")}/${r}`)}return wn.Address4.fromHex(n)}to4in6(){let e=this.to4(),r=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),o="";return/:$/.test(r)||(o=":"),r+o+e.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),r=(this.getBits(80,96)^BigInt("0xffff")).toString(),o=wn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=wn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Ec.testBit)(a,15),d=(0,Ec.testBit)(a,14),f=(0,Ec.testBit)(a,8),p=(0,Ec.testBit)(a,9),h=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:o.address,client4:i.address,flags:a,coneNat:u,microsoft:{reserved:d,universalLocal:p,groupIndividual:f,nonce:h},udpPort:r}}inspect6to4(){let e=this.getBitsBase16(0,16),n=wn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:n.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}static fromAddress4Nat64(e,n="64:ff9b::/96"){let r=new wn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let i=o.binaryZeroPad(),a=r.binaryZeroPad(),u;if(s===96)u=i.slice(0,96)+a;else{let p=64-s;u=[i.slice(0,s),a.slice(0,p),"00000000",a.slice(p),"0".repeat(56-(32-p))].join("")}let d=BigInt(`0b${u}`).toString(16).padStart(32,"0"),f=[];for(let p=0;p<8;p++)f.push(d.slice(p*4,(p+1)*4));return new t(f.join(":"))}toAddress4Nat64(e="64:ff9b::/96"){let n=new t(e),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(n))return null;let o=this.binaryZeroPad(),s;if(r===96)s=o.slice(96,128);else{let a=64-r;s=o.slice(r,r+a)+o.slice(72,72+(32-a))}let i=[];for(let a=0;a<4;a++)i.push(parseInt(s.slice(a*8,(a+1)*8),2).toString());return new wn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(xe.BITS/4,"0"),n=[];for(let r=0,o=e.length;r<o;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(uC)}static fromByteArray(e){return ho.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(uC))}static fromUnsignedByteArray(e){ho.assertByteArray(e,16,"IPv6",0);let n=BigInt("256"),r=BigInt("0"),o=BigInt("1");for(let s=e.length-1;s>=0;s--)r+=o*BigInt(e[s].toString(10)),o*=n;return t.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.getBitsBase2(0,64)==="1111111010000000000000000000000000000000000000000000000000000000"}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let n=this.getType();return n==="Multicast"||n.startsWith("Multicast ")}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(WD)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(GD)?this.to4():null}isTeredo(){return this.isHostInSubnet($D)}is6to4(){return this.isHostInSubnet(qD)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(HD)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()==="Unspecified"}isDocumentation(){return this.isHostInSubnet(zD)}href(e){return e===void 0?e="":e=`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),e.className===void 0&&(e.className=""),e.prefix===void 0&&(e.prefix="/#address="),e.v4===void 0&&(e.v4=!1);let n=this.correctForm;e.v4&&(n=this.to4in6);let r=n.call(this),o=fo.escapeHtml(`${e.prefix}${r}`),s=fo.escapeHtml(r);if(e.className){let i=fo.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return fo.simpleGroup(this.addressMinusSuffix).join(":");vc(typeof this.elidedGroups=="number"),vc(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...fo.simpleGroup(n)):e.push("");let o=["hover-group"];for(let s=this.elisionBegin;s<this.elisionBegin+this.elidedGroups;s++)o.push(`group-${s}`);return e.push(`<span class="${o.join(" ")}"></span>`),r.length?e.push(...fo.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(vc(this.address4 instanceof wn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let n=[],r=new t(this.correctForm());if(r.elidedGroups===0)n.push((0,po.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===xe.GROUPS)n.push((0,po.possibleElisions)(xe.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,po.simpleRegularExpression)(o[0].split(":"))),vc(typeof r.elidedGroups=="number"),n.push((0,po.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,po.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",po.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",po.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Sn.Address6=kn;var lC=Object.keys(xe.TYPES).map(t=>[new kn(t),xe.TYPES[t]]),$D=new kn("2001::/32"),qD=new kn("2002::/16"),HD=new kn("fc00::/7"),zD=new kn("2001:db8::/32"),WD=new kn("::ffff:0:0/96"),GD=new kn("64:ff9b::/96")});var fC=G(ft=>{"use strict";var JD=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),KD=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),VD=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&JD(e,t,n);return KD(e,t),e};Object.defineProperty(ft,"__esModule",{value:!0});ft.v6=ft.AddressError=ft.Address6=ft.Address4=void 0;var YD=Fp();Object.defineProperty(ft,"Address4",{enumerable:!0,get:function(){return YD.Address4}});var XD=dC();Object.defineProperty(ft,"Address6",{enumerable:!0,get:function(){return XD.Address6}});var QD=Fi();Object.defineProperty(ft,"AddressError",{enumerable:!0,get:function(){return QD.AddressError}});var ZD=VD(Mp());ft.v6={helpers:ZD}});var hC=G((mH,jp)=>{"use strict";var eO=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,tO=/(\w*(\.\w*)*)\..*/;jp.exports=function(e){if(e.name.length>0)return e.name;let n=Error.stackTraceLimit;Error.stackTraceLimit=10;try{throw new Error("anonymous function")}catch(r){return Error.stackTraceLimit=n,pC(r.stack)}};function pC(t){let e=t.match(eO);return e?e[1].split(/[/\\]/).slice(-1)[0].match(tO)[1]:"anonymous"}jp.exports.extractPluginName=pC});var mC=G((yH,gC)=>{"use strict";gC.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var Lp=G((_H,xc)=>{"use strict";var nO=hC(),rO=mC(),oO=0;function Up(t,e={}){let n=!1;if(t.default!==void 0&&(t=t.default),typeof t!="function")throw new TypeError(`fastify-plugin expects a function, instead got a '${typeof t}'`);if(typeof e=="string"&&(e={fastify:e}),typeof e!="object"||Array.isArray(e)||e===null)throw new TypeError("The options object should be an object");if(e.fastify!==void 0&&typeof e.fastify!="string")throw new TypeError(`fastify-plugin expects a version string, instead got '${typeof e.fastify}'`);e.name||(n=!0,e.name=nO(t)+"-auto-"+oO++),t[Symbol.for("skip-override")]=e.encapsulate!==!0,t[Symbol.for("fastify.display-name")]=e.name,t[Symbol.for("plugin-meta")]=e,t.default||(t.default=t);let r=rO(e.name);return!n&&!t[r]&&(t[r]=t),t}xc.exports=Up;xc.exports.default=Up;xc.exports.fastifyPlugin=Up});var yC=G(qp=>{var sO=/^(-?(?:\d+)?\.?\d+) *(m(?:illiseconds?|s(?:ecs?)?))?(s(?:ec(?:onds?|s)?)?)?(m(?:in(?:utes?|s)?)?)?(h(?:ours?|rs?)?)?(d(?:ays?)?)?(w(?:eeks?|ks?)?)?(y(?:ears?|rs?)?)?$/,Rc=1e3,Dc=Rc*60,Oc=Dc*60,Mi=Oc*24,$p=Mi*365.25;function iO(t){var e,n=t.toLowerCase().match(sO);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*Rc:n[4]!=null?e*Dc:n[5]!=null?e*Oc:n[6]!=null?e*Mi:n[7]!=null?e*Mi*7:n[8]!=null?e*$p:e}function Ni(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function aO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<Rc?t+(e?" ms":"ms"):r<Dc?Ni(r/Rc,n,"second",e):r<Oc?Ni(r/Dc,n,"minute",e):r<Mi?Ni(r/Oc,n,"hour",e):r<$p?Ni(r/Mi,n,"day",e):Ni(r/$p,n,"year",e)}qp.format=aO;qp.parse=iO});var bC=G(An=>{"use strict";function Nc(t,e){if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("Invalid max value");if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("Invalid ttl value")}var Hp=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},Pc=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function zp(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var Ic=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:zp()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=zp()}getStatistics(){return this.records}},Wp=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=new Map,this.last=null,this.max=e,this.ttl=n}get size(){return this.items.size}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items.clear(),this.first=null,this.last=null}delete(e){let n=this.items.get(e);n!==void 0&&(this.items.delete(e),n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;this.items.delete(e.key),this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items.get(e);if(n!==void 0)return n.expiry}get(e){let n=this.items.get(e);if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return this.items.keys()}set(e,n){let r=this.items.get(e);if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items.set(e,o),this.size===1?this.first=o:this.last.next=o,this.last=o}},Bi=class{constructor(e=1e3,n=0){Nc(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}bumpLru(e){if(this.last===e)return;let n=this.last,r=e.next,o=e.prev;this.first===e&&(this.first=r),e.next=null,e.prev=n,n.next=e,o!==null&&(o.next=r),r!==null&&(r.prev=o),this.last=e}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return this.bumpLru(n),n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl,this.bumpLru(r);return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function _C(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var Gp=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=_C(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new Ic,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=zp()),e[this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){Date.now()>=this.archiveAfter&&(this.collectionStart=new Date,this.currentTimeStamp=_C(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},Fc=class extends Bi{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Gp(r,s!==void 0?s:24,o)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,n){super.set(e,n),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){let e=this.size>0;super.evict(),e&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,n=!1){let r=this.items[e]!==void 0;super.delete(e),r&&!n&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(n),n.value||(this.hitStatistics.addFalsyHit(),(n.value===void 0||n.value===null||n.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),n.value}this.hitStatistics.addMiss()}};An.Fifo=Pc;An.FifoMap=Hp;An.FifoObject=Pc;An.HitStatisticsRecord=Ic;An.Lru=Bi;An.LruHitStatistics=Fc;An.LruMap=Wp;An.LruObject=Bi;An.LruObjectHitStatistics=Fc});var wC=G((wH,CC)=>{"use strict";var{LruMap:cO}=bC();function ji(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new cO(n)}ji.prototype.incr=function(t,e,n,r){let o=Date.now(),s=this.lru.get(t);if(!s)s={current:1,ttl:n,iterationStartMs:o};else if(s.iterationStartMs+n<=o)s.current=1,s.ttl=n,s.iterationStartMs=o;else if(++s.current,this.continueExceeding&&s.current>r)s.ttl=n,s.iterationStartMs=o;else if(this.exponentialBackoff&&s.current>r){let i=s.current-r-1,a=n*2**i;s.ttl=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER,s.iterationStartMs=o}else s.ttl=n-(o-s.iterationStartMs);this.lru.set(t,s),e(null,s)};ji.prototype.read=function(t,e,n,r){let o=Date.now(),s=this.lru.get(t);if(!s||s.iterationStartMs+n<=o){e(null,{current:0,ttl:0});return}let i=n-(o-s.iterationStartMs);e(null,{current:s.current,ttl:i})};ji.prototype.child=function(t){return new ji(t.continueExceeding,t.exponentialBackoff,t.cache)};CC.exports=ji});var SC=G((kH,kC)=>{"use strict";var uO=`
2
2
  -- Key to operate on
3
3
  local key = KEYS[1]
4
4
  -- Time window for the TTL
@@ -27,7 +27,7 @@ var rD=Object.create;var Pp=Object.defineProperty;var oD=Object.getOwnPropertyDe
27
27
  end
28
28
 
29
29
  return {current, timeWindow}
30
- `,uO=`
30
+ `,lO=`
31
31
  -- Key to operate on
32
32
  local key = KEYS[1]
33
33
 
@@ -49,95 +49,95 @@ var rD=Object.create;var Pp=Object.defineProperty;var oD=Object.getOwnPropertyDe
49
49
  end
50
50
 
51
51
  return {tonumber(current), ttl}
52
- `;function ji(t,e,n,r="fastify-rate-limit-"){this.continueExceeding=t,this.exponentialBackoff=e,this.redis=n,this.key=r,this.redis.rateLimit||this.redis.defineCommand("rateLimit",{numberOfKeys:1,lua:cO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:uO})}ji.prototype.incr=function(t,e,n,r){this.redis.rateLimit(this.key+t,n,r,this.continueExceeding,this.exponentialBackoff,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};ji.prototype.read=function(t,e,n,r){this.redis.rateLimitRead(this.key+t,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};ji.prototype.child=function(t){return new ji(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};kC.exports=ji});var MC=G((CH,Li)=>{"use strict";var{isIPv6:lO}=re("node:net"),{Address6:AC}=fC(),dO=$p(),{parse:TC,format:fO}=yC(),pO=wC(),hO=SC(),xC=1e3,RC=6e4,gO="onRequest",DC=64,mO={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},yO={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},Kp=()=>{};function OC(t,e=DC){if(!lO(t))return t.toLowerCase();let n=new AC(t);return n.isMapped4()?n.to4().correctForm():e<128?new AC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function PC(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):DC}var Vp=(t,e)=>OC(t.ip,e),_O=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Yp(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=yO):(n.enableDraftSpec=!1,n.labels=mO),n.addHeaders=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0,[n.labels.retryAfter]:!0},e.addHeaders),n.addHeadersOnExceeding=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0},e.addHeadersOnExceeding),Number.isFinite(e.max)&&e.max>=0?n.max=Math.trunc(e.max):typeof e.max=="function"?n.max=e.max:n.max=xC,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=TC(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=RC,n.hook=e.hook||gO,n.allowList=e.allowList||null,n.ban=Number.isFinite(e.ban)&&e.ban>=0?Math.trunc(e.ban):-1,n.onBanReach=typeof e.onBanReach=="function"?e.onBanReach:Kp,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:Kp,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:Kp,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=PC(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:Vp,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=_O,n.isCustomErrorMessage=!1),n.skipOnError=typeof e.skipOnError=="boolean"?e.skipOnError:!1;let r={rateLimitRan:Symbol("fastify.request.rateLimitRan"),store:null};if(e.store){let o=e.store;r.store=new o(n)}else e.redis?r.store=new hO(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new pO(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=EC(r,n,o);return(i,a)=>FC.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=EC(r,n,o);return NC(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=IC(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),vC(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&vC(r,n,o)})}function IC(...t){let e=Object.assign({},...t);if(Number.isFinite(e.timeWindow)&&e.timeWindow>=0?e.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?e.timeWindow=TC(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=RC),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=xC),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=PC(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function EC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=IC(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function vC(t,e,n){let r=e.hook,o=NC(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function FC(t,e,n,r){let{store:o}=t,s=e.keyGenerator===Vp?Vp(n,e.ipv6Subnet):await e.keyGenerator(n),i=n.routeOptions.config?.rateLimit?.groupId;if(i&&(s+=i),e.allowList){if(typeof e.allowList=="function"){if(await e.allowList(n,s))return{isAllowed:!0,key:s}}else if(e.allowList.indexOf(s)!==-1)return{isAllowed:!0,key:s}}let a=typeof e.max=="number"?e.max:await e.max(n,s),u=typeof e.timeWindow=="number"?e.timeWindow:await e.timeWindow(n,s),d=0,f=0,p=0,h=r?.increment===!1?"read":"incr";if(h==="read"&&typeof o.read!="function")throw new Error("The configured rate-limit store does not implement a `read` method, which is required to use `{ increment: false }`");try{let g=await new Promise((b,m)=>{o[h](s,(w,C)=>{w?m(w):b(C)},u,a)});d=g.current,f=g.ttl,p=Math.ceil(g.ttl/1e3)}catch(g){if(!e.skipOnError)throw g}return{isAllowed:!1,key:s,max:a,timeWindow:u,remaining:Math.max(0,a-d),ttl:f,ttlInSeconds:p,isExceeded:d>a,isBanned:e.ban!==-1&&d-a>e.ban}}function NC(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await FC(t,e,r);if(s.isAllowed)return;let{key:i,max:a,remaining:u,ttl:d,ttlInSeconds:f,isExceeded:p,isBanned:h}=s;if(!p){e.addHeadersOnExceeding[e.labels.rateLimit]&&o.header(e.labels.rateLimit,a),e.addHeadersOnExceeding[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,u),e.addHeadersOnExceeding[e.labels.rateReset]&&o.header(e.labels.rateReset,f),e.onExceeding(r,i);return}e.onExceeded(r,i),e.addHeaders[e.labels.rateLimit]&&o.header(e.labels.rateLimit,a),e.addHeaders[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,0),e.addHeaders[e.labels.rateReset]&&o.header(e.labels.rateReset,f),e.addHeaders[e.labels.retryAfter]&&o.header(e.labels.retryAfter,f);let g={statusCode:429,ban:!1,max:a,ttl:d,after:fO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}Li.exports=dO(Yp,{fastify:"5.x",name:"@fastify/rate-limit"});Li.exports.default=Yp;Li.exports.fastifyRateLimit=Yp;Li.exports.normalizeIP=OC});var BC=G((wH,Mc)=>{Mc.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Mc.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Mc.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Qp=G((kH,UC)=>{var Xp=BC();UC.exports={isSpaceSeparator(t){return typeof t=="string"&&Xp.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Xp.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||Xp.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var HC=G((SH,qC)=>{var rt=Qp(),eh,yt,sr,Uc,Ur,Zt,ot,rh,qi;qC.exports=function(e,n){eh=String(e),yt="start",sr=[],Uc=0,Ur=1,Zt=0,ot=void 0,rh=void 0,qi=void 0;do ot=bO(),kO[yt]();while(ot.type!=="eof");return typeof n=="function"?th({"":qi},"",n):qi};function th(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),i=th(r,s,n);i===void 0?delete r[s]:Object.defineProperty(r,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=th(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Ae,Ce,$i,or,Re;function bO(){for(Ae="default",Ce="",$i=!1,or=1;;){Re=ir();let t=LC[Ae]();if(t)return t}}function ir(){if(eh[Uc])return String.fromCodePoint(eh.codePointAt(Uc))}function Y(){let t=ir();return t===`
53
- `?(Ur++,Zt=0):t?Zt+=t.length:Zt++,t&&(Uc+=t.length),t}var LC={default(){switch(Re){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
52
+ `;function Ui(t,e,n,r="fastify-rate-limit-"){this.continueExceeding=t,this.exponentialBackoff=e,this.redis=n,this.key=r,this.redis.rateLimit||this.redis.defineCommand("rateLimit",{numberOfKeys:1,lua:uO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:lO})}Ui.prototype.incr=function(t,e,n,r){this.redis.rateLimit(this.key+t,n,r,this.continueExceeding,this.exponentialBackoff,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};Ui.prototype.read=function(t,e,n,r){this.redis.rateLimitRead(this.key+t,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};Ui.prototype.child=function(t){return new Ui(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};kC.exports=Ui});var MC=G((SH,Li)=>{"use strict";var{isIPv6:dO}=re("node:net"),{Address6:AC}=fC(),fO=Lp(),{parse:TC,format:pO}=yC(),hO=wC(),gO=SC(),xC=1e3,RC=6e4,mO="onRequest",DC=64,yO={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},_O={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},Jp=()=>{};function OC(t,e=DC){if(!dO(t))return t.toLowerCase();let n=new AC(t);return n.isMapped4()?n.to4().correctForm():e<128?new AC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function PC(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):DC}var Kp=(t,e)=>OC(t.ip,e),bO=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Vp(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=_O):(n.enableDraftSpec=!1,n.labels=yO),n.addHeaders=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0,[n.labels.retryAfter]:!0},e.addHeaders),n.addHeadersOnExceeding=Object.assign({[n.labels.rateLimit]:!0,[n.labels.rateRemaining]:!0,[n.labels.rateReset]:!0},e.addHeadersOnExceeding),Number.isFinite(e.max)&&e.max>=0?n.max=Math.trunc(e.max):typeof e.max=="function"?n.max=e.max:n.max=xC,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=TC(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=RC,n.hook=e.hook||mO,n.allowList=e.allowList||null,n.ban=Number.isFinite(e.ban)&&e.ban>=0?Math.trunc(e.ban):-1,n.onBanReach=typeof e.onBanReach=="function"?e.onBanReach:Jp,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:Jp,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:Jp,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=PC(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:Kp,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=bO,n.isCustomErrorMessage=!1),n.skipOnError=typeof e.skipOnError=="boolean"?e.skipOnError:!1;let r={rateLimitRan:Symbol("fastify.request.rateLimitRan"),store:null};if(e.store){let o=e.store;r.store=new o(n)}else e.redis?r.store=new gO(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new hO(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=EC(r,n,o);return(i,a)=>FC.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=EC(r,n,o);return NC(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=IC(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),vC(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&vC(r,n,o)})}function IC(...t){let e=Object.assign({},...t);if(Number.isFinite(e.timeWindow)&&e.timeWindow>=0?e.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?e.timeWindow=TC(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=RC),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=xC),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=PC(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function EC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=IC(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function vC(t,e,n){let r=e.hook,o=NC(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function FC(t,e,n,r){let{store:o}=t,s=e.keyGenerator===Kp?Kp(n,e.ipv6Subnet):await e.keyGenerator(n),i=n.routeOptions.config?.rateLimit?.groupId;if(i&&(s+=i),e.allowList){if(typeof e.allowList=="function"){if(await e.allowList(n,s))return{isAllowed:!0,key:s}}else if(e.allowList.indexOf(s)!==-1)return{isAllowed:!0,key:s}}let a=typeof e.max=="number"?e.max:await e.max(n,s),u=typeof e.timeWindow=="number"?e.timeWindow:await e.timeWindow(n,s),d=0,f=0,p=0,h=r?.increment===!1?"read":"incr";if(h==="read"&&typeof o.read!="function")throw new Error("The configured rate-limit store does not implement a `read` method, which is required to use `{ increment: false }`");try{let g=await new Promise((b,m)=>{o[h](s,(w,C)=>{w?m(w):b(C)},u,a)});d=g.current,f=g.ttl,p=Math.ceil(g.ttl/1e3)}catch(g){if(!e.skipOnError)throw g}return{isAllowed:!1,key:s,max:a,timeWindow:u,remaining:Math.max(0,a-d),ttl:f,ttlInSeconds:p,isExceeded:d>a,isBanned:e.ban!==-1&&d-a>e.ban}}function NC(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await FC(t,e,r);if(s.isAllowed)return;let{key:i,max:a,remaining:u,ttl:d,ttlInSeconds:f,isExceeded:p,isBanned:h}=s;if(!p){e.addHeadersOnExceeding[e.labels.rateLimit]&&o.header(e.labels.rateLimit,a),e.addHeadersOnExceeding[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,u),e.addHeadersOnExceeding[e.labels.rateReset]&&o.header(e.labels.rateReset,f),e.onExceeding(r,i);return}e.onExceeded(r,i),e.addHeaders[e.labels.rateLimit]&&o.header(e.labels.rateLimit,a),e.addHeaders[e.labels.rateRemaining]&&o.header(e.labels.rateRemaining,0),e.addHeaders[e.labels.rateReset]&&o.header(e.labels.rateReset,f),e.addHeaders[e.labels.retryAfter]&&o.header(e.labels.retryAfter,f);let g={statusCode:429,ban:!1,max:a,ttl:d,after:pO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}Li.exports=fO(Vp,{fastify:"5.x",name:"@fastify/rate-limit"});Li.exports.default=Vp;Li.exports.fastifyRateLimit=Vp;Li.exports.normalizeIP=OC});var BC=G((AH,Mc)=>{Mc.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Mc.exports.ID_Start=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;Mc.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Xp=G((EH,jC)=>{var Yp=BC();jC.exports={isSpaceSeparator(t){return typeof t=="string"&&Yp.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Yp.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||Yp.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var HC=G((vH,qC)=>{var rt=Xp(),Zp,yt,sr,jc,jr,Zt,ot,nh,qi;qC.exports=function(e,n){Zp=String(e),yt="start",sr=[],jc=0,jr=1,Zt=0,ot=void 0,nh=void 0,qi=void 0;do ot=CO(),SO[yt]();while(ot.type!=="eof");return typeof n=="function"?eh({"":qi},"",n):qi};function eh(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),i=eh(r,s,n);i===void 0?delete r[s]:Object.defineProperty(r,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=eh(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Ae,Ce,$i,or,Re;function CO(){for(Ae="default",Ce="",$i=!1,or=1;;){Re=ir();let t=LC[Ae]();if(t)return t}}function ir(){if(Zp[jc])return String.fromCodePoint(Zp.codePointAt(jc))}function Y(){let t=ir();return t===`
53
+ `?(jr++,Zt=0):t?Zt+=t.length:Zt++,t&&(jc+=t.length),t}var LC={default(){switch(Re){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
54
54
  `:case"\r":case"\u2028":case"\u2029":Y();return;case"/":Y(),Ae="comment";return;case void 0:return Y(),qe("eof")}if(rt.isSpaceSeparator(Re)){Y();return}return LC[yt]()},comment(){switch(Re){case"*":Y(),Ae="multiLineComment";return;case"/":Y(),Ae="singleLineComment";return}throw He(Y())},multiLineComment(){switch(Re){case"*":Y(),Ae="multiLineCommentAsterisk";return;case void 0:throw He(Y())}Y()},multiLineCommentAsterisk(){switch(Re){case"*":Y();return;case"/":Y(),Ae="default";return;case void 0:throw He(Y())}Y(),Ae="multiLineComment"},singleLineComment(){switch(Re){case`
55
- `:case"\r":case"\u2028":case"\u2029":Y(),Ae="default";return;case void 0:return Y(),qe("eof")}Y()},value(){switch(Re){case"{":case"[":return qe("punctuator",Y());case"n":return Y(),go("ull"),qe("null",null);case"t":return Y(),go("rue"),qe("boolean",!0);case"f":return Y(),go("alse"),qe("boolean",!1);case"-":case"+":Y()==="-"&&(or=-1),Ae="sign";return;case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),go("nfinity"),qe("numeric",1/0);case"N":return Y(),go("aN"),qe("numeric",NaN);case'"':case"'":$i=Y()==='"',Ce="",Ae="string";return}throw He(Y())},identifierNameStartEscape(){if(Re!=="u")throw He(Y());Y();let t=nh();switch(t){case"$":case"_":break;default:if(!rt.isIdStartChar(t))throw jC();break}Ce+=t,Ae="identifierName"},identifierName(){switch(Re){case"$":case"_":case"\u200C":case"\u200D":Ce+=Y();return;case"\\":Y(),Ae="identifierNameEscape";return}if(rt.isIdContinueChar(Re)){Ce+=Y();return}return qe("identifier",Ce)},identifierNameEscape(){if(Re!=="u")throw He(Y());Y();let t=nh();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!rt.isIdContinueChar(t))throw jC();break}Ce+=t,Ae="identifierName"},sign(){switch(Re){case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),go("nfinity"),qe("numeric",or*(1/0));case"N":return Y(),go("aN"),qe("numeric",NaN)}throw He(Y())},zero(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return;case"x":case"X":Ce+=Y(),Ae="hexadecimal";return}return qe("numeric",or*0)},decimalInteger(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalPointLeading(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}throw He(Y())},decimalPoint(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}return qe("numeric",or*Number(Ce))},decimalFraction(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalExponent(){switch(Re){case"+":case"-":Ce+=Y(),Ae="decimalExponentSign";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentSign(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentInteger(){if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},hexadecimal(){if(rt.isHexDigit(Re)){Ce+=Y(),Ae="hexadecimalInteger";return}throw He(Y())},hexadecimalInteger(){if(rt.isHexDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},string(){switch(Re){case"\\":Y(),Ce+=CO();return;case'"':if($i)return Y(),qe("string",Ce);Ce+=Y();return;case"'":if(!$i)return Y(),qe("string",Ce);Ce+=Y();return;case`
56
- `:case"\r":throw He(Y());case"\u2028":case"\u2029":SO(Re);break;case void 0:throw He(Y())}Ce+=Y()},start(){switch(Re){case"{":case"[":return qe("punctuator",Y())}Ae="value"},beforePropertyName(){switch(Re){case"$":case"_":Ce=Y(),Ae="identifierName";return;case"\\":Y(),Ae="identifierNameStartEscape";return;case"}":return qe("punctuator",Y());case'"':case"'":$i=Y()==='"',Ae="string";return}if(rt.isIdStartChar(Re)){Ce+=Y(),Ae="identifierName";return}throw He(Y())},afterPropertyName(){if(Re===":")return qe("punctuator",Y());throw He(Y())},beforePropertyValue(){Ae="value"},afterPropertyValue(){switch(Re){case",":case"}":return qe("punctuator",Y())}throw He(Y())},beforeArrayValue(){if(Re==="]")return qe("punctuator",Y());Ae="value"},afterArrayValue(){switch(Re){case",":case"]":return qe("punctuator",Y())}throw He(Y())},end(){throw He(Y())}};function qe(t,e){return{type:t,value:e,line:Ur,column:Zt}}function go(t){for(let e of t){if(ir()!==e)throw He(Y());Y()}}function CO(){switch(ir()){case"b":return Y(),"\b";case"f":return Y(),"\f";case"n":return Y(),`
57
- `;case"r":return Y(),"\r";case"t":return Y()," ";case"v":return Y(),"\v";case"0":if(Y(),rt.isDigit(ir()))throw He(Y());return"\0";case"x":return Y(),wO();case"u":return Y(),nh();case`
55
+ `:case"\r":case"\u2028":case"\u2029":Y(),Ae="default";return;case void 0:return Y(),qe("eof")}Y()},value(){switch(Re){case"{":case"[":return qe("punctuator",Y());case"n":return Y(),go("ull"),qe("null",null);case"t":return Y(),go("rue"),qe("boolean",!0);case"f":return Y(),go("alse"),qe("boolean",!1);case"-":case"+":Y()==="-"&&(or=-1),Ae="sign";return;case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),go("nfinity"),qe("numeric",1/0);case"N":return Y(),go("aN"),qe("numeric",NaN);case'"':case"'":$i=Y()==='"',Ce="",Ae="string";return}throw He(Y())},identifierNameStartEscape(){if(Re!=="u")throw He(Y());Y();let t=th();switch(t){case"$":case"_":break;default:if(!rt.isIdStartChar(t))throw UC();break}Ce+=t,Ae="identifierName"},identifierName(){switch(Re){case"$":case"_":case"\u200C":case"\u200D":Ce+=Y();return;case"\\":Y(),Ae="identifierNameEscape";return}if(rt.isIdContinueChar(Re)){Ce+=Y();return}return qe("identifier",Ce)},identifierNameEscape(){if(Re!=="u")throw He(Y());Y();let t=th();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!rt.isIdContinueChar(t))throw UC();break}Ce+=t,Ae="identifierName"},sign(){switch(Re){case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),go("nfinity"),qe("numeric",or*(1/0));case"N":return Y(),go("aN"),qe("numeric",NaN)}throw He(Y())},zero(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return;case"x":case"X":Ce+=Y(),Ae="hexadecimal";return}return qe("numeric",or*0)},decimalInteger(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalPointLeading(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}throw He(Y())},decimalPoint(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}return qe("numeric",or*Number(Ce))},decimalFraction(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalExponent(){switch(Re){case"+":case"-":Ce+=Y(),Ae="decimalExponentSign";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentSign(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentInteger(){if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},hexadecimal(){if(rt.isHexDigit(Re)){Ce+=Y(),Ae="hexadecimalInteger";return}throw He(Y())},hexadecimalInteger(){if(rt.isHexDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},string(){switch(Re){case"\\":Y(),Ce+=wO();return;case'"':if($i)return Y(),qe("string",Ce);Ce+=Y();return;case"'":if(!$i)return Y(),qe("string",Ce);Ce+=Y();return;case`
56
+ `:case"\r":throw He(Y());case"\u2028":case"\u2029":AO(Re);break;case void 0:throw He(Y())}Ce+=Y()},start(){switch(Re){case"{":case"[":return qe("punctuator",Y())}Ae="value"},beforePropertyName(){switch(Re){case"$":case"_":Ce=Y(),Ae="identifierName";return;case"\\":Y(),Ae="identifierNameStartEscape";return;case"}":return qe("punctuator",Y());case'"':case"'":$i=Y()==='"',Ae="string";return}if(rt.isIdStartChar(Re)){Ce+=Y(),Ae="identifierName";return}throw He(Y())},afterPropertyName(){if(Re===":")return qe("punctuator",Y());throw He(Y())},beforePropertyValue(){Ae="value"},afterPropertyValue(){switch(Re){case",":case"}":return qe("punctuator",Y())}throw He(Y())},beforeArrayValue(){if(Re==="]")return qe("punctuator",Y());Ae="value"},afterArrayValue(){switch(Re){case",":case"]":return qe("punctuator",Y())}throw He(Y())},end(){throw He(Y())}};function qe(t,e){return{type:t,value:e,line:jr,column:Zt}}function go(t){for(let e of t){if(ir()!==e)throw He(Y());Y()}}function wO(){switch(ir()){case"b":return Y(),"\b";case"f":return Y(),"\f";case"n":return Y(),`
57
+ `;case"r":return Y(),"\r";case"t":return Y()," ";case"v":return Y(),"\v";case"0":if(Y(),rt.isDigit(ir()))throw He(Y());return"\0";case"x":return Y(),kO();case"u":return Y(),th();case`
58
58
  `:case"\u2028":case"\u2029":return Y(),"";case"\r":return Y(),ir()===`
59
- `&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw He(Y());case void 0:throw He(Y())}return Y()}function wO(){let t="",e=ir();if(!rt.isHexDigit(e)||(t+=Y(),e=ir(),!rt.isHexDigit(e)))throw He(Y());return t+=Y(),String.fromCodePoint(parseInt(t,16))}function nh(){let t="",e=4;for(;e-- >0;){let n=ir();if(!rt.isHexDigit(n))throw He(Y());t+=Y()}return String.fromCodePoint(parseInt(t,16))}var kO={start(){if(ot.type==="eof")throw mo();Zp()},beforePropertyName(){switch(ot.type){case"identifier":case"string":rh=ot.value,yt="afterPropertyName";return;case"punctuator":Bc();return;case"eof":throw mo()}},afterPropertyName(){if(ot.type==="eof")throw mo();yt="beforePropertyValue"},beforePropertyValue(){if(ot.type==="eof")throw mo();Zp()},beforeArrayValue(){if(ot.type==="eof")throw mo();if(ot.type==="punctuator"&&ot.value==="]"){Bc();return}Zp()},afterPropertyValue(){if(ot.type==="eof")throw mo();switch(ot.value){case",":yt="beforePropertyName";return;case"}":Bc()}},afterArrayValue(){if(ot.type==="eof")throw mo();switch(ot.value){case",":yt="beforeArrayValue";return;case"]":Bc()}},end(){}};function Zp(){let t;switch(ot.type){case"punctuator":switch(ot.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ot.value;break}if(qi===void 0)qi=t;else{let e=sr[sr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,rh,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")sr.push(t),Array.isArray(t)?yt="beforeArrayValue":yt="beforePropertyName";else{let e=sr[sr.length-1];e==null?yt="end":Array.isArray(e)?yt="afterArrayValue":yt="afterPropertyValue"}}function Bc(){sr.pop();let t=sr[sr.length-1];t==null?yt="end":Array.isArray(t)?yt="afterArrayValue":yt="afterPropertyValue"}function He(t){return jc(t===void 0?`JSON5: invalid end of input at ${Ur}:${Zt}`:`JSON5: invalid character '${$C(t)}' at ${Ur}:${Zt}`)}function mo(){return jc(`JSON5: invalid end of input at ${Ur}:${Zt}`)}function jC(){return Zt-=5,jc(`JSON5: invalid identifier character at ${Ur}:${Zt}`)}function SO(t){console.warn(`JSON5: '${$C(t)}' in strings is not valid ECMAScript; consider escaping`)}function $C(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function jc(t){let e=new SyntaxError(t);return e.lineNumber=Ur,e.columnNumber=Zt,e}});var WC=G((AH,zC)=>{var oh=Qp();zC.exports=function(e,n,r){let o=[],s="",i,a,u="",d;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,d=n.quote,n=n.replacer),typeof n=="function")a=n;else if(Array.isArray(n)){i=[];for(let m of n){let w;typeof m=="string"?w=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(w=String(m)),w!==void 0&&i.indexOf(w)<0&&i.push(w)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),f("",{"":e});function f(m,w){let C=w[m];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(m):typeof C.toJSON=="function"&&(C=C.toJSON(m))),a&&(C=a.call(w,m,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return p(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?b(C):h(C)}function p(m){let w={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},A="";for(let E=0;E<m.length;E++){let x=m[E];switch(x){case"'":case'"':w[x]++,A+=x;continue;case"\0":if(oh.isDigit(m[E+1])){A+="\\x00";continue}}if(C[x]){A+=C[x];continue}if(x<" "){let O=x.charCodeAt(0).toString(16);A+="\\x"+("00"+O).substring(O.length);continue}A+=x}let k=d||Object.keys(w).reduce((E,x)=>w[E]<w[x]?E:x);return A=A.replace(new RegExp(k,"g"),C[k]),k+A+k}function h(m){if(o.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");o.push(m);let w=s;s=s+u;let C=i||Object.keys(m),A=[];for(let E of C){let x=f(E,m);if(x!==void 0){let O=g(E)+":";u!==""&&(O+=" "),O+=x,A.push(O)}}let k;if(A.length===0)k="{}";else{let E;if(u==="")E=A.join(","),k="{"+E+"}";else{let x=`,
60
- `+s;E=A.join(x),k=`{
59
+ `&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw He(Y());case void 0:throw He(Y())}return Y()}function kO(){let t="",e=ir();if(!rt.isHexDigit(e)||(t+=Y(),e=ir(),!rt.isHexDigit(e)))throw He(Y());return t+=Y(),String.fromCodePoint(parseInt(t,16))}function th(){let t="",e=4;for(;e-- >0;){let n=ir();if(!rt.isHexDigit(n))throw He(Y());t+=Y()}return String.fromCodePoint(parseInt(t,16))}var SO={start(){if(ot.type==="eof")throw mo();Qp()},beforePropertyName(){switch(ot.type){case"identifier":case"string":nh=ot.value,yt="afterPropertyName";return;case"punctuator":Bc();return;case"eof":throw mo()}},afterPropertyName(){if(ot.type==="eof")throw mo();yt="beforePropertyValue"},beforePropertyValue(){if(ot.type==="eof")throw mo();Qp()},beforeArrayValue(){if(ot.type==="eof")throw mo();if(ot.type==="punctuator"&&ot.value==="]"){Bc();return}Qp()},afterPropertyValue(){if(ot.type==="eof")throw mo();switch(ot.value){case",":yt="beforePropertyName";return;case"}":Bc()}},afterArrayValue(){if(ot.type==="eof")throw mo();switch(ot.value){case",":yt="beforeArrayValue";return;case"]":Bc()}},end(){}};function Qp(){let t;switch(ot.type){case"punctuator":switch(ot.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ot.value;break}if(qi===void 0)qi=t;else{let e=sr[sr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,nh,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")sr.push(t),Array.isArray(t)?yt="beforeArrayValue":yt="beforePropertyName";else{let e=sr[sr.length-1];e==null?yt="end":Array.isArray(e)?yt="afterArrayValue":yt="afterPropertyValue"}}function Bc(){sr.pop();let t=sr[sr.length-1];t==null?yt="end":Array.isArray(t)?yt="afterArrayValue":yt="afterPropertyValue"}function He(t){return Uc(t===void 0?`JSON5: invalid end of input at ${jr}:${Zt}`:`JSON5: invalid character '${$C(t)}' at ${jr}:${Zt}`)}function mo(){return Uc(`JSON5: invalid end of input at ${jr}:${Zt}`)}function UC(){return Zt-=5,Uc(`JSON5: invalid identifier character at ${jr}:${Zt}`)}function AO(t){console.warn(`JSON5: '${$C(t)}' in strings is not valid ECMAScript; consider escaping`)}function $C(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function Uc(t){let e=new SyntaxError(t);return e.lineNumber=jr,e.columnNumber=Zt,e}});var WC=G((TH,zC)=>{var rh=Xp();zC.exports=function(e,n,r){let o=[],s="",i,a,u="",d;if(n!=null&&typeof n=="object"&&!Array.isArray(n)&&(r=n.space,d=n.quote,n=n.replacer),typeof n=="function")a=n;else if(Array.isArray(n)){i=[];for(let m of n){let w;typeof m=="string"?w=m:(typeof m=="number"||m instanceof String||m instanceof Number)&&(w=String(m)),w!==void 0&&i.indexOf(w)<0&&i.push(w)}}return r instanceof Number?r=Number(r):r instanceof String&&(r=String(r)),typeof r=="number"?r>0&&(r=Math.min(10,Math.floor(r)),u=" ".substr(0,r)):typeof r=="string"&&(u=r.substr(0,10)),f("",{"":e});function f(m,w){let C=w[m];switch(C!=null&&(typeof C.toJSON5=="function"?C=C.toJSON5(m):typeof C.toJSON=="function"&&(C=C.toJSON(m))),a&&(C=a.call(w,m,C)),C instanceof Number?C=Number(C):C instanceof String?C=String(C):C instanceof Boolean&&(C=C.valueOf()),C){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof C=="string")return p(C,!1);if(typeof C=="number")return String(C);if(typeof C=="object")return Array.isArray(C)?b(C):h(C)}function p(m){let w={"'":.1,'"':.2},C={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},S="";for(let E=0;E<m.length;E++){let x=m[E];switch(x){case"'":case'"':w[x]++,S+=x;continue;case"\0":if(rh.isDigit(m[E+1])){S+="\\x00";continue}}if(C[x]){S+=C[x];continue}if(x<" "){let O=x.charCodeAt(0).toString(16);S+="\\x"+("00"+O).substring(O.length);continue}S+=x}let k=d||Object.keys(w).reduce((E,x)=>w[E]<w[x]?E:x);return S=S.replace(new RegExp(k,"g"),C[k]),k+S+k}function h(m){if(o.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");o.push(m);let w=s;s=s+u;let C=i||Object.keys(m),S=[];for(let E of C){let x=f(E,m);if(x!==void 0){let O=g(E)+":";u!==""&&(O+=" "),O+=x,S.push(O)}}let k;if(S.length===0)k="{}";else{let E;if(u==="")E=S.join(","),k="{"+E+"}";else{let x=`,
60
+ `+s;E=S.join(x),k=`{
61
61
  `+s+E+`,
62
- `+w+"}"}}return o.pop(),s=w,k}function g(m){if(m.length===0)return p(m,!0);let w=String.fromCodePoint(m.codePointAt(0));if(!oh.isIdStartChar(w))return p(m,!0);for(let C=w.length;C<m.length;C++)if(!oh.isIdContinueChar(String.fromCodePoint(m.codePointAt(C))))return p(m,!0);return m}function b(m){if(o.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");o.push(m);let w=s;s=s+u;let C=[];for(let k=0;k<m.length;k++){let E=f(String(k),m);C.push(E!==void 0?E:"null")}let A;if(C.length===0)A="[]";else if(u==="")A="["+C.join(",")+"]";else{let k=`,
63
- `+s,E=C.join(k);A=`[
62
+ `+w+"}"}}return o.pop(),s=w,k}function g(m){if(m.length===0)return p(m,!0);let w=String.fromCodePoint(m.codePointAt(0));if(!rh.isIdStartChar(w))return p(m,!0);for(let C=w.length;C<m.length;C++)if(!rh.isIdContinueChar(String.fromCodePoint(m.codePointAt(C))))return p(m,!0);return m}function b(m){if(o.indexOf(m)>=0)throw TypeError("Converting circular structure to JSON5");o.push(m);let w=s;s=s+u;let C=[];for(let k=0;k<m.length;k++){let E=f(String(k),m);C.push(E!==void 0?E:"null")}let S;if(C.length===0)S="[]";else if(u==="")S="["+C.join(",")+"]";else{let k=`,
63
+ `+s,E=C.join(k);S=`[
64
64
  `+s+E+`,
65
- `+w+"]"}return o.pop(),s=w,A}}});var sh=G((EH,GC)=>{var AO=HC(),EO=WC(),vO={parse:AO,stringify:EO};GC.exports=vO});var Sk=G((L3,j1)=>{j1.exports={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",i:"\u1D62",o:"\u2092",r:"\u1D63",u:"\u1D64",v:"\u1D65",x:"\u2093",\u03B2:"\u1D66",\u03B3:"\u1D67",\u03C1:"\u1D68",\u03C6:"\u1D69",\u03C7:"\u1D6A"}});var Ak=G(($3,L1)=>{L1.exports={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",\u03B1:"\u1D45",\u03B2:"\u1D5D",\u03B3:"\u1D5E",\u03B4:"\u1D5F","\u220A":"\u1D4B",\u03B8:"\u1DBF",\u03B9:"\u1DA5",\u03A6:"\u1DB2",\u03C6:"\u1D60",\u03C7:"\u1D61"}});var Ek=G((q3,$1)=>{$1.exports={"\\texttrademark":"\u2122","\\trademark":"\u2122","\\textregistered":"\xAE","\\registered":"\xAE","\\copyright":"\xA9","\\pilcrow":"\xB6","\\pound":"\xA3","\\euro":"\u20AC","\\cents":"\xA2","\\section":"\xA7","\\space":"\u2423","\\degree":"\xB0","\\zeta":"\u03B6","\\Xi":"\u039E","\\xi":"\u03BE","\\wr":"\u2240","\\wp":"\u2118","\\wedge":"\u2227","\\Vvdash":"\u22AA","\\veebar":"\u22BB","\\vee":"\u2228","\\vdots":"\u22EE","\\Vdash":"\u22A9","\\vDash":"\u22A8","\\vdash":"\u22A2","\\vartriangleright":"\u22B3","\\vartriangleleft":"\u22B2","\\vartriangle":"\u25B3","\\vartheta":"\u03D1","\\varsigma":"\u03C2","\\varrho":"\u03F1","\\varpropto":"\u221D","\\varpi":"\u03D6","\\varphi":"\u03C6","\\varnothing":"\u2205","\\varkappa":"\u03F0","\\varepsilon":"\u03B5","\\upuparrows":"\u21C8","\\Upsilon":"\u03A5","\\upsilon":"\u03C5","\\uplus":"\u228E","\\upharpoonright":"\u21BE","\\upharpoonleft":"\u21BF","\\Updownarrow":"\u21D5","\\updownarrow":"\u2195","\\Uparrow":"\u21D1","\\uparrow":"\u2191","\\unrhd":"\u22B5","\\unlhd":"\u22B4","\\twoheadrightarrow":"\u21A0","\\twoheadleftarrow":"\u219E","\\trianglerighteq":"\u22B5","\\triangleright":"\u25B7","\\triangleq":"\u225C","\\trianglelefteq":"\u22B4","\\triangleleft":"\u25C1","\\triangledown":"\u25BD","\\triangle":"\u25B3","\\top":"\u22A4","\\times":"\xD7","\\thicksim":"\u223C","\\thickapprox":"\u2248","\\Theta":"\u0398","\\theta":"\u03B8","\\therefore":"\u2234","\\tau":"\u03C4","\\swarrow":"\u2199","\\surd":"\u221A","\\supseteq":"\u2287","\\Supset":"\u22D1","\\supset":"\u2283","\\sum":"\u2211","\\succsim":"\u227F","\\succeq":"\u227D","\\succcurlyeq":"\u227D","\\succ":"\u227B","\\subseteq":"\u2286","\\Subset":"\u22D0","\\subset":"\u2282","\\star":"\u22C6","\\square":"\u25A1","\\sqsupseteq":"\u2292","\\sqsupset":"\u2290","\\sqsubseteq":"\u2291","\\sqsubset":"\u228F","\\sqcup":"\u2294","\\sqcap":"\u2293","\\sphericalangle":"\u2222","\\spadesuit":"\u2660","\\smile":"\u2323","\\smallsmile":"\u2323","\\smallsetminus":"\u2216","\\smallfrown":"\u2322","\\simeq":"\u2243","\\sim":"\u223C","\\sigma":"\u03C3","\\shortparallel":"\u2225","\\sharp":"\u266F","\\setminus":"\u2216","\\searrow":"\u2198","\\rtimes":"\u22C8","\\Rsh":"\u21B1","\\Rrightarrow":"\u21DB","\\risingdotseq":"\u2253","\\rightthreetimes":"\u22CC","\\rightsquigarrow":"\u21DD","\\rightrightarrows":"\u21C9","\\rightleftharpoons":"\u21CC","\\rightleftarrows":"\u21C4","\\rightharpoonup":"\u21C0","\\rightharpoondown":"\u21C1","\\rightarrowtail":"\u21A3","\\Rightarrow":"\u21D2","\\rightarrow":"\u2192","\\rho":"\u03C1","\\rhd":"\u22B3","\\rfloor":"\u230B","\\Re":"\u211C","\\rceil":"\u2309","\\Psi":"\u03A8","\\psi":"\u03C8","\\propto":"\u221D","\\prod":"\u220F","\\prime":"\u2032","\\precsim":"\u227E","\\preceq":"\u227C","\\preccurlyeq":"\u227C","\\prec":"\u227A","\\pm":"\xB1","\\Pi":"\u03A0","\\pi":"\u03C0","\\pitchfork":"\u22D4","\\Phi":"\u03A6","\\phi":"\u03D5","\\perp":"\u22A5","\\partial":"\u2202","\\parallel":"\u2225","\\otimes":"\u2297","\\oslash":"\u2298","\\oplus":"\u2295","\\ominus":"\u2296","\\Omega":"\u03A9","\\omega":"\u03C9","\\oint":"\u222E","\\odot":"\u2299","\\nwarrow":"\u2196","\\nu":"\u03BD","\\notin":"\u2209","\\ni":"\u220B","\\nexists":"\u2204","\\neq":"\u2260","\\neg":"\xAC","\\nearrow":"\u2197","\\natural":"\u266E","\\nabla":"\u2207","\\mu":"\u03BC","\\multimap":"\u22B8","\\mp":"\u2213","\\models":"\u22A8","\\mid":"\u2223","\\mho":"\u2127","\\measuredangle":"\u2221","\\mapsto":"\u21A6","\\ltimes":"\u22C9","\\Lsh":"\u21B0","\\lozenge":"\u25CA","\\looparrowright":"\u21AC","\\looparrowleft":"\u21AB","\\Longrightarrow":"\u21D2","\\longrightarrow":"\u2192","\\longmapsto":"\u21D6","\\Longleftrightarrow":"\u21D4","\\longleftrightarrow":"\u2194","\\Longleftarrow":"\u21D0","\\longleftarrow":"\u2190","\\lll":"\u22D8","\\Lleftarrow":"\u21DA","\\ll":"\u226A","\\lhd":"\u22B2","\\lfloor":"\u230A","\\lesssim":"\u2272","\\lessgtr":"\u2276","\\lesseqgtr":"\u22DA","\\lessdot":"\u22D6","\\leqslant":"\u2264","\\leqq":"\u2266","\\leq":"\u2264","\\leftthreetimes":"\u22CB","\\leftrightsquigarrow":"\u21AD","\\leftrightharpoons":"\u21CB","\\leftrightarrows":"\u21C6","\\Leftrightarrow":"\u21D4","\\leftrightarrow":"\u2194","\\leftleftarrows":"\u21C7","\\leftharpoonup":"\u21BC","\\leftharpoondown":"\u21BD","\\leftarrowtail":"\u21A2","\\Leftarrow":"\u21D0","\\leftarrow":"\u2190","\\leadsto":"\u219D","\\le":"\u2264","\\lceil":"\u2308","\\Lambda":"\u039B","\\lambda":"\u03BB","\\kappa":"\u03BA","\\Join":"\u22C8","\\iota":"\u03B9","\\intercal":"\u22BA","\\int":"\u222B","\\infty":"\u221E","\\in":"\u2208","\\implies":"\u21D2","\\Im":"\u2111","\\hslash":"\u210F","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\heartsuit":"\u2661","\\hbar":"\u210F","\\gtrsim":"\u2273","\\gtrless":"\u2277","\\gtreqless":"\u22DB","\\gtrdot":"\u22D7","\\gimel":"\u05D2","\\ggg":"\u22D9","\\gg":"\u226B","\\geqq":"\u2267","\\geq":"\u2265","\\ge":"\u2265","\\Gamma":"\u0393","\\gamma":"\u03B3","\\frown":"\u2322","\\forall":"\u2200","\\flat":"\u266D","\\Finv":"\u2132","\\fallingdotseq":"\u2252","\\exists":"\u2203","\\eth":"\xF0","\\eta":"\u03B7","\\equiv":"\u2261","\\eqcirc":"\u2256","\\epsilon":"\u220A","\\emptyset":"\u2205","\\ell":"\u2113","\\downharpoonright":"\u21C2","\\downharpoonleft":"\u21C3","\\downdownarrows":"\u21CA","\\Downarrow":"\u21D3","\\downarrow":"\u2193","\\dots":"\u2026","\\dotplus":"\u2214","\\doteqdot":"\u2251","\\doteq":"\u2250","\\divideontimes":"\u22C7","\\div":"\xF7","\\digamma":"\u03DC","\\diamondsuit":"\u2662","\\Diamond":"\u25C7","\\diamond":"\u22C4","\\Delta":"\u0394","\\delta":"\u03B4","\\ddots":"\u22F1","\\ddagger":"\u2021","\\dashv":"\u22A3","\\dashrightarrow":"\u21E2","\\dashleftarrow":"\u21E0","\\daleth":"\u05D3","\\dagger":"\u2020","\\curvearrowright":"\u21B7","\\curvearrowleft":"\u21B6","\\curlywedge":"\u22CF","\\curlyvee":"\u22CE","\\curlyeqsucc":"\u22DF","\\curlyeqprec":"\u22DE","\\Cup":"\u22D3","\\cup":"\u222A","\\coprod":"\u2210","\\cong":"\u2245","\\complement":"\u2201","\\clubsuit":"\u2663","\\circledS":"\u24C8","\\circleddash":"\u229D","\\circledcirc":"\u229A","\\circledast":"\u229B","\\circlearrowright":"\u21BB","\\circlearrowleft":"\u21BA","\\circeq":"\u2257","\\circ":"\u2218","\\chi":"\u03C7","\\centerdot":"\u22C5","\\cdots":"\u22EF","\\cdot":"\u22C5","\\Cap":"\u22D2","\\cap":"\u2229","\\Bumpeq":"\u224E","\\bumpeq":"\u224F","\\bullet":"\u2219","\\boxtimes":"\u22A0","\\boxplus":"\u229E","\\boxminus":"\u229F","\\boxdot":"\u22A1","\\Box":"\u25A1","\\bowtie":"\u22C8","\\bot":"\u22A5","\\blacktriangleright":"\u25B7","\\blacktriangleleft":"\u25C0","\\blacktriangledown":"\u25BC","\\blacktriangle":"\u25B2","\\blacksquare":"\u25A0","\\blacklozenge":"\u25C6","\\bigwedge":"\u22C0","\\bigvee":"\u22C1","\\biguplus":"\u228E","\\bigtriangleup":"\u25B3","\\bigtriangledown":"\u25BD","\\bigstar":"\u2605","\\bigsqcup":"\u2294","\\bigotimes":"\u2297","\\bigoplus":"\u2295","\\bigodot":"\u2299","\\bigcup":"\u22C3","\\bigcirc":"\u25CB","\\bigcap":"\u22C2","\\between":"\u226C","\\beth":"\u05D1","\\beta":"\u03B2","\\because":"\u2235","\\barwedge":"\u22BC","\\backsim":"\u223D","\\backprime":"\u2035","\\backepsilon":"\u220D","\\asymp":"\u224D","\\ast":"\u2217","\\approxeq":"\u224A","\\approx":"\u2248","\\angle":"\u2220","\\alpha":"\u03B1","\\aleph":"\u05D0"}});var vk=G((H3,q1)=>{q1.exports={A:"\u{1D538}",B:"\u{1D539}",C:"\u2102",D:"\u{1D53B}",E:"\u{1D53C}",F:"\u{1D53D}",G:"\u{1D53E}",H:"\u210D",I:"\u{1D540}",J:"\u{1D541}",K:"\u{1D542}",L:"\u{1D543}",M:"\u{1D544}",N:"\u2115",O:"\u{1D546}",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\u{1D54A}",T:"\u{1D54B}",U:"\u{1D54C}",V:"\u{1D54D}",W:"\u{1D54E}",X:"\u{1D54F}",Y:"\u{1D550}",Z:"\u2124",a:"\u{1D552}",b:"\u{1D553}",c:"\u{1D554}",d:"\u{1D555}",e:"\u{1D556}",f:"\u{1D557}",g:"\u{1D558}",h:"\u{1D559}",i:"\u{1D55A}",j:"\u{1D55B}",k:"\u{1D55C}",l:"\u{1D55D}",m:"\u{1D55E}",n:"\u{1D55F}",o:"\u{1D560}",p:"\u{1D561}",q:"\u{1D562}",r:"\u{1D563}",s:"\u{1D564}",t:"\u{1D565}",u:"\u{1D566}",v:"\u{1D567}",w:"\u{1D568}",x:"\u{1D569}",y:"\u{1D56A}",z:"\u{1D56B}","0":"\u{1D7D8}","1":"\u{1D7D9}","2":"\u{1D7DA}","3":"\u{1D7DB}","4":"\u{1D7DC}","5":"\u{1D7DD}","6":"\u{1D7DE}","7":"\u{1D7DF}","8":"\u{1D7E0}","9":"\u{1D7E1}"}});var Tk=G((z3,H1)=>{H1.exports={A:"\u{1D400}",B:"\u{1D401}",C:"\u{1D402}",D:"\u{1D403}",E:"\u{1D404}",F:"\u{1D405}",G:"\u{1D406}",H:"\u{1D407}",I:"\u{1D408}",J:"\u{1D409}",K:"\u{1D40A}",L:"\u{1D40B}",M:"\u{1D40C}",N:"\u{1D40D}",O:"\u{1D40E}",P:"\u{1D40F}",Q:"\u{1D410}",R:"\u{1D411}",S:"\u{1D412}",T:"\u{1D413}",U:"\u{1D414}",V:"\u{1D415}",W:"\u{1D416}",X:"\u{1D417}",Y:"\u{1D418}",Z:"\u{1D419}",a:"\u{1D41A}",b:"\u{1D41B}",c:"\u{1D41C}",d:"\u{1D41D}",e:"\u{1D41E}",f:"\u{1D41F}",g:"\u{1D420}",h:"\u{1D421}",i:"\u{1D422}",j:"\u{1D423}",k:"\u{1D424}",l:"\u{1D425}",m:"\u{1D426}",n:"\u{1D427}",o:"\u{1D428}",p:"\u{1D429}",q:"\u{1D42A}",r:"\u{1D42B}",s:"\u{1D42C}",t:"\u{1D42D}",u:"\u{1D42E}",v:"\u{1D42F}",w:"\u{1D430}",x:"\u{1D431}",y:"\u{1D432}",z:"\u{1D433}",\u0391:"\u{1D6A8}",\u0392:"\u{1D6A9}",\u0393:"\u{1D6AA}",\u0394:"\u{1D6AB}",\u0395:"\u{1D6AC}",\u0396:"\u{1D6AD}",\u0397:"\u{1D6AE}",\u0398:"\u{1D6AF}",\u0399:"\u{1D6B0}",\u039A:"\u{1D6B1}",\u039B:"\u{1D6B2}",\u039C:"\u{1D6B3}",\u039D:"\u{1D6B4}",\u039E:"\u{1D6B5}",\u039F:"\u{1D6B6}",\u03A0:"\u{1D6B7}",\u03A1:"\u{1D6B8}","\u03F4":"\u{1D6B9}",\u03A3:"\u{1D6BA}",\u03A4:"\u{1D6BB}",\u03A5:"\u{1D6BC}",\u03A6:"\u{1D6BD}",\u03A7:"\u{1D6BE}",\u03A8:"\u{1D6BF}",\u03A9:"\u{1D6C0}","\u2207":"\u{1D6C1}",\u03B1:"\u{1D6C2}",\u03B2:"\u{1D6C3}",\u03B3:"\u{1D6C4}",\u03B4:"\u{1D6C5}",\u03B5:"\u{1D6C6}",\u03B6:"\u{1D6C7}",\u03B7:"\u{1D6C8}",\u03B8:"\u{1D6C9}",\u03B9:"\u{1D6CA}",\u03BA:"\u{1D6CB}",\u03BB:"\u{1D6CC}",\u03BC:"\u{1D6CD}",\u03BD:"\u{1D6CE}",\u03BE:"\u{1D6CF}",\u03BF:"\u{1D6D0}",\u03C0:"\u{1D6D1}",\u03C1:"\u{1D6D2}",\u03C2:"\u{1D6D3}",\u03C3:"\u{1D6D4}",\u03C4:"\u{1D6D5}",\u03C5:"\u{1D6D6}",\u03C6:"\u{1D6D7}",\u03C7:"\u{1D6D8}",\u03C8:"\u{1D6D9}",\u03C9:"\u{1D6DA}","\u2202":"\u{1D6DB}","\u03F5":"\u{1D6DC}",\u03D1:"\u{1D6DD}",\u03F0:"\u{1D6DE}",\u03D5:"\u{1D6DF}",\u03F1:"\u{1D6E0}",\u03D6:"\u{1D6E1}","0":"\u{1D7CE}","1":"\u{1D7CF}","2":"\u{1D7D0}","3":"\u{1D7D1}","4":"\u{1D7D2}","5":"\u{1D7D3}","6":"\u{1D7D4}","7":"\u{1D7D5}","8":"\u{1D7D6}","9":"\u{1D7D7}"}});var xk=G((W3,z1)=>{z1.exports={A:"\u{1D4D0}",B:"\u{1D4D1}",C:"\u{1D4D2}",D:"\u{1D4D3}",E:"\u{1D4D4}",F:"\u{1D4D5}",G:"\u{1D4D6}",H:"\u{1D4D7}",I:"\u{1D4D8}",J:"\u{1D4D9}",K:"\u{1D4DA}",L:"\u{1D4DB}",M:"\u{1D4DC}",N:"\u{1D4DD}",O:"\u{1D4DE}",P:"\u{1D4DF}",Q:"\u{1D4E0}",R:"\u{1D4E1}",S:"\u{1D4E2}",T:"\u{1D4E3}",U:"\u{1D4E4}",V:"\u{1D4E5}",W:"\u{1D4E6}",X:"\u{1D4E7}",Y:"\u{1D4E8}",Z:"\u{1D4E9}",a:"\u{1D4EA}",b:"\u{1D4EB}",c:"\u{1D4EC}",d:"\u{1D4ED}",e:"\u{1D4EE}",f:"\u{1D4EF}",g:"\u{1D4F0}",h:"\u{1D4F1}",i:"\u{1D4F2}",j:"\u{1D4F3}",k:"\u{1D4F4}",l:"\u{1D4F5}",m:"\u{1D4F6}",n:"\u{1D4F7}",o:"\u{1D4F8}",p:"\u{1D4F9}",q:"\u{1D4FA}",r:"\u{1D4FB}",s:"\u{1D4FC}",t:"\u{1D4FD}",u:"\u{1D4FE}",v:"\u{1D4FF}",w:"\u{1D500}",x:"\u{1D501}",y:"\u{1D502}",z:"\u{1D503}"}});var Rk=G((G3,W1)=>{W1.exports={A:"\u{1D504}",B:"\u{1D505}",C:"\u212D",D:"\u{1D507}",E:"\u{1D508}",F:"\u{1D509}",G:"\u{1D50A}",H:"\u210C",I:"\u2111",J:"\u{1D50D}",K:"\u{1D50E}",L:"\u{1D50F}",M:"\u{1D510}",N:"\u{1D511}",O:"\u{1D512}",P:"\u{1D513}",Q:"\u{1D514}",R:"\u211C",S:"\u{1D516}",T:"\u{1D517}",U:"\u{1D518}",V:"\u{1D519}",W:"\u{1D51A}",X:"\u{1D51B}",Y:"\u{1D51C}",Z:"\u2128",a:"\u{1D51E}",b:"\u{1D51F}",c:"\u{1D520}",d:"\u{1D521}",e:"\u{1D522}",f:"\u{1D523}",g:"\u{1D524}",h:"\u{1D525}",i:"\u{1D526}",j:"\u{1D527}",k:"\u{1D528}",l:"\u{1D529}",m:"\u{1D52A}",n:"\u{1D52B}",o:"\u{1D52C}",p:"\u{1D52D}",q:"\u{1D52E}",r:"\u{1D52F}",s:"\u{1D530}",t:"\u{1D531}",u:"\u{1D532}",v:"\u{1D533}",w:"\u{1D534}",x:"\u{1D535}",y:"\u{1D536}",z:"\u{1D537}"}});var Dk=G((J3,G1)=>{G1.exports={A:"\u{1D434}",B:"\u{1D435}",C:"\u{1D436}",D:"\u{1D437}",E:"\u{1D438}",F:"\u{1D439}",G:"\u{1D43A}",H:"\u{1D43B}",I:"\u{1D43C}",J:"\u{1D43D}",K:"\u{1D43E}",L:"\u{1D43F}",M:"\u{1D440}",N:"\u{1D441}",O:"\u{1D442}",P:"\u{1D443}",Q:"\u{1D444}",R:"\u{1D445}",S:"\u{1D446}",T:"\u{1D447}",U:"\u{1D448}",V:"\u{1D449}",W:"\u{1D44A}",X:"\u{1D44B}",Y:"\u{1D44C}",Z:"\u{1D44D}",a:"\u{1D44E}",b:"\u{1D44F}",c:"\u{1D450}",d:"\u{1D451}",e:"\u{1D452}",f:"\u{1D453}",g:"\u{1D454}",h:"\u210E",i:"\u{1D456}",j:"\u{1D457}",k:"\u{1D458}",l:"\u{1D459}",m:"\u{1D45A}",n:"\u{1D45B}",o:"\u{1D45C}",p:"\u{1D45D}",q:"\u{1D45E}",r:"\u{1D45F}",s:"\u{1D460}",t:"\u{1D461}",u:"\u{1D462}",v:"\u{1D463}",w:"\u{1D464}",x:"\u{1D465}",y:"\u{1D466}",z:"\u{1D467}",\u0391:"\u{1D6E2}",\u0392:"\u{1D6E3}",\u0393:"\u{1D6E4}",\u0394:"\u{1D6E5}",\u0395:"\u{1D6E6}",\u0396:"\u{1D6E7}",\u0397:"\u{1D6E8}",\u0398:"\u{1D6E9}",\u0399:"\u{1D6EA}",\u039A:"\u{1D6EB}",\u039B:"\u{1D6EC}",\u039C:"\u{1D6ED}",\u039D:"\u{1D6EE}",\u039E:"\u{1D6EF}",\u039F:"\u{1D6F0}",\u03A0:"\u{1D6F1}",\u03A1:"\u{1D6F2}","\u03F4":"\u{1D6F3}",\u03A3:"\u{1D6F4}",\u03A4:"\u{1D6F5}",\u03A5:"\u{1D6F6}",\u03A6:"\u{1D6F7}",\u03A7:"\u{1D6F8}",\u03A8:"\u{1D6F9}",\u03A9:"\u{1D6FA}","\u2207":"\u{1D6FB}",\u03B1:"\u{1D6FC}",\u03B2:"\u{1D6FD}",\u03B3:"\u{1D6FE}",\u03B4:"\u{1D6FF}",\u03B5:"\u{1D700}",\u03B6:"\u{1D701}",\u03B7:"\u{1D702}",\u03B8:"\u{1D703}",\u03B9:"\u{1D704}",\u03BA:"\u{1D705}",\u03BB:"\u{1D706}",\u03BC:"\u{1D707}",\u03BD:"\u{1D708}",\u03BE:"\u{1D709}",\u03BF:"\u{1D70A}",\u03C0:"\u{1D70B}",\u03C1:"\u{1D70C}",\u03C2:"\u{1D70D}",\u03C3:"\u{1D70E}",\u03C4:"\u{1D70F}",\u03C5:"\u{1D710}",\u03C6:"\u{1D711}",\u03C7:"\u{1D712}",\u03C8:"\u{1D713}",\u03C9:"\u{1D714}","\u2202":"\u{1D715}","\u03F5":"\u{1D716}",\u03D1:"\u{1D717}",\u03F0:"\u{1D718}",\u03D5:"\u{1D719}",\u03F1:"\u{1D71A}",\u03D6:"\u{1D71B}"}});var Ok=G((K3,J1)=>{J1.exports={A:"\u{1D670}",B:"\u{1D671}",C:"\u{1D672}",D:"\u{1D673}",E:"\u{1D674}",F:"\u{1D675}",G:"\u{1D676}",H:"\u{1D677}",I:"\u{1D678}",J:"\u{1D679}",K:"\u{1D67A}",L:"\u{1D67B}",M:"\u{1D67C}",N:"\u{1D67D}",O:"\u{1D67E}",P:"\u{1D67F}",Q:"\u{1D680}",R:"\u{1D681}",S:"\u{1D682}",T:"\u{1D683}",U:"\u{1D684}",V:"\u{1D685}",W:"\u{1D686}",X:"\u{1D687}",Y:"\u{1D688}",Z:"\u{1D689}",a:"\u{1D68A}",b:"\u{1D68B}",c:"\u{1D68C}",d:"\u{1D68D}",e:"\u{1D68E}",f:"\u{1D68F}",g:"\u{1D690}",h:"\u{1D691}",i:"\u{1D692}",j:"\u{1D693}",k:"\u{1D694}",l:"\u{1D695}",m:"\u{1D696}",n:"\u{1D697}",o:"\u{1D698}",p:"\u{1D699}",q:"\u{1D69A}",r:"\u{1D69B}",s:"\u{1D69C}",t:"\u{1D69D}",u:"\u{1D69E}",v:"\u{1D69F}",w:"\u{1D6A0}",x:"\u{1D6A1}",y:"\u{1D6A2}",z:"\u{1D6A3}","0":"\u{1D7F6}","1":"\u{1D7F7}","2":"\u{1D7F8}","3":"\u{1D7F9}","4":"\u{1D7FA}","5":"\u{1D7FB}","6":"\u{1D7FC}","7":"\u{1D7FD}","8":"\u{1D7FE}","9":"\u{1D7FF}"}});var Nk=G((V3,Fk)=>{var K1=Sk(),V1=Ak(),Pk=Ek(),Y1=vk(),X1=Tk(),Q1=xk(),Z1=Rk(),eI=Dk(),tI=Ok(),Ik=function(t,e){return t[e]!==void 0?t[e]:e};function $r(t,e,n){t=t.replace(e,"^");var r="",o="normal",s,i;for(s=0;s<t.length;s++){if(i=t[s],o==="normal"&&i==="^"){o="modified";continue}else if(o==="modified"&&i==="{"){o="long";continue}else if(o==="modified"){r+=Ik(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=Ik(n,i)}return r}Fk.exports=function(t){return Object.keys(Pk).forEach(function(e){var n=Pk[e];t=t.replace(e,n)}),t=$r(t,"^",V1),t=$r(t,"_",K1),t=$r(t,"\\bb",Y1),t=$r(t,"\\bf",X1),t=$r(t,"\\it",eI),t=$r(t,"\\cal",Q1),t=$r(t,"\\frak",Z1),t=$r(t,"\\mono",tI),t}});var og=G((K8,fS)=>{"use strict";var Mu=Object.prototype.hasOwnProperty,dS=Object.prototype.toString,sS=Object.defineProperty,iS=Object.getOwnPropertyDescriptor,aS=function(e){return typeof Array.isArray=="function"?Array.isArray(e):dS.call(e)==="[object Array]"},cS=function(e){if(!e||dS.call(e)!=="[object Object]")return!1;var n=Mu.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Mu.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Mu.call(e,o)},uS=function(e,n){sS&&n.name==="__proto__"?sS(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},lS=function(e,n){if(n==="__proto__")if(Mu.call(e,n)){if(iS)return iS(e,n).value}else return;return e[n]};fS.exports=function t(){var e,n,r,o,s,i,a=arguments[0],u=1,d=arguments.length,f=!1;for(typeof a=="boolean"&&(f=a,a=arguments[1]||{},u=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});u<d;++u)if(e=arguments[u],e!=null)for(n in e)r=lS(a,n),o=lS(e,n),a!==o&&(f&&o&&(cS(o)||(s=aS(o)))?(s?(s=!1,i=r&&aS(r)?r:[]):i=r&&cS(r)?r:{},uS(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&uS(a,{name:n,newValue:o}));return a}});var pS=G((V8,PI)=>{PI.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var gS=G((Y8,hS)=>{"use strict";var II=pS();hS.exports={pkg:II}});var ag=G(qt=>{"use strict";var yS=qt&&qt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qt,"__esModule",{value:!0});qt.GaxiosError=qt.GAXIOS_ERROR_SYMBOL=void 0;qt.defaultErrorRedactor=_S;var mS=yS(og()),FI=yS(gS()),sg=FI.default.pkg;qt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${sg.name}-gaxios-error`);var ig=class t extends Error{config;response;code;status;error;[qt.GAXIOS_ERROR_SYMBOL]=sg.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&qt.GAXIOS_ERROR_SYMBOL in e&&e[qt.GAXIOS_ERROR_SYMBOL]===sg.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,mS.default)(!0,{},n),this.response&&(this.response.config=(0,mS.default)(!0,{},this.response.config)),this.response){try{this.response.data=NI(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let a of e.data.error.errors)typeof a=="object"&&"message"in a&&typeof a.message=="string"&&i.push(a.message);return Object.assign({message:i.join(`
66
- `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};qt.GaxiosError=ig;function NI(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function _S(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((i,a)=>{(/^authentication$/i.test(a)||/^authorization$/i.test(a)||/secret/i.test(a))&&s.set(a,e)})}function r(s,i){if(typeof s=="object"&&s!==null&&typeof s[i]=="string"){let a=s[i];(/grant_type=/i.test(a)||/assertion=/i.test(a)||/secret/i.test(a))&&(s[i]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((i,a)=>{(["grant_type","assertion"].includes(a)||/secret/.test(a))&&s.set(a,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(_S({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var CS=G(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});cg.getRetryConfig=MI;async function MI(t){let e=bS(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||BI)(t))return{shouldRetry:!1,config:t.config};let o=UI(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function BI(t){let e=bS(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function bS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function UI(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var lg=G(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.GaxiosInterceptorManager=void 0;var ug=class extends Set{};Bu.GaxiosInterceptorManager=ug});var kS=G((eW,wS)=>{var Cs=1e3,ws=Cs*60,ks=ws*60,Ao=ks*24,jI=Ao*7,LI=Ao*365.25;wS.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return $I(t);if(n==="number"&&isFinite(t))return e.long?HI(t):qI(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function $I(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\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(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*LI;case"weeks":case"week":case"w":return n*jI;case"days":case"day":case"d":return n*Ao;case"hours":case"hour":case"hrs":case"hr":case"h":return n*ks;case"minutes":case"minute":case"mins":case"min":case"m":return n*ws;case"seconds":case"second":case"secs":case"sec":case"s":return n*Cs;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function qI(t){var e=Math.abs(t);return e>=Ao?Math.round(t/Ao)+"d":e>=ks?Math.round(t/ks)+"h":e>=ws?Math.round(t/ws)+"m":e>=Cs?Math.round(t/Cs)+"s":t+"ms"}function HI(t){var e=Math.abs(t);return e>=Ao?Uu(t,e,Ao,"day"):e>=ks?Uu(t,e,ks,"hour"):e>=ws?Uu(t,e,ws,"minute"):e>=Cs?Uu(t,e,Cs,"second"):t+" ms"}function Uu(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var dg=G((tW,SS)=>{function zI(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=kS(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let h=0;h<f.length;h++)p=(p<<5)-p+f.charCodeAt(h),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,h=null,g,b;function m(...w){if(!m.enabled)return;let C=m,A=Number(new Date),k=A-(p||A);C.diff=k,C.prev=p,C.curr=A,p=A,w[0]=n.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let E=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";E++;let V=n.formatters[q];if(typeof V=="function"){let j=w[E];O=V.call(C,j),w.splice(E,1),E--}return O}),n.formatArgs.call(C,w),(C.log||n.log).apply(C,w)}return m.namespace=f,m.useColors=n.useColors(),m.color=n.selectColor(f),m.extend=r,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==n.namespaces&&(g=n.namespaces,b=n.enabled(f)),b),set:w=>{h=w}}),typeof n.init=="function"&&n.init(m),m}function r(f,p){let h=n(this.namespace+(typeof p>"u"?":":p)+f);return h.log=this.log,h}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of p)h[0]==="-"?n.skips.push(h.slice(1)):n.names.push(h)}function s(f,p){let h=0,g=0,b=-1,m=0;for(;h<f.length;)if(g<p.length&&(p[g]===f[h]||p[g]==="*"))p[g]==="*"?(b=g,m=h,g++):(h++,g++);else if(b!==-1)g=b+1,m++,h=m;else return!1;for(;g<p.length&&p[g]==="*";)g++;return g===p.length}function i(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function a(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function u(f){return f instanceof Error?f.stack||f.message:f}function d(){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 n.enable(n.load()),n}SS.exports=zI});var AS=G((Et,ju)=>{Et.formatArgs=GI;Et.save=JI;Et.load=KI;Et.useColors=WI;Et.storage=VI();Et.destroy=(()=>{let t=!1;return()=>{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`."))}})();Et.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 WI(){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 GI(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+ju.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}Et.log=console.debug||console.log||(()=>{});function JI(t){try{t?Et.storage.setItem("debug",t):Et.storage.removeItem("debug")}catch{}}function KI(){let t;try{t=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function VI(){try{return localStorage}catch{}}ju.exports=dg()(Et);var{formatters:YI}=ju.exports;YI.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var vS=G((nW,ES)=>{"use strict";ES.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var RS=G((rW,xS)=>{"use strict";var XI=re("os"),TS=re("tty"),Ht=vS(),{env:st}=process,Lu;Ht("no-color")||Ht("no-colors")||Ht("color=false")||Ht("color=never")?Lu=0:(Ht("color")||Ht("colors")||Ht("color=true")||Ht("color=always"))&&(Lu=1);function QI(){if("FORCE_COLOR"in st)return st.FORCE_COLOR==="true"?1:st.FORCE_COLOR==="false"?0:st.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(st.FORCE_COLOR,10),3)}function ZI(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function eF(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=QI();r!==void 0&&(Lu=r);let o=n?Lu:r;if(o===0)return 0;if(n){if(Ht("color=16m")||Ht("color=full")||Ht("color=truecolor"))return 3;if(Ht("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(st.TERM==="dumb")return s;if(process.platform==="win32"){let i=XI.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in st)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in st)||st.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in st)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(st.TEAMCITY_VERSION)?1:0;if(st.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in st){let i=Number.parseInt((st.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(st.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(st.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(st.TERM)||"COLORTERM"in st?1:s}function fg(t,e={}){let n=eF(t,{streamIsTTY:t&&t.isTTY,...e});return ZI(n)}xS.exports={supportsColor:fg,stdout:fg({isTTY:TS.isatty(1)}),stderr:fg({isTTY:TS.isatty(2)})}});var OS=G((it,qu)=>{var tF=re("tty"),$u=re("util");it.init=cF;it.log=sF;it.formatArgs=rF;it.save=iF;it.load=aF;it.useColors=nF;it.destroy=$u.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");it.colors=[6,2,3,4,5,1];try{let t=RS();t&&(t.stderr||t).level>=2&&(it.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{}it.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function nF(){return"colors"in it.inspectOpts?!!it.inspectOpts.colors:tF.isatty(process.stderr.fd)}function rF(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
65
+ `+w+"]"}return o.pop(),s=w,S}}});var oh=G((xH,GC)=>{var EO=HC(),vO=WC(),TO={parse:EO,stringify:vO};GC.exports=TO});var Sk=G((H3,L1)=>{L1.exports={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",i:"\u1D62",o:"\u2092",r:"\u1D63",u:"\u1D64",v:"\u1D65",x:"\u2093",\u03B2:"\u1D66",\u03B3:"\u1D67",\u03C1:"\u1D68",\u03C6:"\u1D69",\u03C7:"\u1D6A"}});var Ak=G((z3,$1)=>{$1.exports={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",\u03B1:"\u1D45",\u03B2:"\u1D5D",\u03B3:"\u1D5E",\u03B4:"\u1D5F","\u220A":"\u1D4B",\u03B8:"\u1DBF",\u03B9:"\u1DA5",\u03A6:"\u1DB2",\u03C6:"\u1D60",\u03C7:"\u1D61"}});var Ek=G((W3,q1)=>{q1.exports={"\\texttrademark":"\u2122","\\trademark":"\u2122","\\textregistered":"\xAE","\\registered":"\xAE","\\copyright":"\xA9","\\pilcrow":"\xB6","\\pound":"\xA3","\\euro":"\u20AC","\\cents":"\xA2","\\section":"\xA7","\\space":"\u2423","\\degree":"\xB0","\\zeta":"\u03B6","\\Xi":"\u039E","\\xi":"\u03BE","\\wr":"\u2240","\\wp":"\u2118","\\wedge":"\u2227","\\Vvdash":"\u22AA","\\veebar":"\u22BB","\\vee":"\u2228","\\vdots":"\u22EE","\\Vdash":"\u22A9","\\vDash":"\u22A8","\\vdash":"\u22A2","\\vartriangleright":"\u22B3","\\vartriangleleft":"\u22B2","\\vartriangle":"\u25B3","\\vartheta":"\u03D1","\\varsigma":"\u03C2","\\varrho":"\u03F1","\\varpropto":"\u221D","\\varpi":"\u03D6","\\varphi":"\u03C6","\\varnothing":"\u2205","\\varkappa":"\u03F0","\\varepsilon":"\u03B5","\\upuparrows":"\u21C8","\\Upsilon":"\u03A5","\\upsilon":"\u03C5","\\uplus":"\u228E","\\upharpoonright":"\u21BE","\\upharpoonleft":"\u21BF","\\Updownarrow":"\u21D5","\\updownarrow":"\u2195","\\Uparrow":"\u21D1","\\uparrow":"\u2191","\\unrhd":"\u22B5","\\unlhd":"\u22B4","\\twoheadrightarrow":"\u21A0","\\twoheadleftarrow":"\u219E","\\trianglerighteq":"\u22B5","\\triangleright":"\u25B7","\\triangleq":"\u225C","\\trianglelefteq":"\u22B4","\\triangleleft":"\u25C1","\\triangledown":"\u25BD","\\triangle":"\u25B3","\\top":"\u22A4","\\times":"\xD7","\\thicksim":"\u223C","\\thickapprox":"\u2248","\\Theta":"\u0398","\\theta":"\u03B8","\\therefore":"\u2234","\\tau":"\u03C4","\\swarrow":"\u2199","\\surd":"\u221A","\\supseteq":"\u2287","\\Supset":"\u22D1","\\supset":"\u2283","\\sum":"\u2211","\\succsim":"\u227F","\\succeq":"\u227D","\\succcurlyeq":"\u227D","\\succ":"\u227B","\\subseteq":"\u2286","\\Subset":"\u22D0","\\subset":"\u2282","\\star":"\u22C6","\\square":"\u25A1","\\sqsupseteq":"\u2292","\\sqsupset":"\u2290","\\sqsubseteq":"\u2291","\\sqsubset":"\u228F","\\sqcup":"\u2294","\\sqcap":"\u2293","\\sphericalangle":"\u2222","\\spadesuit":"\u2660","\\smile":"\u2323","\\smallsmile":"\u2323","\\smallsetminus":"\u2216","\\smallfrown":"\u2322","\\simeq":"\u2243","\\sim":"\u223C","\\sigma":"\u03C3","\\shortparallel":"\u2225","\\sharp":"\u266F","\\setminus":"\u2216","\\searrow":"\u2198","\\rtimes":"\u22C8","\\Rsh":"\u21B1","\\Rrightarrow":"\u21DB","\\risingdotseq":"\u2253","\\rightthreetimes":"\u22CC","\\rightsquigarrow":"\u21DD","\\rightrightarrows":"\u21C9","\\rightleftharpoons":"\u21CC","\\rightleftarrows":"\u21C4","\\rightharpoonup":"\u21C0","\\rightharpoondown":"\u21C1","\\rightarrowtail":"\u21A3","\\Rightarrow":"\u21D2","\\rightarrow":"\u2192","\\rho":"\u03C1","\\rhd":"\u22B3","\\rfloor":"\u230B","\\Re":"\u211C","\\rceil":"\u2309","\\Psi":"\u03A8","\\psi":"\u03C8","\\propto":"\u221D","\\prod":"\u220F","\\prime":"\u2032","\\precsim":"\u227E","\\preceq":"\u227C","\\preccurlyeq":"\u227C","\\prec":"\u227A","\\pm":"\xB1","\\Pi":"\u03A0","\\pi":"\u03C0","\\pitchfork":"\u22D4","\\Phi":"\u03A6","\\phi":"\u03D5","\\perp":"\u22A5","\\partial":"\u2202","\\parallel":"\u2225","\\otimes":"\u2297","\\oslash":"\u2298","\\oplus":"\u2295","\\ominus":"\u2296","\\Omega":"\u03A9","\\omega":"\u03C9","\\oint":"\u222E","\\odot":"\u2299","\\nwarrow":"\u2196","\\nu":"\u03BD","\\notin":"\u2209","\\ni":"\u220B","\\nexists":"\u2204","\\neq":"\u2260","\\neg":"\xAC","\\nearrow":"\u2197","\\natural":"\u266E","\\nabla":"\u2207","\\mu":"\u03BC","\\multimap":"\u22B8","\\mp":"\u2213","\\models":"\u22A8","\\mid":"\u2223","\\mho":"\u2127","\\measuredangle":"\u2221","\\mapsto":"\u21A6","\\ltimes":"\u22C9","\\Lsh":"\u21B0","\\lozenge":"\u25CA","\\looparrowright":"\u21AC","\\looparrowleft":"\u21AB","\\Longrightarrow":"\u21D2","\\longrightarrow":"\u2192","\\longmapsto":"\u21D6","\\Longleftrightarrow":"\u21D4","\\longleftrightarrow":"\u2194","\\Longleftarrow":"\u21D0","\\longleftarrow":"\u2190","\\lll":"\u22D8","\\Lleftarrow":"\u21DA","\\ll":"\u226A","\\lhd":"\u22B2","\\lfloor":"\u230A","\\lesssim":"\u2272","\\lessgtr":"\u2276","\\lesseqgtr":"\u22DA","\\lessdot":"\u22D6","\\leqslant":"\u2264","\\leqq":"\u2266","\\leq":"\u2264","\\leftthreetimes":"\u22CB","\\leftrightsquigarrow":"\u21AD","\\leftrightharpoons":"\u21CB","\\leftrightarrows":"\u21C6","\\Leftrightarrow":"\u21D4","\\leftrightarrow":"\u2194","\\leftleftarrows":"\u21C7","\\leftharpoonup":"\u21BC","\\leftharpoondown":"\u21BD","\\leftarrowtail":"\u21A2","\\Leftarrow":"\u21D0","\\leftarrow":"\u2190","\\leadsto":"\u219D","\\le":"\u2264","\\lceil":"\u2308","\\Lambda":"\u039B","\\lambda":"\u03BB","\\kappa":"\u03BA","\\Join":"\u22C8","\\iota":"\u03B9","\\intercal":"\u22BA","\\int":"\u222B","\\infty":"\u221E","\\in":"\u2208","\\implies":"\u21D2","\\Im":"\u2111","\\hslash":"\u210F","\\hookrightarrow":"\u21AA","\\hookleftarrow":"\u21A9","\\heartsuit":"\u2661","\\hbar":"\u210F","\\gtrsim":"\u2273","\\gtrless":"\u2277","\\gtreqless":"\u22DB","\\gtrdot":"\u22D7","\\gimel":"\u05D2","\\ggg":"\u22D9","\\gg":"\u226B","\\geqq":"\u2267","\\geq":"\u2265","\\ge":"\u2265","\\Gamma":"\u0393","\\gamma":"\u03B3","\\frown":"\u2322","\\forall":"\u2200","\\flat":"\u266D","\\Finv":"\u2132","\\fallingdotseq":"\u2252","\\exists":"\u2203","\\eth":"\xF0","\\eta":"\u03B7","\\equiv":"\u2261","\\eqcirc":"\u2256","\\epsilon":"\u220A","\\emptyset":"\u2205","\\ell":"\u2113","\\downharpoonright":"\u21C2","\\downharpoonleft":"\u21C3","\\downdownarrows":"\u21CA","\\Downarrow":"\u21D3","\\downarrow":"\u2193","\\dots":"\u2026","\\dotplus":"\u2214","\\doteqdot":"\u2251","\\doteq":"\u2250","\\divideontimes":"\u22C7","\\div":"\xF7","\\digamma":"\u03DC","\\diamondsuit":"\u2662","\\Diamond":"\u25C7","\\diamond":"\u22C4","\\Delta":"\u0394","\\delta":"\u03B4","\\ddots":"\u22F1","\\ddagger":"\u2021","\\dashv":"\u22A3","\\dashrightarrow":"\u21E2","\\dashleftarrow":"\u21E0","\\daleth":"\u05D3","\\dagger":"\u2020","\\curvearrowright":"\u21B7","\\curvearrowleft":"\u21B6","\\curlywedge":"\u22CF","\\curlyvee":"\u22CE","\\curlyeqsucc":"\u22DF","\\curlyeqprec":"\u22DE","\\Cup":"\u22D3","\\cup":"\u222A","\\coprod":"\u2210","\\cong":"\u2245","\\complement":"\u2201","\\clubsuit":"\u2663","\\circledS":"\u24C8","\\circleddash":"\u229D","\\circledcirc":"\u229A","\\circledast":"\u229B","\\circlearrowright":"\u21BB","\\circlearrowleft":"\u21BA","\\circeq":"\u2257","\\circ":"\u2218","\\chi":"\u03C7","\\centerdot":"\u22C5","\\cdots":"\u22EF","\\cdot":"\u22C5","\\Cap":"\u22D2","\\cap":"\u2229","\\Bumpeq":"\u224E","\\bumpeq":"\u224F","\\bullet":"\u2219","\\boxtimes":"\u22A0","\\boxplus":"\u229E","\\boxminus":"\u229F","\\boxdot":"\u22A1","\\Box":"\u25A1","\\bowtie":"\u22C8","\\bot":"\u22A5","\\blacktriangleright":"\u25B7","\\blacktriangleleft":"\u25C0","\\blacktriangledown":"\u25BC","\\blacktriangle":"\u25B2","\\blacksquare":"\u25A0","\\blacklozenge":"\u25C6","\\bigwedge":"\u22C0","\\bigvee":"\u22C1","\\biguplus":"\u228E","\\bigtriangleup":"\u25B3","\\bigtriangledown":"\u25BD","\\bigstar":"\u2605","\\bigsqcup":"\u2294","\\bigotimes":"\u2297","\\bigoplus":"\u2295","\\bigodot":"\u2299","\\bigcup":"\u22C3","\\bigcirc":"\u25CB","\\bigcap":"\u22C2","\\between":"\u226C","\\beth":"\u05D1","\\beta":"\u03B2","\\because":"\u2235","\\barwedge":"\u22BC","\\backsim":"\u223D","\\backprime":"\u2035","\\backepsilon":"\u220D","\\asymp":"\u224D","\\ast":"\u2217","\\approxeq":"\u224A","\\approx":"\u2248","\\angle":"\u2220","\\alpha":"\u03B1","\\aleph":"\u05D0"}});var vk=G((G3,H1)=>{H1.exports={A:"\u{1D538}",B:"\u{1D539}",C:"\u2102",D:"\u{1D53B}",E:"\u{1D53C}",F:"\u{1D53D}",G:"\u{1D53E}",H:"\u210D",I:"\u{1D540}",J:"\u{1D541}",K:"\u{1D542}",L:"\u{1D543}",M:"\u{1D544}",N:"\u2115",O:"\u{1D546}",P:"\u2119",Q:"\u211A",R:"\u211D",S:"\u{1D54A}",T:"\u{1D54B}",U:"\u{1D54C}",V:"\u{1D54D}",W:"\u{1D54E}",X:"\u{1D54F}",Y:"\u{1D550}",Z:"\u2124",a:"\u{1D552}",b:"\u{1D553}",c:"\u{1D554}",d:"\u{1D555}",e:"\u{1D556}",f:"\u{1D557}",g:"\u{1D558}",h:"\u{1D559}",i:"\u{1D55A}",j:"\u{1D55B}",k:"\u{1D55C}",l:"\u{1D55D}",m:"\u{1D55E}",n:"\u{1D55F}",o:"\u{1D560}",p:"\u{1D561}",q:"\u{1D562}",r:"\u{1D563}",s:"\u{1D564}",t:"\u{1D565}",u:"\u{1D566}",v:"\u{1D567}",w:"\u{1D568}",x:"\u{1D569}",y:"\u{1D56A}",z:"\u{1D56B}","0":"\u{1D7D8}","1":"\u{1D7D9}","2":"\u{1D7DA}","3":"\u{1D7DB}","4":"\u{1D7DC}","5":"\u{1D7DD}","6":"\u{1D7DE}","7":"\u{1D7DF}","8":"\u{1D7E0}","9":"\u{1D7E1}"}});var Tk=G((J3,z1)=>{z1.exports={A:"\u{1D400}",B:"\u{1D401}",C:"\u{1D402}",D:"\u{1D403}",E:"\u{1D404}",F:"\u{1D405}",G:"\u{1D406}",H:"\u{1D407}",I:"\u{1D408}",J:"\u{1D409}",K:"\u{1D40A}",L:"\u{1D40B}",M:"\u{1D40C}",N:"\u{1D40D}",O:"\u{1D40E}",P:"\u{1D40F}",Q:"\u{1D410}",R:"\u{1D411}",S:"\u{1D412}",T:"\u{1D413}",U:"\u{1D414}",V:"\u{1D415}",W:"\u{1D416}",X:"\u{1D417}",Y:"\u{1D418}",Z:"\u{1D419}",a:"\u{1D41A}",b:"\u{1D41B}",c:"\u{1D41C}",d:"\u{1D41D}",e:"\u{1D41E}",f:"\u{1D41F}",g:"\u{1D420}",h:"\u{1D421}",i:"\u{1D422}",j:"\u{1D423}",k:"\u{1D424}",l:"\u{1D425}",m:"\u{1D426}",n:"\u{1D427}",o:"\u{1D428}",p:"\u{1D429}",q:"\u{1D42A}",r:"\u{1D42B}",s:"\u{1D42C}",t:"\u{1D42D}",u:"\u{1D42E}",v:"\u{1D42F}",w:"\u{1D430}",x:"\u{1D431}",y:"\u{1D432}",z:"\u{1D433}",\u0391:"\u{1D6A8}",\u0392:"\u{1D6A9}",\u0393:"\u{1D6AA}",\u0394:"\u{1D6AB}",\u0395:"\u{1D6AC}",\u0396:"\u{1D6AD}",\u0397:"\u{1D6AE}",\u0398:"\u{1D6AF}",\u0399:"\u{1D6B0}",\u039A:"\u{1D6B1}",\u039B:"\u{1D6B2}",\u039C:"\u{1D6B3}",\u039D:"\u{1D6B4}",\u039E:"\u{1D6B5}",\u039F:"\u{1D6B6}",\u03A0:"\u{1D6B7}",\u03A1:"\u{1D6B8}","\u03F4":"\u{1D6B9}",\u03A3:"\u{1D6BA}",\u03A4:"\u{1D6BB}",\u03A5:"\u{1D6BC}",\u03A6:"\u{1D6BD}",\u03A7:"\u{1D6BE}",\u03A8:"\u{1D6BF}",\u03A9:"\u{1D6C0}","\u2207":"\u{1D6C1}",\u03B1:"\u{1D6C2}",\u03B2:"\u{1D6C3}",\u03B3:"\u{1D6C4}",\u03B4:"\u{1D6C5}",\u03B5:"\u{1D6C6}",\u03B6:"\u{1D6C7}",\u03B7:"\u{1D6C8}",\u03B8:"\u{1D6C9}",\u03B9:"\u{1D6CA}",\u03BA:"\u{1D6CB}",\u03BB:"\u{1D6CC}",\u03BC:"\u{1D6CD}",\u03BD:"\u{1D6CE}",\u03BE:"\u{1D6CF}",\u03BF:"\u{1D6D0}",\u03C0:"\u{1D6D1}",\u03C1:"\u{1D6D2}",\u03C2:"\u{1D6D3}",\u03C3:"\u{1D6D4}",\u03C4:"\u{1D6D5}",\u03C5:"\u{1D6D6}",\u03C6:"\u{1D6D7}",\u03C7:"\u{1D6D8}",\u03C8:"\u{1D6D9}",\u03C9:"\u{1D6DA}","\u2202":"\u{1D6DB}","\u03F5":"\u{1D6DC}",\u03D1:"\u{1D6DD}",\u03F0:"\u{1D6DE}",\u03D5:"\u{1D6DF}",\u03F1:"\u{1D6E0}",\u03D6:"\u{1D6E1}","0":"\u{1D7CE}","1":"\u{1D7CF}","2":"\u{1D7D0}","3":"\u{1D7D1}","4":"\u{1D7D2}","5":"\u{1D7D3}","6":"\u{1D7D4}","7":"\u{1D7D5}","8":"\u{1D7D6}","9":"\u{1D7D7}"}});var xk=G((K3,W1)=>{W1.exports={A:"\u{1D4D0}",B:"\u{1D4D1}",C:"\u{1D4D2}",D:"\u{1D4D3}",E:"\u{1D4D4}",F:"\u{1D4D5}",G:"\u{1D4D6}",H:"\u{1D4D7}",I:"\u{1D4D8}",J:"\u{1D4D9}",K:"\u{1D4DA}",L:"\u{1D4DB}",M:"\u{1D4DC}",N:"\u{1D4DD}",O:"\u{1D4DE}",P:"\u{1D4DF}",Q:"\u{1D4E0}",R:"\u{1D4E1}",S:"\u{1D4E2}",T:"\u{1D4E3}",U:"\u{1D4E4}",V:"\u{1D4E5}",W:"\u{1D4E6}",X:"\u{1D4E7}",Y:"\u{1D4E8}",Z:"\u{1D4E9}",a:"\u{1D4EA}",b:"\u{1D4EB}",c:"\u{1D4EC}",d:"\u{1D4ED}",e:"\u{1D4EE}",f:"\u{1D4EF}",g:"\u{1D4F0}",h:"\u{1D4F1}",i:"\u{1D4F2}",j:"\u{1D4F3}",k:"\u{1D4F4}",l:"\u{1D4F5}",m:"\u{1D4F6}",n:"\u{1D4F7}",o:"\u{1D4F8}",p:"\u{1D4F9}",q:"\u{1D4FA}",r:"\u{1D4FB}",s:"\u{1D4FC}",t:"\u{1D4FD}",u:"\u{1D4FE}",v:"\u{1D4FF}",w:"\u{1D500}",x:"\u{1D501}",y:"\u{1D502}",z:"\u{1D503}"}});var Rk=G((V3,G1)=>{G1.exports={A:"\u{1D504}",B:"\u{1D505}",C:"\u212D",D:"\u{1D507}",E:"\u{1D508}",F:"\u{1D509}",G:"\u{1D50A}",H:"\u210C",I:"\u2111",J:"\u{1D50D}",K:"\u{1D50E}",L:"\u{1D50F}",M:"\u{1D510}",N:"\u{1D511}",O:"\u{1D512}",P:"\u{1D513}",Q:"\u{1D514}",R:"\u211C",S:"\u{1D516}",T:"\u{1D517}",U:"\u{1D518}",V:"\u{1D519}",W:"\u{1D51A}",X:"\u{1D51B}",Y:"\u{1D51C}",Z:"\u2128",a:"\u{1D51E}",b:"\u{1D51F}",c:"\u{1D520}",d:"\u{1D521}",e:"\u{1D522}",f:"\u{1D523}",g:"\u{1D524}",h:"\u{1D525}",i:"\u{1D526}",j:"\u{1D527}",k:"\u{1D528}",l:"\u{1D529}",m:"\u{1D52A}",n:"\u{1D52B}",o:"\u{1D52C}",p:"\u{1D52D}",q:"\u{1D52E}",r:"\u{1D52F}",s:"\u{1D530}",t:"\u{1D531}",u:"\u{1D532}",v:"\u{1D533}",w:"\u{1D534}",x:"\u{1D535}",y:"\u{1D536}",z:"\u{1D537}"}});var Dk=G((Y3,J1)=>{J1.exports={A:"\u{1D434}",B:"\u{1D435}",C:"\u{1D436}",D:"\u{1D437}",E:"\u{1D438}",F:"\u{1D439}",G:"\u{1D43A}",H:"\u{1D43B}",I:"\u{1D43C}",J:"\u{1D43D}",K:"\u{1D43E}",L:"\u{1D43F}",M:"\u{1D440}",N:"\u{1D441}",O:"\u{1D442}",P:"\u{1D443}",Q:"\u{1D444}",R:"\u{1D445}",S:"\u{1D446}",T:"\u{1D447}",U:"\u{1D448}",V:"\u{1D449}",W:"\u{1D44A}",X:"\u{1D44B}",Y:"\u{1D44C}",Z:"\u{1D44D}",a:"\u{1D44E}",b:"\u{1D44F}",c:"\u{1D450}",d:"\u{1D451}",e:"\u{1D452}",f:"\u{1D453}",g:"\u{1D454}",h:"\u210E",i:"\u{1D456}",j:"\u{1D457}",k:"\u{1D458}",l:"\u{1D459}",m:"\u{1D45A}",n:"\u{1D45B}",o:"\u{1D45C}",p:"\u{1D45D}",q:"\u{1D45E}",r:"\u{1D45F}",s:"\u{1D460}",t:"\u{1D461}",u:"\u{1D462}",v:"\u{1D463}",w:"\u{1D464}",x:"\u{1D465}",y:"\u{1D466}",z:"\u{1D467}",\u0391:"\u{1D6E2}",\u0392:"\u{1D6E3}",\u0393:"\u{1D6E4}",\u0394:"\u{1D6E5}",\u0395:"\u{1D6E6}",\u0396:"\u{1D6E7}",\u0397:"\u{1D6E8}",\u0398:"\u{1D6E9}",\u0399:"\u{1D6EA}",\u039A:"\u{1D6EB}",\u039B:"\u{1D6EC}",\u039C:"\u{1D6ED}",\u039D:"\u{1D6EE}",\u039E:"\u{1D6EF}",\u039F:"\u{1D6F0}",\u03A0:"\u{1D6F1}",\u03A1:"\u{1D6F2}","\u03F4":"\u{1D6F3}",\u03A3:"\u{1D6F4}",\u03A4:"\u{1D6F5}",\u03A5:"\u{1D6F6}",\u03A6:"\u{1D6F7}",\u03A7:"\u{1D6F8}",\u03A8:"\u{1D6F9}",\u03A9:"\u{1D6FA}","\u2207":"\u{1D6FB}",\u03B1:"\u{1D6FC}",\u03B2:"\u{1D6FD}",\u03B3:"\u{1D6FE}",\u03B4:"\u{1D6FF}",\u03B5:"\u{1D700}",\u03B6:"\u{1D701}",\u03B7:"\u{1D702}",\u03B8:"\u{1D703}",\u03B9:"\u{1D704}",\u03BA:"\u{1D705}",\u03BB:"\u{1D706}",\u03BC:"\u{1D707}",\u03BD:"\u{1D708}",\u03BE:"\u{1D709}",\u03BF:"\u{1D70A}",\u03C0:"\u{1D70B}",\u03C1:"\u{1D70C}",\u03C2:"\u{1D70D}",\u03C3:"\u{1D70E}",\u03C4:"\u{1D70F}",\u03C5:"\u{1D710}",\u03C6:"\u{1D711}",\u03C7:"\u{1D712}",\u03C8:"\u{1D713}",\u03C9:"\u{1D714}","\u2202":"\u{1D715}","\u03F5":"\u{1D716}",\u03D1:"\u{1D717}",\u03F0:"\u{1D718}",\u03D5:"\u{1D719}",\u03F1:"\u{1D71A}",\u03D6:"\u{1D71B}"}});var Ok=G((X3,K1)=>{K1.exports={A:"\u{1D670}",B:"\u{1D671}",C:"\u{1D672}",D:"\u{1D673}",E:"\u{1D674}",F:"\u{1D675}",G:"\u{1D676}",H:"\u{1D677}",I:"\u{1D678}",J:"\u{1D679}",K:"\u{1D67A}",L:"\u{1D67B}",M:"\u{1D67C}",N:"\u{1D67D}",O:"\u{1D67E}",P:"\u{1D67F}",Q:"\u{1D680}",R:"\u{1D681}",S:"\u{1D682}",T:"\u{1D683}",U:"\u{1D684}",V:"\u{1D685}",W:"\u{1D686}",X:"\u{1D687}",Y:"\u{1D688}",Z:"\u{1D689}",a:"\u{1D68A}",b:"\u{1D68B}",c:"\u{1D68C}",d:"\u{1D68D}",e:"\u{1D68E}",f:"\u{1D68F}",g:"\u{1D690}",h:"\u{1D691}",i:"\u{1D692}",j:"\u{1D693}",k:"\u{1D694}",l:"\u{1D695}",m:"\u{1D696}",n:"\u{1D697}",o:"\u{1D698}",p:"\u{1D699}",q:"\u{1D69A}",r:"\u{1D69B}",s:"\u{1D69C}",t:"\u{1D69D}",u:"\u{1D69E}",v:"\u{1D69F}",w:"\u{1D6A0}",x:"\u{1D6A1}",y:"\u{1D6A2}",z:"\u{1D6A3}","0":"\u{1D7F6}","1":"\u{1D7F7}","2":"\u{1D7F8}","3":"\u{1D7F9}","4":"\u{1D7FA}","5":"\u{1D7FB}","6":"\u{1D7FC}","7":"\u{1D7FD}","8":"\u{1D7FE}","9":"\u{1D7FF}"}});var Nk=G((Q3,Fk)=>{var V1=Sk(),Y1=Ak(),Pk=Ek(),X1=vk(),Q1=Tk(),Z1=xk(),eI=Rk(),tI=Dk(),nI=Ok(),Ik=function(t,e){return t[e]!==void 0?t[e]:e};function $r(t,e,n){t=t.replace(e,"^");var r="",o="normal",s,i;for(s=0;s<t.length;s++){if(i=t[s],o==="normal"&&i==="^"){o="modified";continue}else if(o==="modified"&&i==="{"){o="long";continue}else if(o==="modified"){r+=Ik(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=Ik(n,i)}return r}Fk.exports=function(t){return Object.keys(Pk).forEach(function(e){var n=Pk[e];t=t.replace(e,n)}),t=$r(t,"^",Y1),t=$r(t,"_",V1),t=$r(t,"\\bb",X1),t=$r(t,"\\bf",Q1),t=$r(t,"\\it",tI),t=$r(t,"\\cal",Z1),t=$r(t,"\\frak",eI),t=$r(t,"\\mono",nI),t}});var rg=G((X8,fS)=>{"use strict";var Mu=Object.prototype.hasOwnProperty,dS=Object.prototype.toString,sS=Object.defineProperty,iS=Object.getOwnPropertyDescriptor,aS=function(e){return typeof Array.isArray=="function"?Array.isArray(e):dS.call(e)==="[object Array]"},cS=function(e){if(!e||dS.call(e)!=="[object Object]")return!1;var n=Mu.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Mu.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Mu.call(e,o)},uS=function(e,n){sS&&n.name==="__proto__"?sS(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},lS=function(e,n){if(n==="__proto__")if(Mu.call(e,n)){if(iS)return iS(e,n).value}else return;return e[n]};fS.exports=function t(){var e,n,r,o,s,i,a=arguments[0],u=1,d=arguments.length,f=!1;for(typeof a=="boolean"&&(f=a,a=arguments[1]||{},u=2),(a==null||typeof a!="object"&&typeof a!="function")&&(a={});u<d;++u)if(e=arguments[u],e!=null)for(n in e)r=lS(a,n),o=lS(e,n),a!==o&&(f&&o&&(cS(o)||(s=aS(o)))?(s?(s=!1,i=r&&aS(r)?r:[]):i=r&&cS(r)?r:{},uS(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&uS(a,{name:n,newValue:o}));return a}});var pS=G((Q8,II)=>{II.exports={name:"gaxios",version:"7.3.1",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:{type:"git",directory:"core/packages/gaxios",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","@types/tmp":"^0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.1.3",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^5.0.0","jsdoc-region-tag":"^4.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"14.0.5","null-loader":"^4.0.1","pack-n-play":"^4.0.0",puppeteer:"^24.0.0",sinon:"21.0.3","stream-browserify":"^3.0.0",tmp:"0.2.7","ts-loader":"^9.5.2",typescript:"5.8.3","undici-types":"^7.24.1",webpack:"^5.97.1","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"},homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/gaxios"}});var gS=G((Z8,hS)=>{"use strict";var FI=pS();hS.exports={pkg:FI}});var ig=G(qt=>{"use strict";var yS=qt&&qt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qt,"__esModule",{value:!0});qt.GaxiosError=qt.GAXIOS_ERROR_SYMBOL=void 0;qt.defaultErrorRedactor=_S;var mS=yS(rg()),NI=yS(gS()),og=NI.default.pkg;qt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${og.name}-gaxios-error`);var sg=class t extends Error{config;response;code;status;error;[qt.GAXIOS_ERROR_SYMBOL]=og.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&qt.GAXIOS_ERROR_SYMBOL in e&&e[qt.GAXIOS_ERROR_SYMBOL]===og.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,mS.default)(!0,{},n),this.response&&(this.response.config=(0,mS.default)(!0,{},this.response.config)),this.response){try{this.response.data=MI(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let a of e.data.error.errors)typeof a=="object"&&"message"in a&&typeof a.message=="string"&&i.push(a.message);return Object.assign({message:i.join(`
66
+ `)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};qt.GaxiosError=sg;function MI(t,e){switch(t){case"stream":return e;case"json":return JSON.parse(JSON.stringify(e));case"arraybuffer":return JSON.parse(Buffer.from(e).toString("utf8"));case"blob":return JSON.parse(e.text());default:return e}}function _S(t){let e="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";function n(s){s&&s.forEach((i,a)=>{(/^authentication$/i.test(a)||/^authorization$/i.test(a)||/secret/i.test(a))&&s.set(a,e)})}function r(s,i){if(typeof s=="object"&&s!==null&&typeof s[i]=="string"){let a=s[i];(/grant_type=/i.test(a)||/assertion=/i.test(a)||/secret/i.test(a))&&(s[i]=e)}}function o(s){!s||typeof s!="object"||(s instanceof FormData||s instanceof URLSearchParams||"forEach"in s&&"set"in s?s.forEach((i,a)=>{(["grant_type","assertion"].includes(a)||/secret/.test(a))&&s.set(a,e)}):("grant_type"in s&&(s.grant_type=e),"assertion"in s&&(s.assertion=e),"client_secret"in s&&(s.client_secret=e)))}return t.config&&(n(t.config.headers),r(t.config,"data"),o(t.config.data),r(t.config,"body"),o(t.config.body),t.config.url.searchParams.has("token")&&t.config.url.searchParams.set("token",e),t.config.url.searchParams.has("client_secret")&&t.config.url.searchParams.set("client_secret",e)),t.response&&(_S({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var CS=G(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.getRetryConfig=BI;async function BI(t){let e=bS(t);if(!t||!t.config||!e&&!t.config.retry)return{shouldRetry:!1};e=e||{},e.currentRetryAttempt=e.currentRetryAttempt||0,e.retry=e.retry===void 0||e.retry===null?3:e.retry,e.httpMethodsToRetry=e.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],e.noResponseRetries=e.noResponseRetries===void 0||e.noResponseRetries===null?2:e.noResponseRetries,e.retryDelayMultiplier=e.retryDelayMultiplier?e.retryDelayMultiplier:2,e.timeOfFirstRequest=e.timeOfFirstRequest?e.timeOfFirstRequest:Date.now(),e.totalTimeout=e.totalTimeout?e.totalTimeout:Number.MAX_SAFE_INTEGER,e.maxRetryDelay=e.maxRetryDelay?e.maxRetryDelay:Number.MAX_SAFE_INTEGER;let n=[[100,199],[408,408],[429,429],[500,599]];if(e.statusCodesToRetry=e.statusCodesToRetry||n,t.config.retryConfig=e,!await(e.shouldRetry||jI)(t))return{shouldRetry:!1,config:t.config};let o=UI(e);t.config.retryConfig.currentRetryAttempt+=1;let s=e.retryBackoff?e.retryBackoff(t,o):new Promise(i=>{setTimeout(i,o)});return e.onRetryAttempt&&await e.onRetryAttempt(t),await s,{shouldRetry:!0,config:t.config}}function jI(t){let e=bS(t);if(t.config.signal?.aborted&&t.code!=="TimeoutError"||t.code==="AbortError"||!e||e.retry===0||!t.response&&(e.currentRetryAttempt||0)>=e.noResponseRetries||!e.httpMethodsToRetry||!e.httpMethodsToRetry.includes(t.config.method?.toUpperCase()||"GET"))return!1;if(t.response&&t.response.status){let n=!1;for(let[r,o]of e.statusCodesToRetry){let s=t.response.status;if(s>=r&&s<=o){n=!0;break}}if(!n)return!1}return e.currentRetryAttempt=e.currentRetryAttempt||0,!(e.currentRetryAttempt>=e.retry)}function bS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function UI(t){let n=(t.currentRetryAttempt?0:t.retryDelay??100)+(Math.pow(t.retryDelayMultiplier,t.currentRetryAttempt)-1)/2*1e3,r=t.totalTimeout-(Date.now()-t.timeOfFirstRequest);return Math.min(n,r,t.maxRetryDelay)}});var ug=G(Bu=>{"use strict";Object.defineProperty(Bu,"__esModule",{value:!0});Bu.GaxiosInterceptorManager=void 0;var cg=class extends Set{};Bu.GaxiosInterceptorManager=cg});var kS=G((rW,wS)=>{var Cs=1e3,ws=Cs*60,ks=ws*60,Ao=ks*24,LI=Ao*7,$I=Ao*365.25;wS.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return qI(t);if(n==="number"&&isFinite(t))return e.long?zI(t):HI(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function qI(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\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(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*$I;case"weeks":case"week":case"w":return n*LI;case"days":case"day":case"d":return n*Ao;case"hours":case"hour":case"hrs":case"hr":case"h":return n*ks;case"minutes":case"minute":case"mins":case"min":case"m":return n*ws;case"seconds":case"second":case"secs":case"sec":case"s":return n*Cs;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function HI(t){var e=Math.abs(t);return e>=Ao?Math.round(t/Ao)+"d":e>=ks?Math.round(t/ks)+"h":e>=ws?Math.round(t/ws)+"m":e>=Cs?Math.round(t/Cs)+"s":t+"ms"}function zI(t){var e=Math.abs(t);return e>=Ao?ju(t,e,Ao,"day"):e>=ks?ju(t,e,ks,"hour"):e>=ws?ju(t,e,ws,"minute"):e>=Cs?ju(t,e,Cs,"second"):t+" ms"}function ju(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var lg=G((oW,SS)=>{function WI(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=kS(),n.destroy=d,Object.keys(t).forEach(f=>{n[f]=t[f]}),n.names=[],n.skips=[],n.formatters={};function e(f){let p=0;for(let h=0;h<f.length;h++)p=(p<<5)-p+f.charCodeAt(h),p|=0;return n.colors[Math.abs(p)%n.colors.length]}n.selectColor=e;function n(f){let p,h=null,g,b;function m(...w){if(!m.enabled)return;let C=m,S=Number(new Date),k=S-(p||S);C.diff=k,C.prev=p,C.curr=S,p=S,w[0]=n.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let E=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";E++;let V=n.formatters[q];if(typeof V=="function"){let U=w[E];O=V.call(C,U),w.splice(E,1),E--}return O}),n.formatArgs.call(C,w),(C.log||n.log).apply(C,w)}return m.namespace=f,m.useColors=n.useColors(),m.color=n.selectColor(f),m.extend=r,m.destroy=n.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==n.namespaces&&(g=n.namespaces,b=n.enabled(f)),b),set:w=>{h=w}}),typeof n.init=="function"&&n.init(m),m}function r(f,p){let h=n(this.namespace+(typeof p>"u"?":":p)+f);return h.log=this.log,h}function o(f){n.save(f),n.namespaces=f,n.names=[],n.skips=[];let p=(typeof f=="string"?f:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let h of p)h[0]==="-"?n.skips.push(h.slice(1)):n.names.push(h)}function s(f,p){let h=0,g=0,b=-1,m=0;for(;h<f.length;)if(g<p.length&&(p[g]===f[h]||p[g]==="*"))p[g]==="*"?(b=g,m=h,g++):(h++,g++);else if(b!==-1)g=b+1,m++,h=m;else return!1;for(;g<p.length&&p[g]==="*";)g++;return g===p.length}function i(){let f=[...n.names,...n.skips.map(p=>"-"+p)].join(",");return n.enable(""),f}function a(f){for(let p of n.skips)if(s(f,p))return!1;for(let p of n.names)if(s(f,p))return!0;return!1}function u(f){return f instanceof Error?f.stack||f.message:f}function d(){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 n.enable(n.load()),n}SS.exports=WI});var AS=G((Et,Uu)=>{Et.formatArgs=JI;Et.save=KI;Et.load=VI;Et.useColors=GI;Et.storage=YI();Et.destroy=(()=>{let t=!1;return()=>{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`."))}})();Et.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 GI(){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 JI(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Uu.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}Et.log=console.debug||console.log||(()=>{});function KI(t){try{t?Et.storage.setItem("debug",t):Et.storage.removeItem("debug")}catch{}}function VI(){let t;try{t=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function YI(){try{return localStorage}catch{}}Uu.exports=lg()(Et);var{formatters:XI}=Uu.exports;XI.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var vS=G((sW,ES)=>{"use strict";ES.exports=(t,e=process.argv)=>{let n=t.startsWith("-")?"":t.length===1?"-":"--",r=e.indexOf(n+t),o=e.indexOf("--");return r!==-1&&(o===-1||r<o)}});var RS=G((iW,xS)=>{"use strict";var QI=re("os"),TS=re("tty"),Ht=vS(),{env:st}=process,Lu;Ht("no-color")||Ht("no-colors")||Ht("color=false")||Ht("color=never")?Lu=0:(Ht("color")||Ht("colors")||Ht("color=true")||Ht("color=always"))&&(Lu=1);function ZI(){if("FORCE_COLOR"in st)return st.FORCE_COLOR==="true"?1:st.FORCE_COLOR==="false"?0:st.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(st.FORCE_COLOR,10),3)}function eF(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function tF(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=ZI();r!==void 0&&(Lu=r);let o=n?Lu:r;if(o===0)return 0;if(n){if(Ht("color=16m")||Ht("color=full")||Ht("color=truecolor"))return 3;if(Ht("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(st.TERM==="dumb")return s;if(process.platform==="win32"){let i=QI.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in st)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in st)||st.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in st)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(st.TEAMCITY_VERSION)?1:0;if(st.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in st){let i=Number.parseInt((st.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(st.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(st.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(st.TERM)||"COLORTERM"in st?1:s}function dg(t,e={}){let n=tF(t,{streamIsTTY:t&&t.isTTY,...e});return eF(n)}xS.exports={supportsColor:dg,stdout:dg({isTTY:TS.isatty(1)}),stderr:dg({isTTY:TS.isatty(2)})}});var OS=G((it,qu)=>{var nF=re("tty"),$u=re("util");it.init=uF;it.log=iF;it.formatArgs=oF;it.save=aF;it.load=cF;it.useColors=rF;it.destroy=$u.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");it.colors=[6,2,3,4,5,1];try{let t=RS();t&&(t.stderr||t).level>=2&&(it.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{}it.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function rF(){return"colors"in it.inspectOpts?!!it.inspectOpts.colors:nF.isatty(process.stderr.fd)}function oF(t){let{namespace:e,useColors:n}=this;if(n){let r=this.color,o="\x1B[3"+(r<8?r:"8;5;"+r),s=` ${o};1m${e} \x1B[0m`;t[0]=s+t[0].split(`
67
67
  `).join(`
68
- `+s),t.push(o+"m+"+qu.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=oF()+e+" "+t[0]}function oF(){return it.inspectOpts.hideDate?"":new Date().toISOString()+" "}function sF(...t){return process.stderr.write($u.formatWithOptions(it.inspectOpts,...t)+`
69
- `)}function iF(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function aF(){return process.env.DEBUG}function cF(t){t.inspectOpts={};let e=Object.keys(it.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=it.inspectOpts[e[n]]}qu.exports=dg()(it);var{formatters:DS}=qu.exports;DS.o=function(t){return this.inspectOpts.colors=this.useColors,$u.inspect(t,this.inspectOpts).split(`
70
- `).map(e=>e.trim()).join(" ")};DS.O=function(t){return this.inspectOpts.colors=this.useColors,$u.inspect(t,this.inspectOpts)}});var hg=G((oW,pg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?pg.exports=AS():pg.exports=OS()});var FS=G(vt=>{"use strict";var uF=vt&&vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lF=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PS=vt&&vt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&uF(e,t,n);return lF(e,t),e};Object.defineProperty(vt,"__esModule",{value:!0});vt.req=vt.json=vt.toBuffer=void 0;var dF=PS(re("http")),fF=PS(re("https"));async function IS(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}vt.toBuffer=IS;async function pF(t){let n=(await IS(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}vt.json=pF;function hF(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?fF:dF).request(t,e),o=new Promise((s,i)=>{r.once("response",s).once("error",i).end()});return r.then=o.then.bind(o),r}vt.req=hF});var US=G(Pt=>{"use strict";var MS=Pt&&Pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gF=Pt&&Pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BS=Pt&&Pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&MS(e,t,n);return gF(e,t),e},mF=Pt&&Pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&MS(e,t,n)};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Agent=void 0;var yF=BS(re("net")),NS=BS(re("http")),_F=re("https");mF(FS(),Pt);var Pn=Symbol("AgentBaseInternalState"),gg=class extends NS.Agent{constructor(e){super(e),this[Pn]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
71
- `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new yF.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?_F.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),i=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(a=>{if(this.decrementSockets(s,i),a instanceof NS.Agent)try{return a.addRequest(e,o)}catch(u){return r(u)}this[Pn].currentSocket=a,super.createSocket(e,n,r)},a=>{this.decrementSockets(s,i),r(a)})}createConnection(){let e=this[Pn].currentSocket;if(this[Pn].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Pn].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Pn]&&(this[Pn].defaultPort=e)}get protocol(){return this[Pn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Pn]&&(this[Pn].protocol=e)}};Pt.Agent=gg});var jS=G(Ss=>{"use strict";var bF=Ss&&Ss.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ss,"__esModule",{value:!0});Ss.parseProxyResponse=void 0;var CF=bF(hg()),Hu=(0,CF.default)("https-proxy-agent:parse-proxy-response");function wF(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let f=t.read();f?d(f):t.once("readable",s)}function i(){t.removeListener("end",a),t.removeListener("error",u),t.removeListener("readable",s)}function a(){i(),Hu("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(f){i(),Hu("onerror %o",f),n(f)}function d(f){o.push(f),r+=f.length;let p=Buffer.concat(o,r),h=p.indexOf(`\r
68
+ `+s),t.push(o+"m+"+qu.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=sF()+e+" "+t[0]}function sF(){return it.inspectOpts.hideDate?"":new Date().toISOString()+" "}function iF(...t){return process.stderr.write($u.formatWithOptions(it.inspectOpts,...t)+`
69
+ `)}function aF(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function cF(){return process.env.DEBUG}function uF(t){t.inspectOpts={};let e=Object.keys(it.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=it.inspectOpts[e[n]]}qu.exports=lg()(it);var{formatters:DS}=qu.exports;DS.o=function(t){return this.inspectOpts.colors=this.useColors,$u.inspect(t,this.inspectOpts).split(`
70
+ `).map(e=>e.trim()).join(" ")};DS.O=function(t){return this.inspectOpts.colors=this.useColors,$u.inspect(t,this.inspectOpts)}});var pg=G((aW,fg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?fg.exports=AS():fg.exports=OS()});var FS=G(vt=>{"use strict";var lF=vt&&vt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),dF=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PS=vt&&vt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&lF(e,t,n);return dF(e,t),e};Object.defineProperty(vt,"__esModule",{value:!0});vt.req=vt.json=vt.toBuffer=void 0;var fF=PS(re("http")),pF=PS(re("https"));async function IS(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}vt.toBuffer=IS;async function hF(t){let n=(await IS(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}vt.json=hF;function gF(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?pF:fF).request(t,e),o=new Promise((s,i)=>{r.once("response",s).once("error",i).end()});return r.then=o.then.bind(o),r}vt.req=gF});var jS=G(Pt=>{"use strict";var MS=Pt&&Pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),mF=Pt&&Pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),BS=Pt&&Pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&MS(e,t,n);return mF(e,t),e},yF=Pt&&Pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&MS(e,t,n)};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Agent=void 0;var _F=BS(re("net")),NS=BS(re("http")),bF=re("https");yF(FS(),Pt);var Pn=Symbol("AgentBaseInternalState"),hg=class extends NS.Agent{constructor(e){super(e),this[Pn]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
71
+ `).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new _F.Socket({writable:!1});return this.sockets[e].push(n),this.totalSocketCount++,n}decrementSockets(e,n){if(!this.sockets[e]||n===null)return;let r=this.sockets[e],o=r.indexOf(n);o!==-1&&(r.splice(o,1),this.totalSocketCount--,r.length===0&&delete this.sockets[e])}getName(e){return this.isSecureEndpoint(e)?bF.Agent.prototype.getName.call(this,e):super.getName(e)}createSocket(e,n,r){let o={...n,secureEndpoint:this.isSecureEndpoint(n)},s=this.getName(o),i=this.incrementSockets(s);Promise.resolve().then(()=>this.connect(e,o)).then(a=>{if(this.decrementSockets(s,i),a instanceof NS.Agent)try{return a.addRequest(e,o)}catch(u){return r(u)}this[Pn].currentSocket=a,super.createSocket(e,n,r)},a=>{this.decrementSockets(s,i),r(a)})}createConnection(){let e=this[Pn].currentSocket;if(this[Pn].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Pn].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Pn]&&(this[Pn].defaultPort=e)}get protocol(){return this[Pn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Pn]&&(this[Pn].protocol=e)}};Pt.Agent=hg});var US=G(Ss=>{"use strict";var CF=Ss&&Ss.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ss,"__esModule",{value:!0});Ss.parseProxyResponse=void 0;var wF=CF(pg()),Hu=(0,wF.default)("https-proxy-agent:parse-proxy-response");function kF(t){return new Promise((e,n)=>{let r=0,o=[];function s(){let f=t.read();f?d(f):t.once("readable",s)}function i(){t.removeListener("end",a),t.removeListener("error",u),t.removeListener("readable",s)}function a(){i(),Hu("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(f){i(),Hu("onerror %o",f),n(f)}function d(f){o.push(f),r+=f.length;let p=Buffer.concat(o,r),h=p.indexOf(`\r
72
72
  \r
73
73
  `);if(h===-1){Hu("have not received end of HTTP headers yet..."),s();return}let g=p.slice(0,h).toString("ascii").split(`\r
74
- `),b=g.shift();if(!b)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let m=b.split(" "),w=+m[1],C=m.slice(2).join(" "),A={};for(let k of g){if(!k)continue;let E=k.indexOf(":");if(E===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${k}"`));let x=k.slice(0,E).toLowerCase(),O=k.slice(E+1).trimStart(),q=A[x];typeof q=="string"?A[x]=[q,O]:Array.isArray(q)?q.push(O):A[x]=O}Hu("got proxy server response: %o %o",b,A),i(),e({connect:{statusCode:w,statusText:C,headers:A},buffered:p})}t.on("error",u),t.on("end",a),s()})}Ss.parseProxyResponse=wF});var WS=G(zt=>{"use strict";var kF=zt&&zt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),SF=zt&&zt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),HS=zt&&zt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&kF(e,t,n);return SF(e,t),e},zS=zt&&zt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zt,"__esModule",{value:!0});zt.HttpsProxyAgent=void 0;var zu=HS(re("net")),LS=HS(re("tls")),AF=zS(re("assert")),EF=zS(hg()),vF=US(),TF=re("url"),xF=jS(),na=(0,EF.default)("https-proxy-agent"),$S=t=>t.servername===void 0&&t.host&&!zu.isIP(t.host)?{...t,servername:t.host}:t,Wu=class extends vF.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new TF.URL(e):e,this.proxyHeaders=n?.headers??{},na("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?qS(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(na("Creating `tls.Socket`: %o",this.connectOpts),o=LS.connect($S(this.connectOpts))):(na("Creating `net.Socket`: %o",this.connectOpts),o=zu.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=zu.isIPv6(n.host)?`[${n.host}]`:n.host,a=`CONNECT ${i}:${n.port} HTTP/1.1\r
74
+ `),b=g.shift();if(!b)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let m=b.split(" "),w=+m[1],C=m.slice(2).join(" "),S={};for(let k of g){if(!k)continue;let E=k.indexOf(":");if(E===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${k}"`));let x=k.slice(0,E).toLowerCase(),O=k.slice(E+1).trimStart(),q=S[x];typeof q=="string"?S[x]=[q,O]:Array.isArray(q)?q.push(O):S[x]=O}Hu("got proxy server response: %o %o",b,S),i(),e({connect:{statusCode:w,statusText:C,headers:S},buffered:p})}t.on("error",u),t.on("end",a),s()})}Ss.parseProxyResponse=kF});var WS=G(zt=>{"use strict";var SF=zt&&zt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),AF=zt&&zt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),HS=zt&&zt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&SF(e,t,n);return AF(e,t),e},zS=zt&&zt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zt,"__esModule",{value:!0});zt.HttpsProxyAgent=void 0;var zu=HS(re("net")),LS=HS(re("tls")),EF=zS(re("assert")),vF=zS(pg()),TF=jS(),xF=re("url"),RF=US(),na=(0,vF.default)("https-proxy-agent"),$S=t=>t.servername===void 0&&t.host&&!zu.isIP(t.host)?{...t,servername:t.host}:t,Wu=class extends TF.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new xF.URL(e):e,this.proxyHeaders=n?.headers??{},na("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let r=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),o=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...n?qS(n,"headers"):null,host:r,port:o}}async connect(e,n){let{proxy:r}=this;if(!n.host)throw new TypeError('No "host" provided');let o;r.protocol==="https:"?(na("Creating `tls.Socket`: %o",this.connectOpts),o=LS.connect($S(this.connectOpts))):(na("Creating `net.Socket`: %o",this.connectOpts),o=zu.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=zu.isIPv6(n.host)?`[${n.host}]`:n.host,a=`CONNECT ${i}:${n.port} HTTP/1.1\r
75
75
  `;if(r.username||r.password){let h=`${decodeURIComponent(r.username)}:${decodeURIComponent(r.password)}`;s["Proxy-Authorization"]=`Basic ${Buffer.from(h).toString("base64")}`}s.Host=`${i}:${n.port}`,s["Proxy-Connection"]||(s["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close");for(let h of Object.keys(s))a+=`${h}: ${s[h]}\r
76
- `;let u=(0,xF.parseProxyResponse)(o);o.write(`${a}\r
77
- `);let{connect:d,buffered:f}=await u;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",RF),n.secureEndpoint?(na("Upgrading socket connection to TLS"),LS.connect({...qS($S(n),"host","path","port"),socket:o})):o;o.destroy();let p=new zu.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{na("Replaying proxy buffer for failed request"),(0,AF.default)(h.listenerCount("data")>0),h.push(f),h.push(null)}),p}};Wu.protocols=["http","https"];zt.HttpsProxyAgent=Wu;function RF(t){t.resume()}function qS(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function yg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var DF,OF,mg,Gu=Br(()=>{DF=Object.defineProperty,OF=(t,e)=>DF(t,"name",{value:e,configurable:!0}),mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};OF(yg,"getDefaultExportFromCjs")});var YS={};tC(YS,{toFormData:()=>VS});function KS(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function VS(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new UF(n[1]||n[2]),o,s,i,a,u,d,f=[],p=new vo,h=It(C=>{i+=w.decode(C,{stream:!0})},"onPartData"),g=It(C=>{f.push(C)},"appendToFile"),b=It(()=>{let C=new As(f,d,{type:u});p.append(a,C)},"appendFileToFormData"),m=It(()=>{p.append(a,i)},"appendEntryToFormData"),w=new TextDecoder("utf-8");w.decode(),r.onPartBegin=function(){r.onPartData=h,r.onPartEnd=m,o="",s="",i="",a="",u="",d=null,f.length=0},r.onHeaderField=function(C){o+=w.decode(C,{stream:!0})},r.onHeaderValue=function(C){s+=w.decode(C,{stream:!0})},r.onHeaderEnd=function(){if(s+=w.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(a=C[2]||C[3]||""),d=KS(s),d&&(r.onPartData=g,r.onPartEnd=b)}else o==="content-type"&&(u=s);s="",o=""};for await(let C of t)r.write(C);return r.end(),p}var PF,It,In,je,GS,zr,Ju,Ku,IF,ra,FF,NF,MF,BF,Eo,JS,UF,XS=Br(()=>{Vu();Gu();PF=Object.defineProperty,It=(t,e)=>PF(t,"name",{value:e,configurable:!0}),In=0,je={START_BOUNDARY:In++,HEADER_FIELD_START:In++,HEADER_FIELD:In++,HEADER_VALUE_START:In++,HEADER_VALUE:In++,HEADER_VALUE_ALMOST_DONE:In++,HEADERS_ALMOST_DONE:In++,PART_DATA_START:In++,PART_DATA:In++,END:In++},GS=1,zr={PART_BOUNDARY:GS,LAST_BOUNDARY:GS*=2},Ju=10,Ku=13,IF=32,ra=45,FF=58,NF=97,MF=122,BF=It(t=>t|32,"lower"),Eo=It(()=>{},"noop"),JS=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Eo,this.onHeaderField=Eo,this.onHeadersEnd=Eo,this.onHeaderValue=Eo,this.onPartBegin=Eo,this.onPartData=Eo,this.onPartEnd=Eo,this.boundaryChars={},e=`\r
78
- --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=je.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:i,boundaryChars:a,index:u,state:d,flags:f}=this,p=this.boundary.length,h=p-1,g=e.length,b,m,w=It(E=>{this[E+"Mark"]=n},"mark"),C=It(E=>{delete this[E+"Mark"]},"clear"),A=It((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),k=It((E,x)=>{let O=E+"Mark";O in this&&(x?(A(E,this[O],n,e),delete this[O]):(A(E,this[O],e.length,e),this[O]=0))},"dataCallback");for(n=0;n<r;n++)switch(b=e[n],d){case je.START_BOUNDARY:if(u===i.length-2){if(b===ra)f|=zr.LAST_BOUNDARY;else if(b!==Ku)return;u++;break}else if(u-1===i.length-2){if(f&zr.LAST_BOUNDARY&&b===ra)d=je.END,f=0;else if(!(f&zr.LAST_BOUNDARY)&&b===Ju)u=0,A("onPartBegin"),d=je.HEADER_FIELD_START;else return;break}b!==i[u+2]&&(u=-2),b===i[u+2]&&u++;break;case je.HEADER_FIELD_START:d=je.HEADER_FIELD,w("onHeaderField"),u=0;case je.HEADER_FIELD:if(b===Ku){C("onHeaderField"),d=je.HEADERS_ALMOST_DONE;break}if(u++,b===ra)break;if(b===FF){if(u===1)return;k("onHeaderField",!0),d=je.HEADER_VALUE_START;break}if(m=BF(b),m<NF||m>MF)return;break;case je.HEADER_VALUE_START:if(b===IF)break;w("onHeaderValue"),d=je.HEADER_VALUE;case je.HEADER_VALUE:b===Ku&&(k("onHeaderValue",!0),A("onHeaderEnd"),d=je.HEADER_VALUE_ALMOST_DONE);break;case je.HEADER_VALUE_ALMOST_DONE:if(b!==Ju)return;d=je.HEADER_FIELD_START;break;case je.HEADERS_ALMOST_DONE:if(b!==Ju)return;A("onHeadersEnd"),d=je.PART_DATA_START;break;case je.PART_DATA_START:d=je.PART_DATA,w("onPartData");case je.PART_DATA:if(o=u,u===0){for(n+=h;n<g&&!(e[n]in a);)n+=p;n-=h,b=e[n]}if(u<i.length)i[u]===b?(u===0&&k("onPartData",!0),u++):u=0;else if(u===i.length)u++,b===Ku?f|=zr.PART_BOUNDARY:b===ra?f|=zr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&zr.PART_BOUNDARY){if(u=0,b===Ju){f&=~zr.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),d=je.HEADER_FIELD_START;break}}else f&zr.LAST_BOUNDARY&&b===ra?(A("onPartEnd"),d=je.END,f=0):u=0;if(u>0)s[u-1]=b;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);A("onPartData",0,o,E),o=0,w("onPartData"),n--}break;case je.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}k("onHeaderField"),k("onHeaderValue"),k("onPartData"),this.index=u,this.state=d,this.flags=f}end(){if(this.state===je.HEADER_FIELD_START&&this.index===0||this.state===je.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==je.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};It(JS,"MultipartParser");UF=JS;It(KS,"_fileName");It(VS,"toFormData")});import la from"node:http";import LF from"node:https";import vs from"node:zlib";import Mn,{PassThrough as ol,pipeline as Ts}from"node:stream";import{Buffer as pt}from"node:buffer";import{types as sl,deprecate as il,promisify as $F}from"node:util";import{format as qF}from"node:url";import{isIP as HF}from"node:net";import{promises as zF,statSync as lA,createReadStream as WF}from"node:fs";import{basename as GF}from"node:path";function dA(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",i=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(i+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(i+=";charset=US-ASCII",r="US-ASCII");let a=o?"base64":"ascii",u=unescape(t.substring(e+1)),d=Buffer.from(u,a);return d.type=s,d.typeFull=i,d.charset=r,d}function fA(){return ZS||(ZS=1,(function(t,e){(function(n,r){r(e)})(JF,function(n){function r(){}y(r,"noop");function o(c){return typeof c=="object"&&c!==null||typeof c=="function"}y(o,"typeIsObject");let s=r;function i(c,l){try{Object.defineProperty(c,"name",{value:l,configurable:!0})}catch{}}y(i,"setFunctionName");let a=Promise,u=Promise.prototype.then,d=Promise.reject.bind(a);function f(c){return new a(c)}y(f,"newPromise");function p(c){return f(l=>l(c))}y(p,"promiseResolvedWith");function h(c){return d(c)}y(h,"promiseRejectedWith");function g(c,l,_){return u.call(c,l,_)}y(g,"PerformPromiseThen");function b(c,l,_){g(g(c,l,_),void 0,s)}y(b,"uponPromise");function m(c,l){b(c,l)}y(m,"uponFulfillment");function w(c,l){b(c,void 0,l)}y(w,"uponRejection");function C(c,l,_){return g(c,l,_)}y(C,"transformPromiseWith");function A(c){g(c,void 0,s)}y(A,"setPromiseIsHandledToTrue");let k=y(c=>{if(typeof queueMicrotask=="function")k=queueMicrotask;else{let l=p(void 0);k=y(_=>g(l,_),"_queueMicrotask")}return k(c)},"_queueMicrotask");function E(c,l,_){if(typeof c!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(c,l,_)}y(E,"reflectCall");function x(c,l,_){try{return p(E(c,l,_))}catch(v){return h(v)}}y(x,"promiseCall");let O=16384,q=class{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(l){let _=this._back,v=_;_._elements.length===O-1&&(v={_elements:[],_next:void 0}),_._elements.push(l),v!==_&&(this._back=v,_._next=v),++this._size}shift(){let l=this._front,_=l,v=this._cursor,I=v+1,$=l._elements,W=$[v];return I===O&&(_=l._next,I=0),--this._size,this._cursor=I,l!==_&&(this._front=_),$[v]=void 0,W}forEach(l){let _=this._cursor,v=this._front,I=v._elements;for(;(_!==I.length||v._next!==void 0)&&!(_===I.length&&(v=v._next,I=v._elements,_=0,I.length===0));)l(I[_]),++_}peek(){let l=this._front,_=this._cursor;return l._elements[_]}};y(q,"SimpleQueue");let V=q,j=Symbol("[[AbortSteps]]"),ee=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),te=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function _e(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ae(c):Z(c,l._storedError)}y(_e,"ReadableStreamReaderGenericInitialize");function Oe(c,l){let _=c._ownerReadableStream;return Ut(_,l)}y(Oe,"ReadableStreamReaderGenericCancel");function Te(c){let l=c._ownerReadableStream;l._state==="readable"?Ie(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):we(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._readableStreamController[Q](),l._reader=void 0,c._ownerReadableStream=void 0}y(Te,"ReadableStreamReaderGenericRelease");function Ke(c){return new TypeError("Cannot "+c+" a stream using a released reader")}y(Ke,"readerLockException");function ne(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_})}y(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Ie(c,l)}y(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ae(c){ne(c),H(c)}y(ae,"defaultReaderClosedPromiseInitializeAsResolved");function Ie(c,l){c._closedPromise_reject!==void 0&&(A(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}y(Ie,"defaultReaderClosedPromiseReject");function we(c,l){Z(c,l)}y(we,"defaultReaderClosedPromiseResetToRejected");function H(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}y(H,"defaultReaderClosedPromiseResolve");let Ee=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},Ze=Math.trunc||function(c){return c<0?Math.ceil(c):Math.floor(c)};function X(c){return typeof c=="object"||typeof c=="function"}y(X,"isDictionary");function de(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}y(de,"assertDictionary");function ce(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}y(ce,"assertFunction");function S(c){return typeof c=="object"&&c!==null||typeof c=="function"}y(S,"isObject");function T(c,l){if(!S(c))throw new TypeError(`${l} is not an object.`)}y(T,"assertObject");function R(c,l,_){if(c===void 0)throw new TypeError(`Parameter ${l} is required in '${_}'.`)}y(R,"assertRequiredArgument");function M(c,l,_){if(c===void 0)throw new TypeError(`${l} is required in '${_}'.`)}y(M,"assertRequiredField");function D(c){return Number(c)}y(D,"convertUnrestrictedDouble");function F(c){return c===0?0:c}y(F,"censorNegativeZero");function L(c){return F(Ze(c))}y(L,"integerPart");function P(c,l){let _=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ee(v))throw new TypeError(`${l} is not a finite number`);if(v=L(v),v<0||v>_)throw new TypeError(`${l} is outside the accepted range of 0 to ${_}, inclusive`);return!Ee(v)||v===0?0:v}y(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!Qn(c))throw new TypeError(`${l} is not a ReadableStream.`)}y(N,"assertReadableStream");function U(c){return new me(c)}y(U,"AcquireReadableStreamDefaultReader");function B(c,l){c._reader._readRequests.push(l)}y(B,"ReadableStreamAddReadRequest");function K(c,l,_){let v=c._reader._readRequests.shift();_?v._closeSteps():v._chunkSteps(l)}y(K,"ReadableStreamFulfillReadRequest");function ie(c){return c._reader._readRequests.length}y(ie,"ReadableStreamGetNumReadRequests");function ue(c){let l=c._reader;return!(l===void 0||!he(l))}y(ue,"ReadableStreamHasDefaultReader");let be=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");_e(this,l),this._readRequests=new V}get closed(){return he(this)?this._closedPromise:h(mn("closed"))}cancel(l=void 0){return he(this)?this._ownerReadableStream===void 0?h(Ke("cancel")):Oe(this,l):h(mn("cancel"))}read(){if(!he(this))return h(mn("read"));if(this._ownerReadableStream===void 0)return h(Ke("read from"));let l,_,v=f((I,$)=>{l=I,_=$});return ye(this,{_chunkSteps:y(I=>l({value:I,done:!1}),"_chunkSteps"),_closeSteps:y(()=>l({value:void 0,done:!0}),"_closeSteps"),_errorSteps:y(I=>_(I),"_errorSteps")}),v}releaseLock(){if(!he(this))throw mn("releaseLock");this._ownerReadableStream!==void 0&&Fe(this)}};y(be,"ReadableStreamDefaultReader");let me=be;Object.defineProperties(me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(me.prototype.cancel,"cancel"),i(me.prototype.read,"read"),i(me.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(me.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function he(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof me}y(he,"IsReadableStreamDefaultReader");function ye(c,l){let _=c._ownerReadableStream;_._disturbed=!0,_._state==="closed"?l._closeSteps():_._state==="errored"?l._errorSteps(_._storedError):_._readableStreamController[te](l)}y(ye,"ReadableStreamDefaultReaderRead");function Fe(c){Te(c);let l=new TypeError("Reader was released");Xe(c,l)}y(Fe,"ReadableStreamDefaultReaderRelease");function Xe(c,l){let _=c._readRequests;c._readRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Xe,"ReadableStreamDefaultReaderErrorReadRequests");function mn(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}y(mn,"defaultReaderBrandCheckException");let li=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),jo=class{constructor(l,_){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=_}next(){let l=y(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?C(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let _=y(()=>this._returnSteps(l),"returnSteps");return this._ongoingPromise?C(this._ongoingPromise,_,_):_()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,_,v,I=f(($,W)=>{_=$,v=W});return ye(l,{_chunkSteps:y($=>{this._ongoingPromise=void 0,k(()=>_({value:$,done:!1}))},"_chunkSteps"),_closeSteps:y(()=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),_({value:void 0,done:!0})},"_closeSteps"),_errorSteps:y($=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),v($)},"_errorSteps")}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let _=this._reader;if(!this._preventCancel){let v=Oe(_,l);return Te(_),C(v,()=>({value:l,done:!0}))}return Te(_),p({value:l,done:!0})}};y(jo,"ReadableStreamAsyncIteratorImpl");let xt=jo,Ar={next(){return et(this)?this._asyncIteratorImpl.next():h(Ue("next"))},return(c){return et(this)?this._asyncIteratorImpl.return(c):h(Ue("return"))}};Object.setPrototypeOf(Ar,li);function ht(c,l){let _=U(c),v=new xt(_,l),I=Object.create(Ar);return I._asyncIteratorImpl=v,I}y(ht,"AcquireReadableStreamAsyncIterator");function et(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof xt}catch{return!1}}y(et,"IsReadableStreamAsyncIterator");function Ue(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}y(Ue,"streamAsyncIteratorBrandCheckException");let i0=Number.isNaN||function(c){return c!==c};var Rf,Df,Of;function Lo(c){return c.slice()}y(Lo,"CreateArrayFromList");function Pf(c,l,_,v,I){new Uint8Array(c).set(new Uint8Array(_,v,I),l)}y(Pf,"CopyDataBlockBytes");let Jn=y(c=>(typeof c.transfer=="function"?Jn=y(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Jn=y(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):Jn=y(l=>l,"TransferArrayBuffer"),Jn(c)),"TransferArrayBuffer"),Er=y(c=>(typeof c.detached=="boolean"?Er=y(l=>l.detached,"IsDetachedBuffer"):Er=y(l=>l.byteLength===0,"IsDetachedBuffer"),Er(c)),"IsDetachedBuffer");function If(c,l,_){if(c.slice)return c.slice(l,_);let v=_-l,I=new ArrayBuffer(v);return Pf(I,0,c,l,v),I}y(If,"ArrayBufferSlice");function di(c,l){let _=c[l];if(_!=null){if(typeof _!="function")throw new TypeError(`${String(l)} is not a function`);return _}}y(di,"GetMethod");function a0(c){let l={[Symbol.iterator]:()=>c.iterator},_=(async function*(){return yield*l})(),v=_.next;return{iterator:_,nextMethod:v,done:!1}}y(a0,"CreateAsyncFromSyncIterator");let Ff=(Of=(Rf=Symbol.asyncIterator)!==null&&Rf!==void 0?Rf:(Df=Symbol.for)===null||Df===void 0?void 0:Df.call(Symbol,"Symbol.asyncIterator"))!==null&&Of!==void 0?Of:"@@asyncIterator";function Nf(c,l="sync",_){if(_===void 0)if(l==="async"){if(_=di(c,Ff),_===void 0){let $=di(c,Symbol.iterator),W=Nf(c,"sync",$);return a0(W)}}else _=di(c,Symbol.iterator);if(_===void 0)throw new TypeError("The object is not iterable");let v=E(_,c,[]);if(!o(v))throw new TypeError("The iterator method must return an object");let I=v.next;return{iterator:v,nextMethod:I,done:!1}}y(Nf,"GetIterator");function c0(c){let l=E(c.nextMethod,c.iterator,[]);if(!o(l))throw new TypeError("The iterator.next() method must return an object");return l}y(c0,"IteratorNext");function u0(c){return!!c.done}y(u0,"IteratorComplete");function l0(c){return c.value}y(l0,"IteratorValue");function d0(c){return!(typeof c!="number"||i0(c)||c<0)}y(d0,"IsNonNegativeNumber");function Mf(c){let l=If(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}y(Mf,"CloneAsUint8Array");function Ga(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}y(Ga,"DequeueValue");function Ja(c,l,_){if(!d0(_)||_===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:_}),c._queueTotalSize+=_}y(Ja,"EnqueueValueWithSize");function f0(c){return c._queue.peek().value}y(f0,"PeekQueueValue");function Kn(c){c._queue=new V,c._queueTotalSize=0}y(Kn,"ResetQueue");function Bf(c){return c===DataView}y(Bf,"isDataViewConstructor");function p0(c){return Bf(c.constructor)}y(p0,"isDataView");function h0(c){return Bf(c)?1:c.BYTES_PER_ELEMENT}y(h0,"arrayBufferViewElementSize");let g0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ka(this))throw Za("view");return this._view}respond(l){if(!Ka(this))throw Za("respond");if(R(l,1,"respond"),l=P(l,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");gi(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!Ka(this))throw Za("respondWithNewView");if(R(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");mi(this._associatedReadableByteStreamController,l)}};y(g0,"ReadableStreamBYOBRequest");let ro=g0;Object.defineProperties(ro.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(ro.prototype.respond,"respond"),i(ro.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ro.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let m0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!vr(this))throw qo("byobRequest");return Qa(this)}get desiredSize(){if(!vr(this))throw qo("desiredSize");return Jf(this)}close(){if(!vr(this))throw qo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw new TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);$o(this)}enqueue(l){if(!vr(this))throw qo("enqueue");if(R(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let _=this._controlledReadableByteStream._state;if(_!=="readable")throw new TypeError(`The stream (in ${_} state) is not in the readable state and cannot be enqueued to`);hi(this,l)}error(l=void 0){if(!vr(this))throw qo("error");Rt(this,l)}[z](l){Uf(this),Kn(this);let _=this._cancelAlgorithm(l);return pi(this),_}[te](l){let _=this._controlledReadableByteStream;if(this._queueTotalSize>0){Gf(this,l);return}let v=this._autoAllocateChunkSize;if(v!==void 0){let I;try{I=new ArrayBuffer(v)}catch(W){l._errorSteps(W);return}let $={buffer:I,bufferByteLength:v,byteOffset:0,byteLength:v,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push($)}B(_,l),Tr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};y(m0,"ReadableByteStreamController");let Vn=m0;Object.defineProperties(Vn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Vn.prototype.close,"close"),i(Vn.prototype.enqueue,"enqueue"),i(Vn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Vn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function vr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof Vn}y(vr,"IsReadableByteStreamController");function Ka(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof ro}y(Ka,"IsReadableStreamBYOBRequest");function Tr(c){if(!w0(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();b(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Tr(c)),null),_=>(Rt(c,_),null))}y(Tr,"ReadableByteStreamControllerCallPullIfNeeded");function Uf(c){Ya(c),c._pendingPullIntos=new V}y(Uf,"ReadableByteStreamControllerClearPendingPullIntos");function Va(c,l){let _=!1;c._state==="closed"&&(_=!0);let v=jf(l);l.readerType==="default"?K(c,v,_):T0(c,v,_)}y(Va,"ReadableByteStreamControllerCommitPullIntoDescriptor");function jf(c){let l=c.bytesFilled,_=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/_)}y(jf,"ReadableByteStreamControllerConvertPullIntoDescriptor");function fi(c,l,_,v){c._queue.push({buffer:l,byteOffset:_,byteLength:v}),c._queueTotalSize+=v}y(fi,"ReadableByteStreamControllerEnqueueChunkToQueue");function Lf(c,l,_,v){let I;try{I=If(l,_,_+v)}catch($){throw Rt(c,$),$}fi(c,I,0,v)}y(Lf,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function $f(c,l){l.bytesFilled>0&&Lf(c,l.buffer,l.byteOffset,l.bytesFilled),oo(c)}y($f,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function qf(c,l){let _=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+_,I=_,$=!1,W=v%l.elementSize,se=v-W;se>=l.minimumFill&&(I=se-l.bytesFilled,$=!0);let le=c._queue;for(;I>0;){let ge=le.peek(),ke=Math.min(I,ge.byteLength),Se=l.byteOffset+l.bytesFilled;Pf(l.buffer,Se,ge.buffer,ge.byteOffset,ke),ge.byteLength===ke?le.shift():(ge.byteOffset+=ke,ge.byteLength-=ke),c._queueTotalSize-=ke,Hf(c,ke,l),I-=ke}return $}y(qf,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function Hf(c,l,_){_.bytesFilled+=l}y(Hf,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function zf(c){c._queueTotalSize===0&&c._closeRequested?(pi(c),Vo(c._controlledReadableByteStream)):Tr(c)}y(zf,"ReadableByteStreamControllerHandleQueueDrain");function Ya(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}y(Ya,"ReadableByteStreamControllerInvalidateBYOBRequest");function Xa(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();qf(c,l)&&(oo(c),Va(c._controlledReadableByteStream,l))}}y(Xa,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function y0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let _=l._readRequests.shift();Gf(c,_)}}y(y0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function _0(c,l,_,v){let I=c._controlledReadableByteStream,$=l.constructor,W=h0($),{byteOffset:se,byteLength:le}=l,ge=_*W,ke;try{ke=Jn(l.buffer)}catch(Be){v._errorSteps(Be);return}let Se={buffer:ke,bufferByteLength:ke.byteLength,byteOffset:se,byteLength:le,bytesFilled:0,minimumFill:ge,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(Se),Yf(I,v);return}if(I._state==="closed"){let Be=new $(Se.buffer,Se.byteOffset,0);v._closeSteps(Be);return}if(c._queueTotalSize>0){if(qf(c,Se)){let Be=jf(Se);zf(c),v._chunkSteps(Be);return}if(c._closeRequested){let Be=new TypeError("Insufficient bytes to fill elements in the given buffer");Rt(c,Be),v._errorSteps(Be);return}}c._pendingPullIntos.push(Se),Yf(I,v),Tr(c)}y(_0,"ReadableByteStreamControllerPullInto");function b0(c,l){l.readerType==="none"&&oo(c);let _=c._controlledReadableByteStream;if(ec(_))for(;Xf(_)>0;){let v=oo(c);Va(_,v)}}y(b0,"ReadableByteStreamControllerRespondInClosedState");function C0(c,l,_){if(Hf(c,l,_),_.readerType==="none"){$f(c,_),Xa(c);return}if(_.bytesFilled<_.minimumFill)return;oo(c);let v=_.bytesFilled%_.elementSize;if(v>0){let I=_.byteOffset+_.bytesFilled;Lf(c,_.buffer,I-v,v)}_.bytesFilled-=v,Va(c._controlledReadableByteStream,_),Xa(c)}y(C0,"ReadableByteStreamControllerRespondInReadableState");function Wf(c,l){let _=c._pendingPullIntos.peek();Ya(c),c._controlledReadableByteStream._state==="closed"?b0(c,_):C0(c,l,_),Tr(c)}y(Wf,"ReadableByteStreamControllerRespondInternal");function oo(c){return c._pendingPullIntos.shift()}y(oo,"ReadableByteStreamControllerShiftPendingPullInto");function w0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ue(l)&&ie(l)>0||ec(l)&&Xf(l)>0||Jf(c)>0)}y(w0,"ReadableByteStreamControllerShouldCallPull");function pi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}y(pi,"ReadableByteStreamControllerClearAlgorithms");function $o(c){let l=c._controlledReadableByteStream;if(!(c._closeRequested||l._state!=="readable")){if(c._queueTotalSize>0){c._closeRequested=!0;return}if(c._pendingPullIntos.length>0){let _=c._pendingPullIntos.peek();if(_.bytesFilled%_.elementSize!==0){let v=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Rt(c,v),v}}pi(c),Vo(l)}}y($o,"ReadableByteStreamControllerClose");function hi(c,l){let _=c._controlledReadableByteStream;if(c._closeRequested||_._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Er(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=Jn(v);if(c._pendingPullIntos.length>0){let se=c._pendingPullIntos.peek();if(Er(se.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ya(c),se.buffer=Jn(se.buffer),se.readerType==="none"&&$f(c,se)}if(ue(_))if(y0(c),ie(_)===0)fi(c,W,I,$);else{c._pendingPullIntos.length>0&&oo(c);let se=new Uint8Array(W,I,$);K(_,se,!1)}else ec(_)?(fi(c,W,I,$),Xa(c)):fi(c,W,I,$);Tr(c)}y(hi,"ReadableByteStreamControllerEnqueue");function Rt(c,l){let _=c._controlledReadableByteStream;_._state==="readable"&&(Uf(c),Kn(c),pi(c),Cp(_,l))}y(Rt,"ReadableByteStreamControllerError");function Gf(c,l){let _=c._queue.shift();c._queueTotalSize-=_.byteLength,zf(c);let v=new Uint8Array(_.buffer,_.byteOffset,_.byteLength);l._chunkSteps(v)}y(Gf,"ReadableByteStreamControllerFillReadRequestFromQueue");function Qa(c){if(c._byobRequest===null&&c._pendingPullIntos.length>0){let l=c._pendingPullIntos.peek(),_=new Uint8Array(l.buffer,l.byteOffset+l.bytesFilled,l.byteLength-l.bytesFilled),v=Object.create(ro.prototype);S0(v,c,_),c._byobRequest=v}return c._byobRequest}y(Qa,"ReadableByteStreamControllerGetBYOBRequest");function Jf(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Jf,"ReadableByteStreamControllerGetDesiredSize");function gi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(l===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(_.bytesFilled+l>_.byteLength)throw new RangeError("bytesWritten out of range")}_.buffer=Jn(_.buffer),Wf(c,l)}y(gi,"ReadableByteStreamControllerRespond");function mi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(l.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(_.byteOffset+_.bytesFilled!==l.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(_.bufferByteLength!==l.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(_.bytesFilled+l.byteLength>_.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let v=l.byteLength;_.buffer=Jn(l.buffer),Wf(c,v)}y(mi,"ReadableByteStreamControllerRespondWithNewView");function Kf(c,l,_,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,Kn(l),l._closeRequested=!1,l._started=!1,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,l._autoAllocateChunkSize=W,l._pendingPullIntos=new V,c._readableStreamController=l;let se=_();b(p(se),()=>(l._started=!0,Tr(l),null),le=>(Rt(l,le),null))}y(Kf,"SetUpReadableByteStreamController");function k0(c,l,_){let v=Object.create(Vn.prototype),I,$,W;l.start!==void 0?I=y(()=>l.start(v),"startAlgorithm"):I=y(()=>{},"startAlgorithm"),l.pull!==void 0?$=y(()=>l.pull(v),"pullAlgorithm"):$=y(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?W=y(le=>l.cancel(le),"cancelAlgorithm"):W=y(()=>p(void 0),"cancelAlgorithm");let se=l.autoAllocateChunkSize;if(se===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Kf(c,v,I,$,W,_,se)}y(k0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function S0(c,l,_){c._associatedReadableByteStreamController=l,c._view=_}y(S0,"SetUpReadableStreamBYOBRequest");function Za(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}y(Za,"byobRequestBrandCheckException");function qo(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}y(qo,"byteStreamControllerBrandCheckException");function A0(c,l){de(c,l);let _=c?.mode;return{mode:_===void 0?void 0:E0(_,`${l} has member 'mode' that`)}}y(A0,"convertReaderOptions");function E0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}y(E0,"convertReadableStreamReaderMode");function v0(c,l){var _;de(c,l);let v=(_=c?.min)!==null&&_!==void 0?_:1;return{min:P(v,`${l} has member 'min' that`)}}y(v0,"convertByobReadOptions");function Vf(c){return new xr(c)}y(Vf,"AcquireReadableStreamBYOBReader");function Yf(c,l){c._reader._readIntoRequests.push(l)}y(Yf,"ReadableStreamAddReadIntoRequest");function T0(c,l,_){let v=c._reader._readIntoRequests.shift();_?v._closeSteps(l):v._chunkSteps(l)}y(T0,"ReadableStreamFulfillReadIntoRequest");function Xf(c){return c._reader._readIntoRequests.length}y(Xf,"ReadableStreamGetNumReadIntoRequests");function ec(c){let l=c._reader;return!(l===void 0||!Rr(l))}y(ec,"ReadableStreamHasBYOBReader");let x0=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!vr(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");_e(this,l),this._readIntoRequests=new V}get closed(){return Rr(this)?this._closedPromise:h(yi("closed"))}cancel(l=void 0){return Rr(this)?this._ownerReadableStream===void 0?h(Ke("cancel")):Oe(this,l):h(yi("cancel"))}read(l,_={}){if(!Rr(this))return h(yi("read"));if(!ArrayBuffer.isView(l))return h(new TypeError("view must be an array buffer view"));if(l.byteLength===0)return h(new TypeError("view must have non-zero byteLength"));if(l.buffer.byteLength===0)return h(new TypeError("view's buffer must have non-zero byteLength"));if(Er(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=v0(_,"options")}catch(le){return h(le)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(p0(l)){if(I>l.byteLength)return h(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(I>l.length)return h(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return h(Ke("read from"));let $,W,se=f((le,ge)=>{$=le,W=ge});return Qf(this,l,I,{_chunkSteps:y(le=>$({value:le,done:!1}),"_chunkSteps"),_closeSteps:y(le=>$({value:le,done:!0}),"_closeSteps"),_errorSteps:y(le=>W(le),"_errorSteps")}),se}releaseLock(){if(!Rr(this))throw yi("releaseLock");this._ownerReadableStream!==void 0&&R0(this)}};y(x0,"ReadableStreamBYOBReader");let xr=x0;Object.defineProperties(xr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(xr.prototype.cancel,"cancel"),i(xr.prototype.read,"read"),i(xr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Rr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof xr}y(Rr,"IsReadableStreamBYOBReader");function Qf(c,l,_,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):_0(I._readableStreamController,l,_,v)}y(Qf,"ReadableStreamBYOBReaderRead");function R0(c){Te(c);let l=new TypeError("Reader was released");Zf(c,l)}y(R0,"ReadableStreamBYOBReaderRelease");function Zf(c,l){let _=c._readIntoRequests;c._readIntoRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Zf,"ReadableStreamBYOBReaderErrorReadIntoRequests");function yi(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}y(yi,"byobReaderBrandCheckException");function Ho(c,l){let{highWaterMark:_}=c;if(_===void 0)return l;if(i0(_)||_<0)throw new RangeError("Invalid highWaterMark");return _}y(Ho,"ExtractHighWaterMark");function _i(c){let{size:l}=c;return l||(()=>1)}y(_i,"ExtractSizeAlgorithm");function bi(c,l){de(c,l);let _=c?.highWaterMark,v=c?.size;return{highWaterMark:_===void 0?void 0:D(_),size:v===void 0?void 0:D0(v,`${l} has member 'size' that`)}}y(bi,"convertQueuingStrategy");function D0(c,l){return ce(c,l),_=>D(c(_))}y(D0,"convertQueuingStrategySize");function O0(c,l){de(c,l);let _=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:_===void 0?void 0:P0(_,c,`${l} has member 'abort' that`),close:v===void 0?void 0:I0(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:F0(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:N0(W,c,`${l} has member 'write' that`),type:$}}y(O0,"convertUnderlyingSink");function P0(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(P0,"convertUnderlyingSinkAbortCallback");function I0(c,l,_){return ce(c,_),()=>x(c,l,[])}y(I0,"convertUnderlyingSinkCloseCallback");function F0(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(F0,"convertUnderlyingSinkStartCallback");function N0(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}y(N0,"convertUnderlyingSinkWriteCallback");function ep(c,l){if(!so(c))throw new TypeError(`${l} is not a WritableStream.`)}y(ep,"assertWritableStream");function M0(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}y(M0,"isAbortSignal");let eD=typeof AbortController=="function";function B0(){if(eD)return new AbortController}y(B0,"createAbortController");let U0=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=bi(_,"Second parameter"),I=O0(l,"First parameter");if(np(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=_i(v),W=Ho(v,1);tb(this,I,W,$)}get locked(){if(!so(this))throw Ai("locked");return io(this)}abort(l=void 0){return so(this)?io(this)?h(new TypeError("Cannot abort a stream that already has a writer")):Ci(this,l):h(Ai("abort"))}close(){return so(this)?io(this)?h(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?h(new TypeError("Cannot close an already-closing stream")):rp(this):h(Ai("close"))}getWriter(){if(!so(this))throw Ai("getWriter");return tp(this)}};y(U0,"WritableStream");let Dr=U0;Object.defineProperties(Dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Dr.prototype.abort,"abort"),i(Dr.prototype.close,"close"),i(Dr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function tp(c){return new Yn(c)}y(tp,"AcquireWritableStreamDefaultWriter");function j0(c,l,_,v,I=1,$=()=>1){let W=Object.create(Dr.prototype);np(W);let se=Object.create(zo.prototype);return cp(W,se,c,l,_,v,I,$),W}y(j0,"CreateWritableStream");function np(c){c._state="writable",c._storedError=void 0,c._writer=void 0,c._writableStreamController=void 0,c._writeRequests=new V,c._inFlightWriteRequest=void 0,c._closeRequest=void 0,c._inFlightCloseRequest=void 0,c._pendingAbortRequest=void 0,c._backpressure=!1}y(np,"InitializeWritableStream");function so(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Dr}y(so,"IsWritableStream");function io(c){return c._writer!==void 0}y(io,"IsWritableStreamLocked");function Ci(c,l){var _;if(c._state==="closed"||c._state==="errored")return p(void 0);c._writableStreamController._abortReason=l,(_=c._writableStreamController._abortController)===null||_===void 0||_.abort(l);let v=c._state;if(v==="closed"||v==="errored")return p(void 0);if(c._pendingAbortRequest!==void 0)return c._pendingAbortRequest._promise;let I=!1;v==="erroring"&&(I=!0,l=void 0);let $=f((W,se)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:se,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||nc(c,l),$}y(Ci,"WritableStreamAbort");function rp(c){let l=c._state;if(l==="closed"||l==="errored")return h(new TypeError(`The stream (in ${l} state) is not in the writable state and cannot be closed`));let _=f((I,$)=>{let W={_resolve:I,_reject:$};c._closeRequest=W}),v=c._writer;return v!==void 0&&c._backpressure&&l==="writable"&&lc(v),nb(c._writableStreamController),_}y(rp,"WritableStreamClose");function L0(c){return f((l,_)=>{let v={_resolve:l,_reject:_};c._writeRequests.push(v)})}y(L0,"WritableStreamAddWriteRequest");function tc(c,l){if(c._state==="writable"){nc(c,l);return}rc(c)}y(tc,"WritableStreamDealWithRejection");function nc(c,l){let _=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&sp(v,l),!W0(c)&&_._started&&rc(c)}y(nc,"WritableStreamStartErroring");function rc(c){c._state="errored",c._writableStreamController[ee]();let l=c._storedError;if(c._writeRequests.forEach(I=>{I._reject(l)}),c._writeRequests=new V,c._pendingAbortRequest===void 0){wi(c);return}let _=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,_._wasAlreadyErroring){_._reject(l),wi(c);return}let v=c._writableStreamController[j](_._reason);b(v,()=>(_._resolve(),wi(c),null),I=>(_._reject(I),wi(c),null))}y(rc,"WritableStreamFinishErroring");function $0(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}y($0,"WritableStreamFinishInFlightWrite");function q0(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,tc(c,l)}y(q0,"WritableStreamFinishInFlightWriteWithError");function H0(c){c._inFlightCloseRequest._resolve(void 0),c._inFlightCloseRequest=void 0,c._state==="erroring"&&(c._storedError=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._resolve(),c._pendingAbortRequest=void 0)),c._state="closed";let l=c._writer;l!==void 0&&fp(l)}y(H0,"WritableStreamFinishInFlightClose");function z0(c,l){c._inFlightCloseRequest._reject(l),c._inFlightCloseRequest=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._reject(l),c._pendingAbortRequest=void 0),tc(c,l)}y(z0,"WritableStreamFinishInFlightCloseWithError");function Xt(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}y(Xt,"WritableStreamCloseQueuedOrInFlight");function W0(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}y(W0,"WritableStreamHasOperationMarkedInFlight");function G0(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}y(G0,"WritableStreamMarkCloseRequestInFlight");function J0(c){c._inFlightWriteRequest=c._writeRequests.shift()}y(J0,"WritableStreamMarkFirstWriteRequestInFlight");function wi(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&cc(l,c._storedError)}y(wi,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function oc(c,l){let _=c._writer;_!==void 0&&l!==c._backpressure&&(l?ub(_):lc(_)),c._backpressure=l}y(oc,"WritableStreamUpdateBackpressure");let K0=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),ep(l,"First parameter"),io(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let _=l._state;if(_==="writable")!Xt(l)&&l._backpressure?vi(this):pp(this),Ei(this);else if(_==="erroring")uc(this,l._storedError),Ei(this);else if(_==="closed")pp(this),ab(this);else{let v=l._storedError;uc(this,v),dp(this,v)}}get closed(){return Or(this)?this._closedPromise:h(Pr("closed"))}get desiredSize(){if(!Or(this))throw Pr("desiredSize");if(this._ownerWritableStream===void 0)throw Go("desiredSize");return Q0(this)}get ready(){return Or(this)?this._readyPromise:h(Pr("ready"))}abort(l=void 0){return Or(this)?this._ownerWritableStream===void 0?h(Go("abort")):V0(this,l):h(Pr("abort"))}close(){if(!Or(this))return h(Pr("close"));let l=this._ownerWritableStream;return l===void 0?h(Go("close")):Xt(l)?h(new TypeError("Cannot close an already-closing stream")):op(this)}releaseLock(){if(!Or(this))throw Pr("releaseLock");this._ownerWritableStream!==void 0&&ip(this)}write(l=void 0){return Or(this)?this._ownerWritableStream===void 0?h(Go("write to")):ap(this,l):h(Pr("write"))}};y(K0,"WritableStreamDefaultWriter");let Yn=K0;Object.defineProperties(Yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(Yn.prototype.abort,"abort"),i(Yn.prototype.close,"close"),i(Yn.prototype.releaseLock,"releaseLock"),i(Yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Or(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof Yn}y(Or,"IsWritableStreamDefaultWriter");function V0(c,l){let _=c._ownerWritableStream;return Ci(_,l)}y(V0,"WritableStreamDefaultWriterAbort");function op(c){let l=c._ownerWritableStream;return rp(l)}y(op,"WritableStreamDefaultWriterClose");function Y0(c){let l=c._ownerWritableStream,_=l._state;return Xt(l)||_==="closed"?p(void 0):_==="errored"?h(l._storedError):op(c)}y(Y0,"WritableStreamDefaultWriterCloseWithErrorPropagation");function X0(c,l){c._closedPromiseState==="pending"?cc(c,l):cb(c,l)}y(X0,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function sp(c,l){c._readyPromiseState==="pending"?hp(c,l):lb(c,l)}y(sp,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function Q0(c){let l=c._ownerWritableStream,_=l._state;return _==="errored"||_==="erroring"?null:_==="closed"?0:up(l._writableStreamController)}y(Q0,"WritableStreamDefaultWriterGetDesiredSize");function ip(c){let l=c._ownerWritableStream,_=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");sp(c,_),X0(c,_),l._writer=void 0,c._ownerWritableStream=void 0}y(ip,"WritableStreamDefaultWriterRelease");function ap(c,l){let _=c._ownerWritableStream,v=_._writableStreamController,I=rb(v,l);if(_!==c._ownerWritableStream)return h(Go("write to"));let $=_._state;if($==="errored")return h(_._storedError);if(Xt(_)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(_._storedError);let W=L0(_);return ob(v,l,I),W}y(ap,"WritableStreamDefaultWriterWrite");let Z0={},eb=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!sc(this))throw ac("abortReason");return this._abortReason}get signal(){if(!sc(this))throw ac("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!sc(this))throw ac("error");this._controlledWritableStream._state==="writable"&&lp(this,l)}[j](l){let _=this._abortAlgorithm(l);return ki(this),_}[ee](){Kn(this)}};y(eb,"WritableStreamDefaultController");let zo=eb;Object.defineProperties(zo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function sc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof zo}y(sc,"IsWritableStreamDefaultController");function cp(c,l,_,v,I,$,W,se){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._abortReason=void 0,l._abortController=B0(),l._started=!1,l._strategySizeAlgorithm=se,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let le=ic(l);oc(c,le);let ge=_(),ke=p(ge);b(ke,()=>(l._started=!0,Si(l),null),Se=>(l._started=!0,tc(c,Se),null))}y(cp,"SetUpWritableStreamDefaultController");function tb(c,l,_,v){let I=Object.create(zo.prototype),$,W,se,le;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.write!==void 0?W=y(ge=>l.write(ge,I),"writeAlgorithm"):W=y(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?se=y(()=>l.close(),"closeAlgorithm"):se=y(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?le=y(ge=>l.abort(ge),"abortAlgorithm"):le=y(()=>p(void 0),"abortAlgorithm"),cp(c,I,$,W,se,le,_,v)}y(tb,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function ki(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(ki,"WritableStreamDefaultControllerClearAlgorithms");function nb(c){Ja(c,Z0,0),Si(c)}y(nb,"WritableStreamDefaultControllerClose");function rb(c,l){try{return c._strategySizeAlgorithm(l)}catch(_){return Wo(c,_),1}}y(rb,"WritableStreamDefaultControllerGetChunkSize");function up(c){return c._strategyHWM-c._queueTotalSize}y(up,"WritableStreamDefaultControllerGetDesiredSize");function ob(c,l,_){try{Ja(c,l,_)}catch(I){Wo(c,I);return}let v=c._controlledWritableStream;if(!Xt(v)&&v._state==="writable"){let I=ic(c);oc(v,I)}Si(c)}y(ob,"WritableStreamDefaultControllerWrite");function Si(c){let l=c._controlledWritableStream;if(!c._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){rc(l);return}if(c._queue.length===0)return;let _=f0(c);_===Z0?sb(c):ib(c,_)}y(Si,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function Wo(c,l){c._controlledWritableStream._state==="writable"&&lp(c,l)}y(Wo,"WritableStreamDefaultControllerErrorIfNeeded");function sb(c){let l=c._controlledWritableStream;G0(l),Ga(c);let _=c._closeAlgorithm();ki(c),b(_,()=>(H0(l),null),v=>(z0(l,v),null))}y(sb,"WritableStreamDefaultControllerProcessClose");function ib(c,l){let _=c._controlledWritableStream;J0(_);let v=c._writeAlgorithm(l);b(v,()=>{$0(_);let I=_._state;if(Ga(c),!Xt(_)&&I==="writable"){let $=ic(c);oc(_,$)}return Si(c),null},I=>(_._state==="writable"&&ki(c),q0(_,I),null))}y(ib,"WritableStreamDefaultControllerProcessWrite");function ic(c){return up(c)<=0}y(ic,"WritableStreamDefaultControllerGetBackpressure");function lp(c,l){let _=c._controlledWritableStream;ki(c),nc(_,l)}y(lp,"WritableStreamDefaultControllerError");function Ai(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}y(Ai,"streamBrandCheckException$2");function ac(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}y(ac,"defaultControllerBrandCheckException$2");function Pr(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}y(Pr,"defaultWriterBrandCheckException");function Go(c){return new TypeError("Cannot "+c+" a stream using a released writer")}y(Go,"defaultWriterLockException");function Ei(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_,c._closedPromiseState="pending"})}y(Ei,"defaultWriterClosedPromiseInitialize");function dp(c,l){Ei(c),cc(c,l)}y(dp,"defaultWriterClosedPromiseInitializeAsRejected");function ab(c){Ei(c),fp(c)}y(ab,"defaultWriterClosedPromiseInitializeAsResolved");function cc(c,l){c._closedPromise_reject!==void 0&&(A(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="rejected")}y(cc,"defaultWriterClosedPromiseReject");function cb(c,l){dp(c,l)}y(cb,"defaultWriterClosedPromiseResetToRejected");function fp(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="resolved")}y(fp,"defaultWriterClosedPromiseResolve");function vi(c){c._readyPromise=f((l,_)=>{c._readyPromise_resolve=l,c._readyPromise_reject=_}),c._readyPromiseState="pending"}y(vi,"defaultWriterReadyPromiseInitialize");function uc(c,l){vi(c),hp(c,l)}y(uc,"defaultWriterReadyPromiseInitializeAsRejected");function pp(c){vi(c),lc(c)}y(pp,"defaultWriterReadyPromiseInitializeAsResolved");function hp(c,l){c._readyPromise_reject!==void 0&&(A(c._readyPromise),c._readyPromise_reject(l),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="rejected")}y(hp,"defaultWriterReadyPromiseReject");function ub(c){vi(c)}y(ub,"defaultWriterReadyPromiseReset");function lb(c,l){uc(c,l)}y(lb,"defaultWriterReadyPromiseResetToRejected");function lc(c){c._readyPromise_resolve!==void 0&&(c._readyPromise_resolve(void 0),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="fulfilled")}y(lc,"defaultWriterReadyPromiseResolve");function db(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof mg<"u")return mg}y(db,"getGlobals");let tD=db();function fb(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}y(fb,"isDOMExceptionConstructor");function pb(){let c=tD?.DOMException;return fb(c)?c:void 0}y(pb,"getFromGlobal");function hb(){let c=y(function(l,_){this.message=l||"",this.name=_||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},"DOMException");return i(c,"DOMException"),c.prototype=Object.create(Error.prototype),Object.defineProperty(c.prototype,"constructor",{value:c,writable:!0,configurable:!0}),c}y(hb,"createPolyfill");let nD=pb()||hb();function gp(c,l,_,v,I,$){let W=U(c),se=tp(l);c._disturbed=!0;let le=!1,ge=p(void 0);return f((ke,Se)=>{let Be;if($!==void 0){if(Be=y(()=>{let fe=$.reason!==void 0?$.reason:new nD("Aborted","AbortError"),De=[];v||De.push(()=>l._state==="writable"?Ci(l,fe):p(void 0)),I||De.push(()=>c._state==="readable"?Ut(c,fe):p(void 0)),gt(()=>Promise.all(De.map(Me=>Me())),!0,fe)},"abortAlgorithm"),$.aborted){Be();return}$.addEventListener("abort",Be)}function Ct(){return f((fe,De)=>{function Me(mt){mt?fe():g(er(),Me,De)}y(Me,"next"),Me(!1)})}y(Ct,"pipeLoop");function er(){return le?p(!0):g(se._readyPromise,()=>f((fe,De)=>{ye(W,{_chunkSteps:y(Me=>{ge=g(ap(se,Me),void 0,r),fe(!1)},"_chunkSteps"),_closeSteps:y(()=>fe(!0),"_closeSteps"),_errorSteps:De})}))}if(y(er,"pipeStep"),jt(c,W._closedPromise,fe=>(v?wt(!0,fe):gt(()=>Ci(l,fe),!0,fe),null)),jt(l,se._closedPromise,fe=>(I?wt(!0,fe):gt(()=>Ut(c,fe),!0,fe),null)),tt(c,W._closedPromise,()=>(_?wt():gt(()=>Y0(se)),null)),Xt(l)||l._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");I?wt(!0,fe):gt(()=>Ut(c,fe),!0,fe)}A(Ct());function Qt(){let fe=ge;return g(ge,()=>fe!==ge?Qt():void 0)}y(Qt,"waitForWritesToFinish");function jt(fe,De,Me){fe._state==="errored"?Me(fe._storedError):w(De,Me)}y(jt,"isOrBecomesErrored");function tt(fe,De,Me){fe._state==="closed"?Me():m(De,Me)}y(tt,"isOrBecomesClosed");function gt(fe,De,Me){if(le)return;le=!0,l._state==="writable"&&!Xt(l)?m(Qt(),mt):mt();function mt(){return b(fe(),()=>tr(De,Me),Mr=>tr(!0,Mr)),null}y(mt,"doTheRest")}y(gt,"shutdownWithAction");function wt(fe,De){le||(le=!0,l._state==="writable"&&!Xt(l)?m(Qt(),()=>tr(fe,De)):tr(fe,De))}y(wt,"shutdown");function tr(fe,De){return ip(se),Te(W),$!==void 0&&$.removeEventListener("abort",Be),fe?Se(De):ke(void 0),null}y(tr,"finalize")})}y(gp,"ReadableStreamPipeTo");let gb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ti(this))throw Ri("desiredSize");return dc(this)}close(){if(!Ti(this))throw Ri("close");if(!co(this))throw new TypeError("The stream is not in a state that permits close");Ir(this)}enqueue(l=void 0){if(!Ti(this))throw Ri("enqueue");if(!co(this))throw new TypeError("The stream is not in a state that permits enqueue");return ao(this,l)}error(l=void 0){if(!Ti(this))throw Ri("error");Bt(this,l)}[z](l){Kn(this);let _=this._cancelAlgorithm(l);return xi(this),_}[te](l){let _=this._controlledReadableStream;if(this._queue.length>0){let v=Ga(this);this._closeRequested&&this._queue.length===0?(xi(this),Vo(_)):Jo(this),l._chunkSteps(v)}else B(_,l),Jo(this)}[Q](){}};y(gb,"ReadableStreamDefaultController");let Xn=gb;Object.defineProperties(Xn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Xn.prototype.close,"close"),i(Xn.prototype.enqueue,"enqueue"),i(Xn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ti(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof Xn}y(Ti,"IsReadableStreamDefaultController");function Jo(c){if(!mp(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();b(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Jo(c)),null),_=>(Bt(c,_),null))}y(Jo,"ReadableStreamDefaultControllerCallPullIfNeeded");function mp(c){let l=c._controlledReadableStream;return!co(c)||!c._started?!1:!!(Zn(l)&&ie(l)>0||dc(c)>0)}y(mp,"ReadableStreamDefaultControllerShouldCallPull");function xi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(xi,"ReadableStreamDefaultControllerClearAlgorithms");function Ir(c){if(!co(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(xi(c),Vo(l))}y(Ir,"ReadableStreamDefaultControllerClose");function ao(c,l){if(!co(c))return;let _=c._controlledReadableStream;if(Zn(_)&&ie(_)>0)K(_,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Bt(c,I),I}try{Ja(c,l,v)}catch(I){throw Bt(c,I),I}}Jo(c)}y(ao,"ReadableStreamDefaultControllerEnqueue");function Bt(c,l){let _=c._controlledReadableStream;_._state==="readable"&&(Kn(c),xi(c),Cp(_,l))}y(Bt,"ReadableStreamDefaultControllerError");function dc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(dc,"ReadableStreamDefaultControllerGetDesiredSize");function mb(c){return!mp(c)}y(mb,"ReadableStreamDefaultControllerHasBackpressure");function co(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}y(co,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function yp(c,l,_,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._started=!1,l._closeRequested=!1,l._pullAgain=!1,l._pulling=!1,l._strategySizeAlgorithm=W,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,c._readableStreamController=l;let se=_();b(p(se),()=>(l._started=!0,Jo(l),null),le=>(Bt(l,le),null))}y(yp,"SetUpReadableStreamDefaultController");function yb(c,l,_,v){let I=Object.create(Xn.prototype),$,W,se;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.pull!==void 0?W=y(()=>l.pull(I),"pullAlgorithm"):W=y(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?se=y(le=>l.cancel(le),"cancelAlgorithm"):se=y(()=>p(void 0),"cancelAlgorithm"),yp(c,I,$,W,se,_,v)}y(yb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function Ri(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}y(Ri,"defaultControllerBrandCheckException$1");function _b(c,l){return vr(c._readableStreamController)?Cb(c):bb(c)}y(_b,"ReadableStreamTee");function bb(c,l){let _=U(c),v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(tt=>{Se=tt});function Ct(){return v?(I=!0,p(void 0)):(v=!0,ye(_,{_chunkSteps:y(tt=>{k(()=>{I=!1;let gt=tt,wt=tt;$||ao(ge._readableStreamController,gt),W||ao(ke._readableStreamController,wt),v=!1,I&&Ct()})},"_chunkSteps"),_closeSteps:y(()=>{v=!1,$||Ir(ge._readableStreamController),W||Ir(ke._readableStreamController),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{v=!1},"_errorSteps")}),p(void 0))}y(Ct,"pullAlgorithm");function er(tt){if($=!0,se=tt,W){let gt=Lo([se,le]),wt=Ut(c,gt);Se(wt)}return Be}y(er,"cancel1Algorithm");function Qt(tt){if(W=!0,le=tt,$){let gt=Lo([se,le]),wt=Ut(c,gt);Se(wt)}return Be}y(Qt,"cancel2Algorithm");function jt(){}return y(jt,"startAlgorithm"),ge=Ko(jt,Ct,er),ke=Ko(jt,Ct,Qt),w(_._closedPromise,tt=>(Bt(ge._readableStreamController,tt),Bt(ke._readableStreamController,tt),(!$||!W)&&Se(void 0),null)),[ge,ke]}y(bb,"ReadableStreamDefaultTee");function Cb(c){let l=U(c),_=!1,v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(fe=>{Se=fe});function Ct(fe){w(fe._closedPromise,De=>(fe!==l||(Rt(ge._readableStreamController,De),Rt(ke._readableStreamController,De),(!$||!W)&&Se(void 0)),null))}y(Ct,"forwardReaderError");function er(){Rr(l)&&(Te(l),l=U(c),Ct(l)),ye(l,{_chunkSteps:y(fe=>{k(()=>{v=!1,I=!1;let De=fe,Me=fe;if(!$&&!W)try{Me=Mf(fe)}catch(mt){Rt(ge._readableStreamController,mt),Rt(ke._readableStreamController,mt),Se(Ut(c,mt));return}$||hi(ge._readableStreamController,De),W||hi(ke._readableStreamController,Me),_=!1,v?jt():I&&tt()})},"_chunkSteps"),_closeSteps:y(()=>{_=!1,$||$o(ge._readableStreamController),W||$o(ke._readableStreamController),ge._readableStreamController._pendingPullIntos.length>0&&gi(ge._readableStreamController,0),ke._readableStreamController._pendingPullIntos.length>0&&gi(ke._readableStreamController,0),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(er,"pullWithDefaultReader");function Qt(fe,De){he(l)&&(Te(l),l=Vf(c),Ct(l));let Me=De?ke:ge,mt=De?ge:ke;Qf(l,fe,1,{_chunkSteps:y(Mr=>{k(()=>{v=!1,I=!1;let Yo=De?W:$;if(De?$:W)Yo||mi(Me._readableStreamController,Mr);else{let Xo;try{Xo=Mf(Mr)}catch(Op){Rt(Me._readableStreamController,Op),Rt(mt._readableStreamController,Op),Se(Ut(c,Op));return}Yo||mi(Me._readableStreamController,Mr),hi(mt._readableStreamController,Xo)}_=!1,v?jt():I&&tt()})},"_chunkSteps"),_closeSteps:y(Mr=>{_=!1;let Yo=De?W:$,Xo=De?$:W;Yo||$o(Me._readableStreamController),Xo||$o(mt._readableStreamController),Mr!==void 0&&(Yo||mi(Me._readableStreamController,Mr),!Xo&&mt._readableStreamController._pendingPullIntos.length>0&&gi(mt._readableStreamController,0)),(!Yo||!Xo)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(Qt,"pullWithBYOBReader");function jt(){if(_)return v=!0,p(void 0);_=!0;let fe=Qa(ge._readableStreamController);return fe===null?er():Qt(fe._view,!1),p(void 0)}y(jt,"pull1Algorithm");function tt(){if(_)return I=!0,p(void 0);_=!0;let fe=Qa(ke._readableStreamController);return fe===null?er():Qt(fe._view,!0),p(void 0)}y(tt,"pull2Algorithm");function gt(fe){if($=!0,se=fe,W){let De=Lo([se,le]),Me=Ut(c,De);Se(Me)}return Be}y(gt,"cancel1Algorithm");function wt(fe){if(W=!0,le=fe,$){let De=Lo([se,le]),Me=Ut(c,De);Se(Me)}return Be}y(wt,"cancel2Algorithm");function tr(){}return y(tr,"startAlgorithm"),ge=bp(tr,jt,gt),ke=bp(tr,tt,wt),Ct(l),[ge,ke]}y(Cb,"ReadableByteStreamTee");function wb(c){return o(c)&&typeof c.getReader<"u"}y(wb,"isReadableStreamLike");function kb(c){return wb(c)?Ab(c.getReader()):Sb(c)}y(kb,"ReadableStreamFrom");function Sb(c){let l,_=Nf(c,"async"),v=r;function I(){let W;try{W=c0(_)}catch(le){return h(le)}let se=p(W);return C(se,le=>{if(!o(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(u0(le))Ir(l._readableStreamController);else{let ge=l0(le);ao(l._readableStreamController,ge)}})}y(I,"pullAlgorithm");function $(W){let se=_.iterator,le;try{le=di(se,"return")}catch(Se){return h(Se)}if(le===void 0)return p(void 0);let ge;try{ge=E(le,se,[W])}catch(Se){return h(Se)}let ke=p(ge);return C(ke,Se=>{if(!o(Se))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return y($,"cancelAlgorithm"),l=Ko(v,I,$,0),l}y(Sb,"ReadableStreamFromIterable");function Ab(c){let l,_=r;function v(){let $;try{$=c.read()}catch(W){return h(W)}return C($,W=>{if(!o(W))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Ir(l._readableStreamController);else{let se=W.value;ao(l._readableStreamController,se)}})}y(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return y(I,"cancelAlgorithm"),l=Ko(_,v,I,0),l}y(Ab,"ReadableStreamFromDefaultReader");function Eb(c,l){de(c,l);let _=c,v=_?.autoAllocateChunkSize,I=_?.cancel,$=_?.pull,W=_?.start,se=_?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:vb(I,_,`${l} has member 'cancel' that`),pull:$===void 0?void 0:Tb($,_,`${l} has member 'pull' that`),start:W===void 0?void 0:xb(W,_,`${l} has member 'start' that`),type:se===void 0?void 0:Rb(se,`${l} has member 'type' that`)}}y(Eb,"convertUnderlyingDefaultOrByteSource");function vb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(vb,"convertUnderlyingSourceCancelCallback");function Tb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(Tb,"convertUnderlyingSourcePullCallback");function xb(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(xb,"convertUnderlyingSourceStartCallback");function Rb(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}y(Rb,"convertReadableStreamType");function Db(c,l){return de(c,l),{preventCancel:!!c?.preventCancel}}y(Db,"convertIteratorOptions");function _p(c,l){de(c,l);let _=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&Ob($,`${l} has member 'signal' that`),{preventAbort:!!_,preventCancel:!!v,preventClose:!!I,signal:$}}y(_p,"convertPipeOptions");function Ob(c,l){if(!M0(c))throw new TypeError(`${l} is not an AbortSignal.`)}y(Ob,"assertAbortSignal");function Pb(c,l){de(c,l);let _=c?.readable;M(_,"readable","ReadableWritablePair"),N(_,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),ep(v,`${l} has member 'writable' that`),{readable:_,writable:v}}y(Pb,"convertReadableWritablePair");let Ib=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=bi(_,"Second parameter"),I=Eb(l,"First parameter");if(fc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=Ho(v,0);k0(this,I,$)}else{let $=_i(v),W=Ho(v,1);yb(this,I,W,$)}}get locked(){if(!Qn(this))throw Fr("locked");return Zn(this)}cancel(l=void 0){return Qn(this)?Zn(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):Ut(this,l):h(Fr("cancel"))}getReader(l=void 0){if(!Qn(this))throw Fr("getReader");return A0(l,"First parameter").mode===void 0?U(this):Vf(this)}pipeThrough(l,_={}){if(!Qn(this))throw Fr("pipeThrough");R(l,1,"pipeThrough");let v=Pb(l,"First parameter"),I=_p(_,"Second parameter");if(Zn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(io(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=gp(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return A($),v.readable}pipeTo(l,_={}){if(!Qn(this))return h(Fr("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!so(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=_p(_,"Second parameter")}catch(I){return h(I)}return Zn(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):io(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):gp(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!Qn(this))throw Fr("tee");let l=_b(this);return Lo(l)}values(l=void 0){if(!Qn(this))throw Fr("values");let _=Db(l,"First parameter");return ht(this,_.preventCancel)}[Ff](l){return this.values(l)}static from(l){return kb(l)}};y(Ib,"ReadableStream");let dt=Ib;Object.defineProperties(dt,{from:{enumerable:!0}}),Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(dt.from,"from"),i(dt.prototype.cancel,"cancel"),i(dt.prototype.getReader,"getReader"),i(dt.prototype.pipeThrough,"pipeThrough"),i(dt.prototype.pipeTo,"pipeTo"),i(dt.prototype.tee,"tee"),i(dt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(dt.prototype,Ff,{value:dt.prototype.values,writable:!0,configurable:!0});function Ko(c,l,_,v=1,I=()=>1){let $=Object.create(dt.prototype);fc($);let W=Object.create(Xn.prototype);return yp($,W,c,l,_,v,I),$}y(Ko,"CreateReadableStream");function bp(c,l,_){let v=Object.create(dt.prototype);fc(v);let I=Object.create(Vn.prototype);return Kf(v,I,c,l,_,0,void 0),v}y(bp,"CreateReadableByteStream");function fc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}y(fc,"InitializeReadableStream");function Qn(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof dt}y(Qn,"IsReadableStream");function Zn(c){return c._reader!==void 0}y(Zn,"IsReadableStreamLocked");function Ut(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);Vo(c);let _=c._reader;if(_!==void 0&&Rr(_)){let I=_._readIntoRequests;_._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return C(v,r)}y(Ut,"ReadableStreamCancel");function Vo(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),he(l))){let _=l._readRequests;l._readRequests=new V,_.forEach(v=>{v._closeSteps()})}}y(Vo,"ReadableStreamClose");function Cp(c,l){c._state="errored",c._storedError=l;let _=c._reader;_!==void 0&&(Ie(_,l),he(_)?Xe(_,l):Zf(_,l))}y(Cp,"ReadableStreamError");function Fr(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}y(Fr,"streamBrandCheckException$1");function wp(c,l){de(c,l);let _=c?.highWaterMark;return M(_,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(_)}}y(wp,"convertQueuingStrategyInit");let Fb=y(c=>c.byteLength,"byteLengthSizeFunction");i(Fb,"size");let Nb=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=wp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Sp(this))throw kp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Sp(this))throw kp("size");return Fb}};y(Nb,"ByteLengthQueuingStrategy");let pc=Nb;Object.defineProperties(pc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function kp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}y(kp,"byteLengthBrandCheckException");function Sp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof pc}y(Sp,"IsByteLengthQueuingStrategy");let Mb=y(()=>1,"countSizeFunction");i(Mb,"size");let Bb=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=wp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Ep(this))throw Ap("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Ep(this))throw Ap("size");return Mb}};y(Bb,"CountQueuingStrategy");let hc=Bb;Object.defineProperties(hc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Ap(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}y(Ap,"countBrandCheckException");function Ep(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof hc}y(Ep,"IsCountQueuingStrategy");function Ub(c,l){de(c,l);let _=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,se=c?.writableType;return{cancel:_===void 0?void 0:qb(_,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:jb(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:Lb($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:$b(W,c,`${l} has member 'transform' that`),writableType:se}}y(Ub,"convertTransformer");function jb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(jb,"convertTransformerFlushCallback");function Lb(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(Lb,"convertTransformerStartCallback");function $b(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}y($b,"convertTransformerTransformCallback");function qb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(qb,"convertTransformerCancelCallback");let Hb=class{constructor(l={},_={},v={}){l===void 0&&(l=null);let I=bi(_,"Second parameter"),$=bi(v,"Third parameter"),W=Ub(l,"First parameter");if(W.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(W.writableType!==void 0)throw new RangeError("Invalid writableType specified");let se=Ho($,0),le=_i($),ge=Ho(I,1),ke=_i(I),Se,Be=f(Ct=>{Se=Ct});zb(this,Be,ge,ke,se,le),Jb(this,W),W.start!==void 0?Se(W.start(this._transformStreamController)):Se(void 0)}get readable(){if(!vp(this))throw Dp("readable");return this._readable}get writable(){if(!vp(this))throw Dp("writable");return this._writable}};y(Hb,"TransformStream");let gc=Hb;Object.defineProperties(gc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function zb(c,l,_,v,I,$){function W(){return l}y(W,"startAlgorithm");function se(Be){return Yb(c,Be)}y(se,"writeAlgorithm");function le(Be){return Xb(c,Be)}y(le,"abortAlgorithm");function ge(){return Qb(c)}y(ge,"closeAlgorithm"),c._writable=j0(W,se,ge,le,_,v);function ke(){return Zb(c)}y(ke,"pullAlgorithm");function Se(Be){return eC(c,Be)}y(Se,"cancelAlgorithm"),c._readable=Ko(W,ke,Se,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Di(c,!0),c._transformStreamController=void 0}y(zb,"InitializeTransformStream");function vp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof gc}y(vp,"IsTransformStream");function Tp(c,l){Bt(c._readable._readableStreamController,l),mc(c,l)}y(Tp,"TransformStreamError");function mc(c,l){Pi(c._transformStreamController),Wo(c._writable._writableStreamController,l),yc(c)}y(mc,"TransformStreamErrorWritableAndUnblockWrite");function yc(c){c._backpressure&&Di(c,!1)}y(yc,"TransformStreamUnblockWrite");function Di(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(_=>{c._backpressureChangePromise_resolve=_}),c._backpressure=l}y(Di,"TransformStreamSetBackpressure");let Wb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Oi(this))throw Ii("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return dc(l)}enqueue(l=void 0){if(!Oi(this))throw Ii("enqueue");xp(this,l)}error(l=void 0){if(!Oi(this))throw Ii("error");Kb(this,l)}terminate(){if(!Oi(this))throw Ii("terminate");Vb(this)}};y(Wb,"TransformStreamDefaultController");let Nr=Wb;Object.defineProperties(Nr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Nr.prototype.enqueue,"enqueue"),i(Nr.prototype.error,"error"),i(Nr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Oi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Nr}y(Oi,"IsTransformStreamDefaultController");function Gb(c,l,_,v,I){l._controlledTransformStream=c,c._transformStreamController=l,l._transformAlgorithm=_,l._flushAlgorithm=v,l._cancelAlgorithm=I,l._finishPromise=void 0,l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}y(Gb,"SetUpTransformStreamDefaultController");function Jb(c,l){let _=Object.create(Nr.prototype),v,I,$;l.transform!==void 0?v=y(W=>l.transform(W,_),"transformAlgorithm"):v=y(W=>{try{return xp(_,W),p(void 0)}catch(se){return h(se)}},"transformAlgorithm"),l.flush!==void 0?I=y(()=>l.flush(_),"flushAlgorithm"):I=y(()=>p(void 0),"flushAlgorithm"),l.cancel!==void 0?$=y(W=>l.cancel(W),"cancelAlgorithm"):$=y(()=>p(void 0),"cancelAlgorithm"),Gb(c,_,v,I,$)}y(Jb,"SetUpTransformStreamDefaultControllerFromTransformer");function Pi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Pi,"TransformStreamDefaultControllerClearAlgorithms");function xp(c,l){let _=c._controlledTransformStream,v=_._readable._readableStreamController;if(!co(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{ao(v,l)}catch(I){throw mc(_,I),_._readable._storedError}mb(v)!==_._backpressure&&Di(_,!0)}y(xp,"TransformStreamDefaultControllerEnqueue");function Kb(c,l){Tp(c._controlledTransformStream,l)}y(Kb,"TransformStreamDefaultControllerError");function Rp(c,l){let _=c._transformAlgorithm(l);return C(_,void 0,v=>{throw Tp(c._controlledTransformStream,v),v})}y(Rp,"TransformStreamDefaultControllerPerformTransform");function Vb(c){let l=c._controlledTransformStream,_=l._readable._readableStreamController;Ir(_);let v=new TypeError("TransformStream terminated");mc(l,v)}y(Vb,"TransformStreamDefaultControllerTerminate");function Yb(c,l){let _=c._transformStreamController;if(c._backpressure){let v=c._backpressureChangePromise;return C(v,()=>{let I=c._writable;if(I._state==="erroring")throw I._storedError;return Rp(_,l)})}return Rp(_,l)}y(Yb,"TransformStreamDefaultSinkWriteAlgorithm");function Xb(c,l){let _=c._transformStreamController;if(_._finishPromise!==void 0)return _._finishPromise;let v=c._readable;_._finishPromise=f(($,W)=>{_._finishPromise_resolve=$,_._finishPromise_reject=W});let I=_._cancelAlgorithm(l);return Pi(_),b(I,()=>(v._state==="errored"?uo(_,v._storedError):(Bt(v._readableStreamController,l),_c(_)),null),$=>(Bt(v._readableStreamController,$),uo(_,$),null)),_._finishPromise}y(Xb,"TransformStreamDefaultSinkAbortAlgorithm");function Qb(c){let l=c._transformStreamController;if(l._finishPromise!==void 0)return l._finishPromise;let _=c._readable;l._finishPromise=f((I,$)=>{l._finishPromise_resolve=I,l._finishPromise_reject=$});let v=l._flushAlgorithm();return Pi(l),b(v,()=>(_._state==="errored"?uo(l,_._storedError):(Ir(_._readableStreamController),_c(l)),null),I=>(Bt(_._readableStreamController,I),uo(l,I),null)),l._finishPromise}y(Qb,"TransformStreamDefaultSinkCloseAlgorithm");function Zb(c){return Di(c,!1),c._backpressureChangePromise}y(Zb,"TransformStreamDefaultSourcePullAlgorithm");function eC(c,l){let _=c._transformStreamController;if(_._finishPromise!==void 0)return _._finishPromise;let v=c._writable;_._finishPromise=f(($,W)=>{_._finishPromise_resolve=$,_._finishPromise_reject=W});let I=_._cancelAlgorithm(l);return Pi(_),b(I,()=>(v._state==="errored"?uo(_,v._storedError):(Wo(v._writableStreamController,l),yc(c),_c(_)),null),$=>(Wo(v._writableStreamController,$),yc(c),uo(_,$),null)),_._finishPromise}y(eC,"TransformStreamDefaultSourceCancelAlgorithm");function Ii(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}y(Ii,"defaultControllerBrandCheckException");function _c(c){c._finishPromise_resolve!==void 0&&(c._finishPromise_resolve(),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}y(_c,"defaultControllerFinishPromiseResolve");function uo(c,l){c._finishPromise_reject!==void 0&&(A(c._finishPromise),c._finishPromise_reject(l),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}y(uo,"defaultControllerFinishPromiseReject");function Dp(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}y(Dp,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=pc,n.CountQueuingStrategy=hc,n.ReadableByteStreamController=Vn,n.ReadableStream=dt,n.ReadableStreamBYOBReader=xr,n.ReadableStreamBYOBRequest=ro,n.ReadableStreamDefaultController=Xn,n.ReadableStreamDefaultReader=me,n.TransformStream=gc,n.TransformStreamDefaultController=Nr,n.WritableStream=Dr,n.WritableStreamDefaultController=zo,n.WritableStreamDefaultWriter=Yn})})(Zu,Zu.exports)),Zu.exports}function tA(){if(eA)return QS;eA=1;let t=65536;if(!globalThis.ReadableStream)try{let e=re("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,re("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,fA())}try{let{Blob:e}=re("buffer");e&&!e.prototype.stream&&(e.prototype.stream=y(function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let i=await o.slice(r,Math.min(o.size,r+t)).arrayBuffer();r+=i.byteLength,s.enqueue(new Uint8Array(i)),r===o.size&&s.close()}})},"name"))}catch{}return QS}async function*el(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,nA),i=n.buffer.slice(r,r+s);r+=i.byteLength,yield new Uint8Array(i)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let s=await o.slice(r,Math.min(o.size,r+nA)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function hA(t,e=Do){var n=`${rA()}${rA()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
79
- Content-Disposition: form-data; name="`;return t.forEach((s,i)=>typeof s=="string"?r.push(o+kg(i)+`"\r
76
+ `;let u=(0,RF.parseProxyResponse)(o);o.write(`${a}\r
77
+ `);let{connect:d,buffered:f}=await u;if(e.emit("proxyConnect",d),this.emit("proxyConnect",d,e),d.statusCode===200)return e.once("socket",DF),n.secureEndpoint?(na("Upgrading socket connection to TLS"),LS.connect({...qS($S(n),"host","path","port"),socket:o})):o;o.destroy();let p=new zu.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{na("Replaying proxy buffer for failed request"),(0,EF.default)(h.listenerCount("data")>0),h.push(f),h.push(null)}),p}};Wu.protocols=["http","https"];zt.HttpsProxyAgent=Wu;function DF(t){t.resume()}function qS(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function mg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var OF,PF,gg,Gu=Br(()=>{OF=Object.defineProperty,PF=(t,e)=>OF(t,"name",{value:e,configurable:!0}),gg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};PF(mg,"getDefaultExportFromCjs")});var YS={};tC(YS,{toFormData:()=>VS});function KS(t){let e=t.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i);if(!e)return;let n=e[2]||e[3]||"",r=n.slice(n.lastIndexOf("\\")+1);return r=r.replace(/%22/g,'"'),r=r.replace(/&#(\d{4});/g,(o,s)=>String.fromCharCode(s)),r}async function VS(t,e){if(!/multipart/i.test(e))throw new TypeError("Failed to fetch");let n=e.match(/boundary=(?:"([^"]+)"|([^;]+))/i);if(!n)throw new TypeError("no or bad content-type header, no multipart boundary");let r=new UF(n[1]||n[2]),o,s,i,a,u,d,f=[],p=new vo,h=It(C=>{i+=w.decode(C,{stream:!0})},"onPartData"),g=It(C=>{f.push(C)},"appendToFile"),b=It(()=>{let C=new As(f,d,{type:u});p.append(a,C)},"appendFileToFormData"),m=It(()=>{p.append(a,i)},"appendEntryToFormData"),w=new TextDecoder("utf-8");w.decode(),r.onPartBegin=function(){r.onPartData=h,r.onPartEnd=m,o="",s="",i="",a="",u="",d=null,f.length=0},r.onHeaderField=function(C){o+=w.decode(C,{stream:!0})},r.onHeaderValue=function(C){s+=w.decode(C,{stream:!0})},r.onHeaderEnd=function(){if(s+=w.decode(),o=o.toLowerCase(),o==="content-disposition"){let C=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);C&&(a=C[2]||C[3]||""),d=KS(s),d&&(r.onPartData=g,r.onPartEnd=b)}else o==="content-type"&&(u=s);s="",o=""};for await(let C of t)r.write(C);return r.end(),p}var IF,It,In,Ue,GS,zr,Ju,Ku,FF,ra,NF,MF,BF,jF,Eo,JS,UF,XS=Br(()=>{Vu();Gu();IF=Object.defineProperty,It=(t,e)=>IF(t,"name",{value:e,configurable:!0}),In=0,Ue={START_BOUNDARY:In++,HEADER_FIELD_START:In++,HEADER_FIELD:In++,HEADER_VALUE_START:In++,HEADER_VALUE:In++,HEADER_VALUE_ALMOST_DONE:In++,HEADERS_ALMOST_DONE:In++,PART_DATA_START:In++,PART_DATA:In++,END:In++},GS=1,zr={PART_BOUNDARY:GS,LAST_BOUNDARY:GS*=2},Ju=10,Ku=13,FF=32,ra=45,NF=58,MF=97,BF=122,jF=It(t=>t|32,"lower"),Eo=It(()=>{},"noop"),JS=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Eo,this.onHeaderField=Eo,this.onHeadersEnd=Eo,this.onHeaderValue=Eo,this.onPartBegin=Eo,this.onPartData=Eo,this.onPartEnd=Eo,this.boundaryChars={},e=`\r
78
+ --`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=Ue.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:i,boundaryChars:a,index:u,state:d,flags:f}=this,p=this.boundary.length,h=p-1,g=e.length,b,m,w=It(E=>{this[E+"Mark"]=n},"mark"),C=It(E=>{delete this[E+"Mark"]},"clear"),S=It((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),k=It((E,x)=>{let O=E+"Mark";O in this&&(x?(S(E,this[O],n,e),delete this[O]):(S(E,this[O],e.length,e),this[O]=0))},"dataCallback");for(n=0;n<r;n++)switch(b=e[n],d){case Ue.START_BOUNDARY:if(u===i.length-2){if(b===ra)f|=zr.LAST_BOUNDARY;else if(b!==Ku)return;u++;break}else if(u-1===i.length-2){if(f&zr.LAST_BOUNDARY&&b===ra)d=Ue.END,f=0;else if(!(f&zr.LAST_BOUNDARY)&&b===Ju)u=0,S("onPartBegin"),d=Ue.HEADER_FIELD_START;else return;break}b!==i[u+2]&&(u=-2),b===i[u+2]&&u++;break;case Ue.HEADER_FIELD_START:d=Ue.HEADER_FIELD,w("onHeaderField"),u=0;case Ue.HEADER_FIELD:if(b===Ku){C("onHeaderField"),d=Ue.HEADERS_ALMOST_DONE;break}if(u++,b===ra)break;if(b===NF){if(u===1)return;k("onHeaderField",!0),d=Ue.HEADER_VALUE_START;break}if(m=jF(b),m<MF||m>BF)return;break;case Ue.HEADER_VALUE_START:if(b===FF)break;w("onHeaderValue"),d=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:b===Ku&&(k("onHeaderValue",!0),S("onHeaderEnd"),d=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(b!==Ju)return;d=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(b!==Ju)return;S("onHeadersEnd"),d=Ue.PART_DATA_START;break;case Ue.PART_DATA_START:d=Ue.PART_DATA,w("onPartData");case Ue.PART_DATA:if(o=u,u===0){for(n+=h;n<g&&!(e[n]in a);)n+=p;n-=h,b=e[n]}if(u<i.length)i[u]===b?(u===0&&k("onPartData",!0),u++):u=0;else if(u===i.length)u++,b===Ku?f|=zr.PART_BOUNDARY:b===ra?f|=zr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&zr.PART_BOUNDARY){if(u=0,b===Ju){f&=~zr.PART_BOUNDARY,S("onPartEnd"),S("onPartBegin"),d=Ue.HEADER_FIELD_START;break}}else f&zr.LAST_BOUNDARY&&b===ra?(S("onPartEnd"),d=Ue.END,f=0):u=0;if(u>0)s[u-1]=b;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);S("onPartData",0,o,E),o=0,w("onPartData"),n--}break;case Ue.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}k("onHeaderField"),k("onHeaderValue"),k("onPartData"),this.index=u,this.state=d,this.flags=f}end(){if(this.state===Ue.HEADER_FIELD_START&&this.index===0||this.state===Ue.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Ue.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};It(JS,"MultipartParser");UF=JS;It(KS,"_fileName");It(VS,"toFormData")});import la from"node:http";import $F from"node:https";import vs from"node:zlib";import Mn,{PassThrough as ol,pipeline as Ts}from"node:stream";import{Buffer as pt}from"node:buffer";import{types as sl,deprecate as il,promisify as qF}from"node:util";import{format as HF}from"node:url";import{isIP as zF}from"node:net";import{promises as WF,statSync as lA,createReadStream as GF}from"node:fs";import{basename as JF}from"node:path";function dA(t){if(!/^data:/i.test(t))throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');t=t.replace(/\r?\n/g,"");let e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");let n=t.substring(5,e).split(";"),r="",o=!1,s=n[0]||"text/plain",i=s;for(let f=1;f<n.length;f++)n[f]==="base64"?o=!0:n[f]&&(i+=`;${n[f]}`,n[f].indexOf("charset=")===0&&(r=n[f].substring(8)));!n[0]&&!r.length&&(i+=";charset=US-ASCII",r="US-ASCII");let a=o?"base64":"ascii",u=unescape(t.substring(e+1)),d=Buffer.from(u,a);return d.type=s,d.typeFull=i,d.charset=r,d}function fA(){return ZS||(ZS=1,(function(t,e){(function(n,r){r(e)})(KF,function(n){function r(){}y(r,"noop");function o(c){return typeof c=="object"&&c!==null||typeof c=="function"}y(o,"typeIsObject");let s=r;function i(c,l){try{Object.defineProperty(c,"name",{value:l,configurable:!0})}catch{}}y(i,"setFunctionName");let a=Promise,u=Promise.prototype.then,d=Promise.reject.bind(a);function f(c){return new a(c)}y(f,"newPromise");function p(c){return f(l=>l(c))}y(p,"promiseResolvedWith");function h(c){return d(c)}y(h,"promiseRejectedWith");function g(c,l,_){return u.call(c,l,_)}y(g,"PerformPromiseThen");function b(c,l,_){g(g(c,l,_),void 0,s)}y(b,"uponPromise");function m(c,l){b(c,l)}y(m,"uponFulfillment");function w(c,l){b(c,void 0,l)}y(w,"uponRejection");function C(c,l,_){return g(c,l,_)}y(C,"transformPromiseWith");function S(c){g(c,void 0,s)}y(S,"setPromiseIsHandledToTrue");let k=y(c=>{if(typeof queueMicrotask=="function")k=queueMicrotask;else{let l=p(void 0);k=y(_=>g(l,_),"_queueMicrotask")}return k(c)},"_queueMicrotask");function E(c,l,_){if(typeof c!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(c,l,_)}y(E,"reflectCall");function x(c,l,_){try{return p(E(c,l,_))}catch(v){return h(v)}}y(x,"promiseCall");let O=16384,q=class{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(l){let _=this._back,v=_;_._elements.length===O-1&&(v={_elements:[],_next:void 0}),_._elements.push(l),v!==_&&(this._back=v,_._next=v),++this._size}shift(){let l=this._front,_=l,v=this._cursor,I=v+1,$=l._elements,W=$[v];return I===O&&(_=l._next,I=0),--this._size,this._cursor=I,l!==_&&(this._front=_),$[v]=void 0,W}forEach(l){let _=this._cursor,v=this._front,I=v._elements;for(;(_!==I.length||v._next!==void 0)&&!(_===I.length&&(v=v._next,I=v._elements,_=0,I.length===0));)l(I[_]),++_}peek(){let l=this._front,_=this._cursor;return l._elements[_]}};y(q,"SimpleQueue");let V=q,U=Symbol("[[AbortSteps]]"),ee=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),te=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function _e(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ae(c):Z(c,l._storedError)}y(_e,"ReadableStreamReaderGenericInitialize");function Oe(c,l){let _=c._ownerReadableStream;return jt(_,l)}y(Oe,"ReadableStreamReaderGenericCancel");function Te(c){let l=c._ownerReadableStream;l._state==="readable"?Ie(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):we(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._readableStreamController[Q](),l._reader=void 0,c._ownerReadableStream=void 0}y(Te,"ReadableStreamReaderGenericRelease");function Ke(c){return new TypeError("Cannot "+c+" a stream using a released reader")}y(Ke,"readerLockException");function ne(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_})}y(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Ie(c,l)}y(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ae(c){ne(c),H(c)}y(ae,"defaultReaderClosedPromiseInitializeAsResolved");function Ie(c,l){c._closedPromise_reject!==void 0&&(S(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}y(Ie,"defaultReaderClosedPromiseReject");function we(c,l){Z(c,l)}y(we,"defaultReaderClosedPromiseResetToRejected");function H(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}y(H,"defaultReaderClosedPromiseResolve");let Ee=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},Ze=Math.trunc||function(c){return c<0?Math.ceil(c):Math.floor(c)};function X(c){return typeof c=="object"||typeof c=="function"}y(X,"isDictionary");function de(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}y(de,"assertDictionary");function ce(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}y(ce,"assertFunction");function A(c){return typeof c=="object"&&c!==null||typeof c=="function"}y(A,"isObject");function T(c,l){if(!A(c))throw new TypeError(`${l} is not an object.`)}y(T,"assertObject");function R(c,l,_){if(c===void 0)throw new TypeError(`Parameter ${l} is required in '${_}'.`)}y(R,"assertRequiredArgument");function M(c,l,_){if(c===void 0)throw new TypeError(`${l} is required in '${_}'.`)}y(M,"assertRequiredField");function D(c){return Number(c)}y(D,"convertUnrestrictedDouble");function F(c){return c===0?0:c}y(F,"censorNegativeZero");function L(c){return F(Ze(c))}y(L,"integerPart");function P(c,l){let _=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ee(v))throw new TypeError(`${l} is not a finite number`);if(v=L(v),v<0||v>_)throw new TypeError(`${l} is outside the accepted range of 0 to ${_}, inclusive`);return!Ee(v)||v===0?0:v}y(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!Qn(c))throw new TypeError(`${l} is not a ReadableStream.`)}y(N,"assertReadableStream");function j(c){return new me(c)}y(j,"AcquireReadableStreamDefaultReader");function B(c,l){c._reader._readRequests.push(l)}y(B,"ReadableStreamAddReadRequest");function K(c,l,_){let v=c._reader._readRequests.shift();_?v._closeSteps():v._chunkSteps(l)}y(K,"ReadableStreamFulfillReadRequest");function ie(c){return c._reader._readRequests.length}y(ie,"ReadableStreamGetNumReadRequests");function ue(c){let l=c._reader;return!(l===void 0||!he(l))}y(ue,"ReadableStreamHasDefaultReader");let be=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");_e(this,l),this._readRequests=new V}get closed(){return he(this)?this._closedPromise:h(mn("closed"))}cancel(l=void 0){return he(this)?this._ownerReadableStream===void 0?h(Ke("cancel")):Oe(this,l):h(mn("cancel"))}read(){if(!he(this))return h(mn("read"));if(this._ownerReadableStream===void 0)return h(Ke("read from"));let l,_,v=f((I,$)=>{l=I,_=$});return ye(this,{_chunkSteps:y(I=>l({value:I,done:!1}),"_chunkSteps"),_closeSteps:y(()=>l({value:void 0,done:!0}),"_closeSteps"),_errorSteps:y(I=>_(I),"_errorSteps")}),v}releaseLock(){if(!he(this))throw mn("releaseLock");this._ownerReadableStream!==void 0&&Fe(this)}};y(be,"ReadableStreamDefaultReader");let me=be;Object.defineProperties(me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(me.prototype.cancel,"cancel"),i(me.prototype.read,"read"),i(me.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(me.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function he(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof me}y(he,"IsReadableStreamDefaultReader");function ye(c,l){let _=c._ownerReadableStream;_._disturbed=!0,_._state==="closed"?l._closeSteps():_._state==="errored"?l._errorSteps(_._storedError):_._readableStreamController[te](l)}y(ye,"ReadableStreamDefaultReaderRead");function Fe(c){Te(c);let l=new TypeError("Reader was released");Xe(c,l)}y(Fe,"ReadableStreamDefaultReaderRelease");function Xe(c,l){let _=c._readRequests;c._readRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Xe,"ReadableStreamDefaultReaderErrorReadRequests");function mn(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}y(mn,"defaultReaderBrandCheckException");let li=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),Uo=class{constructor(l,_){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=_}next(){let l=y(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?C(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let _=y(()=>this._returnSteps(l),"returnSteps");return this._ongoingPromise?C(this._ongoingPromise,_,_):_()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,_,v,I=f(($,W)=>{_=$,v=W});return ye(l,{_chunkSteps:y($=>{this._ongoingPromise=void 0,k(()=>_({value:$,done:!1}))},"_chunkSteps"),_closeSteps:y(()=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),_({value:void 0,done:!0})},"_closeSteps"),_errorSteps:y($=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),v($)},"_errorSteps")}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let _=this._reader;if(!this._preventCancel){let v=Oe(_,l);return Te(_),C(v,()=>({value:l,done:!0}))}return Te(_),p({value:l,done:!0})}};y(Uo,"ReadableStreamAsyncIteratorImpl");let xt=Uo,Ar={next(){return et(this)?this._asyncIteratorImpl.next():h(je("next"))},return(c){return et(this)?this._asyncIteratorImpl.return(c):h(je("return"))}};Object.setPrototypeOf(Ar,li);function ht(c,l){let _=j(c),v=new xt(_,l),I=Object.create(Ar);return I._asyncIteratorImpl=v,I}y(ht,"AcquireReadableStreamAsyncIterator");function et(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof xt}catch{return!1}}y(et,"IsReadableStreamAsyncIterator");function je(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}y(je,"streamAsyncIteratorBrandCheckException");let i0=Number.isNaN||function(c){return c!==c};var xf,Rf,Df;function Lo(c){return c.slice()}y(Lo,"CreateArrayFromList");function Of(c,l,_,v,I){new Uint8Array(c).set(new Uint8Array(_,v,I),l)}y(Of,"CopyDataBlockBytes");let Jn=y(c=>(typeof c.transfer=="function"?Jn=y(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Jn=y(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):Jn=y(l=>l,"TransferArrayBuffer"),Jn(c)),"TransferArrayBuffer"),Er=y(c=>(typeof c.detached=="boolean"?Er=y(l=>l.detached,"IsDetachedBuffer"):Er=y(l=>l.byteLength===0,"IsDetachedBuffer"),Er(c)),"IsDetachedBuffer");function Pf(c,l,_){if(c.slice)return c.slice(l,_);let v=_-l,I=new ArrayBuffer(v);return Of(I,0,c,l,v),I}y(Pf,"ArrayBufferSlice");function di(c,l){let _=c[l];if(_!=null){if(typeof _!="function")throw new TypeError(`${String(l)} is not a function`);return _}}y(di,"GetMethod");function a0(c){let l={[Symbol.iterator]:()=>c.iterator},_=(async function*(){return yield*l})(),v=_.next;return{iterator:_,nextMethod:v,done:!1}}y(a0,"CreateAsyncFromSyncIterator");let If=(Df=(xf=Symbol.asyncIterator)!==null&&xf!==void 0?xf:(Rf=Symbol.for)===null||Rf===void 0?void 0:Rf.call(Symbol,"Symbol.asyncIterator"))!==null&&Df!==void 0?Df:"@@asyncIterator";function Ff(c,l="sync",_){if(_===void 0)if(l==="async"){if(_=di(c,If),_===void 0){let $=di(c,Symbol.iterator),W=Ff(c,"sync",$);return a0(W)}}else _=di(c,Symbol.iterator);if(_===void 0)throw new TypeError("The object is not iterable");let v=E(_,c,[]);if(!o(v))throw new TypeError("The iterator method must return an object");let I=v.next;return{iterator:v,nextMethod:I,done:!1}}y(Ff,"GetIterator");function c0(c){let l=E(c.nextMethod,c.iterator,[]);if(!o(l))throw new TypeError("The iterator.next() method must return an object");return l}y(c0,"IteratorNext");function u0(c){return!!c.done}y(u0,"IteratorComplete");function l0(c){return c.value}y(l0,"IteratorValue");function d0(c){return!(typeof c!="number"||i0(c)||c<0)}y(d0,"IsNonNegativeNumber");function Nf(c){let l=Pf(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}y(Nf,"CloneAsUint8Array");function Ga(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}y(Ga,"DequeueValue");function Ja(c,l,_){if(!d0(_)||_===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:_}),c._queueTotalSize+=_}y(Ja,"EnqueueValueWithSize");function f0(c){return c._queue.peek().value}y(f0,"PeekQueueValue");function Kn(c){c._queue=new V,c._queueTotalSize=0}y(Kn,"ResetQueue");function Mf(c){return c===DataView}y(Mf,"isDataViewConstructor");function p0(c){return Mf(c.constructor)}y(p0,"isDataView");function h0(c){return Mf(c)?1:c.BYTES_PER_ELEMENT}y(h0,"arrayBufferViewElementSize");let g0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ka(this))throw Za("view");return this._view}respond(l){if(!Ka(this))throw Za("respond");if(R(l,1,"respond"),l=P(l,"First parameter"),this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");gi(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!Ka(this))throw Za("respondWithNewView");if(R(l,1,"respondWithNewView"),!ArrayBuffer.isView(l))throw new TypeError("You can only respond with array buffer views");if(this._associatedReadableByteStreamController===void 0)throw new TypeError("This BYOB request has been invalidated");if(Er(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");mi(this._associatedReadableByteStreamController,l)}};y(g0,"ReadableStreamBYOBRequest");let ro=g0;Object.defineProperties(ro.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(ro.prototype.respond,"respond"),i(ro.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ro.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let m0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!vr(this))throw qo("byobRequest");return Qa(this)}get desiredSize(){if(!vr(this))throw qo("desiredSize");return Gf(this)}close(){if(!vr(this))throw qo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw new TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);$o(this)}enqueue(l){if(!vr(this))throw qo("enqueue");if(R(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let _=this._controlledReadableByteStream._state;if(_!=="readable")throw new TypeError(`The stream (in ${_} state) is not in the readable state and cannot be enqueued to`);hi(this,l)}error(l=void 0){if(!vr(this))throw qo("error");Rt(this,l)}[z](l){Bf(this),Kn(this);let _=this._cancelAlgorithm(l);return pi(this),_}[te](l){let _=this._controlledReadableByteStream;if(this._queueTotalSize>0){Wf(this,l);return}let v=this._autoAllocateChunkSize;if(v!==void 0){let I;try{I=new ArrayBuffer(v)}catch(W){l._errorSteps(W);return}let $={buffer:I,bufferByteLength:v,byteOffset:0,byteLength:v,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push($)}B(_,l),Tr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};y(m0,"ReadableByteStreamController");let Vn=m0;Object.defineProperties(Vn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Vn.prototype.close,"close"),i(Vn.prototype.enqueue,"enqueue"),i(Vn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Vn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function vr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof Vn}y(vr,"IsReadableByteStreamController");function Ka(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof ro}y(Ka,"IsReadableStreamBYOBRequest");function Tr(c){if(!w0(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();b(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Tr(c)),null),_=>(Rt(c,_),null))}y(Tr,"ReadableByteStreamControllerCallPullIfNeeded");function Bf(c){Ya(c),c._pendingPullIntos=new V}y(Bf,"ReadableByteStreamControllerClearPendingPullIntos");function Va(c,l){let _=!1;c._state==="closed"&&(_=!0);let v=jf(l);l.readerType==="default"?K(c,v,_):T0(c,v,_)}y(Va,"ReadableByteStreamControllerCommitPullIntoDescriptor");function jf(c){let l=c.bytesFilled,_=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/_)}y(jf,"ReadableByteStreamControllerConvertPullIntoDescriptor");function fi(c,l,_,v){c._queue.push({buffer:l,byteOffset:_,byteLength:v}),c._queueTotalSize+=v}y(fi,"ReadableByteStreamControllerEnqueueChunkToQueue");function Uf(c,l,_,v){let I;try{I=Pf(l,_,_+v)}catch($){throw Rt(c,$),$}fi(c,I,0,v)}y(Uf,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function Lf(c,l){l.bytesFilled>0&&Uf(c,l.buffer,l.byteOffset,l.bytesFilled),oo(c)}y(Lf,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function $f(c,l){let _=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+_,I=_,$=!1,W=v%l.elementSize,se=v-W;se>=l.minimumFill&&(I=se-l.bytesFilled,$=!0);let le=c._queue;for(;I>0;){let ge=le.peek(),ke=Math.min(I,ge.byteLength),Se=l.byteOffset+l.bytesFilled;Of(l.buffer,Se,ge.buffer,ge.byteOffset,ke),ge.byteLength===ke?le.shift():(ge.byteOffset+=ke,ge.byteLength-=ke),c._queueTotalSize-=ke,qf(c,ke,l),I-=ke}return $}y($f,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function qf(c,l,_){_.bytesFilled+=l}y(qf,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function Hf(c){c._queueTotalSize===0&&c._closeRequested?(pi(c),Vo(c._controlledReadableByteStream)):Tr(c)}y(Hf,"ReadableByteStreamControllerHandleQueueDrain");function Ya(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}y(Ya,"ReadableByteStreamControllerInvalidateBYOBRequest");function Xa(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();$f(c,l)&&(oo(c),Va(c._controlledReadableByteStream,l))}}y(Xa,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function y0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let _=l._readRequests.shift();Wf(c,_)}}y(y0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function _0(c,l,_,v){let I=c._controlledReadableByteStream,$=l.constructor,W=h0($),{byteOffset:se,byteLength:le}=l,ge=_*W,ke;try{ke=Jn(l.buffer)}catch(Be){v._errorSteps(Be);return}let Se={buffer:ke,bufferByteLength:ke.byteLength,byteOffset:se,byteLength:le,bytesFilled:0,minimumFill:ge,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(Se),Vf(I,v);return}if(I._state==="closed"){let Be=new $(Se.buffer,Se.byteOffset,0);v._closeSteps(Be);return}if(c._queueTotalSize>0){if($f(c,Se)){let Be=jf(Se);Hf(c),v._chunkSteps(Be);return}if(c._closeRequested){let Be=new TypeError("Insufficient bytes to fill elements in the given buffer");Rt(c,Be),v._errorSteps(Be);return}}c._pendingPullIntos.push(Se),Vf(I,v),Tr(c)}y(_0,"ReadableByteStreamControllerPullInto");function b0(c,l){l.readerType==="none"&&oo(c);let _=c._controlledReadableByteStream;if(ec(_))for(;Yf(_)>0;){let v=oo(c);Va(_,v)}}y(b0,"ReadableByteStreamControllerRespondInClosedState");function C0(c,l,_){if(qf(c,l,_),_.readerType==="none"){Lf(c,_),Xa(c);return}if(_.bytesFilled<_.minimumFill)return;oo(c);let v=_.bytesFilled%_.elementSize;if(v>0){let I=_.byteOffset+_.bytesFilled;Uf(c,_.buffer,I-v,v)}_.bytesFilled-=v,Va(c._controlledReadableByteStream,_),Xa(c)}y(C0,"ReadableByteStreamControllerRespondInReadableState");function zf(c,l){let _=c._pendingPullIntos.peek();Ya(c),c._controlledReadableByteStream._state==="closed"?b0(c,_):C0(c,l,_),Tr(c)}y(zf,"ReadableByteStreamControllerRespondInternal");function oo(c){return c._pendingPullIntos.shift()}y(oo,"ReadableByteStreamControllerShiftPendingPullInto");function w0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ue(l)&&ie(l)>0||ec(l)&&Yf(l)>0||Gf(c)>0)}y(w0,"ReadableByteStreamControllerShouldCallPull");function pi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}y(pi,"ReadableByteStreamControllerClearAlgorithms");function $o(c){let l=c._controlledReadableByteStream;if(!(c._closeRequested||l._state!=="readable")){if(c._queueTotalSize>0){c._closeRequested=!0;return}if(c._pendingPullIntos.length>0){let _=c._pendingPullIntos.peek();if(_.bytesFilled%_.elementSize!==0){let v=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Rt(c,v),v}}pi(c),Vo(l)}}y($o,"ReadableByteStreamControllerClose");function hi(c,l){let _=c._controlledReadableByteStream;if(c._closeRequested||_._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Er(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=Jn(v);if(c._pendingPullIntos.length>0){let se=c._pendingPullIntos.peek();if(Er(se.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ya(c),se.buffer=Jn(se.buffer),se.readerType==="none"&&Lf(c,se)}if(ue(_))if(y0(c),ie(_)===0)fi(c,W,I,$);else{c._pendingPullIntos.length>0&&oo(c);let se=new Uint8Array(W,I,$);K(_,se,!1)}else ec(_)?(fi(c,W,I,$),Xa(c)):fi(c,W,I,$);Tr(c)}y(hi,"ReadableByteStreamControllerEnqueue");function Rt(c,l){let _=c._controlledReadableByteStream;_._state==="readable"&&(Bf(c),Kn(c),pi(c),bp(_,l))}y(Rt,"ReadableByteStreamControllerError");function Wf(c,l){let _=c._queue.shift();c._queueTotalSize-=_.byteLength,Hf(c);let v=new Uint8Array(_.buffer,_.byteOffset,_.byteLength);l._chunkSteps(v)}y(Wf,"ReadableByteStreamControllerFillReadRequestFromQueue");function Qa(c){if(c._byobRequest===null&&c._pendingPullIntos.length>0){let l=c._pendingPullIntos.peek(),_=new Uint8Array(l.buffer,l.byteOffset+l.bytesFilled,l.byteLength-l.bytesFilled),v=Object.create(ro.prototype);S0(v,c,_),c._byobRequest=v}return c._byobRequest}y(Qa,"ReadableByteStreamControllerGetBYOBRequest");function Gf(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Gf,"ReadableByteStreamControllerGetDesiredSize");function gi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(l===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(_.bytesFilled+l>_.byteLength)throw new RangeError("bytesWritten out of range")}_.buffer=Jn(_.buffer),zf(c,l)}y(gi,"ReadableByteStreamControllerRespond");function mi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(l.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(_.byteOffset+_.bytesFilled!==l.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(_.bufferByteLength!==l.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(_.bytesFilled+l.byteLength>_.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let v=l.byteLength;_.buffer=Jn(l.buffer),zf(c,v)}y(mi,"ReadableByteStreamControllerRespondWithNewView");function Jf(c,l,_,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,Kn(l),l._closeRequested=!1,l._started=!1,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,l._autoAllocateChunkSize=W,l._pendingPullIntos=new V,c._readableStreamController=l;let se=_();b(p(se),()=>(l._started=!0,Tr(l),null),le=>(Rt(l,le),null))}y(Jf,"SetUpReadableByteStreamController");function k0(c,l,_){let v=Object.create(Vn.prototype),I,$,W;l.start!==void 0?I=y(()=>l.start(v),"startAlgorithm"):I=y(()=>{},"startAlgorithm"),l.pull!==void 0?$=y(()=>l.pull(v),"pullAlgorithm"):$=y(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?W=y(le=>l.cancel(le),"cancelAlgorithm"):W=y(()=>p(void 0),"cancelAlgorithm");let se=l.autoAllocateChunkSize;if(se===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Jf(c,v,I,$,W,_,se)}y(k0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function S0(c,l,_){c._associatedReadableByteStreamController=l,c._view=_}y(S0,"SetUpReadableStreamBYOBRequest");function Za(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}y(Za,"byobRequestBrandCheckException");function qo(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}y(qo,"byteStreamControllerBrandCheckException");function A0(c,l){de(c,l);let _=c?.mode;return{mode:_===void 0?void 0:E0(_,`${l} has member 'mode' that`)}}y(A0,"convertReaderOptions");function E0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}y(E0,"convertReadableStreamReaderMode");function v0(c,l){var _;de(c,l);let v=(_=c?.min)!==null&&_!==void 0?_:1;return{min:P(v,`${l} has member 'min' that`)}}y(v0,"convertByobReadOptions");function Kf(c){return new xr(c)}y(Kf,"AcquireReadableStreamBYOBReader");function Vf(c,l){c._reader._readIntoRequests.push(l)}y(Vf,"ReadableStreamAddReadIntoRequest");function T0(c,l,_){let v=c._reader._readIntoRequests.shift();_?v._closeSteps(l):v._chunkSteps(l)}y(T0,"ReadableStreamFulfillReadIntoRequest");function Yf(c){return c._reader._readIntoRequests.length}y(Yf,"ReadableStreamGetNumReadIntoRequests");function ec(c){let l=c._reader;return!(l===void 0||!Rr(l))}y(ec,"ReadableStreamHasBYOBReader");let x0=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!vr(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");_e(this,l),this._readIntoRequests=new V}get closed(){return Rr(this)?this._closedPromise:h(yi("closed"))}cancel(l=void 0){return Rr(this)?this._ownerReadableStream===void 0?h(Ke("cancel")):Oe(this,l):h(yi("cancel"))}read(l,_={}){if(!Rr(this))return h(yi("read"));if(!ArrayBuffer.isView(l))return h(new TypeError("view must be an array buffer view"));if(l.byteLength===0)return h(new TypeError("view must have non-zero byteLength"));if(l.buffer.byteLength===0)return h(new TypeError("view's buffer must have non-zero byteLength"));if(Er(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=v0(_,"options")}catch(le){return h(le)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(p0(l)){if(I>l.byteLength)return h(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(I>l.length)return h(new RangeError("options.min must be less than or equal to view's length"));if(this._ownerReadableStream===void 0)return h(Ke("read from"));let $,W,se=f((le,ge)=>{$=le,W=ge});return Xf(this,l,I,{_chunkSteps:y(le=>$({value:le,done:!1}),"_chunkSteps"),_closeSteps:y(le=>$({value:le,done:!0}),"_closeSteps"),_errorSteps:y(le=>W(le),"_errorSteps")}),se}releaseLock(){if(!Rr(this))throw yi("releaseLock");this._ownerReadableStream!==void 0&&R0(this)}};y(x0,"ReadableStreamBYOBReader");let xr=x0;Object.defineProperties(xr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(xr.prototype.cancel,"cancel"),i(xr.prototype.read,"read"),i(xr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(xr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Rr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof xr}y(Rr,"IsReadableStreamBYOBReader");function Xf(c,l,_,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):_0(I._readableStreamController,l,_,v)}y(Xf,"ReadableStreamBYOBReaderRead");function R0(c){Te(c);let l=new TypeError("Reader was released");Qf(c,l)}y(R0,"ReadableStreamBYOBReaderRelease");function Qf(c,l){let _=c._readIntoRequests;c._readIntoRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Qf,"ReadableStreamBYOBReaderErrorReadIntoRequests");function yi(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}y(yi,"byobReaderBrandCheckException");function Ho(c,l){let{highWaterMark:_}=c;if(_===void 0)return l;if(i0(_)||_<0)throw new RangeError("Invalid highWaterMark");return _}y(Ho,"ExtractHighWaterMark");function _i(c){let{size:l}=c;return l||(()=>1)}y(_i,"ExtractSizeAlgorithm");function bi(c,l){de(c,l);let _=c?.highWaterMark,v=c?.size;return{highWaterMark:_===void 0?void 0:D(_),size:v===void 0?void 0:D0(v,`${l} has member 'size' that`)}}y(bi,"convertQueuingStrategy");function D0(c,l){return ce(c,l),_=>D(c(_))}y(D0,"convertQueuingStrategySize");function O0(c,l){de(c,l);let _=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:_===void 0?void 0:P0(_,c,`${l} has member 'abort' that`),close:v===void 0?void 0:I0(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:F0(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:N0(W,c,`${l} has member 'write' that`),type:$}}y(O0,"convertUnderlyingSink");function P0(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(P0,"convertUnderlyingSinkAbortCallback");function I0(c,l,_){return ce(c,_),()=>x(c,l,[])}y(I0,"convertUnderlyingSinkCloseCallback");function F0(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(F0,"convertUnderlyingSinkStartCallback");function N0(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}y(N0,"convertUnderlyingSinkWriteCallback");function Zf(c,l){if(!so(c))throw new TypeError(`${l} is not a WritableStream.`)}y(Zf,"assertWritableStream");function M0(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}y(M0,"isAbortSignal");let tD=typeof AbortController=="function";function B0(){if(tD)return new AbortController}y(B0,"createAbortController");let j0=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=bi(_,"Second parameter"),I=O0(l,"First parameter");if(tp(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=_i(v),W=Ho(v,1);tb(this,I,W,$)}get locked(){if(!so(this))throw Ai("locked");return io(this)}abort(l=void 0){return so(this)?io(this)?h(new TypeError("Cannot abort a stream that already has a writer")):Ci(this,l):h(Ai("abort"))}close(){return so(this)?io(this)?h(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?h(new TypeError("Cannot close an already-closing stream")):np(this):h(Ai("close"))}getWriter(){if(!so(this))throw Ai("getWriter");return ep(this)}};y(j0,"WritableStream");let Dr=j0;Object.defineProperties(Dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Dr.prototype.abort,"abort"),i(Dr.prototype.close,"close"),i(Dr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function ep(c){return new Yn(c)}y(ep,"AcquireWritableStreamDefaultWriter");function U0(c,l,_,v,I=1,$=()=>1){let W=Object.create(Dr.prototype);tp(W);let se=Object.create(zo.prototype);return ap(W,se,c,l,_,v,I,$),W}y(U0,"CreateWritableStream");function tp(c){c._state="writable",c._storedError=void 0,c._writer=void 0,c._writableStreamController=void 0,c._writeRequests=new V,c._inFlightWriteRequest=void 0,c._closeRequest=void 0,c._inFlightCloseRequest=void 0,c._pendingAbortRequest=void 0,c._backpressure=!1}y(tp,"InitializeWritableStream");function so(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Dr}y(so,"IsWritableStream");function io(c){return c._writer!==void 0}y(io,"IsWritableStreamLocked");function Ci(c,l){var _;if(c._state==="closed"||c._state==="errored")return p(void 0);c._writableStreamController._abortReason=l,(_=c._writableStreamController._abortController)===null||_===void 0||_.abort(l);let v=c._state;if(v==="closed"||v==="errored")return p(void 0);if(c._pendingAbortRequest!==void 0)return c._pendingAbortRequest._promise;let I=!1;v==="erroring"&&(I=!0,l=void 0);let $=f((W,se)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:se,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||nc(c,l),$}y(Ci,"WritableStreamAbort");function np(c){let l=c._state;if(l==="closed"||l==="errored")return h(new TypeError(`The stream (in ${l} state) is not in the writable state and cannot be closed`));let _=f((I,$)=>{let W={_resolve:I,_reject:$};c._closeRequest=W}),v=c._writer;return v!==void 0&&c._backpressure&&l==="writable"&&lc(v),nb(c._writableStreamController),_}y(np,"WritableStreamClose");function L0(c){return f((l,_)=>{let v={_resolve:l,_reject:_};c._writeRequests.push(v)})}y(L0,"WritableStreamAddWriteRequest");function tc(c,l){if(c._state==="writable"){nc(c,l);return}rc(c)}y(tc,"WritableStreamDealWithRejection");function nc(c,l){let _=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&op(v,l),!W0(c)&&_._started&&rc(c)}y(nc,"WritableStreamStartErroring");function rc(c){c._state="errored",c._writableStreamController[ee]();let l=c._storedError;if(c._writeRequests.forEach(I=>{I._reject(l)}),c._writeRequests=new V,c._pendingAbortRequest===void 0){wi(c);return}let _=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,_._wasAlreadyErroring){_._reject(l),wi(c);return}let v=c._writableStreamController[U](_._reason);b(v,()=>(_._resolve(),wi(c),null),I=>(_._reject(I),wi(c),null))}y(rc,"WritableStreamFinishErroring");function $0(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}y($0,"WritableStreamFinishInFlightWrite");function q0(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,tc(c,l)}y(q0,"WritableStreamFinishInFlightWriteWithError");function H0(c){c._inFlightCloseRequest._resolve(void 0),c._inFlightCloseRequest=void 0,c._state==="erroring"&&(c._storedError=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._resolve(),c._pendingAbortRequest=void 0)),c._state="closed";let l=c._writer;l!==void 0&&dp(l)}y(H0,"WritableStreamFinishInFlightClose");function z0(c,l){c._inFlightCloseRequest._reject(l),c._inFlightCloseRequest=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._reject(l),c._pendingAbortRequest=void 0),tc(c,l)}y(z0,"WritableStreamFinishInFlightCloseWithError");function Xt(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}y(Xt,"WritableStreamCloseQueuedOrInFlight");function W0(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}y(W0,"WritableStreamHasOperationMarkedInFlight");function G0(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}y(G0,"WritableStreamMarkCloseRequestInFlight");function J0(c){c._inFlightWriteRequest=c._writeRequests.shift()}y(J0,"WritableStreamMarkFirstWriteRequestInFlight");function wi(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&cc(l,c._storedError)}y(wi,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function oc(c,l){let _=c._writer;_!==void 0&&l!==c._backpressure&&(l?ub(_):lc(_)),c._backpressure=l}y(oc,"WritableStreamUpdateBackpressure");let K0=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Zf(l,"First parameter"),io(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let _=l._state;if(_==="writable")!Xt(l)&&l._backpressure?vi(this):fp(this),Ei(this);else if(_==="erroring")uc(this,l._storedError),Ei(this);else if(_==="closed")fp(this),ab(this);else{let v=l._storedError;uc(this,v),lp(this,v)}}get closed(){return Or(this)?this._closedPromise:h(Pr("closed"))}get desiredSize(){if(!Or(this))throw Pr("desiredSize");if(this._ownerWritableStream===void 0)throw Go("desiredSize");return Q0(this)}get ready(){return Or(this)?this._readyPromise:h(Pr("ready"))}abort(l=void 0){return Or(this)?this._ownerWritableStream===void 0?h(Go("abort")):V0(this,l):h(Pr("abort"))}close(){if(!Or(this))return h(Pr("close"));let l=this._ownerWritableStream;return l===void 0?h(Go("close")):Xt(l)?h(new TypeError("Cannot close an already-closing stream")):rp(this)}releaseLock(){if(!Or(this))throw Pr("releaseLock");this._ownerWritableStream!==void 0&&sp(this)}write(l=void 0){return Or(this)?this._ownerWritableStream===void 0?h(Go("write to")):ip(this,l):h(Pr("write"))}};y(K0,"WritableStreamDefaultWriter");let Yn=K0;Object.defineProperties(Yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(Yn.prototype.abort,"abort"),i(Yn.prototype.close,"close"),i(Yn.prototype.releaseLock,"releaseLock"),i(Yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Or(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof Yn}y(Or,"IsWritableStreamDefaultWriter");function V0(c,l){let _=c._ownerWritableStream;return Ci(_,l)}y(V0,"WritableStreamDefaultWriterAbort");function rp(c){let l=c._ownerWritableStream;return np(l)}y(rp,"WritableStreamDefaultWriterClose");function Y0(c){let l=c._ownerWritableStream,_=l._state;return Xt(l)||_==="closed"?p(void 0):_==="errored"?h(l._storedError):rp(c)}y(Y0,"WritableStreamDefaultWriterCloseWithErrorPropagation");function X0(c,l){c._closedPromiseState==="pending"?cc(c,l):cb(c,l)}y(X0,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function op(c,l){c._readyPromiseState==="pending"?pp(c,l):lb(c,l)}y(op,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function Q0(c){let l=c._ownerWritableStream,_=l._state;return _==="errored"||_==="erroring"?null:_==="closed"?0:cp(l._writableStreamController)}y(Q0,"WritableStreamDefaultWriterGetDesiredSize");function sp(c){let l=c._ownerWritableStream,_=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");op(c,_),X0(c,_),l._writer=void 0,c._ownerWritableStream=void 0}y(sp,"WritableStreamDefaultWriterRelease");function ip(c,l){let _=c._ownerWritableStream,v=_._writableStreamController,I=rb(v,l);if(_!==c._ownerWritableStream)return h(Go("write to"));let $=_._state;if($==="errored")return h(_._storedError);if(Xt(_)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(_._storedError);let W=L0(_);return ob(v,l,I),W}y(ip,"WritableStreamDefaultWriterWrite");let Z0={},eb=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!sc(this))throw ac("abortReason");return this._abortReason}get signal(){if(!sc(this))throw ac("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!sc(this))throw ac("error");this._controlledWritableStream._state==="writable"&&up(this,l)}[U](l){let _=this._abortAlgorithm(l);return ki(this),_}[ee](){Kn(this)}};y(eb,"WritableStreamDefaultController");let zo=eb;Object.defineProperties(zo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function sc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof zo}y(sc,"IsWritableStreamDefaultController");function ap(c,l,_,v,I,$,W,se){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._abortReason=void 0,l._abortController=B0(),l._started=!1,l._strategySizeAlgorithm=se,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let le=ic(l);oc(c,le);let ge=_(),ke=p(ge);b(ke,()=>(l._started=!0,Si(l),null),Se=>(l._started=!0,tc(c,Se),null))}y(ap,"SetUpWritableStreamDefaultController");function tb(c,l,_,v){let I=Object.create(zo.prototype),$,W,se,le;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.write!==void 0?W=y(ge=>l.write(ge,I),"writeAlgorithm"):W=y(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?se=y(()=>l.close(),"closeAlgorithm"):se=y(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?le=y(ge=>l.abort(ge),"abortAlgorithm"):le=y(()=>p(void 0),"abortAlgorithm"),ap(c,I,$,W,se,le,_,v)}y(tb,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function ki(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(ki,"WritableStreamDefaultControllerClearAlgorithms");function nb(c){Ja(c,Z0,0),Si(c)}y(nb,"WritableStreamDefaultControllerClose");function rb(c,l){try{return c._strategySizeAlgorithm(l)}catch(_){return Wo(c,_),1}}y(rb,"WritableStreamDefaultControllerGetChunkSize");function cp(c){return c._strategyHWM-c._queueTotalSize}y(cp,"WritableStreamDefaultControllerGetDesiredSize");function ob(c,l,_){try{Ja(c,l,_)}catch(I){Wo(c,I);return}let v=c._controlledWritableStream;if(!Xt(v)&&v._state==="writable"){let I=ic(c);oc(v,I)}Si(c)}y(ob,"WritableStreamDefaultControllerWrite");function Si(c){let l=c._controlledWritableStream;if(!c._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){rc(l);return}if(c._queue.length===0)return;let _=f0(c);_===Z0?sb(c):ib(c,_)}y(Si,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function Wo(c,l){c._controlledWritableStream._state==="writable"&&up(c,l)}y(Wo,"WritableStreamDefaultControllerErrorIfNeeded");function sb(c){let l=c._controlledWritableStream;G0(l),Ga(c);let _=c._closeAlgorithm();ki(c),b(_,()=>(H0(l),null),v=>(z0(l,v),null))}y(sb,"WritableStreamDefaultControllerProcessClose");function ib(c,l){let _=c._controlledWritableStream;J0(_);let v=c._writeAlgorithm(l);b(v,()=>{$0(_);let I=_._state;if(Ga(c),!Xt(_)&&I==="writable"){let $=ic(c);oc(_,$)}return Si(c),null},I=>(_._state==="writable"&&ki(c),q0(_,I),null))}y(ib,"WritableStreamDefaultControllerProcessWrite");function ic(c){return cp(c)<=0}y(ic,"WritableStreamDefaultControllerGetBackpressure");function up(c,l){let _=c._controlledWritableStream;ki(c),nc(_,l)}y(up,"WritableStreamDefaultControllerError");function Ai(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}y(Ai,"streamBrandCheckException$2");function ac(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}y(ac,"defaultControllerBrandCheckException$2");function Pr(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}y(Pr,"defaultWriterBrandCheckException");function Go(c){return new TypeError("Cannot "+c+" a stream using a released writer")}y(Go,"defaultWriterLockException");function Ei(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_,c._closedPromiseState="pending"})}y(Ei,"defaultWriterClosedPromiseInitialize");function lp(c,l){Ei(c),cc(c,l)}y(lp,"defaultWriterClosedPromiseInitializeAsRejected");function ab(c){Ei(c),dp(c)}y(ab,"defaultWriterClosedPromiseInitializeAsResolved");function cc(c,l){c._closedPromise_reject!==void 0&&(S(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="rejected")}y(cc,"defaultWriterClosedPromiseReject");function cb(c,l){lp(c,l)}y(cb,"defaultWriterClosedPromiseResetToRejected");function dp(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="resolved")}y(dp,"defaultWriterClosedPromiseResolve");function vi(c){c._readyPromise=f((l,_)=>{c._readyPromise_resolve=l,c._readyPromise_reject=_}),c._readyPromiseState="pending"}y(vi,"defaultWriterReadyPromiseInitialize");function uc(c,l){vi(c),pp(c,l)}y(uc,"defaultWriterReadyPromiseInitializeAsRejected");function fp(c){vi(c),lc(c)}y(fp,"defaultWriterReadyPromiseInitializeAsResolved");function pp(c,l){c._readyPromise_reject!==void 0&&(S(c._readyPromise),c._readyPromise_reject(l),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="rejected")}y(pp,"defaultWriterReadyPromiseReject");function ub(c){vi(c)}y(ub,"defaultWriterReadyPromiseReset");function lb(c,l){uc(c,l)}y(lb,"defaultWriterReadyPromiseResetToRejected");function lc(c){c._readyPromise_resolve!==void 0&&(c._readyPromise_resolve(void 0),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="fulfilled")}y(lc,"defaultWriterReadyPromiseResolve");function db(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof gg<"u")return gg}y(db,"getGlobals");let nD=db();function fb(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}y(fb,"isDOMExceptionConstructor");function pb(){let c=nD?.DOMException;return fb(c)?c:void 0}y(pb,"getFromGlobal");function hb(){let c=y(function(l,_){this.message=l||"",this.name=_||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)},"DOMException");return i(c,"DOMException"),c.prototype=Object.create(Error.prototype),Object.defineProperty(c.prototype,"constructor",{value:c,writable:!0,configurable:!0}),c}y(hb,"createPolyfill");let rD=pb()||hb();function hp(c,l,_,v,I,$){let W=j(c),se=ep(l);c._disturbed=!0;let le=!1,ge=p(void 0);return f((ke,Se)=>{let Be;if($!==void 0){if(Be=y(()=>{let fe=$.reason!==void 0?$.reason:new rD("Aborted","AbortError"),De=[];v||De.push(()=>l._state==="writable"?Ci(l,fe):p(void 0)),I||De.push(()=>c._state==="readable"?jt(c,fe):p(void 0)),gt(()=>Promise.all(De.map(Me=>Me())),!0,fe)},"abortAlgorithm"),$.aborted){Be();return}$.addEventListener("abort",Be)}function Ct(){return f((fe,De)=>{function Me(mt){mt?fe():g(er(),Me,De)}y(Me,"next"),Me(!1)})}y(Ct,"pipeLoop");function er(){return le?p(!0):g(se._readyPromise,()=>f((fe,De)=>{ye(W,{_chunkSteps:y(Me=>{ge=g(ip(se,Me),void 0,r),fe(!1)},"_chunkSteps"),_closeSteps:y(()=>fe(!0),"_closeSteps"),_errorSteps:De})}))}if(y(er,"pipeStep"),Ut(c,W._closedPromise,fe=>(v?wt(!0,fe):gt(()=>Ci(l,fe),!0,fe),null)),Ut(l,se._closedPromise,fe=>(I?wt(!0,fe):gt(()=>jt(c,fe),!0,fe),null)),tt(c,W._closedPromise,()=>(_?wt():gt(()=>Y0(se)),null)),Xt(l)||l._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");I?wt(!0,fe):gt(()=>jt(c,fe),!0,fe)}S(Ct());function Qt(){let fe=ge;return g(ge,()=>fe!==ge?Qt():void 0)}y(Qt,"waitForWritesToFinish");function Ut(fe,De,Me){fe._state==="errored"?Me(fe._storedError):w(De,Me)}y(Ut,"isOrBecomesErrored");function tt(fe,De,Me){fe._state==="closed"?Me():m(De,Me)}y(tt,"isOrBecomesClosed");function gt(fe,De,Me){if(le)return;le=!0,l._state==="writable"&&!Xt(l)?m(Qt(),mt):mt();function mt(){return b(fe(),()=>tr(De,Me),Mr=>tr(!0,Mr)),null}y(mt,"doTheRest")}y(gt,"shutdownWithAction");function wt(fe,De){le||(le=!0,l._state==="writable"&&!Xt(l)?m(Qt(),()=>tr(fe,De)):tr(fe,De))}y(wt,"shutdown");function tr(fe,De){return sp(se),Te(W),$!==void 0&&$.removeEventListener("abort",Be),fe?Se(De):ke(void 0),null}y(tr,"finalize")})}y(hp,"ReadableStreamPipeTo");let gb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Ti(this))throw Ri("desiredSize");return dc(this)}close(){if(!Ti(this))throw Ri("close");if(!co(this))throw new TypeError("The stream is not in a state that permits close");Ir(this)}enqueue(l=void 0){if(!Ti(this))throw Ri("enqueue");if(!co(this))throw new TypeError("The stream is not in a state that permits enqueue");return ao(this,l)}error(l=void 0){if(!Ti(this))throw Ri("error");Bt(this,l)}[z](l){Kn(this);let _=this._cancelAlgorithm(l);return xi(this),_}[te](l){let _=this._controlledReadableStream;if(this._queue.length>0){let v=Ga(this);this._closeRequested&&this._queue.length===0?(xi(this),Vo(_)):Jo(this),l._chunkSteps(v)}else B(_,l),Jo(this)}[Q](){}};y(gb,"ReadableStreamDefaultController");let Xn=gb;Object.defineProperties(Xn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Xn.prototype.close,"close"),i(Xn.prototype.enqueue,"enqueue"),i(Xn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Ti(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof Xn}y(Ti,"IsReadableStreamDefaultController");function Jo(c){if(!gp(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();b(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Jo(c)),null),_=>(Bt(c,_),null))}y(Jo,"ReadableStreamDefaultControllerCallPullIfNeeded");function gp(c){let l=c._controlledReadableStream;return!co(c)||!c._started?!1:!!(Zn(l)&&ie(l)>0||dc(c)>0)}y(gp,"ReadableStreamDefaultControllerShouldCallPull");function xi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(xi,"ReadableStreamDefaultControllerClearAlgorithms");function Ir(c){if(!co(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(xi(c),Vo(l))}y(Ir,"ReadableStreamDefaultControllerClose");function ao(c,l){if(!co(c))return;let _=c._controlledReadableStream;if(Zn(_)&&ie(_)>0)K(_,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Bt(c,I),I}try{Ja(c,l,v)}catch(I){throw Bt(c,I),I}}Jo(c)}y(ao,"ReadableStreamDefaultControllerEnqueue");function Bt(c,l){let _=c._controlledReadableStream;_._state==="readable"&&(Kn(c),xi(c),bp(_,l))}y(Bt,"ReadableStreamDefaultControllerError");function dc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(dc,"ReadableStreamDefaultControllerGetDesiredSize");function mb(c){return!gp(c)}y(mb,"ReadableStreamDefaultControllerHasBackpressure");function co(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}y(co,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function mp(c,l,_,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._started=!1,l._closeRequested=!1,l._pullAgain=!1,l._pulling=!1,l._strategySizeAlgorithm=W,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,c._readableStreamController=l;let se=_();b(p(se),()=>(l._started=!0,Jo(l),null),le=>(Bt(l,le),null))}y(mp,"SetUpReadableStreamDefaultController");function yb(c,l,_,v){let I=Object.create(Xn.prototype),$,W,se;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.pull!==void 0?W=y(()=>l.pull(I),"pullAlgorithm"):W=y(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?se=y(le=>l.cancel(le),"cancelAlgorithm"):se=y(()=>p(void 0),"cancelAlgorithm"),mp(c,I,$,W,se,_,v)}y(yb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function Ri(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}y(Ri,"defaultControllerBrandCheckException$1");function _b(c,l){return vr(c._readableStreamController)?Cb(c):bb(c)}y(_b,"ReadableStreamTee");function bb(c,l){let _=j(c),v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(tt=>{Se=tt});function Ct(){return v?(I=!0,p(void 0)):(v=!0,ye(_,{_chunkSteps:y(tt=>{k(()=>{I=!1;let gt=tt,wt=tt;$||ao(ge._readableStreamController,gt),W||ao(ke._readableStreamController,wt),v=!1,I&&Ct()})},"_chunkSteps"),_closeSteps:y(()=>{v=!1,$||Ir(ge._readableStreamController),W||Ir(ke._readableStreamController),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{v=!1},"_errorSteps")}),p(void 0))}y(Ct,"pullAlgorithm");function er(tt){if($=!0,se=tt,W){let gt=Lo([se,le]),wt=jt(c,gt);Se(wt)}return Be}y(er,"cancel1Algorithm");function Qt(tt){if(W=!0,le=tt,$){let gt=Lo([se,le]),wt=jt(c,gt);Se(wt)}return Be}y(Qt,"cancel2Algorithm");function Ut(){}return y(Ut,"startAlgorithm"),ge=Ko(Ut,Ct,er),ke=Ko(Ut,Ct,Qt),w(_._closedPromise,tt=>(Bt(ge._readableStreamController,tt),Bt(ke._readableStreamController,tt),(!$||!W)&&Se(void 0),null)),[ge,ke]}y(bb,"ReadableStreamDefaultTee");function Cb(c){let l=j(c),_=!1,v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(fe=>{Se=fe});function Ct(fe){w(fe._closedPromise,De=>(fe!==l||(Rt(ge._readableStreamController,De),Rt(ke._readableStreamController,De),(!$||!W)&&Se(void 0)),null))}y(Ct,"forwardReaderError");function er(){Rr(l)&&(Te(l),l=j(c),Ct(l)),ye(l,{_chunkSteps:y(fe=>{k(()=>{v=!1,I=!1;let De=fe,Me=fe;if(!$&&!W)try{Me=Nf(fe)}catch(mt){Rt(ge._readableStreamController,mt),Rt(ke._readableStreamController,mt),Se(jt(c,mt));return}$||hi(ge._readableStreamController,De),W||hi(ke._readableStreamController,Me),_=!1,v?Ut():I&&tt()})},"_chunkSteps"),_closeSteps:y(()=>{_=!1,$||$o(ge._readableStreamController),W||$o(ke._readableStreamController),ge._readableStreamController._pendingPullIntos.length>0&&gi(ge._readableStreamController,0),ke._readableStreamController._pendingPullIntos.length>0&&gi(ke._readableStreamController,0),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(er,"pullWithDefaultReader");function Qt(fe,De){he(l)&&(Te(l),l=Kf(c),Ct(l));let Me=De?ke:ge,mt=De?ge:ke;Xf(l,fe,1,{_chunkSteps:y(Mr=>{k(()=>{v=!1,I=!1;let Yo=De?W:$;if(De?$:W)Yo||mi(Me._readableStreamController,Mr);else{let Xo;try{Xo=Nf(Mr)}catch(Dp){Rt(Me._readableStreamController,Dp),Rt(mt._readableStreamController,Dp),Se(jt(c,Dp));return}Yo||mi(Me._readableStreamController,Mr),hi(mt._readableStreamController,Xo)}_=!1,v?Ut():I&&tt()})},"_chunkSteps"),_closeSteps:y(Mr=>{_=!1;let Yo=De?W:$,Xo=De?$:W;Yo||$o(Me._readableStreamController),Xo||$o(mt._readableStreamController),Mr!==void 0&&(Yo||mi(Me._readableStreamController,Mr),!Xo&&mt._readableStreamController._pendingPullIntos.length>0&&gi(mt._readableStreamController,0)),(!Yo||!Xo)&&Se(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(Qt,"pullWithBYOBReader");function Ut(){if(_)return v=!0,p(void 0);_=!0;let fe=Qa(ge._readableStreamController);return fe===null?er():Qt(fe._view,!1),p(void 0)}y(Ut,"pull1Algorithm");function tt(){if(_)return I=!0,p(void 0);_=!0;let fe=Qa(ke._readableStreamController);return fe===null?er():Qt(fe._view,!0),p(void 0)}y(tt,"pull2Algorithm");function gt(fe){if($=!0,se=fe,W){let De=Lo([se,le]),Me=jt(c,De);Se(Me)}return Be}y(gt,"cancel1Algorithm");function wt(fe){if(W=!0,le=fe,$){let De=Lo([se,le]),Me=jt(c,De);Se(Me)}return Be}y(wt,"cancel2Algorithm");function tr(){}return y(tr,"startAlgorithm"),ge=_p(tr,Ut,gt),ke=_p(tr,tt,wt),Ct(l),[ge,ke]}y(Cb,"ReadableByteStreamTee");function wb(c){return o(c)&&typeof c.getReader<"u"}y(wb,"isReadableStreamLike");function kb(c){return wb(c)?Ab(c.getReader()):Sb(c)}y(kb,"ReadableStreamFrom");function Sb(c){let l,_=Ff(c,"async"),v=r;function I(){let W;try{W=c0(_)}catch(le){return h(le)}let se=p(W);return C(se,le=>{if(!o(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(u0(le))Ir(l._readableStreamController);else{let ge=l0(le);ao(l._readableStreamController,ge)}})}y(I,"pullAlgorithm");function $(W){let se=_.iterator,le;try{le=di(se,"return")}catch(Se){return h(Se)}if(le===void 0)return p(void 0);let ge;try{ge=E(le,se,[W])}catch(Se){return h(Se)}let ke=p(ge);return C(ke,Se=>{if(!o(Se))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return y($,"cancelAlgorithm"),l=Ko(v,I,$,0),l}y(Sb,"ReadableStreamFromIterable");function Ab(c){let l,_=r;function v(){let $;try{$=c.read()}catch(W){return h(W)}return C($,W=>{if(!o(W))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Ir(l._readableStreamController);else{let se=W.value;ao(l._readableStreamController,se)}})}y(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return y(I,"cancelAlgorithm"),l=Ko(_,v,I,0),l}y(Ab,"ReadableStreamFromDefaultReader");function Eb(c,l){de(c,l);let _=c,v=_?.autoAllocateChunkSize,I=_?.cancel,$=_?.pull,W=_?.start,se=_?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:vb(I,_,`${l} has member 'cancel' that`),pull:$===void 0?void 0:Tb($,_,`${l} has member 'pull' that`),start:W===void 0?void 0:xb(W,_,`${l} has member 'start' that`),type:se===void 0?void 0:Rb(se,`${l} has member 'type' that`)}}y(Eb,"convertUnderlyingDefaultOrByteSource");function vb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(vb,"convertUnderlyingSourceCancelCallback");function Tb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(Tb,"convertUnderlyingSourcePullCallback");function xb(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(xb,"convertUnderlyingSourceStartCallback");function Rb(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}y(Rb,"convertReadableStreamType");function Db(c,l){return de(c,l),{preventCancel:!!c?.preventCancel}}y(Db,"convertIteratorOptions");function yp(c,l){de(c,l);let _=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&Ob($,`${l} has member 'signal' that`),{preventAbort:!!_,preventCancel:!!v,preventClose:!!I,signal:$}}y(yp,"convertPipeOptions");function Ob(c,l){if(!M0(c))throw new TypeError(`${l} is not an AbortSignal.`)}y(Ob,"assertAbortSignal");function Pb(c,l){de(c,l);let _=c?.readable;M(_,"readable","ReadableWritablePair"),N(_,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),Zf(v,`${l} has member 'writable' that`),{readable:_,writable:v}}y(Pb,"convertReadableWritablePair");let Ib=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=bi(_,"Second parameter"),I=Eb(l,"First parameter");if(fc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=Ho(v,0);k0(this,I,$)}else{let $=_i(v),W=Ho(v,1);yb(this,I,W,$)}}get locked(){if(!Qn(this))throw Fr("locked");return Zn(this)}cancel(l=void 0){return Qn(this)?Zn(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):jt(this,l):h(Fr("cancel"))}getReader(l=void 0){if(!Qn(this))throw Fr("getReader");return A0(l,"First parameter").mode===void 0?j(this):Kf(this)}pipeThrough(l,_={}){if(!Qn(this))throw Fr("pipeThrough");R(l,1,"pipeThrough");let v=Pb(l,"First parameter"),I=yp(_,"Second parameter");if(Zn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(io(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=hp(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return S($),v.readable}pipeTo(l,_={}){if(!Qn(this))return h(Fr("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!so(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=yp(_,"Second parameter")}catch(I){return h(I)}return Zn(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):io(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):hp(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!Qn(this))throw Fr("tee");let l=_b(this);return Lo(l)}values(l=void 0){if(!Qn(this))throw Fr("values");let _=Db(l,"First parameter");return ht(this,_.preventCancel)}[If](l){return this.values(l)}static from(l){return kb(l)}};y(Ib,"ReadableStream");let dt=Ib;Object.defineProperties(dt,{from:{enumerable:!0}}),Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(dt.from,"from"),i(dt.prototype.cancel,"cancel"),i(dt.prototype.getReader,"getReader"),i(dt.prototype.pipeThrough,"pipeThrough"),i(dt.prototype.pipeTo,"pipeTo"),i(dt.prototype.tee,"tee"),i(dt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(dt.prototype,If,{value:dt.prototype.values,writable:!0,configurable:!0});function Ko(c,l,_,v=1,I=()=>1){let $=Object.create(dt.prototype);fc($);let W=Object.create(Xn.prototype);return mp($,W,c,l,_,v,I),$}y(Ko,"CreateReadableStream");function _p(c,l,_){let v=Object.create(dt.prototype);fc(v);let I=Object.create(Vn.prototype);return Jf(v,I,c,l,_,0,void 0),v}y(_p,"CreateReadableByteStream");function fc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}y(fc,"InitializeReadableStream");function Qn(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof dt}y(Qn,"IsReadableStream");function Zn(c){return c._reader!==void 0}y(Zn,"IsReadableStreamLocked");function jt(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);Vo(c);let _=c._reader;if(_!==void 0&&Rr(_)){let I=_._readIntoRequests;_._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return C(v,r)}y(jt,"ReadableStreamCancel");function Vo(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),he(l))){let _=l._readRequests;l._readRequests=new V,_.forEach(v=>{v._closeSteps()})}}y(Vo,"ReadableStreamClose");function bp(c,l){c._state="errored",c._storedError=l;let _=c._reader;_!==void 0&&(Ie(_,l),he(_)?Xe(_,l):Qf(_,l))}y(bp,"ReadableStreamError");function Fr(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}y(Fr,"streamBrandCheckException$1");function Cp(c,l){de(c,l);let _=c?.highWaterMark;return M(_,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(_)}}y(Cp,"convertQueuingStrategyInit");let Fb=y(c=>c.byteLength,"byteLengthSizeFunction");i(Fb,"size");let Nb=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=Cp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!kp(this))throw wp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!kp(this))throw wp("size");return Fb}};y(Nb,"ByteLengthQueuingStrategy");let pc=Nb;Object.defineProperties(pc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function wp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}y(wp,"byteLengthBrandCheckException");function kp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof pc}y(kp,"IsByteLengthQueuingStrategy");let Mb=y(()=>1,"countSizeFunction");i(Mb,"size");let Bb=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=Cp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Ap(this))throw Sp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Ap(this))throw Sp("size");return Mb}};y(Bb,"CountQueuingStrategy");let hc=Bb;Object.defineProperties(hc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Sp(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}y(Sp,"countBrandCheckException");function Ap(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof hc}y(Ap,"IsCountQueuingStrategy");function jb(c,l){de(c,l);let _=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,se=c?.writableType;return{cancel:_===void 0?void 0:qb(_,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:Ub(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:Lb($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:$b(W,c,`${l} has member 'transform' that`),writableType:se}}y(jb,"convertTransformer");function Ub(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(Ub,"convertTransformerFlushCallback");function Lb(c,l,_){return ce(c,_),v=>E(c,l,[v])}y(Lb,"convertTransformerStartCallback");function $b(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}y($b,"convertTransformerTransformCallback");function qb(c,l,_){return ce(c,_),v=>x(c,l,[v])}y(qb,"convertTransformerCancelCallback");let Hb=class{constructor(l={},_={},v={}){l===void 0&&(l=null);let I=bi(_,"Second parameter"),$=bi(v,"Third parameter"),W=jb(l,"First parameter");if(W.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(W.writableType!==void 0)throw new RangeError("Invalid writableType specified");let se=Ho($,0),le=_i($),ge=Ho(I,1),ke=_i(I),Se,Be=f(Ct=>{Se=Ct});zb(this,Be,ge,ke,se,le),Jb(this,W),W.start!==void 0?Se(W.start(this._transformStreamController)):Se(void 0)}get readable(){if(!Ep(this))throw Rp("readable");return this._readable}get writable(){if(!Ep(this))throw Rp("writable");return this._writable}};y(Hb,"TransformStream");let gc=Hb;Object.defineProperties(gc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(gc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function zb(c,l,_,v,I,$){function W(){return l}y(W,"startAlgorithm");function se(Be){return Yb(c,Be)}y(se,"writeAlgorithm");function le(Be){return Xb(c,Be)}y(le,"abortAlgorithm");function ge(){return Qb(c)}y(ge,"closeAlgorithm"),c._writable=U0(W,se,ge,le,_,v);function ke(){return Zb(c)}y(ke,"pullAlgorithm");function Se(Be){return eC(c,Be)}y(Se,"cancelAlgorithm"),c._readable=Ko(W,ke,Se,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Di(c,!0),c._transformStreamController=void 0}y(zb,"InitializeTransformStream");function Ep(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof gc}y(Ep,"IsTransformStream");function vp(c,l){Bt(c._readable._readableStreamController,l),mc(c,l)}y(vp,"TransformStreamError");function mc(c,l){Pi(c._transformStreamController),Wo(c._writable._writableStreamController,l),yc(c)}y(mc,"TransformStreamErrorWritableAndUnblockWrite");function yc(c){c._backpressure&&Di(c,!1)}y(yc,"TransformStreamUnblockWrite");function Di(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(_=>{c._backpressureChangePromise_resolve=_}),c._backpressure=l}y(Di,"TransformStreamSetBackpressure");let Wb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Oi(this))throw Ii("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return dc(l)}enqueue(l=void 0){if(!Oi(this))throw Ii("enqueue");Tp(this,l)}error(l=void 0){if(!Oi(this))throw Ii("error");Kb(this,l)}terminate(){if(!Oi(this))throw Ii("terminate");Vb(this)}};y(Wb,"TransformStreamDefaultController");let Nr=Wb;Object.defineProperties(Nr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Nr.prototype.enqueue,"enqueue"),i(Nr.prototype.error,"error"),i(Nr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Nr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Oi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Nr}y(Oi,"IsTransformStreamDefaultController");function Gb(c,l,_,v,I){l._controlledTransformStream=c,c._transformStreamController=l,l._transformAlgorithm=_,l._flushAlgorithm=v,l._cancelAlgorithm=I,l._finishPromise=void 0,l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}y(Gb,"SetUpTransformStreamDefaultController");function Jb(c,l){let _=Object.create(Nr.prototype),v,I,$;l.transform!==void 0?v=y(W=>l.transform(W,_),"transformAlgorithm"):v=y(W=>{try{return Tp(_,W),p(void 0)}catch(se){return h(se)}},"transformAlgorithm"),l.flush!==void 0?I=y(()=>l.flush(_),"flushAlgorithm"):I=y(()=>p(void 0),"flushAlgorithm"),l.cancel!==void 0?$=y(W=>l.cancel(W),"cancelAlgorithm"):$=y(()=>p(void 0),"cancelAlgorithm"),Gb(c,_,v,I,$)}y(Jb,"SetUpTransformStreamDefaultControllerFromTransformer");function Pi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Pi,"TransformStreamDefaultControllerClearAlgorithms");function Tp(c,l){let _=c._controlledTransformStream,v=_._readable._readableStreamController;if(!co(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{ao(v,l)}catch(I){throw mc(_,I),_._readable._storedError}mb(v)!==_._backpressure&&Di(_,!0)}y(Tp,"TransformStreamDefaultControllerEnqueue");function Kb(c,l){vp(c._controlledTransformStream,l)}y(Kb,"TransformStreamDefaultControllerError");function xp(c,l){let _=c._transformAlgorithm(l);return C(_,void 0,v=>{throw vp(c._controlledTransformStream,v),v})}y(xp,"TransformStreamDefaultControllerPerformTransform");function Vb(c){let l=c._controlledTransformStream,_=l._readable._readableStreamController;Ir(_);let v=new TypeError("TransformStream terminated");mc(l,v)}y(Vb,"TransformStreamDefaultControllerTerminate");function Yb(c,l){let _=c._transformStreamController;if(c._backpressure){let v=c._backpressureChangePromise;return C(v,()=>{let I=c._writable;if(I._state==="erroring")throw I._storedError;return xp(_,l)})}return xp(_,l)}y(Yb,"TransformStreamDefaultSinkWriteAlgorithm");function Xb(c,l){let _=c._transformStreamController;if(_._finishPromise!==void 0)return _._finishPromise;let v=c._readable;_._finishPromise=f(($,W)=>{_._finishPromise_resolve=$,_._finishPromise_reject=W});let I=_._cancelAlgorithm(l);return Pi(_),b(I,()=>(v._state==="errored"?uo(_,v._storedError):(Bt(v._readableStreamController,l),_c(_)),null),$=>(Bt(v._readableStreamController,$),uo(_,$),null)),_._finishPromise}y(Xb,"TransformStreamDefaultSinkAbortAlgorithm");function Qb(c){let l=c._transformStreamController;if(l._finishPromise!==void 0)return l._finishPromise;let _=c._readable;l._finishPromise=f((I,$)=>{l._finishPromise_resolve=I,l._finishPromise_reject=$});let v=l._flushAlgorithm();return Pi(l),b(v,()=>(_._state==="errored"?uo(l,_._storedError):(Ir(_._readableStreamController),_c(l)),null),I=>(Bt(_._readableStreamController,I),uo(l,I),null)),l._finishPromise}y(Qb,"TransformStreamDefaultSinkCloseAlgorithm");function Zb(c){return Di(c,!1),c._backpressureChangePromise}y(Zb,"TransformStreamDefaultSourcePullAlgorithm");function eC(c,l){let _=c._transformStreamController;if(_._finishPromise!==void 0)return _._finishPromise;let v=c._writable;_._finishPromise=f(($,W)=>{_._finishPromise_resolve=$,_._finishPromise_reject=W});let I=_._cancelAlgorithm(l);return Pi(_),b(I,()=>(v._state==="errored"?uo(_,v._storedError):(Wo(v._writableStreamController,l),yc(c),_c(_)),null),$=>(Wo(v._writableStreamController,$),yc(c),uo(_,$),null)),_._finishPromise}y(eC,"TransformStreamDefaultSourceCancelAlgorithm");function Ii(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}y(Ii,"defaultControllerBrandCheckException");function _c(c){c._finishPromise_resolve!==void 0&&(c._finishPromise_resolve(),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}y(_c,"defaultControllerFinishPromiseResolve");function uo(c,l){c._finishPromise_reject!==void 0&&(S(c._finishPromise),c._finishPromise_reject(l),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}y(uo,"defaultControllerFinishPromiseReject");function Rp(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}y(Rp,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=pc,n.CountQueuingStrategy=hc,n.ReadableByteStreamController=Vn,n.ReadableStream=dt,n.ReadableStreamBYOBReader=xr,n.ReadableStreamBYOBRequest=ro,n.ReadableStreamDefaultController=Xn,n.ReadableStreamDefaultReader=me,n.TransformStream=gc,n.TransformStreamDefaultController=Nr,n.WritableStream=Dr,n.WritableStreamDefaultController=zo,n.WritableStreamDefaultWriter=Yn})})(Zu,Zu.exports)),Zu.exports}function tA(){if(eA)return QS;eA=1;let t=65536;if(!globalThis.ReadableStream)try{let e=re("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,re("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,fA())}try{let{Blob:e}=re("buffer");e&&!e.prototype.stream&&(e.prototype.stream=y(function(n){let r=0,o=this;return new ReadableStream({type:"bytes",async pull(s){let i=await o.slice(r,Math.min(o.size,r+t)).arrayBuffer();r+=i.byteLength,s.enqueue(new Uint8Array(i)),r===o.size&&s.close()}})},"name"))}catch{}return QS}async function*el(t,e=!0){for(let n of t)if("stream"in n)yield*n.stream();else if(ArrayBuffer.isView(n))if(e){let r=n.byteOffset,o=n.byteOffset+n.byteLength;for(;r!==o;){let s=Math.min(o-r,nA),i=n.buffer.slice(r,r+s);r+=i.byteLength,yield new Uint8Array(i)}}else yield n;else{let r=0,o=n;for(;r!==o.size;){let s=await o.slice(r,Math.min(o.size,r+nA)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function hA(t,e=Do){var n=`${rA()}${rA()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
79
+ Content-Disposition: form-data; name="`;return t.forEach((s,i)=>typeof s=="string"?r.push(o+wg(i)+`"\r
80
80
  \r
81
81
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
82
82
  `)}\r
83
- `):r.push(o+kg(i)+`"; filename="${kg(s.name,1)}"\r
83
+ `):r.push(o+wg(i)+`"; filename="${wg(s.name,1)}"\r
84
84
  Content-Type: ${s.type||"application/octet-stream"}\r
85
85
  \r
86
86
  `,s,`\r
87
- `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function tl(t){if(t[Tt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[Tt].disturbed=!0,t[Tt].error)throw t[Tt].error;let{body:e}=t;if(e===null)return pt.alloc(0);if(!(e instanceof Mn))return pt.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new Wt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof fl?o:new Wt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?pt.from(n.join("")):pt.concat(n,r)}catch(o){throw new Wt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new Wt(`Premature close of server response while trying to fetch ${t.url}`)}function kA(t=[]){return new hr(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return nl(e),Ag(e,String(n)),!0}catch{return!1}}))}function Eg(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function EA(t){if(!AA.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function vA(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=HF(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function xo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:vA(t)}function TA(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Eg(o),i=Eg(o,!0);s.toString().length>4096&&(s=i),e&&(s=e(s)),n&&(i=n(i));let a=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return s;case"strict-origin":return xo(s)&&!xo(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===a.origin?s:xo(s)&&!xo(a)?"no-referrer":i;case"same-origin":return s.origin===a.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===a.origin?s:i;case"no-referrer-when-downgrade":return xo(s)&&!xo(a)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function xA(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&AA.has(r)&&(n=r);return n}function PA(){if(sA)return Sg;if(sA=1,!globalThis.DOMException)try{let{MessageChannel:t}=re("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}return Sg=globalThis.DOMException,Sg}async function Ng(t,e){return new Promise((n,r)=>{let o=new da(t,e),{parsedURL:s,options:i}=uN(o);if(!fN.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let b=dA(o.url),m=new Fn(b,{headers:{"Content-Type":b.typeFull}});n(m);return}let a=(s.protocol==="https:"?LF:la).request,{signal:u}=o,d=null,f=y(()=>{let b=new Ig("The operation was aborted.");r(b),o.body&&o.body instanceof Mn.Readable&&o.body.destroy(b),!(!d||!d.body)&&d.body.emit("error",b)},"abort");if(u&&u.aborted){f();return}let p=y(()=>{f(),g()},"abortAndFinalize"),h=a(s.toString(),i);u&&u.addEventListener("abort",p);let g=y(()=>{h.abort(),u&&u.removeEventListener("abort",p)},"finalize");h.on("error",b=>{r(new Wt(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),g()}),qA(h,b=>{d&&d.body&&d.body.destroy(b)}),process.version<"v14"&&h.on("socket",b=>{let m;b.prependListener("end",()=>{m=b._eventsCount}),b.prependListener("close",w=>{if(d&&m<b._eventsCount&&!w){let C=new Error("Premature close");C.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",C)}})}),h.on("response",b=>{h.setTimeout(0);let m=kA(b.rawHeaders);if(pl(b.statusCode)){let E=m.get("Location"),x=null;try{x=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){r(new Wt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":r(new Wt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),g();return;case"manual":break;case"follow":{if(x===null)break;if(o.counter>=o.follow){r(new Wt(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let O={headers:new hr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Pg(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!ZF(o.url,x)||!eN(o.url,x))for(let V of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete(V);if(b.statusCode!==303&&o.body&&e.body instanceof Mn.Readable){r(new Wt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),g();return}(b.statusCode===303||(b.statusCode===301||b.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=xA(m);q&&(O.referrerPolicy=q),n(Ng(new da(x,O))),g();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}u&&b.once("end",()=>{u.removeEventListener("abort",p)});let w=Ts(b,new ol,E=>{E&&r(E)});process.version<"v12.10"&&b.on("aborted",p);let C={url:o.url,status:b.statusCode,statusText:b.statusMessage,headers:m,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=m.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||b.statusCode===204||b.statusCode===304){d=new Fn(w,C),n(d);return}let k={flush:vs.Z_SYNC_FLUSH,finishFlush:vs.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){w=Ts(w,vs.createGunzip(k),E=>{E&&r(E)}),d=new Fn(w,C),n(d);return}if(A==="deflate"||A==="x-deflate"){let E=Ts(b,new ol,x=>{x&&r(x)});E.once("data",x=>{(x[0]&15)===8?w=Ts(w,vs.createInflate(),O=>{O&&r(O)}):w=Ts(w,vs.createInflateRaw(),O=>{O&&r(O)}),d=new Fn(w,C),n(d)}),E.once("end",()=>{d||(d=new Fn(w,C),n(d))});return}if(A==="br"){w=Ts(w,vs.createBrotliDecompress(),E=>{E&&r(E)}),d=new Fn(w,C),n(d);return}d=new Fn(w,C),n(d)}),oN(h,o).catch(r)})}function qA(t,e){let n=pt.from(`0\r
87
+ `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function tl(t){if(t[Tt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[Tt].disturbed=!0,t[Tt].error)throw t[Tt].error;let{body:e}=t;if(e===null)return pt.alloc(0);if(!(e instanceof Mn))return pt.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new Wt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof fl?o:new Wt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?pt.from(n.join("")):pt.concat(n,r)}catch(o){throw new Wt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new Wt(`Premature close of server response while trying to fetch ${t.url}`)}function kA(t=[]){return new hr(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return nl(e),Sg(e,String(n)),!0}catch{return!1}}))}function Ag(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function EA(t){if(!AA.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function vA(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=zF(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function xo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:vA(t)}function TA(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Ag(o),i=Ag(o,!0);s.toString().length>4096&&(s=i),e&&(s=e(s)),n&&(i=n(i));let a=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return s;case"strict-origin":return xo(s)&&!xo(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===a.origin?s:xo(s)&&!xo(a)?"no-referrer":i;case"same-origin":return s.origin===a.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===a.origin?s:i;case"no-referrer-when-downgrade":return xo(s)&&!xo(a)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function xA(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&AA.has(r)&&(n=r);return n}function PA(){if(sA)return kg;if(sA=1,!globalThis.DOMException)try{let{MessageChannel:t}=re("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}return kg=globalThis.DOMException,kg}async function Fg(t,e){return new Promise((n,r)=>{let o=new da(t,e),{parsedURL:s,options:i}=lN(o);if(!pN.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let b=dA(o.url),m=new Fn(b,{headers:{"Content-Type":b.typeFull}});n(m);return}let a=(s.protocol==="https:"?$F:la).request,{signal:u}=o,d=null,f=y(()=>{let b=new Pg("The operation was aborted.");r(b),o.body&&o.body instanceof Mn.Readable&&o.body.destroy(b),!(!d||!d.body)&&d.body.emit("error",b)},"abort");if(u&&u.aborted){f();return}let p=y(()=>{f(),g()},"abortAndFinalize"),h=a(s.toString(),i);u&&u.addEventListener("abort",p);let g=y(()=>{h.abort(),u&&u.removeEventListener("abort",p)},"finalize");h.on("error",b=>{r(new Wt(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),g()}),qA(h,b=>{d&&d.body&&d.body.destroy(b)}),process.version<"v14"&&h.on("socket",b=>{let m;b.prependListener("end",()=>{m=b._eventsCount}),b.prependListener("close",w=>{if(d&&m<b._eventsCount&&!w){let C=new Error("Premature close");C.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",C)}})}),h.on("response",b=>{h.setTimeout(0);let m=kA(b.rawHeaders);if(pl(b.statusCode)){let E=m.get("Location"),x=null;try{x=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){r(new Wt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":r(new Wt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),g();return;case"manual":break;case"follow":{if(x===null)break;if(o.counter>=o.follow){r(new Wt(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let O={headers:new hr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Og(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!eN(o.url,x)||!tN(o.url,x))for(let V of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete(V);if(b.statusCode!==303&&o.body&&e.body instanceof Mn.Readable){r(new Wt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),g();return}(b.statusCode===303||(b.statusCode===301||b.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=xA(m);q&&(O.referrerPolicy=q),n(Fg(new da(x,O))),g();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}u&&b.once("end",()=>{u.removeEventListener("abort",p)});let w=Ts(b,new ol,E=>{E&&r(E)});process.version<"v12.10"&&b.on("aborted",p);let C={url:o.url,status:b.statusCode,statusText:b.statusMessage,headers:m,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},S=m.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||S===null||b.statusCode===204||b.statusCode===304){d=new Fn(w,C),n(d);return}let k={flush:vs.Z_SYNC_FLUSH,finishFlush:vs.Z_SYNC_FLUSH};if(S==="gzip"||S==="x-gzip"){w=Ts(w,vs.createGunzip(k),E=>{E&&r(E)}),d=new Fn(w,C),n(d);return}if(S==="deflate"||S==="x-deflate"){let E=Ts(b,new ol,x=>{x&&r(x)});E.once("data",x=>{(x[0]&15)===8?w=Ts(w,vs.createInflate(),O=>{O&&r(O)}):w=Ts(w,vs.createInflateRaw(),O=>{O&&r(O)}),d=new Fn(w,C),n(d)}),E.once("end",()=>{d||(d=new Fn(w,C),n(d))});return}if(S==="br"){w=Ts(w,vs.createBrotliDecompress(),E=>{E&&r(E)}),d=new Fn(w,C),n(d);return}d=new Fn(w,C),n(d)}),sN(h,o).catch(r)})}function qA(t,e){let n=pt.from(`0\r
88
88
  \r
89
- `),r=!1,o=!1,s;t.on("response",i=>{let{headers:a}=i;r=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),t.on("socket",i=>{let a=y(()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},"onSocketClose"),u=y(d=>{o=pt.compare(d.slice(-5),n)===0,!o&&s&&(o=pt.compare(s.slice(-3),n.slice(0,3))===0&&pt.compare(d.slice(-2),n.slice(3))===0),s=d},"onData");i.prependListener("close",a),i.on("data",u),t.on("close",()=>{i.removeListener("close",a),i.removeListener("data",u)})})}function Le(t){let e=HA.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function Tg(t){if(t.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",t.passiveListener);return}t.event.cancelable&&(t.canceled=!0,typeof t.event.preventDefault=="function"&&t.event.preventDefault())}function Ro(t,e){HA.set(this,{eventTarget:t,event:e,eventPhase:2,currentTarget:t,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:e.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let n=Object.keys(e);for(let r=0;r<n.length;++r){let o=n[r];o in this||Object.defineProperty(this,o,Mg(o))}}function Mg(t){return{get(){return Le(this).event[t]},set(e){Le(this).event[t]=e},configurable:!0,enumerable:!0}}function zA(t){return{value(){let e=Le(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function WA(t,e){let n=Object.keys(e);if(n.length===0)return t;function r(o,s){t.call(this,o,s)}y(r,"CustomEvent"),r.prototype=Object.create(t.prototype,{constructor:{value:r,configurable:!0,writable:!0}});for(let o=0;o<n.length;++o){let s=n[o];if(!(s in t.prototype)){let i=typeof Object.getOwnPropertyDescriptor(e,s).value=="function";Object.defineProperty(r.prototype,s,i?zA(s):Mg(s))}}return r}function Bg(t){if(t==null||t===Object.prototype)return Ro;let e=vg.get(t);return e==null&&(e=WA(Bg(Object.getPrototypeOf(t)),t),vg.set(t,e)),e}function GA(t,e){let n=Bg(Object.getPrototypeOf(e));return new n(t,e)}function JA(t){return Le(t).immediateStopped}function KA(t,e){Le(t).eventPhase=e}function VA(t,e){Le(t).currentTarget=e}function xg(t,e){Le(t).passiveListener=e}function ua(t){return t!==null&&typeof t=="object"}function Ds(t){let e=YA.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function XA(t){return{get(){let e=Ds(this).get(t);for(;e!=null;){if(e.listenerType===rl)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!ua(e)&&(e=null);let n=Ds(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===rl?r!==null?r.next=o.next:o.next!==null?n.set(t,o.next):n.delete(t):r=o,o=o.next;if(e!==null){let s={listener:e,listenerType:rl,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function Ug(t,e){Object.defineProperty(t,`on${e}`,XA(e))}function Rg(t){function e(){Nn.call(this)}y(e,"CustomEventTarget"),e.prototype=Object.create(Nn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)Ug(e.prototype,t[n]);return e}function Nn(){if(this instanceof Nn){YA.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return Rg(arguments[0]);if(arguments.length>0){let t=new Array(arguments.length);for(let e=0;e<arguments.length;++e)t[e]=arguments[e];return Rg(t)}throw new TypeError("Cannot call a class as a function")}function ZA(){let t=Object.create(ul.prototype);return Nn.call(t),ll.set(t,!1),t}function eE(t){ll.get(t)===!1&&(ll.set(t,!0),t.dispatchEvent({type:"abort"}))}function Dg(t){let e=tE.get(t);if(e==null)throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${t===null?"null":typeof t}`);return e}function Og(){!globalThis.process?.versions?.node&&!globalThis.process?.env?.DISABLE_NODE_FETCH_NATIVE_WARN&&console.warn("[node-fetch-native] Node.js compatible build of `node-fetch-native` is being used in a non-Node.js environment. Please make sure you are using proper export conditions or report this issue to https://github.com/unjs/node-fetch-native. You can set `process.env.DISABLE_NODE_FETCH_NATIVE_WARN` to disable this warning.")}var jF,cA,y,uA,ze,pr,rn,Wr,Yu,Es,_g,oa,Xu,Qu,bg,tn,Cg,xs,Rs,wg,QS,Zu,JF,ZS,eA,nA,pA,Do,KF,As,aa,VF,YF,rA,XF,oA,kg,To,vo,gA,fl,mA,Wt,al,yA,cl,QF,ZF,eN,tN,Tt,_A,ca,Pg,nN,bA,rN,oN,nl,Ag,CA,hr,sN,pl,nn,SA,Fn,iN,AA,aN,at,sa,cN,RA,da,uN,OA,Ig,Sg,sA,lN,dN,Fg,IA,FA,NA,MA,BA,UA,jA,$A,fN,HA,vg,YA,iA,aA,rl,QA,ul,ll,dl,tE,pN,hN,nE,Vu=Br(()=>{Gu();jF=Object.defineProperty,cA=t=>{throw TypeError(t)},y=(t,e)=>jF(t,"name",{value:e,configurable:!0}),uA=(t,e,n)=>e.has(t)||cA("Cannot "+n),ze=(t,e,n)=>(uA(t,e,"read from private field"),n?n.call(t):e.get(t)),pr=(t,e,n)=>e.has(t)?cA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),rn=(t,e,n,r)=>(uA(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);y(dA,"dataUriToBuffer");QS={},Zu={exports:{}};JF=Zu.exports;y(fA,"requirePonyfill_es2018");y(tA,"requireStreams"),tA();nA=65536;y(el,"toIterator");pA=(oa=class{constructor(t=[],e={}){if(pr(this,Wr,[]),pr(this,Yu,""),pr(this,Es,0),pr(this,_g,"transparent"),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof e!="object"&&typeof e!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");e===null&&(e={});let n=new TextEncoder;for(let o of t){let s;ArrayBuffer.isView(o)?s=new Uint8Array(o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)):o instanceof ArrayBuffer?s=new Uint8Array(o.slice(0)):o instanceof oa?s=o:s=n.encode(`${o}`),rn(this,Es,ze(this,Es)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),ze(this,Wr).push(s)}rn(this,_g,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);rn(this,Yu,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return ze(this,Es)}get type(){return ze(this,Yu)}async text(){let t=new TextDecoder,e="";for await(let n of el(ze(this,Wr),!1))e+=t.decode(n,{stream:!0});return e+=t.decode(),e}async arrayBuffer(){let t=new Uint8Array(this.size),e=0;for await(let n of el(ze(this,Wr),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=el(ze(this,Wr),!0);return new globalThis.ReadableStream({type:"bytes",async pull(e){let n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,e=this.size,n=""){let{size:r}=this,o=t<0?Math.max(r+t,0):Math.min(t,r),s=e<0?Math.max(r+e,0):Math.min(e,r),i=Math.max(s-o,0),a=ze(this,Wr),u=[],d=0;for(let p of a){if(d>=i)break;let h=ArrayBuffer.isView(p)?p.byteLength:p.size;if(o&&h<=o)o-=h,s-=h;else{let g;ArrayBuffer.isView(p)?(g=p.subarray(o,Math.min(h,s)),d+=g.byteLength):(g=p.slice(o,Math.min(h,s)),d+=g.size),s-=h,u.push(g),o=0}}let f=new oa([],{type:String(n).toLowerCase()});return rn(f,Es,i),rn(f,Wr,u),f}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t=="object"&&typeof t.constructor=="function"&&(typeof t.stream=="function"||typeof t.arrayBuffer=="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}},Wr=new WeakMap,Yu=new WeakMap,Es=new WeakMap,_g=new WeakMap,y(oa,"Blob"),oa);Object.defineProperties(pA.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Do=pA,KF=(bg=class extends Do{constructor(t,e,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n),pr(this,Xu,0),pr(this,Qu,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||rn(this,Xu,r),rn(this,Qu,String(e))}get name(){return ze(this,Qu)}get lastModified(){return ze(this,Xu)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Do&&/^(File)$/.test(t[Symbol.toStringTag])}},Xu=new WeakMap,Qu=new WeakMap,y(bg,"File"),bg),As=KF;({toStringTag:aa,iterator:VF,hasInstance:YF}=Symbol),rA=Math.random,XF="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),oA=y((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[aa])?[(n=n!==void 0?n+"":e[aa]=="File"?e.name:"blob",t),e.name!==n||e[aa]=="blob"?new As([e],n,e):e]:[t,e+""]),"f"),kg=y((t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
90
- `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),To=y((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),vo=(Cg=class{constructor(...t){if(pr(this,tn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[aa](){return"FormData"}[VF](){return this.entries()}static[YF](t){return t&&typeof t=="object"&&t[aa]==="FormData"&&!XF.some(e=>typeof t[e]!="function")}append(...t){To("append",arguments,2),ze(this,tn).push(oA(...t))}delete(t){To("delete",arguments,1),t+="",rn(this,tn,ze(this,tn).filter(([e])=>e!==t))}get(t){To("get",arguments,1),t+="";for(var e=ze(this,tn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return To("getAll",arguments,1),e=[],t+="",ze(this,tn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return To("has",arguments,1),t+="",ze(this,tn).some(e=>e[0]===t)}forEach(t,e){To("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){To("set",arguments,2);var e=[],n=!0;t=oA(...t),ze(this,tn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),rn(this,tn,e)}*entries(){yield*ze(this,tn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},tn=new WeakMap,y(Cg,"FormData"),Cg);y(hA,"formDataToBlob");gA=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};y(gA,"FetchBaseError");fl=gA,mA=class extends fl{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};y(mA,"FetchError");Wt=mA,al=Symbol.toStringTag,yA=y(t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[al]==="URLSearchParams","isURLSearchParameters"),cl=y(t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[al]),"isBlob"),QF=y(t=>typeof t=="object"&&(t[al]==="AbortSignal"||t[al]==="EventTarget"),"isAbortSignal"),ZF=y((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),eN=y((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),tN=$F(Mn.pipeline),Tt=Symbol("Body internals"),_A=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:yA(e)?e=pt.from(e.toString()):cl(e)||pt.isBuffer(e)||(sl.isAnyArrayBuffer(e)?e=pt.from(e):ArrayBuffer.isView(e)?e=pt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mn||(e instanceof vo?(e=hA(e),r=e.type.split("=")[1]):e=pt.from(String(e))));let o=e;pt.isBuffer(e)?o=Mn.Readable.from(e):cl(e)&&(o=Mn.Readable.from(e.stream())),this[Tt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Mn&&e.on("error",s=>{let i=s instanceof fl?s:new Wt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Tt].error=i})}get body(){return this[Tt].stream}get bodyUsed(){return this[Tt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await tl(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new vo,o=new URLSearchParams(await this.text());for(let[s,i]of o)r.append(s,i);return r}let{toFormData:n}=await Promise.resolve().then(()=>(XS(),YS));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Tt].body&&this[Tt].body.type||"",n=await this.arrayBuffer();return new Do([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await tl(this);return new TextDecoder().decode(e)}buffer(){return tl(this)}};y(_A,"Body");ca=_A;ca.prototype.buffer=il(ca.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(ca.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:il(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});y(tl,"consumeBody");Pg=y((t,e)=>{let n,r,{body:o}=t[Tt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Mn&&typeof o.getBoundary!="function"&&(n=new ol({highWaterMark:e}),r=new ol({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Tt].stream=n,o=r),o},"clone"),nN=il(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),bA=y((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":yA(t)?"application/x-www-form-urlencoded;charset=UTF-8":cl(t)?t.type||null:pt.isBuffer(t)||sl.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof vo?`multipart/form-data; boundary=${e[Tt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${nN(t)}`:t instanceof Mn?null:"text/plain;charset=UTF-8","extractContentType"),rN=y(t=>{let{body:e}=t[Tt];return e===null?0:cl(e)?e.size:pt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),oN=y(async(t,{body:e})=>{e===null?t.end():await tN(e,t)},"writeToStream"),nl=typeof la.validateHeaderName=="function"?la.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Ag=typeof la.validateHeaderValue=="function"?la.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},CA=class wA extends URLSearchParams{constructor(e){let n=[];if(e instanceof wA){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(i=>[o,i]))}else if(e!=null)if(typeof e=="object"&&!sl.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||sl.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(nl(r),Ag(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(i,a)=>(nl(i),Ag(i,String(a)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(a)));case"delete":case"has":case"getAll":return i=>(nl(i),URLSearchParams.prototype[o].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};y(CA,"Headers");hr=CA;Object.defineProperties(hr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));y(kA,"fromRawHeaders");sN=new Set([301,302,303,307,308]),pl=y(t=>sN.has(t),"isRedirect"),nn=Symbol("Response internals"),SA=class ia extends ca{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new hr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=bA(e,this);s&&o.append("Content-Type",s)}this[nn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||""}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new ia(Pg(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!pl(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new ia(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new ia(null,{status:0,statusText:""});return e[nn].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new hr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new ia(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};y(SA,"Response");Fn=SA;Object.defineProperties(Fn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});iN=y(t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""},"getSearch");y(Eg,"stripURLForUseAsAReferrer");AA=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),aN="strict-origin-when-cross-origin";y(EA,"validateReferrerPolicy");y(vA,"isOriginPotentiallyTrustworthy");y(xo,"isUrlPotentiallyTrustworthy");y(TA,"determineRequestsReferrer");y(xA,"parseReferrerPolicyFromHeader");at=Symbol("Request internals"),sa=y(t=>typeof t=="object"&&typeof t[at]=="object","isRequest"),cN=il(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),RA=class DA extends ca{constructor(e,n={}){let r;if(sa(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!sa(n)&&"data"in n&&cN(),(n.body!=null||sa(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:sa(e)&&e.body!==null?Pg(e):null;super(s,{size:n.size||e.size||0});let i=new hr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=bA(s,this);d&&i.set("Content-Type",d)}let a=sa(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!QF(a))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=n.referrer==null?e.referrer:n.referrer;if(u==="")u="no-referrer";else if(u){let d=new URL(u);u=/^about:(\/\/)?client$/.test(d)?"client":d}else u=void 0;this[at]={method:o,redirect:n.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:a,referrer:u},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[at].method}get url(){return qF(this[at].parsedURL)}get headers(){return this[at].headers}get redirect(){return this[at].redirect}get signal(){return this[at].signal}get referrer(){if(this[at].referrer==="no-referrer")return"";if(this[at].referrer==="client")return"about:client";if(this[at].referrer)return this[at].referrer.toString()}get referrerPolicy(){return this[at].referrerPolicy}set referrerPolicy(e){this[at].referrerPolicy=EA(e)}clone(){return new DA(this)}get[Symbol.toStringTag](){return"Request"}};y(RA,"Request");da=RA;Object.defineProperties(da.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});uN=y(t=>{let{parsedURL:e}=t[at],n=new hr(t[at].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let a=rN(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=aN),t.referrer&&t.referrer!=="no-referrer"?t[at].referrer=TA(t):t[at].referrer="no-referrer",t[at].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=iN(e),i={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:i}},"getNodeRequestOptions"),OA=class extends fl{constructor(e,n="aborted"){super(e,n)}};y(OA,"AbortError");Ig=OA;y(PA,"requireNodeDomexception");lN=PA(),dN=yg(lN),{stat:Fg}=zF,IA=y((t,e)=>BA(lA(t),t,e),"blobFromSync"),FA=y((t,e)=>Fg(t).then(n=>BA(n,t,e)),"blobFrom"),NA=y((t,e)=>Fg(t).then(n=>UA(n,t,e)),"fileFrom"),MA=y((t,e)=>UA(lA(t),t,e),"fileFromSync"),BA=y((t,e,n="")=>new Do([new $A({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),UA=y((t,e,n="")=>new As([new $A({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],GF(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),jA=class LA{constructor(e){pr(this,xs),pr(this,Rs),rn(this,xs,e.path),rn(this,Rs,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new LA({path:ze(this,xs),lastModified:this.lastModified,size:n-e,start:ze(this,Rs)+e})}async*stream(){let{mtimeMs:e}=await Fg(ze(this,xs));if(e>this.lastModified)throw new dN("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*WF(ze(this,xs),{start:ze(this,Rs),end:ze(this,Rs)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};xs=new WeakMap,Rs=new WeakMap,y(jA,"BlobDataItem");$A=jA,fN=new Set(["data:","http:","https:"]);y(Ng,"fetch$1");y(qA,"fixResponseChunkedTransferBadEnding");HA=new WeakMap,vg=new WeakMap;y(Le,"pd");y(Tg,"setCancelFlag");y(Ro,"Event"),Ro.prototype={get type(){return Le(this).event.type},get target(){return Le(this).eventTarget},get currentTarget(){return Le(this).currentTarget},composedPath(){let t=Le(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Le(this).eventPhase},stopPropagation(){let t=Le(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Le(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Le(this).event.bubbles},get cancelable(){return!!Le(this).event.cancelable},preventDefault(){Tg(Le(this))},get defaultPrevented(){return Le(this).canceled},get composed(){return!!Le(this).event.composed},get timeStamp(){return Le(this).timeStamp},get srcElement(){return Le(this).eventTarget},get cancelBubble(){return Le(this).stopped},set cancelBubble(t){if(!t)return;let e=Le(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Le(this).canceled},set returnValue(t){t||Tg(Le(this))},initEvent(){}},Object.defineProperty(Ro.prototype,"constructor",{value:Ro,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Ro.prototype,window.Event.prototype),vg.set(window.Event.prototype,Ro));y(Mg,"defineRedirectDescriptor");y(zA,"defineCallDescriptor");y(WA,"defineWrapper");y(Bg,"getWrapper");y(GA,"wrapEvent");y(JA,"isStopped");y(KA,"setEventPhase");y(VA,"setCurrentTarget");y(xg,"setPassiveListener");YA=new WeakMap,iA=1,aA=2,rl=3;y(ua,"isObject");y(Ds,"getListeners");y(XA,"defineEventAttributeDescriptor");y(Ug,"defineEventAttribute");y(Rg,"defineCustomEventTarget");y(Nn,"EventTarget"),Nn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!ua(e))throw new TypeError("'listener' should be a function or an object.");let r=Ds(this),o=ua(n),s=(o?n.capture:n)?iA:aA,i={listener:e,listenerType:s,passive:o&&!!n.passive,once:o&&!!n.once,next:null},a=r.get(t);if(a===void 0){r.set(t,i);return}let u=null;for(;a!=null;){if(a.listener===e&&a.listenerType===s)return;u=a,a=a.next}u.next=i},removeEventListener(t,e,n){if(e==null)return;let r=Ds(this),o=(ua(n)?n.capture:n)?iA:aA,s=null,i=r.get(t);for(;i!=null;){if(i.listener===e&&i.listenerType===o){s!==null?s.next=i.next:i.next!==null?r.set(t,i.next):r.delete(t);return}s=i,i=i.next}},dispatchEvent(t){if(t==null||typeof t.type!="string")throw new TypeError('"event.type" should be a string.');let e=Ds(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=GA(this,t),s=null;for(;r!=null;){if(r.once?s!==null?s.next=r.next:r.next!==null?e.set(n,r.next):e.delete(n):s=r,xg(o,r.passive?r.listener:null),typeof r.listener=="function")try{r.listener.call(this,o)}catch(i){typeof console<"u"&&typeof console.error=="function"&&console.error(i)}else r.listenerType!==rl&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(JA(o))break;r=r.next}return xg(o,null),KA(o,0),VA(o,null),!o.defaultPrevented}},Object.defineProperty(Nn.prototype,"constructor",{value:Nn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(Nn.prototype,window.EventTarget.prototype);QA=class extends Nn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=ll.get(this);if(typeof e!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return e}};y(QA,"AbortSignal");ul=QA;Ug(ul.prototype,"abort");y(ZA,"createAbortSignal");y(eE,"abortSignal");ll=new WeakMap;Object.defineProperties(ul.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ul.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});dl=(wg=class{constructor(){tE.set(this,ZA())}get signal(){return Dg(this)}abort(){eE(Dg(this))}},y(wg,"AbortController"),wg),tE=new WeakMap;y(Dg,"getSignal"),Object.defineProperties(dl.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});pN=Object.defineProperty,hN=y((t,e)=>pN(t,"name",{value:e,configurable:!0}),"e"),nE=Ng;Og();y(Og,"s"),hN(Og,"checkNodeEnvironment")});var rE={};tC(rE,{AbortController:()=>kN,AbortError:()=>Ig,Blob:()=>mN,FetchError:()=>Wt,File:()=>yN,FormData:()=>_N,Headers:()=>bN,Request:()=>CN,Response:()=>wN,blobFrom:()=>FA,blobFromSync:()=>IA,default:()=>gN,fetch:()=>gN,fileFrom:()=>NA,fileFromSync:()=>MA,isRedirect:()=>pl});var Gr,gN,mN,yN,_N,bN,CN,wN,kN,oE=Br(()=>{Vu();Vu();Gu();Gr=!!globalThis.process?.env?.FORCE_NODE_FETCH,gN=!Gr&&globalThis.fetch||nE,mN=!Gr&&globalThis.Blob||Do,yN=!Gr&&globalThis.File||As,_N=!Gr&&globalThis.FormData||vo,bN=!Gr&&globalThis.Headers||hr,CN=!Gr&&globalThis.Request||da,wN=!Gr&&globalThis.Response||Fn,kN=!Gr&&globalThis.AbortController||dl});var aE=G(Ps=>{"use strict";var SN=Ps&&Ps.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Os;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.Gaxios=void 0;var AN=SN(og()),EN=re("https"),Oo=ag(),vN=CS(),sE=re("stream"),iE=lg(),TN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),xN=204,hl=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new iE.GaxiosInterceptorManager,response:new iE.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Os.mergeHeaders(s,n.headers),r&&Os.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Os.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=Buffer.concat(o.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=Oo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Oo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Oo.GaxiosError?r=n:n instanceof Error?r=new Oo.GaxiosError(n.message,e,void 0,n):r=new Oo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,vN.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===xN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Oo.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of s)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(r.toString()))return!1}else if(i instanceof URL){if(i.origin===r.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let a=i.replace(/^\*\./,".");if(r.hostname.endsWith(a))return!1}else if(i===r.origin||i===r.hostname||i===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Os.mergeHeaders(n,e.headers);let r=(0,AN.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let i=r.paramsSerializer(r.params);i.startsWith("?")&&(i=i.slice(1));let a=r.url.toString().includes("?")?"&":"?";r.url=r.url+a+i}else{let i=r.url instanceof URL?r.url:new URL(r.url);for(let[a,u]of new URLSearchParams(r.params))i.searchParams.append(a,u);r.url=i}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof sE.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let i=await TN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=sE.Readable.from(this.getMultipartRequest(r.multipart,i))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let i=await Os.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new i(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new EN.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Oo.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
89
+ `),r=!1,o=!1,s;t.on("response",i=>{let{headers:a}=i;r=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),t.on("socket",i=>{let a=y(()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},"onSocketClose"),u=y(d=>{o=pt.compare(d.slice(-5),n)===0,!o&&s&&(o=pt.compare(s.slice(-3),n.slice(0,3))===0&&pt.compare(d.slice(-2),n.slice(3))===0),s=d},"onData");i.prependListener("close",a),i.on("data",u),t.on("close",()=>{i.removeListener("close",a),i.removeListener("data",u)})})}function Le(t){let e=HA.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function vg(t){if(t.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",t.passiveListener);return}t.event.cancelable&&(t.canceled=!0,typeof t.event.preventDefault=="function"&&t.event.preventDefault())}function Ro(t,e){HA.set(this,{eventTarget:t,event:e,eventPhase:2,currentTarget:t,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:e.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let n=Object.keys(e);for(let r=0;r<n.length;++r){let o=n[r];o in this||Object.defineProperty(this,o,Ng(o))}}function Ng(t){return{get(){return Le(this).event[t]},set(e){Le(this).event[t]=e},configurable:!0,enumerable:!0}}function zA(t){return{value(){let e=Le(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function WA(t,e){let n=Object.keys(e);if(n.length===0)return t;function r(o,s){t.call(this,o,s)}y(r,"CustomEvent"),r.prototype=Object.create(t.prototype,{constructor:{value:r,configurable:!0,writable:!0}});for(let o=0;o<n.length;++o){let s=n[o];if(!(s in t.prototype)){let i=typeof Object.getOwnPropertyDescriptor(e,s).value=="function";Object.defineProperty(r.prototype,s,i?zA(s):Ng(s))}}return r}function Mg(t){if(t==null||t===Object.prototype)return Ro;let e=Eg.get(t);return e==null&&(e=WA(Mg(Object.getPrototypeOf(t)),t),Eg.set(t,e)),e}function GA(t,e){let n=Mg(Object.getPrototypeOf(e));return new n(t,e)}function JA(t){return Le(t).immediateStopped}function KA(t,e){Le(t).eventPhase=e}function VA(t,e){Le(t).currentTarget=e}function Tg(t,e){Le(t).passiveListener=e}function ua(t){return t!==null&&typeof t=="object"}function Ds(t){let e=YA.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function XA(t){return{get(){let e=Ds(this).get(t);for(;e!=null;){if(e.listenerType===rl)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!ua(e)&&(e=null);let n=Ds(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===rl?r!==null?r.next=o.next:o.next!==null?n.set(t,o.next):n.delete(t):r=o,o=o.next;if(e!==null){let s={listener:e,listenerType:rl,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function Bg(t,e){Object.defineProperty(t,`on${e}`,XA(e))}function xg(t){function e(){Nn.call(this)}y(e,"CustomEventTarget"),e.prototype=Object.create(Nn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)Bg(e.prototype,t[n]);return e}function Nn(){if(this instanceof Nn){YA.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return xg(arguments[0]);if(arguments.length>0){let t=new Array(arguments.length);for(let e=0;e<arguments.length;++e)t[e]=arguments[e];return xg(t)}throw new TypeError("Cannot call a class as a function")}function ZA(){let t=Object.create(ul.prototype);return Nn.call(t),ll.set(t,!1),t}function eE(t){ll.get(t)===!1&&(ll.set(t,!0),t.dispatchEvent({type:"abort"}))}function Rg(t){let e=tE.get(t);if(e==null)throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${t===null?"null":typeof t}`);return e}function Dg(){!globalThis.process?.versions?.node&&!globalThis.process?.env?.DISABLE_NODE_FETCH_NATIVE_WARN&&console.warn("[node-fetch-native] Node.js compatible build of `node-fetch-native` is being used in a non-Node.js environment. Please make sure you are using proper export conditions or report this issue to https://github.com/unjs/node-fetch-native. You can set `process.env.DISABLE_NODE_FETCH_NATIVE_WARN` to disable this warning.")}var LF,cA,y,uA,ze,pr,rn,Wr,Yu,Es,yg,oa,Xu,Qu,_g,tn,bg,xs,Rs,Cg,QS,Zu,KF,ZS,eA,nA,pA,Do,VF,As,aa,YF,XF,rA,QF,oA,wg,To,vo,gA,fl,mA,Wt,al,yA,cl,ZF,eN,tN,nN,Tt,_A,ca,Og,rN,bA,oN,sN,nl,Sg,CA,hr,iN,pl,nn,SA,Fn,aN,AA,cN,at,sa,uN,RA,da,lN,OA,Pg,kg,sA,dN,fN,Ig,IA,FA,NA,MA,BA,jA,UA,$A,pN,HA,Eg,YA,iA,aA,rl,QA,ul,ll,dl,tE,hN,gN,nE,Vu=Br(()=>{Gu();LF=Object.defineProperty,cA=t=>{throw TypeError(t)},y=(t,e)=>LF(t,"name",{value:e,configurable:!0}),uA=(t,e,n)=>e.has(t)||cA("Cannot "+n),ze=(t,e,n)=>(uA(t,e,"read from private field"),n?n.call(t):e.get(t)),pr=(t,e,n)=>e.has(t)?cA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),rn=(t,e,n,r)=>(uA(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);y(dA,"dataUriToBuffer");QS={},Zu={exports:{}};KF=Zu.exports;y(fA,"requirePonyfill_es2018");y(tA,"requireStreams"),tA();nA=65536;y(el,"toIterator");pA=(oa=class{constructor(t=[],e={}){if(pr(this,Wr,[]),pr(this,Yu,""),pr(this,Es,0),pr(this,yg,"transparent"),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof e!="object"&&typeof e!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");e===null&&(e={});let n=new TextEncoder;for(let o of t){let s;ArrayBuffer.isView(o)?s=new Uint8Array(o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)):o instanceof ArrayBuffer?s=new Uint8Array(o.slice(0)):o instanceof oa?s=o:s=n.encode(`${o}`),rn(this,Es,ze(this,Es)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),ze(this,Wr).push(s)}rn(this,yg,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);rn(this,Yu,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return ze(this,Es)}get type(){return ze(this,Yu)}async text(){let t=new TextDecoder,e="";for await(let n of el(ze(this,Wr),!1))e+=t.decode(n,{stream:!0});return e+=t.decode(),e}async arrayBuffer(){let t=new Uint8Array(this.size),e=0;for await(let n of el(ze(this,Wr),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=el(ze(this,Wr),!0);return new globalThis.ReadableStream({type:"bytes",async pull(e){let n=await t.next();n.done?e.close():e.enqueue(n.value)},async cancel(){await t.return()}})}slice(t=0,e=this.size,n=""){let{size:r}=this,o=t<0?Math.max(r+t,0):Math.min(t,r),s=e<0?Math.max(r+e,0):Math.min(e,r),i=Math.max(s-o,0),a=ze(this,Wr),u=[],d=0;for(let p of a){if(d>=i)break;let h=ArrayBuffer.isView(p)?p.byteLength:p.size;if(o&&h<=o)o-=h,s-=h;else{let g;ArrayBuffer.isView(p)?(g=p.subarray(o,Math.min(h,s)),d+=g.byteLength):(g=p.slice(o,Math.min(h,s)),d+=g.size),s-=h,u.push(g),o=0}}let f=new oa([],{type:String(n).toLowerCase()});return rn(f,Es,i),rn(f,Wr,u),f}get[Symbol.toStringTag](){return"Blob"}static[Symbol.hasInstance](t){return t&&typeof t=="object"&&typeof t.constructor=="function"&&(typeof t.stream=="function"||typeof t.arrayBuffer=="function")&&/^(Blob|File)$/.test(t[Symbol.toStringTag])}},Wr=new WeakMap,Yu=new WeakMap,Es=new WeakMap,yg=new WeakMap,y(oa,"Blob"),oa);Object.defineProperties(pA.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Do=pA,VF=(_g=class extends Do{constructor(t,e,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n),pr(this,Xu,0),pr(this,Qu,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||rn(this,Xu,r),rn(this,Qu,String(e))}get name(){return ze(this,Qu)}get lastModified(){return ze(this,Xu)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Do&&/^(File)$/.test(t[Symbol.toStringTag])}},Xu=new WeakMap,Qu=new WeakMap,y(_g,"File"),_g),As=VF;({toStringTag:aa,iterator:YF,hasInstance:XF}=Symbol),rA=Math.random,QF="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),oA=y((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[aa])?[(n=n!==void 0?n+"":e[aa]=="File"?e.name:"blob",t),e.name!==n||e[aa]=="blob"?new As([e],n,e):e]:[t,e+""]),"f"),wg=y((t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
90
+ `)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),To=y((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),vo=(bg=class{constructor(...t){if(pr(this,tn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[aa](){return"FormData"}[YF](){return this.entries()}static[XF](t){return t&&typeof t=="object"&&t[aa]==="FormData"&&!QF.some(e=>typeof t[e]!="function")}append(...t){To("append",arguments,2),ze(this,tn).push(oA(...t))}delete(t){To("delete",arguments,1),t+="",rn(this,tn,ze(this,tn).filter(([e])=>e!==t))}get(t){To("get",arguments,1),t+="";for(var e=ze(this,tn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return To("getAll",arguments,1),e=[],t+="",ze(this,tn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return To("has",arguments,1),t+="",ze(this,tn).some(e=>e[0]===t)}forEach(t,e){To("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){To("set",arguments,2);var e=[],n=!0;t=oA(...t),ze(this,tn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),rn(this,tn,e)}*entries(){yield*ze(this,tn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},tn=new WeakMap,y(bg,"FormData"),bg);y(hA,"formDataToBlob");gA=class extends Error{constructor(e,n){super(e),Error.captureStackTrace(this,this.constructor),this.type=n}get name(){return this.constructor.name}get[Symbol.toStringTag](){return this.constructor.name}};y(gA,"FetchBaseError");fl=gA,mA=class extends fl{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};y(mA,"FetchError");Wt=mA,al=Symbol.toStringTag,yA=y(t=>typeof t=="object"&&typeof t.append=="function"&&typeof t.delete=="function"&&typeof t.get=="function"&&typeof t.getAll=="function"&&typeof t.has=="function"&&typeof t.set=="function"&&typeof t.sort=="function"&&t[al]==="URLSearchParams","isURLSearchParameters"),cl=y(t=>t&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&typeof t.constructor=="function"&&/^(Blob|File)$/.test(t[al]),"isBlob"),ZF=y(t=>typeof t=="object"&&(t[al]==="AbortSignal"||t[al]==="EventTarget"),"isAbortSignal"),eN=y((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),tN=y((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),nN=qF(Mn.pipeline),Tt=Symbol("Body internals"),_A=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:yA(e)?e=pt.from(e.toString()):cl(e)||pt.isBuffer(e)||(sl.isAnyArrayBuffer(e)?e=pt.from(e):ArrayBuffer.isView(e)?e=pt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mn||(e instanceof vo?(e=hA(e),r=e.type.split("=")[1]):e=pt.from(String(e))));let o=e;pt.isBuffer(e)?o=Mn.Readable.from(e):cl(e)&&(o=Mn.Readable.from(e.stream())),this[Tt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Mn&&e.on("error",s=>{let i=s instanceof fl?s:new Wt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Tt].error=i})}get body(){return this[Tt].stream}get bodyUsed(){return this[Tt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await tl(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new vo,o=new URLSearchParams(await this.text());for(let[s,i]of o)r.append(s,i);return r}let{toFormData:n}=await Promise.resolve().then(()=>(XS(),YS));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Tt].body&&this[Tt].body.type||"",n=await this.arrayBuffer();return new Do([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await tl(this);return new TextDecoder().decode(e)}buffer(){return tl(this)}};y(_A,"Body");ca=_A;ca.prototype.buffer=il(ca.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(ca.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:il(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});y(tl,"consumeBody");Og=y((t,e)=>{let n,r,{body:o}=t[Tt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Mn&&typeof o.getBoundary!="function"&&(n=new ol({highWaterMark:e}),r=new ol({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Tt].stream=n,o=r),o},"clone"),rN=il(t=>t.getBoundary(),"form-data doesn't follow the spec and requires special treatment. Use alternative package","https://github.com/node-fetch/node-fetch/issues/1167"),bA=y((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":yA(t)?"application/x-www-form-urlencoded;charset=UTF-8":cl(t)?t.type||null:pt.isBuffer(t)||sl.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof vo?`multipart/form-data; boundary=${e[Tt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${rN(t)}`:t instanceof Mn?null:"text/plain;charset=UTF-8","extractContentType"),oN=y(t=>{let{body:e}=t[Tt];return e===null?0:cl(e)?e.size:pt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),sN=y(async(t,{body:e})=>{e===null?t.end():await nN(e,t)},"writeToStream"),nl=typeof la.validateHeaderName=="function"?la.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Sg=typeof la.validateHeaderValue=="function"?la.validateHeaderValue:(t,e)=>{if(/[^\t\u0020-\u007E\u0080-\u00FF]/.test(e)){let n=new TypeError(`Invalid character in header content ["${t}"]`);throw Object.defineProperty(n,"code",{value:"ERR_INVALID_CHAR"}),n}},CA=class wA extends URLSearchParams{constructor(e){let n=[];if(e instanceof wA){let r=e.raw();for(let[o,s]of Object.entries(r))n.push(...s.map(i=>[o,i]))}else if(e!=null)if(typeof e=="object"&&!sl.isBoxedPrimitive(e)){let r=e[Symbol.iterator];if(r==null)n.push(...Object.entries(e));else{if(typeof r!="function")throw new TypeError("Header pairs must be iterable");n=[...e].map(o=>{if(typeof o!="object"||sl.isBoxedPrimitive(o))throw new TypeError("Each header pair must be an iterable object");return[...o]}).map(o=>{if(o.length!==2)throw new TypeError("Each header pair must be a name/value tuple");return[...o]})}}else throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");return n=n.length>0?n.map(([r,o])=>(nl(r),Sg(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(i,a)=>(nl(i),Sg(i,String(a)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(a)));case"delete":case"has":case"getAll":return i=>(nl(i),URLSearchParams.prototype[o].call(r,String(i).toLowerCase()));case"keys":return()=>(r.sort(),new Set(URLSearchParams.prototype.keys.call(r)).keys());default:return Reflect.get(r,o,s)}}})}get[Symbol.toStringTag](){return this.constructor.name}toString(){return Object.prototype.toString.call(this)}get(e){let n=this.getAll(e);if(n.length===0)return null;let r=n.join(", ");return/^content-encoding$/i.test(e)&&(r=r.toLowerCase()),r}forEach(e,n=void 0){for(let r of this.keys())Reflect.apply(e,n,[this.get(r),r,this])}*values(){for(let e of this.keys())yield this.get(e)}*entries(){for(let e of this.keys())yield[e,this.get(e)]}[Symbol.iterator](){return this.entries()}raw(){return[...this.keys()].reduce((e,n)=>(e[n]=this.getAll(n),e),{})}[Symbol.for("nodejs.util.inspect.custom")](){return[...this.keys()].reduce((e,n)=>{let r=this.getAll(n);return n==="host"?e[n]=r[0]:e[n]=r.length>1?r:r[0],e},{})}};y(CA,"Headers");hr=CA;Object.defineProperties(hr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));y(kA,"fromRawHeaders");iN=new Set([301,302,303,307,308]),pl=y(t=>iN.has(t),"isRedirect"),nn=Symbol("Response internals"),SA=class ia extends ca{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new hr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=bA(e,this);s&&o.append("Content-Type",s)}this[nn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||""}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new ia(Og(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!pl(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new ia(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new ia(null,{status:0,statusText:""});return e[nn].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new hr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new ia(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};y(SA,"Response");Fn=SA;Object.defineProperties(Fn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});aN=y(t=>{if(t.search)return t.search;let e=t.href.length-1,n=t.hash||(t.href[e]==="#"?"#":"");return t.href[e-n.length]==="?"?"?":""},"getSearch");y(Ag,"stripURLForUseAsAReferrer");AA=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),cN="strict-origin-when-cross-origin";y(EA,"validateReferrerPolicy");y(vA,"isOriginPotentiallyTrustworthy");y(xo,"isUrlPotentiallyTrustworthy");y(TA,"determineRequestsReferrer");y(xA,"parseReferrerPolicyFromHeader");at=Symbol("Request internals"),sa=y(t=>typeof t=="object"&&typeof t[at]=="object","isRequest"),uN=il(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),RA=class DA extends ca{constructor(e,n={}){let r;if(sa(e)?r=new URL(e.url):(r=new URL(e),e={}),r.username!==""||r.password!=="")throw new TypeError(`${r} is an url with embedded credentials.`);let o=n.method||e.method||"GET";if(/^(delete|get|head|options|post|put)$/i.test(o)&&(o=o.toUpperCase()),!sa(n)&&"data"in n&&uN(),(n.body!=null||sa(e)&&e.body!==null)&&(o==="GET"||o==="HEAD"))throw new TypeError("Request with GET/HEAD method cannot have body");let s=n.body?n.body:sa(e)&&e.body!==null?Og(e):null;super(s,{size:n.size||e.size||0});let i=new hr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=bA(s,this);d&&i.set("Content-Type",d)}let a=sa(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!ZF(a))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=n.referrer==null?e.referrer:n.referrer;if(u==="")u="no-referrer";else if(u){let d=new URL(u);u=/^about:(\/\/)?client$/.test(d)?"client":d}else u=void 0;this[at]={method:o,redirect:n.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:a,referrer:u},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[at].method}get url(){return HF(this[at].parsedURL)}get headers(){return this[at].headers}get redirect(){return this[at].redirect}get signal(){return this[at].signal}get referrer(){if(this[at].referrer==="no-referrer")return"";if(this[at].referrer==="client")return"about:client";if(this[at].referrer)return this[at].referrer.toString()}get referrerPolicy(){return this[at].referrerPolicy}set referrerPolicy(e){this[at].referrerPolicy=EA(e)}clone(){return new DA(this)}get[Symbol.toStringTag](){return"Request"}};y(RA,"Request");da=RA;Object.defineProperties(da.prototype,{method:{enumerable:!0},url:{enumerable:!0},headers:{enumerable:!0},redirect:{enumerable:!0},clone:{enumerable:!0},signal:{enumerable:!0},referrer:{enumerable:!0},referrerPolicy:{enumerable:!0}});lN=y(t=>{let{parsedURL:e}=t[at],n=new hr(t[at].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let a=oN(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=cN),t.referrer&&t.referrer!=="no-referrer"?t[at].referrer=TA(t):t[at].referrer="no-referrer",t[at].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=aN(e),i={path:e.pathname+s,method:t.method,headers:n[Symbol.for("nodejs.util.inspect.custom")](),insecureHTTPParser:t.insecureHTTPParser,agent:o};return{parsedURL:e,options:i}},"getNodeRequestOptions"),OA=class extends fl{constructor(e,n="aborted"){super(e,n)}};y(OA,"AbortError");Pg=OA;y(PA,"requireNodeDomexception");dN=PA(),fN=mg(dN),{stat:Ig}=WF,IA=y((t,e)=>BA(lA(t),t,e),"blobFromSync"),FA=y((t,e)=>Ig(t).then(n=>BA(n,t,e)),"blobFrom"),NA=y((t,e)=>Ig(t).then(n=>jA(n,t,e)),"fileFrom"),MA=y((t,e)=>jA(lA(t),t,e),"fileFromSync"),BA=y((t,e,n="")=>new Do([new $A({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),jA=y((t,e,n="")=>new As([new $A({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],JF(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),UA=class LA{constructor(e){pr(this,xs),pr(this,Rs),rn(this,xs,e.path),rn(this,Rs,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new LA({path:ze(this,xs),lastModified:this.lastModified,size:n-e,start:ze(this,Rs)+e})}async*stream(){let{mtimeMs:e}=await Ig(ze(this,xs));if(e>this.lastModified)throw new fN("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.","NotReadableError");yield*GF(ze(this,xs),{start:ze(this,Rs),end:ze(this,Rs)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};xs=new WeakMap,Rs=new WeakMap,y(UA,"BlobDataItem");$A=UA,pN=new Set(["data:","http:","https:"]);y(Fg,"fetch$1");y(qA,"fixResponseChunkedTransferBadEnding");HA=new WeakMap,Eg=new WeakMap;y(Le,"pd");y(vg,"setCancelFlag");y(Ro,"Event"),Ro.prototype={get type(){return Le(this).event.type},get target(){return Le(this).eventTarget},get currentTarget(){return Le(this).currentTarget},composedPath(){let t=Le(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Le(this).eventPhase},stopPropagation(){let t=Le(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Le(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Le(this).event.bubbles},get cancelable(){return!!Le(this).event.cancelable},preventDefault(){vg(Le(this))},get defaultPrevented(){return Le(this).canceled},get composed(){return!!Le(this).event.composed},get timeStamp(){return Le(this).timeStamp},get srcElement(){return Le(this).eventTarget},get cancelBubble(){return Le(this).stopped},set cancelBubble(t){if(!t)return;let e=Le(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Le(this).canceled},set returnValue(t){t||vg(Le(this))},initEvent(){}},Object.defineProperty(Ro.prototype,"constructor",{value:Ro,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Ro.prototype,window.Event.prototype),Eg.set(window.Event.prototype,Ro));y(Ng,"defineRedirectDescriptor");y(zA,"defineCallDescriptor");y(WA,"defineWrapper");y(Mg,"getWrapper");y(GA,"wrapEvent");y(JA,"isStopped");y(KA,"setEventPhase");y(VA,"setCurrentTarget");y(Tg,"setPassiveListener");YA=new WeakMap,iA=1,aA=2,rl=3;y(ua,"isObject");y(Ds,"getListeners");y(XA,"defineEventAttributeDescriptor");y(Bg,"defineEventAttribute");y(xg,"defineCustomEventTarget");y(Nn,"EventTarget"),Nn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!ua(e))throw new TypeError("'listener' should be a function or an object.");let r=Ds(this),o=ua(n),s=(o?n.capture:n)?iA:aA,i={listener:e,listenerType:s,passive:o&&!!n.passive,once:o&&!!n.once,next:null},a=r.get(t);if(a===void 0){r.set(t,i);return}let u=null;for(;a!=null;){if(a.listener===e&&a.listenerType===s)return;u=a,a=a.next}u.next=i},removeEventListener(t,e,n){if(e==null)return;let r=Ds(this),o=(ua(n)?n.capture:n)?iA:aA,s=null,i=r.get(t);for(;i!=null;){if(i.listener===e&&i.listenerType===o){s!==null?s.next=i.next:i.next!==null?r.set(t,i.next):r.delete(t);return}s=i,i=i.next}},dispatchEvent(t){if(t==null||typeof t.type!="string")throw new TypeError('"event.type" should be a string.');let e=Ds(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=GA(this,t),s=null;for(;r!=null;){if(r.once?s!==null?s.next=r.next:r.next!==null?e.set(n,r.next):e.delete(n):s=r,Tg(o,r.passive?r.listener:null),typeof r.listener=="function")try{r.listener.call(this,o)}catch(i){typeof console<"u"&&typeof console.error=="function"&&console.error(i)}else r.listenerType!==rl&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(JA(o))break;r=r.next}return Tg(o,null),KA(o,0),VA(o,null),!o.defaultPrevented}},Object.defineProperty(Nn.prototype,"constructor",{value:Nn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(Nn.prototype,window.EventTarget.prototype);QA=class extends Nn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=ll.get(this);if(typeof e!="boolean")throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this===null?"null":typeof this}`);return e}};y(QA,"AbortSignal");ul=QA;Bg(ul.prototype,"abort");y(ZA,"createAbortSignal");y(eE,"abortSignal");ll=new WeakMap;Object.defineProperties(ul.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ul.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});dl=(Cg=class{constructor(){tE.set(this,ZA())}get signal(){return Rg(this)}abort(){eE(Rg(this))}},y(Cg,"AbortController"),Cg),tE=new WeakMap;y(Rg,"getSignal"),Object.defineProperties(dl.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});hN=Object.defineProperty,gN=y((t,e)=>hN(t,"name",{value:e,configurable:!0}),"e"),nE=Fg;Dg();y(Dg,"s"),gN(Dg,"checkNodeEnvironment")});var rE={};tC(rE,{AbortController:()=>SN,AbortError:()=>Pg,Blob:()=>yN,FetchError:()=>Wt,File:()=>_N,FormData:()=>bN,Headers:()=>CN,Request:()=>wN,Response:()=>kN,blobFrom:()=>FA,blobFromSync:()=>IA,default:()=>mN,fetch:()=>mN,fileFrom:()=>NA,fileFromSync:()=>MA,isRedirect:()=>pl});var Gr,mN,yN,_N,bN,CN,wN,kN,SN,oE=Br(()=>{Vu();Vu();Gu();Gr=!!globalThis.process?.env?.FORCE_NODE_FETCH,mN=!Gr&&globalThis.fetch||nE,yN=!Gr&&globalThis.Blob||Do,_N=!Gr&&globalThis.File||As,bN=!Gr&&globalThis.FormData||vo,CN=!Gr&&globalThis.Headers||hr,wN=!Gr&&globalThis.Request||da,kN=!Gr&&globalThis.Response||Fn,SN=!Gr&&globalThis.AbortController||dl});var aE=G(Ps=>{"use strict";var AN=Ps&&Ps.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Os;Object.defineProperty(Ps,"__esModule",{value:!0});Ps.Gaxios=void 0;var EN=AN(rg()),vN=re("https"),Oo=ig(),TN=CS(),sE=re("stream"),iE=ug(),xN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),RN=204,hl=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new iE.GaxiosInterceptorManager,response:new iE.GaxiosInterceptorManager}}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&Os.mergeHeaders(s,n.headers),r&&Os.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}async request(e={}){let n=await this.#r(e);return n=await this.#t(n),this.#n(this._request(n))}async _defaultAdapter(e){let n=e.fetchImplementation||this.defaults.fetchImplementation||await Os.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=Buffer.concat(o.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=Oo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Oo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Oo.GaxiosError?r=n:n instanceof Error?r=new Oo.GaxiosError(n.message,e,void 0,n):r=new Oo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,TN.getRetryConfig)(r);if(o&&s)return r.config.retryConfig.currentRetryAttempt=s.retryConfig.currentRetryAttempt,e.retryConfig=r.config?.retryConfig,this.#o(e),this._request(e);throw e.errorRedactor&&e.errorRedactor(r),r}}async getResponseData(e,n){if(n.status===RN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Oo.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of s)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(r.toString()))return!1}else if(i instanceof URL){if(i.origin===r.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let a=i.replace(/^\*\./,".");if(r.hostname.endsWith(a))return!1}else if(i===r.origin||i===r.hostname||i===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Os.mergeHeaders(n,e.headers);let r=(0,EN.default)(!0,{},this.defaults,e);if(!r.url)throw new Error("URL is required.");if(r.baseURL&&(r.url=new URL(r.url,r.baseURL)),r.url=new URL(r.url),r.params)if(r.paramsSerializer){let i=r.paramsSerializer(r.params);i.startsWith("?")&&(i=i.slice(1));let a=r.url.toString().includes("?")?"&":"?";r.url=r.url+a+i}else{let i=r.url instanceof URL?r.url:new URL(r.url);for(let[a,u]of new URLSearchParams(r.params))i.searchParams.append(a,u);r.url=i}typeof e.maxContentLength=="number"&&(r.size=e.maxContentLength),typeof e.maxRedirects=="number"&&(r.follow=e.maxRedirects);let o=typeof r.data=="string"||r.data instanceof ArrayBuffer||r.data instanceof Blob||globalThis.File&&r.data instanceof File||r.data instanceof FormData||r.data instanceof sE.Readable||r.data instanceof ReadableStream||r.data instanceof String||r.data instanceof URLSearchParams||ArrayBuffer.isView(r.data)||["Blob","File","FormData"].includes(r.data?.constructor?.name||"");if(r.multipart?.length){let i=await xN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=sE.Readable.from(this.getMultipartRequest(r.multipart,i))}else o?r.body=r.data:typeof r.data=="object"?n.get("Content-Type")==="application/x-www-form-urlencoded"?r.body=r.paramsSerializer?r.paramsSerializer(r.data):new URLSearchParams(r.data):(n.has("content-type")||n.set("content-type","application/json"),r.body=JSON.stringify(r.data)):r.data&&(r.body=r.data);r.validateStatus=r.validateStatus||this.validateStatus,r.responseType=r.responseType||"unknown",!n.has("accept")&&r.responseType==="json"&&n.set("accept","application/json");let s=r.proxy||process?.env?.HTTPS_PROXY||process?.env?.https_proxy||process?.env?.HTTP_PROXY||process?.env?.http_proxy;if(!r.agent)if(s&&this.#e(r.url,r.noProxy)){let i=await Os.#a();this.agentCache.has(s)?r.agent=this.agentCache.get(s):(r.agent=new i(s,{cert:r.cert,key:r.key}),this.agentCache.set(s,r.agent))}else r.cert&&r.key&&(this.agentCache.has(r.key)?r.agent=this.agentCache.get(r.key):(r.agent=new vN.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Oo.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
91
91
  Content-Type: ${s}\r
92
92
  \r
93
93
  `,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
94
- `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>nr(WS()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(oE(),rE))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,i)=>{i==="set-cookie"?e.append(i,s):e.set(i,s)});return e}};Ps.Gaxios=hl;Os=hl});var lt=G(bt=>{"use strict";var RN=bt&&bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),DN=bt&&bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&RN(e,t,n)};Object.defineProperty(bt,"__esModule",{value:!0});bt.instance=bt.Gaxios=bt.GaxiosError=void 0;bt.request=PN;var cE=aE();Object.defineProperty(bt,"Gaxios",{enumerable:!0,get:function(){return cE.Gaxios}});var ON=ag();Object.defineProperty(bt,"GaxiosError",{enumerable:!0,get:function(){return ON.GaxiosError}});DN(lg(),bt);bt.instance=new cE.Gaxios;async function PN(t){return bt.instance.request(t)}});var jg=G((uE,gl)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",i=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(x){var O,q,V,j=H.prototype={constructor:H,toString:null,valueOf:null},ee=new H(1),z=20,te=4,Q=-7,_e=21,Oe=-1e7,Te=1e7,Ke=!1,ne=1,Z=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",we=!0;function H(S,T){var R,M,D,F,L,P,N,U,B=this;if(!(B instanceof H))return new H(S,T);if(T==null){if(S&&S._isBigNumber===!0){B.s=S.s,!S.c||S.e>Te?B.c=B.e=null:S.e<Oe?B.c=[B.e=0]:(B.e=S.e,B.c=S.c.slice());return}if((P=typeof S=="number")&&S*0==0){if(B.s=1/S<0?(S=-S,-1):1,S===~~S){for(F=0,L=S;L>=10;L/=10,F++);F>Te?B.c=B.e=null:(B.e=F,B.c=[S]);return}U=String(S)}else{if(!n.test(U=String(S)))return V(B,U,P);B.s=U.charCodeAt(0)==45?(U=U.slice(1),-1):1}(F=U.indexOf("."))>-1&&(U=U.replace(".","")),(L=U.search(/e/i))>0?(F<0&&(F=L),F+=+U.slice(L+1),U=U.substring(0,L)):F<0&&(F=U.length)}else{if(C(T,2,Ie.length,"Base"),T==10&&we)return B=new H(S),de(B,z+B.e+1,te);if(U=String(S),P=typeof S=="number"){if(S*0!=0)return V(B,U,P,T);if(B.s=1/S<0?(U=U.slice(1),-1):1,H.DEBUG&&U.replace(/^0\.0*|\./,"").length>15)throw Error(i+S)}else B.s=U.charCodeAt(0)===45?(U=U.slice(1),-1):1;for(R=Ie.slice(0,T),F=L=0,N=U.length;L<N;L++)if(R.indexOf(M=U.charAt(L))<0){if(M=="."){if(L>F){F=N;continue}}else if(!D&&(U==U.toUpperCase()&&(U=U.toLowerCase())||U==U.toLowerCase()&&(U=U.toUpperCase()))){D=!0,L=-1,F=0;continue}return V(B,String(S),P,T)}P=!1,U=q(U,T,10,B.s),(F=U.indexOf("."))>-1?U=U.replace(".",""):F=U.length}for(L=0;U.charCodeAt(L)===48;L++);for(N=U.length;U.charCodeAt(--N)===48;);if(U=U.slice(L,++N)){if(N-=L,P&&H.DEBUG&&N>15&&(S>d||S!==o(S)))throw Error(i+B.s*S);if((F=F-L-1)>Te)B.c=B.e=null;else if(F<Oe)B.c=[B.e=0];else{if(B.e=F,B.c=[],L=(F+1)%u,F<0&&(L+=u),L<N){for(L&&B.c.push(+U.slice(0,L)),N-=u;L<N;)B.c.push(+U.slice(L,L+=u));L=u-(U=U.slice(L)).length}else L-=N;for(;L--;U+="0");B.c.push(+U)}}else B.c=[B.e=0]}H.clone=g,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(S){var T,R;if(S!=null)if(typeof S=="object"){if(S.hasOwnProperty(T="DECIMAL_PLACES")&&(R=S[T],C(R,0,h,T),z=R),S.hasOwnProperty(T="ROUNDING_MODE")&&(R=S[T],C(R,0,8,T),te=R),S.hasOwnProperty(T="EXPONENTIAL_AT")&&(R=S[T],R&&R.pop?(C(R[0],-h,0,T),C(R[1],0,h,T),Q=R[0],_e=R[1]):(C(R,-h,h,T),Q=-(_e=R<0?-R:R))),S.hasOwnProperty(T="RANGE"))if(R=S[T],R&&R.pop)C(R[0],-h,-1,T),C(R[1],1,h,T),Oe=R[0],Te=R[1];else if(C(R,-h,h,T),R)Oe=-(Te=R<0?-R:R);else throw Error(s+T+" cannot be zero: "+R);if(S.hasOwnProperty(T="CRYPTO"))if(R=S[T],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ke=R;else throw Ke=!R,Error(s+"crypto unavailable");else Ke=R;else throw Error(s+T+" not true or false: "+R);if(S.hasOwnProperty(T="MODULO_MODE")&&(R=S[T],C(R,0,9,T),ne=R),S.hasOwnProperty(T="POW_PRECISION")&&(R=S[T],C(R,0,h,T),Z=R),S.hasOwnProperty(T="FORMAT"))if(R=S[T],typeof R=="object")ae=R;else throw Error(s+T+" not an object: "+R);if(S.hasOwnProperty(T="ALPHABET"))if(R=S[T],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))we=R.slice(0,10)=="0123456789",Ie=R;else throw Error(s+T+" invalid: "+R)}else throw Error(s+"Object expected: "+S);return{DECIMAL_PLACES:z,ROUNDING_MODE:te,EXPONENTIAL_AT:[Q,_e],RANGE:[Oe,Te],CRYPTO:Ke,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ae,ALPHABET:Ie}},H.isBigNumber=function(S){if(!S||S._isBigNumber!==!0)return!1;if(!H.DEBUG)return!0;var T,R,M=S.c,D=S.e,F=S.s;e:if({}.toString.call(M)=="[object Array]"){if((F===1||F===-1)&&D>=-h&&D<=h&&D===o(D)){if(M[0]===0){if(D===0&&M.length===1)return!0;break e}if(T=(D+1)%u,T<1&&(T+=u),String(M[0]).length==T){for(T=0;T<M.length;T++)if(R=M[T],R<0||R>=a||R!==o(R))break e;if(R!==0)return!0}}}else if(M===null&&D===null&&(F===null||F===1||F===-1))return!0;throw Error(s+"Invalid BigNumber: "+S)},H.maximum=H.max=function(){return Ze(arguments,-1)},H.minimum=H.min=function(){return Ze(arguments,1)},H.random=(function(){var S=9007199254740992,T=Math.random()*S&2097151?function(){return o(Math.random()*S)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var M,D,F,L,P,N=0,U=[],B=new H(ee);if(R==null?R=z:C(R,0,h),L=r(R/u),Ke)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(L*=2));N<L;)P=M[N]*131072+(M[N+1]>>>11),P>=9e15?(D=crypto.getRandomValues(new Uint32Array(2)),M[N]=D[0],M[N+1]=D[1]):(U.push(P%1e14),N+=2);N=L/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(L*=7);N<L;)P=(M[N]&31)*281474976710656+M[N+1]*1099511627776+M[N+2]*4294967296+M[N+3]*16777216+(M[N+4]<<16)+(M[N+5]<<8)+M[N+6],P>=9e15?crypto.randomBytes(7).copy(M,N):(U.push(P%1e14),N+=7);N=L/7}else throw Ke=!1,Error(s+"crypto unavailable");if(!Ke)for(;N<L;)P=T(),P<9e15&&(U[N++]=P%1e14);for(L=U[--N],R%=u,L&&R&&(P=f[u-R],U[N]=o(L/P)*P);U[N]===0;U.pop(),N--);if(N<0)U=[F=0];else{for(F=-1;U[0]===0;U.splice(0,1),F-=u);for(N=1,P=U[0];P>=10;P/=10,N++);N<u&&(F-=u-N)}return B.e=F,B.c=U,B}})(),H.sum=function(){for(var S=1,T=arguments,R=new H(T[0]);S<T.length;)R=R.plus(T[S++]);return R},q=(function(){var S="0123456789";function T(R,M,D,F){for(var L,P=[0],N,U=0,B=R.length;U<B;){for(N=P.length;N--;P[N]*=M);for(P[0]+=F.indexOf(R.charAt(U++)),L=0;L<P.length;L++)P[L]>D-1&&(P[L+1]==null&&(P[L+1]=0),P[L+1]+=P[L]/D|0,P[L]%=D)}return P.reverse()}return function(R,M,D,F,L){var P,N,U,B,K,ie,ue,be,me=R.indexOf("."),he=z,ye=te;for(me>=0&&(B=Z,Z=0,R=R.replace(".",""),be=new H(M),ie=be.pow(R.length-me),Z=B,be.c=T(E(m(ie.c),ie.e,"0"),10,D,S),be.e=be.c.length),ue=T(R,M,D,L?(P=Ie,S):(P=S,Ie)),U=B=ue.length;ue[--B]==0;ue.pop());if(!ue[0])return P.charAt(0);if(me<0?--U:(ie.c=ue,ie.e=U,ie.s=F,ie=O(ie,be,he,ye,D),ue=ie.c,K=ie.r,U=ie.e),N=U+he+1,me=ue[N],B=D/2,K=K||N<0||ue[N+1]!=null,K=ye<4?(me!=null||K)&&(ye==0||ye==(ie.s<0?3:2)):me>B||me==B&&(ye==4||K||ye==6&&ue[N-1]&1||ye==(ie.s<0?8:7)),N<1||!ue[0])R=K?E(P.charAt(1),-he,P.charAt(0)):P.charAt(0);else{if(ue.length=N,K)for(--D;++ue[--N]>D;)ue[N]=0,N||(++U,ue=[1].concat(ue));for(B=ue.length;!ue[--B];);for(me=0,R="";me<=B;R+=P.charAt(ue[me++]));R=E(R,U,P.charAt(0))}return R}})(),O=(function(){function S(M,D,F){var L,P,N,U,B=0,K=M.length,ie=D%p,ue=D/p|0;for(M=M.slice();K--;)N=M[K]%p,U=M[K]/p|0,L=ue*N+U*ie,P=ie*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ue*U,M[K]=P%F;return B&&(M=[B].concat(M)),M}function T(M,D,F,L){var P,N;if(F!=L)N=F>L?1:-1;else for(P=N=0;P<F;P++)if(M[P]!=D[P]){N=M[P]>D[P]?1:-1;break}return N}function R(M,D,F,L){for(var P=0;F--;)M[F]-=P,P=M[F]<D[F]?1:0,M[F]=P*L+M[F]-D[F];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,D,F,L,P){var N,U,B,K,ie,ue,be,me,he,ye,Fe,Xe,mn,li,jo,xt,Ar,ht=M.s==D.s?1:-1,et=M.c,Ue=D.c;if(!et||!et[0]||!Ue||!Ue[0])return new H(!M.s||!D.s||(et?Ue&&et[0]==Ue[0]:!Ue)?NaN:et&&et[0]==0||!Ue?ht*0:ht/0);for(me=new H(ht),he=me.c=[],U=M.e-D.e,ht=F+U+1,P||(P=a,U=b(M.e/u)-b(D.e/u),ht=ht/u|0),B=0;Ue[B]==(et[B]||0);B++);if(Ue[B]>(et[B]||0)&&U--,ht<0)he.push(1),K=!0;else{for(li=et.length,xt=Ue.length,B=0,ht+=2,ie=o(P/(Ue[0]+1)),ie>1&&(Ue=S(Ue,ie,P),et=S(et,ie,P),xt=Ue.length,li=et.length),mn=xt,ye=et.slice(0,xt),Fe=ye.length;Fe<xt;ye[Fe++]=0);Ar=Ue.slice(),Ar=[0].concat(Ar),jo=Ue[0],Ue[1]>=P/2&&jo++;do{if(ie=0,N=T(Ue,ye,xt,Fe),N<0){if(Xe=ye[0],xt!=Fe&&(Xe=Xe*P+(ye[1]||0)),ie=o(Xe/jo),ie>1)for(ie>=P&&(ie=P-1),ue=S(Ue,ie,P),be=ue.length,Fe=ye.length;T(ue,ye,be,Fe)==1;)ie--,R(ue,xt<be?Ar:Ue,be,P),be=ue.length,N=1;else ie==0&&(N=ie=1),ue=Ue.slice(),be=ue.length;if(be<Fe&&(ue=[0].concat(ue)),R(ye,ue,Fe,P),Fe=ye.length,N==-1)for(;T(Ue,ye,xt,Fe)<1;)ie++,R(ye,xt<Fe?Ar:Ue,Fe,P),Fe=ye.length}else N===0&&(ie++,ye=[0]);he[B++]=ie,ye[0]?ye[Fe++]=et[mn]||0:(ye=[et[mn]],Fe=1)}while((mn++<li||ye[0]!=null)&&ht--);K=ye[0]!=null,he[0]||he.splice(0,1)}if(P==a){for(B=1,ht=he[0];ht>=10;ht/=10,B++);de(me,F+(me.e=B+U*u-1)+1,L,K)}else me.e=U,me.r=+K;return me}})();function Ee(S,T,R,M){var D,F,L,P,N;if(R==null?R=te:C(R,0,8),!S.c)return S.toString();if(D=S.c[0],L=S.e,T==null)N=m(S.c),N=M==1||M==2&&(L<=Q||L>=_e)?k(N,L):E(N,L,"0");else if(S=de(new H(S),T,R),F=S.e,N=m(S.c),P=N.length,M==1||M==2&&(T<=F||F<=Q)){for(;P<T;N+="0",P++);N=k(N,F)}else if(T-=L+(M===2&&F>L),N=E(N,F,"0"),F+1>P){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=F-P,T>0)for(F+1==P&&(N+=".");T--;N+="0");return S.s<0&&D?"-"+N:N}function Ze(S,T){for(var R,M,D=1,F=new H(S[0]);D<S.length;D++)M=new H(S[D]),(!M.s||(R=w(F,M))===T||R===0&&F.s===T)&&(F=M);return F}function X(S,T,R){for(var M=1,D=T.length;!T[--D];T.pop());for(D=T[0];D>=10;D/=10,M++);return(R=M+R*u-1)>Te?S.c=S.e=null:R<Oe?S.c=[S.e=0]:(S.e=R,S.c=T),S}V=(function(){var S=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,R=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,D=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(F,L,P,N){var U,B=P?L:L.replace(D,"");if(M.test(B))F.s=isNaN(B)?null:B<0?-1:1;else{if(!P&&(B=B.replace(S,function(K,ie,ue){return U=(ue=ue.toLowerCase())=="x"?16:ue=="b"?2:8,!N||N==U?ie:K}),N&&(U=N,B=B.replace(T,"$1").replace(R,"0.$1")),L!=B))return new H(B,U);if(H.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+L);F.s=null}F.c=F.e=null}})();function de(S,T,R,M){var D,F,L,P,N,U,B,K=S.c,ie=f;if(K){e:{for(D=1,P=K[0];P>=10;P/=10,D++);if(F=T-D,F<0)F+=u,L=T,N=K[U=0],B=o(N/ie[D-L-1]%10);else if(U=r((F+1)/u),U>=K.length)if(M){for(;K.length<=U;K.push(0));N=B=0,D=1,F%=u,L=F-u+1}else break e;else{for(N=P=K[U],D=1;P>=10;P/=10,D++);F%=u,L=F-u+D,B=L<0?0:o(N/ie[D-L-1]%10)}if(M=M||T<0||K[U+1]!=null||(L<0?N:N%ie[D-L-1]),M=R<4?(B||M)&&(R==0||R==(S.s<0?3:2)):B>5||B==5&&(R==4||M||R==6&&(F>0?L>0?N/ie[D-L]:0:K[U-1])%10&1||R==(S.s<0?8:7)),T<1||!K[0])return K.length=0,M?(T-=S.e+1,K[0]=ie[(u-T%u)%u],S.e=-T||0):K[0]=S.e=0,S;if(F==0?(K.length=U,P=1,U--):(K.length=U+1,P=ie[u-F],K[U]=L>0?o(N/ie[D-L]%ie[L])*P:0),M)for(;;)if(U==0){for(F=1,L=K[0];L>=10;L/=10,F++);for(L=K[0]+=P,P=1;L>=10;L/=10,P++);F!=P&&(S.e++,K[0]==a&&(K[0]=1));break}else{if(K[U]+=P,K[U]!=a)break;K[U--]=0,P=1}for(F=K.length;K[--F]===0;K.pop());}S.e>Te?S.c=S.e=null:S.e<Oe&&(S.c=[S.e=0])}return S}function ce(S){var T,R=S.e;return R===null?S.toString():(T=m(S.c),T=R<=Q||R>=_e?k(T,R):E(T,R,"0"),S.s<0?"-"+T:T)}return j.absoluteValue=j.abs=function(){var S=new H(this);return S.s<0&&(S.s=1),S},j.comparedTo=function(S,T){return w(this,new H(S,T))},j.decimalPlaces=j.dp=function(S,T){var R,M,D,F=this;if(S!=null)return C(S,0,h),T==null?T=te:C(T,0,8),de(new H(F),S+F.e+1,T);if(!(R=F.c))return null;if(M=((D=R.length-1)-b(this.e/u))*u,D=R[D])for(;D%10==0;D/=10,M--);return M<0&&(M=0),M},j.dividedBy=j.div=function(S,T){return O(this,new H(S,T),z,te)},j.dividedToIntegerBy=j.idiv=function(S,T){return O(this,new H(S,T),0,1)},j.exponentiatedBy=j.pow=function(S,T){var R,M,D,F,L,P,N,U,B,K=this;if(S=new H(S),S.c&&!S.isInteger())throw Error(s+"Exponent not an integer: "+ce(S));if(T!=null&&(T=new H(T)),P=S.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!S.c||!S.c[0])return B=new H(Math.pow(+ce(K),P?S.s*(2-A(S)):+ce(S))),T?B.mod(T):B;if(N=S.s<0,T){if(T.c?!T.c[0]:!T.s)return new H(NaN);M=!N&&K.isInteger()&&T.isInteger(),M&&(K=K.mod(T))}else{if(S.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||P&&K.c[1]>=24e7:K.c[0]<8e13||P&&K.c[0]<=9999975e7)))return F=K.s<0&&A(S)?-0:0,K.e>-1&&(F=1/F),new H(N?1/F:F);Z&&(F=r(Z/u+2))}for(P?(R=new H(.5),N&&(S.s=1),U=A(S)):(D=Math.abs(+ce(S)),U=D%2),B=new H(ee);;){if(U){if(B=B.times(K),!B.c)break;F?B.c.length>F&&(B.c.length=F):M&&(B=B.mod(T))}if(D){if(D=o(D/2),D===0)break;U=D%2}else if(S=S.times(R),de(S,S.e+1,1),S.e>14)U=A(S);else{if(D=+ce(S),D===0)break;U=D%2}K=K.times(K),F?K.c&&K.c.length>F&&(K.c.length=F):M&&(K=K.mod(T))}return M?B:(N&&(B=ee.div(B)),T?B.mod(T):F?de(B,Z,te,L):B)},j.integerValue=function(S){var T=new H(this);return S==null?S=te:C(S,0,8),de(T,T.e+1,S)},j.isEqualTo=j.eq=function(S,T){return w(this,new H(S,T))===0},j.isFinite=function(){return!!this.c},j.isGreaterThan=j.gt=function(S,T){return w(this,new H(S,T))>0},j.isGreaterThanOrEqualTo=j.gte=function(S,T){return(T=w(this,new H(S,T)))===1||T===0},j.isInteger=function(){return!!this.c&&b(this.e/u)>this.c.length-2},j.isLessThan=j.lt=function(S,T){return w(this,new H(S,T))<0},j.isLessThanOrEqualTo=j.lte=function(S,T){return(T=w(this,new H(S,T)))===-1||T===0},j.isNaN=function(){return!this.s},j.isNegative=function(){return this.s<0},j.isPositive=function(){return this.s>0},j.isZero=function(){return!!this.c&&this.c[0]==0},j.minus=function(S,T){var R,M,D,F,L=this,P=L.s;if(S=new H(S,T),T=S.s,!P||!T)return new H(NaN);if(P!=T)return S.s=-T,L.plus(S);var N=L.e/u,U=S.e/u,B=L.c,K=S.c;if(!N||!U){if(!B||!K)return B?(S.s=-T,S):new H(K?L:NaN);if(!B[0]||!K[0])return K[0]?(S.s=-T,S):new H(B[0]?L:te==3?-0:0)}if(N=b(N),U=b(U),B=B.slice(),P=N-U){for((F=P<0)?(P=-P,D=B):(U=N,D=K),D.reverse(),T=P;T--;D.push(0));D.reverse()}else for(M=(F=(P=B.length)<(T=K.length))?P:T,P=T=0;T<M;T++)if(B[T]!=K[T]){F=B[T]<K[T];break}if(F&&(D=B,B=K,K=D,S.s=-S.s),T=(M=K.length)-(R=B.length),T>0)for(;T--;B[R++]=0);for(T=a-1;M>P;){if(B[--M]<K[M]){for(R=M;R&&!B[--R];B[R]=T);--B[R],B[M]+=a}B[M]-=K[M]}for(;B[0]==0;B.splice(0,1),--U);return B[0]?X(S,B,U):(S.s=te==3?-1:1,S.c=[S.e=0],S)},j.modulo=j.mod=function(S,T){var R,M,D=this;return S=new H(S,T),!D.c||!S.s||S.c&&!S.c[0]?new H(NaN):!S.c||D.c&&!D.c[0]?new H(D):(ne==9?(M=S.s,S.s=1,R=O(D,S,0,3),S.s=M,R.s*=M):R=O(D,S,0,ne),S=D.minus(R.times(S)),!S.c[0]&&ne==1&&(S.s=D.s),S)},j.multipliedBy=j.times=function(S,T){var R,M,D,F,L,P,N,U,B,K,ie,ue,be,me,he,ye=this,Fe=ye.c,Xe=(S=new H(S,T)).c;if(!Fe||!Xe||!Fe[0]||!Xe[0])return!ye.s||!S.s||Fe&&!Fe[0]&&!Xe||Xe&&!Xe[0]&&!Fe?S.c=S.e=S.s=null:(S.s*=ye.s,!Fe||!Xe?S.c=S.e=null:(S.c=[0],S.e=0)),S;for(M=b(ye.e/u)+b(S.e/u),S.s*=ye.s,N=Fe.length,K=Xe.length,N<K&&(be=Fe,Fe=Xe,Xe=be,D=N,N=K,K=D),D=N+K,be=[];D--;be.push(0));for(me=a,he=p,D=K;--D>=0;){for(R=0,ie=Xe[D]%he,ue=Xe[D]/he|0,L=N,F=D+L;F>D;)U=Fe[--L]%he,B=Fe[L]/he|0,P=ue*U+B*ie,U=ie*U+P%he*he+be[F]+R,R=(U/me|0)+(P/he|0)+ue*B,be[F--]=U%me;be[F]=R}return R?++M:be.splice(0,1),X(S,be,M)},j.negated=function(){var S=new H(this);return S.s=-S.s||null,S},j.plus=function(S,T){var R,M=this,D=M.s;if(S=new H(S,T),T=S.s,!D||!T)return new H(NaN);if(D!=T)return S.s=-T,M.minus(S);var F=M.e/u,L=S.e/u,P=M.c,N=S.c;if(!F||!L){if(!P||!N)return new H(D/0);if(!P[0]||!N[0])return N[0]?S:new H(P[0]?M:D*0)}if(F=b(F),L=b(L),P=P.slice(),D=F-L){for(D>0?(L=F,R=N):(D=-D,R=P),R.reverse();D--;R.push(0));R.reverse()}for(D=P.length,T=N.length,D-T<0&&(R=N,N=P,P=R,T=D),D=0;T;)D=(P[--T]=P[T]+N[T]+D)/a|0,P[T]=a===P[T]?0:P[T]%a;return D&&(P=[D].concat(P),++L),X(S,P,L)},j.precision=j.sd=function(S,T){var R,M,D,F=this;if(S!=null&&S!==!!S)return C(S,1,h),T==null?T=te:C(T,0,8),de(new H(F),S,T);if(!(R=F.c))return null;if(D=R.length-1,M=D*u+1,D=R[D]){for(;D%10==0;D/=10,M--);for(D=R[0];D>=10;D/=10,M++);}return S&&F.e+1>M&&(M=F.e+1),M},j.shiftedBy=function(S){return C(S,-d,d),this.times("1e"+S)},j.squareRoot=j.sqrt=function(){var S,T,R,M,D,F=this,L=F.c,P=F.s,N=F.e,U=z+4,B=new H("0.5");if(P!==1||!L||!L[0])return new H(!P||P<0&&(!L||L[0])?NaN:L?F:1/0);if(P=Math.sqrt(+ce(F)),P==0||P==1/0?(T=m(L),(T.length+N)%2==0&&(T+="0"),P=Math.sqrt(+T),N=b((N+1)/2)-(N<0||N%2),P==1/0?T="5e"+N:(T=P.toExponential(),T=T.slice(0,T.indexOf("e")+1)+N),R=new H(T)):R=new H(P+""),R.c[0]){for(N=R.e,P=N+U,P<3&&(P=0);;)if(D=R,R=B.times(D.plus(O(F,D,U,1))),m(D.c).slice(0,P)===(T=m(R.c)).slice(0,P))if(R.e<N&&--P,T=T.slice(P-3,P+1),T=="9999"||!M&&T=="4999"){if(!M&&(de(D,D.e+z+2,0),D.times(D).eq(F))){R=D;break}U+=4,P+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(de(R,R.e+z+2,1),S=!R.times(R).eq(F));break}}return de(R,R.e+z+1,te,S)},j.toExponential=function(S,T){return S!=null&&(C(S,0,h),S++),Ee(this,S,T,1)},j.toFixed=function(S,T){return S!=null&&(C(S,0,h),S=S+this.e+1),Ee(this,S,T)},j.toFormat=function(S,T,R){var M,D=this;if(R==null)S!=null&&T&&typeof T=="object"?(R=T,T=null):S&&typeof S=="object"?(R=S,S=T=null):R=ae;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(M=D.toFixed(S,T),D.c){var F,L=M.split("."),P=+R.groupSize,N=+R.secondaryGroupSize,U=R.groupSeparator||"",B=L[0],K=L[1],ie=D.s<0,ue=ie?B.slice(1):B,be=ue.length;if(N&&(F=P,P=N,N=F,be-=F),P>0&&be>0){for(F=be%P||P,B=ue.substr(0,F);F<be;F+=P)B+=U+ue.substr(F,P);N>0&&(B+=U+ue.slice(F)),ie&&(B="-"+B)}M=K?B+(R.decimalSeparator||"")+((N=+R.fractionGroupSize)?K.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):K):B}return(R.prefix||"")+M+(R.suffix||"")},j.toFraction=function(S){var T,R,M,D,F,L,P,N,U,B,K,ie,ue=this,be=ue.c;if(S!=null&&(P=new H(S),!P.isInteger()&&(P.c||P.s!==1)||P.lt(ee)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+ce(P));if(!be)return new H(ue);for(T=new H(ee),U=R=new H(ee),M=N=new H(ee),ie=m(be),F=T.e=ie.length-ue.e-1,T.c[0]=f[(L=F%u)<0?u+L:L],S=!S||P.comparedTo(T)>0?F>0?T:U:P,L=Te,Te=1/0,P=new H(ie),N.c[0]=0;B=O(P,T,0,1),D=R.plus(B.times(M)),D.comparedTo(S)!=1;)R=M,M=D,U=N.plus(B.times(D=U)),N=D,T=P.minus(B.times(D=T)),P=D;return D=O(S.minus(R),M,0,1),N=N.plus(D.times(U)),R=R.plus(D.times(M)),N.s=U.s=ue.s,F=F*2,K=O(U,M,F,te).minus(ue).abs().comparedTo(O(N,R,F,te).minus(ue).abs())<1?[U,M]:[N,R],Te=L,K},j.toNumber=function(){return+ce(this)},j.toPrecision=function(S,T){return S!=null&&C(S,1,h),Ee(this,S,T,2)},j.toString=function(S){var T,R=this,M=R.s,D=R.e;return D===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(S==null?T=D<=Q||D>=_e?k(m(R.c),D):E(m(R.c),D,"0"):S===10&&we?(R=de(new H(R),z+D+1,te),T=E(m(R.c),R.e,"0")):(C(S,2,Ie.length,"Base"),T=q(E(m(R.c),D,"0"),10,S,M,!0)),M<0&&R.c[0]&&(T="-"+T)),T},j.valueOf=j.toJSON=function(){return ce(this)},j._isBigNumber=!0,x!=null&&H.set(x),H}function b(x){var O=x|0;return x>0||x===O?O:O-1}function m(x){for(var O,q,V=1,j=x.length,ee=x[0]+"";V<j;){for(O=x[V++]+"",q=u-O.length;q--;O="0"+O);ee+=O}for(j=ee.length;ee.charCodeAt(--j)===48;);return ee.slice(0,j+1||1)}function w(x,O){var q,V,j=x.c,ee=O.c,z=x.s,te=O.s,Q=x.e,_e=O.e;if(!z||!te)return null;if(q=j&&!j[0],V=ee&&!ee[0],q||V)return q?V?0:-te:z;if(z!=te)return z;if(q=z<0,V=Q==_e,!j||!ee)return V?0:!j^q?1:-1;if(!V)return Q>_e^q?1:-1;for(te=(Q=j.length)<(_e=ee.length)?Q:_e,z=0;z<te;z++)if(j[z]!=ee[z])return j[z]>ee[z]^q?1:-1;return Q==_e?0:Q>_e^q?1:-1}function C(x,O,q,V){if(x<O||x>q||x!==o(x))throw Error(s+(V||"Argument")+(typeof x=="number"?x<O||x>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(x))}function A(x){var O=x.c.length-1;return b(x.e/u)==O&&x.c[O]%2!=0}function k(x,O){return(x.length>1?x.charAt(0)+"."+x.slice(1):x)+(O<0?"e":"e+")+O}function E(x,O,q){var V,j;if(O<0){for(j=q+".";++O;j+=q);x=j+x}else if(V=x.length,++O>V){for(j=q,O-=V;--O;j+=q);x+=j}else O<V&&(x=x.slice(0,O)+"."+x.slice(O));return x}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof gl<"u"&&gl.exports?gl.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(uE)});var pE=G((e5,fE)=>{var lE=jg(),dE=fE.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function a(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function u(d,f){var p,h,g,b,m=r,w,C=f[d],A=C!=null&&(C instanceof lE||lE.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(d)),typeof i=="function"&&(C=i.call(f,d,C)),typeof C){case"string":return A?C:a(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(r+=o,w=[],Object.prototype.toString.apply(C)==="[object Array]"){for(b=C.length,p=0;p<b;p+=1)w[p]=u(p,C)||"null";return g=w.length===0?"[]":r?`[
94
+ `}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>nr(WS()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(oE(),rE))).default,this.#i}static mergeHeaders(e,...n){e=e instanceof Headers?e:new Headers(e);for(let r of n)(r instanceof Headers?r:new Headers(r)).forEach((s,i)=>{i==="set-cookie"?e.append(i,s):e.set(i,s)});return e}};Ps.Gaxios=hl;Os=hl});var lt=G(bt=>{"use strict";var DN=bt&&bt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ON=bt&&bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&DN(e,t,n)};Object.defineProperty(bt,"__esModule",{value:!0});bt.instance=bt.Gaxios=bt.GaxiosError=void 0;bt.request=IN;var cE=aE();Object.defineProperty(bt,"Gaxios",{enumerable:!0,get:function(){return cE.Gaxios}});var PN=ig();Object.defineProperty(bt,"GaxiosError",{enumerable:!0,get:function(){return PN.GaxiosError}});ON(ug(),bt);bt.instance=new cE.Gaxios;async function IN(t){return bt.instance.request(t)}});var jg=G((uE,gl)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",i=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(x){var O,q,V,U=H.prototype={constructor:H,toString:null,valueOf:null},ee=new H(1),z=20,te=4,Q=-7,_e=21,Oe=-1e7,Te=1e7,Ke=!1,ne=1,Z=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",we=!0;function H(A,T){var R,M,D,F,L,P,N,j,B=this;if(!(B instanceof H))return new H(A,T);if(T==null){if(A&&A._isBigNumber===!0){B.s=A.s,!A.c||A.e>Te?B.c=B.e=null:A.e<Oe?B.c=[B.e=0]:(B.e=A.e,B.c=A.c.slice());return}if((P=typeof A=="number")&&A*0==0){if(B.s=1/A<0?(A=-A,-1):1,A===~~A){for(F=0,L=A;L>=10;L/=10,F++);F>Te?B.c=B.e=null:(B.e=F,B.c=[A]);return}j=String(A)}else{if(!n.test(j=String(A)))return V(B,j,P);B.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(F=j.indexOf("."))>-1&&(j=j.replace(".","")),(L=j.search(/e/i))>0?(F<0&&(F=L),F+=+j.slice(L+1),j=j.substring(0,L)):F<0&&(F=j.length)}else{if(C(T,2,Ie.length,"Base"),T==10&&we)return B=new H(A),de(B,z+B.e+1,te);if(j=String(A),P=typeof A=="number"){if(A*0!=0)return V(B,j,P,T);if(B.s=1/A<0?(j=j.slice(1),-1):1,H.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(i+A)}else B.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(R=Ie.slice(0,T),F=L=0,N=j.length;L<N;L++)if(R.indexOf(M=j.charAt(L))<0){if(M=="."){if(L>F){F=N;continue}}else if(!D&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){D=!0,L=-1,F=0;continue}return V(B,String(A),P,T)}P=!1,j=q(j,T,10,B.s),(F=j.indexOf("."))>-1?j=j.replace(".",""):F=j.length}for(L=0;j.charCodeAt(L)===48;L++);for(N=j.length;j.charCodeAt(--N)===48;);if(j=j.slice(L,++N)){if(N-=L,P&&H.DEBUG&&N>15&&(A>d||A!==o(A)))throw Error(i+B.s*A);if((F=F-L-1)>Te)B.c=B.e=null;else if(F<Oe)B.c=[B.e=0];else{if(B.e=F,B.c=[],L=(F+1)%u,F<0&&(L+=u),L<N){for(L&&B.c.push(+j.slice(0,L)),N-=u;L<N;)B.c.push(+j.slice(L,L+=u));L=u-(j=j.slice(L)).length}else L-=N;for(;L--;j+="0");B.c.push(+j)}}else B.c=[B.e=0]}H.clone=g,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(A){var T,R;if(A!=null)if(typeof A=="object"){if(A.hasOwnProperty(T="DECIMAL_PLACES")&&(R=A[T],C(R,0,h,T),z=R),A.hasOwnProperty(T="ROUNDING_MODE")&&(R=A[T],C(R,0,8,T),te=R),A.hasOwnProperty(T="EXPONENTIAL_AT")&&(R=A[T],R&&R.pop?(C(R[0],-h,0,T),C(R[1],0,h,T),Q=R[0],_e=R[1]):(C(R,-h,h,T),Q=-(_e=R<0?-R:R))),A.hasOwnProperty(T="RANGE"))if(R=A[T],R&&R.pop)C(R[0],-h,-1,T),C(R[1],1,h,T),Oe=R[0],Te=R[1];else if(C(R,-h,h,T),R)Oe=-(Te=R<0?-R:R);else throw Error(s+T+" cannot be zero: "+R);if(A.hasOwnProperty(T="CRYPTO"))if(R=A[T],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ke=R;else throw Ke=!R,Error(s+"crypto unavailable");else Ke=R;else throw Error(s+T+" not true or false: "+R);if(A.hasOwnProperty(T="MODULO_MODE")&&(R=A[T],C(R,0,9,T),ne=R),A.hasOwnProperty(T="POW_PRECISION")&&(R=A[T],C(R,0,h,T),Z=R),A.hasOwnProperty(T="FORMAT"))if(R=A[T],typeof R=="object")ae=R;else throw Error(s+T+" not an object: "+R);if(A.hasOwnProperty(T="ALPHABET"))if(R=A[T],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))we=R.slice(0,10)=="0123456789",Ie=R;else throw Error(s+T+" invalid: "+R)}else throw Error(s+"Object expected: "+A);return{DECIMAL_PLACES:z,ROUNDING_MODE:te,EXPONENTIAL_AT:[Q,_e],RANGE:[Oe,Te],CRYPTO:Ke,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ae,ALPHABET:Ie}},H.isBigNumber=function(A){if(!A||A._isBigNumber!==!0)return!1;if(!H.DEBUG)return!0;var T,R,M=A.c,D=A.e,F=A.s;e:if({}.toString.call(M)=="[object Array]"){if((F===1||F===-1)&&D>=-h&&D<=h&&D===o(D)){if(M[0]===0){if(D===0&&M.length===1)return!0;break e}if(T=(D+1)%u,T<1&&(T+=u),String(M[0]).length==T){for(T=0;T<M.length;T++)if(R=M[T],R<0||R>=a||R!==o(R))break e;if(R!==0)return!0}}}else if(M===null&&D===null&&(F===null||F===1||F===-1))return!0;throw Error(s+"Invalid BigNumber: "+A)},H.maximum=H.max=function(){return Ze(arguments,-1)},H.minimum=H.min=function(){return Ze(arguments,1)},H.random=(function(){var A=9007199254740992,T=Math.random()*A&2097151?function(){return o(Math.random()*A)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var M,D,F,L,P,N=0,j=[],B=new H(ee);if(R==null?R=z:C(R,0,h),L=r(R/u),Ke)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(L*=2));N<L;)P=M[N]*131072+(M[N+1]>>>11),P>=9e15?(D=crypto.getRandomValues(new Uint32Array(2)),M[N]=D[0],M[N+1]=D[1]):(j.push(P%1e14),N+=2);N=L/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(L*=7);N<L;)P=(M[N]&31)*281474976710656+M[N+1]*1099511627776+M[N+2]*4294967296+M[N+3]*16777216+(M[N+4]<<16)+(M[N+5]<<8)+M[N+6],P>=9e15?crypto.randomBytes(7).copy(M,N):(j.push(P%1e14),N+=7);N=L/7}else throw Ke=!1,Error(s+"crypto unavailable");if(!Ke)for(;N<L;)P=T(),P<9e15&&(j[N++]=P%1e14);for(L=j[--N],R%=u,L&&R&&(P=f[u-R],j[N]=o(L/P)*P);j[N]===0;j.pop(),N--);if(N<0)j=[F=0];else{for(F=-1;j[0]===0;j.splice(0,1),F-=u);for(N=1,P=j[0];P>=10;P/=10,N++);N<u&&(F-=u-N)}return B.e=F,B.c=j,B}})(),H.sum=function(){for(var A=1,T=arguments,R=new H(T[0]);A<T.length;)R=R.plus(T[A++]);return R},q=(function(){var A="0123456789";function T(R,M,D,F){for(var L,P=[0],N,j=0,B=R.length;j<B;){for(N=P.length;N--;P[N]*=M);for(P[0]+=F.indexOf(R.charAt(j++)),L=0;L<P.length;L++)P[L]>D-1&&(P[L+1]==null&&(P[L+1]=0),P[L+1]+=P[L]/D|0,P[L]%=D)}return P.reverse()}return function(R,M,D,F,L){var P,N,j,B,K,ie,ue,be,me=R.indexOf("."),he=z,ye=te;for(me>=0&&(B=Z,Z=0,R=R.replace(".",""),be=new H(M),ie=be.pow(R.length-me),Z=B,be.c=T(E(m(ie.c),ie.e,"0"),10,D,A),be.e=be.c.length),ue=T(R,M,D,L?(P=Ie,A):(P=A,Ie)),j=B=ue.length;ue[--B]==0;ue.pop());if(!ue[0])return P.charAt(0);if(me<0?--j:(ie.c=ue,ie.e=j,ie.s=F,ie=O(ie,be,he,ye,D),ue=ie.c,K=ie.r,j=ie.e),N=j+he+1,me=ue[N],B=D/2,K=K||N<0||ue[N+1]!=null,K=ye<4?(me!=null||K)&&(ye==0||ye==(ie.s<0?3:2)):me>B||me==B&&(ye==4||K||ye==6&&ue[N-1]&1||ye==(ie.s<0?8:7)),N<1||!ue[0])R=K?E(P.charAt(1),-he,P.charAt(0)):P.charAt(0);else{if(ue.length=N,K)for(--D;++ue[--N]>D;)ue[N]=0,N||(++j,ue=[1].concat(ue));for(B=ue.length;!ue[--B];);for(me=0,R="";me<=B;R+=P.charAt(ue[me++]));R=E(R,j,P.charAt(0))}return R}})(),O=(function(){function A(M,D,F){var L,P,N,j,B=0,K=M.length,ie=D%p,ue=D/p|0;for(M=M.slice();K--;)N=M[K]%p,j=M[K]/p|0,L=ue*N+j*ie,P=ie*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ue*j,M[K]=P%F;return B&&(M=[B].concat(M)),M}function T(M,D,F,L){var P,N;if(F!=L)N=F>L?1:-1;else for(P=N=0;P<F;P++)if(M[P]!=D[P]){N=M[P]>D[P]?1:-1;break}return N}function R(M,D,F,L){for(var P=0;F--;)M[F]-=P,P=M[F]<D[F]?1:0,M[F]=P*L+M[F]-D[F];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,D,F,L,P){var N,j,B,K,ie,ue,be,me,he,ye,Fe,Xe,mn,li,Uo,xt,Ar,ht=M.s==D.s?1:-1,et=M.c,je=D.c;if(!et||!et[0]||!je||!je[0])return new H(!M.s||!D.s||(et?je&&et[0]==je[0]:!je)?NaN:et&&et[0]==0||!je?ht*0:ht/0);for(me=new H(ht),he=me.c=[],j=M.e-D.e,ht=F+j+1,P||(P=a,j=b(M.e/u)-b(D.e/u),ht=ht/u|0),B=0;je[B]==(et[B]||0);B++);if(je[B]>(et[B]||0)&&j--,ht<0)he.push(1),K=!0;else{for(li=et.length,xt=je.length,B=0,ht+=2,ie=o(P/(je[0]+1)),ie>1&&(je=A(je,ie,P),et=A(et,ie,P),xt=je.length,li=et.length),mn=xt,ye=et.slice(0,xt),Fe=ye.length;Fe<xt;ye[Fe++]=0);Ar=je.slice(),Ar=[0].concat(Ar),Uo=je[0],je[1]>=P/2&&Uo++;do{if(ie=0,N=T(je,ye,xt,Fe),N<0){if(Xe=ye[0],xt!=Fe&&(Xe=Xe*P+(ye[1]||0)),ie=o(Xe/Uo),ie>1)for(ie>=P&&(ie=P-1),ue=A(je,ie,P),be=ue.length,Fe=ye.length;T(ue,ye,be,Fe)==1;)ie--,R(ue,xt<be?Ar:je,be,P),be=ue.length,N=1;else ie==0&&(N=ie=1),ue=je.slice(),be=ue.length;if(be<Fe&&(ue=[0].concat(ue)),R(ye,ue,Fe,P),Fe=ye.length,N==-1)for(;T(je,ye,xt,Fe)<1;)ie++,R(ye,xt<Fe?Ar:je,Fe,P),Fe=ye.length}else N===0&&(ie++,ye=[0]);he[B++]=ie,ye[0]?ye[Fe++]=et[mn]||0:(ye=[et[mn]],Fe=1)}while((mn++<li||ye[0]!=null)&&ht--);K=ye[0]!=null,he[0]||he.splice(0,1)}if(P==a){for(B=1,ht=he[0];ht>=10;ht/=10,B++);de(me,F+(me.e=B+j*u-1)+1,L,K)}else me.e=j,me.r=+K;return me}})();function Ee(A,T,R,M){var D,F,L,P,N;if(R==null?R=te:C(R,0,8),!A.c)return A.toString();if(D=A.c[0],L=A.e,T==null)N=m(A.c),N=M==1||M==2&&(L<=Q||L>=_e)?k(N,L):E(N,L,"0");else if(A=de(new H(A),T,R),F=A.e,N=m(A.c),P=N.length,M==1||M==2&&(T<=F||F<=Q)){for(;P<T;N+="0",P++);N=k(N,F)}else if(T-=L+(M===2&&F>L),N=E(N,F,"0"),F+1>P){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=F-P,T>0)for(F+1==P&&(N+=".");T--;N+="0");return A.s<0&&D?"-"+N:N}function Ze(A,T){for(var R,M,D=1,F=new H(A[0]);D<A.length;D++)M=new H(A[D]),(!M.s||(R=w(F,M))===T||R===0&&F.s===T)&&(F=M);return F}function X(A,T,R){for(var M=1,D=T.length;!T[--D];T.pop());for(D=T[0];D>=10;D/=10,M++);return(R=M+R*u-1)>Te?A.c=A.e=null:R<Oe?A.c=[A.e=0]:(A.e=R,A.c=T),A}V=(function(){var A=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,R=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,D=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(F,L,P,N){var j,B=P?L:L.replace(D,"");if(M.test(B))F.s=isNaN(B)?null:B<0?-1:1;else{if(!P&&(B=B.replace(A,function(K,ie,ue){return j=(ue=ue.toLowerCase())=="x"?16:ue=="b"?2:8,!N||N==j?ie:K}),N&&(j=N,B=B.replace(T,"$1").replace(R,"0.$1")),L!=B))return new H(B,j);if(H.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+L);F.s=null}F.c=F.e=null}})();function de(A,T,R,M){var D,F,L,P,N,j,B,K=A.c,ie=f;if(K){e:{for(D=1,P=K[0];P>=10;P/=10,D++);if(F=T-D,F<0)F+=u,L=T,N=K[j=0],B=o(N/ie[D-L-1]%10);else if(j=r((F+1)/u),j>=K.length)if(M){for(;K.length<=j;K.push(0));N=B=0,D=1,F%=u,L=F-u+1}else break e;else{for(N=P=K[j],D=1;P>=10;P/=10,D++);F%=u,L=F-u+D,B=L<0?0:o(N/ie[D-L-1]%10)}if(M=M||T<0||K[j+1]!=null||(L<0?N:N%ie[D-L-1]),M=R<4?(B||M)&&(R==0||R==(A.s<0?3:2)):B>5||B==5&&(R==4||M||R==6&&(F>0?L>0?N/ie[D-L]:0:K[j-1])%10&1||R==(A.s<0?8:7)),T<1||!K[0])return K.length=0,M?(T-=A.e+1,K[0]=ie[(u-T%u)%u],A.e=-T||0):K[0]=A.e=0,A;if(F==0?(K.length=j,P=1,j--):(K.length=j+1,P=ie[u-F],K[j]=L>0?o(N/ie[D-L]%ie[L])*P:0),M)for(;;)if(j==0){for(F=1,L=K[0];L>=10;L/=10,F++);for(L=K[0]+=P,P=1;L>=10;L/=10,P++);F!=P&&(A.e++,K[0]==a&&(K[0]=1));break}else{if(K[j]+=P,K[j]!=a)break;K[j--]=0,P=1}for(F=K.length;K[--F]===0;K.pop());}A.e>Te?A.c=A.e=null:A.e<Oe&&(A.c=[A.e=0])}return A}function ce(A){var T,R=A.e;return R===null?A.toString():(T=m(A.c),T=R<=Q||R>=_e?k(T,R):E(T,R,"0"),A.s<0?"-"+T:T)}return U.absoluteValue=U.abs=function(){var A=new H(this);return A.s<0&&(A.s=1),A},U.comparedTo=function(A,T){return w(this,new H(A,T))},U.decimalPlaces=U.dp=function(A,T){var R,M,D,F=this;if(A!=null)return C(A,0,h),T==null?T=te:C(T,0,8),de(new H(F),A+F.e+1,T);if(!(R=F.c))return null;if(M=((D=R.length-1)-b(this.e/u))*u,D=R[D])for(;D%10==0;D/=10,M--);return M<0&&(M=0),M},U.dividedBy=U.div=function(A,T){return O(this,new H(A,T),z,te)},U.dividedToIntegerBy=U.idiv=function(A,T){return O(this,new H(A,T),0,1)},U.exponentiatedBy=U.pow=function(A,T){var R,M,D,F,L,P,N,j,B,K=this;if(A=new H(A),A.c&&!A.isInteger())throw Error(s+"Exponent not an integer: "+ce(A));if(T!=null&&(T=new H(T)),P=A.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!A.c||!A.c[0])return B=new H(Math.pow(+ce(K),P?A.s*(2-S(A)):+ce(A))),T?B.mod(T):B;if(N=A.s<0,T){if(T.c?!T.c[0]:!T.s)return new H(NaN);M=!N&&K.isInteger()&&T.isInteger(),M&&(K=K.mod(T))}else{if(A.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||P&&K.c[1]>=24e7:K.c[0]<8e13||P&&K.c[0]<=9999975e7)))return F=K.s<0&&S(A)?-0:0,K.e>-1&&(F=1/F),new H(N?1/F:F);Z&&(F=r(Z/u+2))}for(P?(R=new H(.5),N&&(A.s=1),j=S(A)):(D=Math.abs(+ce(A)),j=D%2),B=new H(ee);;){if(j){if(B=B.times(K),!B.c)break;F?B.c.length>F&&(B.c.length=F):M&&(B=B.mod(T))}if(D){if(D=o(D/2),D===0)break;j=D%2}else if(A=A.times(R),de(A,A.e+1,1),A.e>14)j=S(A);else{if(D=+ce(A),D===0)break;j=D%2}K=K.times(K),F?K.c&&K.c.length>F&&(K.c.length=F):M&&(K=K.mod(T))}return M?B:(N&&(B=ee.div(B)),T?B.mod(T):F?de(B,Z,te,L):B)},U.integerValue=function(A){var T=new H(this);return A==null?A=te:C(A,0,8),de(T,T.e+1,A)},U.isEqualTo=U.eq=function(A,T){return w(this,new H(A,T))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(A,T){return w(this,new H(A,T))>0},U.isGreaterThanOrEqualTo=U.gte=function(A,T){return(T=w(this,new H(A,T)))===1||T===0},U.isInteger=function(){return!!this.c&&b(this.e/u)>this.c.length-2},U.isLessThan=U.lt=function(A,T){return w(this,new H(A,T))<0},U.isLessThanOrEqualTo=U.lte=function(A,T){return(T=w(this,new H(A,T)))===-1||T===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(A,T){var R,M,D,F,L=this,P=L.s;if(A=new H(A,T),T=A.s,!P||!T)return new H(NaN);if(P!=T)return A.s=-T,L.plus(A);var N=L.e/u,j=A.e/u,B=L.c,K=A.c;if(!N||!j){if(!B||!K)return B?(A.s=-T,A):new H(K?L:NaN);if(!B[0]||!K[0])return K[0]?(A.s=-T,A):new H(B[0]?L:te==3?-0:0)}if(N=b(N),j=b(j),B=B.slice(),P=N-j){for((F=P<0)?(P=-P,D=B):(j=N,D=K),D.reverse(),T=P;T--;D.push(0));D.reverse()}else for(M=(F=(P=B.length)<(T=K.length))?P:T,P=T=0;T<M;T++)if(B[T]!=K[T]){F=B[T]<K[T];break}if(F&&(D=B,B=K,K=D,A.s=-A.s),T=(M=K.length)-(R=B.length),T>0)for(;T--;B[R++]=0);for(T=a-1;M>P;){if(B[--M]<K[M]){for(R=M;R&&!B[--R];B[R]=T);--B[R],B[M]+=a}B[M]-=K[M]}for(;B[0]==0;B.splice(0,1),--j);return B[0]?X(A,B,j):(A.s=te==3?-1:1,A.c=[A.e=0],A)},U.modulo=U.mod=function(A,T){var R,M,D=this;return A=new H(A,T),!D.c||!A.s||A.c&&!A.c[0]?new H(NaN):!A.c||D.c&&!D.c[0]?new H(D):(ne==9?(M=A.s,A.s=1,R=O(D,A,0,3),A.s=M,R.s*=M):R=O(D,A,0,ne),A=D.minus(R.times(A)),!A.c[0]&&ne==1&&(A.s=D.s),A)},U.multipliedBy=U.times=function(A,T){var R,M,D,F,L,P,N,j,B,K,ie,ue,be,me,he,ye=this,Fe=ye.c,Xe=(A=new H(A,T)).c;if(!Fe||!Xe||!Fe[0]||!Xe[0])return!ye.s||!A.s||Fe&&!Fe[0]&&!Xe||Xe&&!Xe[0]&&!Fe?A.c=A.e=A.s=null:(A.s*=ye.s,!Fe||!Xe?A.c=A.e=null:(A.c=[0],A.e=0)),A;for(M=b(ye.e/u)+b(A.e/u),A.s*=ye.s,N=Fe.length,K=Xe.length,N<K&&(be=Fe,Fe=Xe,Xe=be,D=N,N=K,K=D),D=N+K,be=[];D--;be.push(0));for(me=a,he=p,D=K;--D>=0;){for(R=0,ie=Xe[D]%he,ue=Xe[D]/he|0,L=N,F=D+L;F>D;)j=Fe[--L]%he,B=Fe[L]/he|0,P=ue*j+B*ie,j=ie*j+P%he*he+be[F]+R,R=(j/me|0)+(P/he|0)+ue*B,be[F--]=j%me;be[F]=R}return R?++M:be.splice(0,1),X(A,be,M)},U.negated=function(){var A=new H(this);return A.s=-A.s||null,A},U.plus=function(A,T){var R,M=this,D=M.s;if(A=new H(A,T),T=A.s,!D||!T)return new H(NaN);if(D!=T)return A.s=-T,M.minus(A);var F=M.e/u,L=A.e/u,P=M.c,N=A.c;if(!F||!L){if(!P||!N)return new H(D/0);if(!P[0]||!N[0])return N[0]?A:new H(P[0]?M:D*0)}if(F=b(F),L=b(L),P=P.slice(),D=F-L){for(D>0?(L=F,R=N):(D=-D,R=P),R.reverse();D--;R.push(0));R.reverse()}for(D=P.length,T=N.length,D-T<0&&(R=N,N=P,P=R,T=D),D=0;T;)D=(P[--T]=P[T]+N[T]+D)/a|0,P[T]=a===P[T]?0:P[T]%a;return D&&(P=[D].concat(P),++L),X(A,P,L)},U.precision=U.sd=function(A,T){var R,M,D,F=this;if(A!=null&&A!==!!A)return C(A,1,h),T==null?T=te:C(T,0,8),de(new H(F),A,T);if(!(R=F.c))return null;if(D=R.length-1,M=D*u+1,D=R[D]){for(;D%10==0;D/=10,M--);for(D=R[0];D>=10;D/=10,M++);}return A&&F.e+1>M&&(M=F.e+1),M},U.shiftedBy=function(A){return C(A,-d,d),this.times("1e"+A)},U.squareRoot=U.sqrt=function(){var A,T,R,M,D,F=this,L=F.c,P=F.s,N=F.e,j=z+4,B=new H("0.5");if(P!==1||!L||!L[0])return new H(!P||P<0&&(!L||L[0])?NaN:L?F:1/0);if(P=Math.sqrt(+ce(F)),P==0||P==1/0?(T=m(L),(T.length+N)%2==0&&(T+="0"),P=Math.sqrt(+T),N=b((N+1)/2)-(N<0||N%2),P==1/0?T="5e"+N:(T=P.toExponential(),T=T.slice(0,T.indexOf("e")+1)+N),R=new H(T)):R=new H(P+""),R.c[0]){for(N=R.e,P=N+j,P<3&&(P=0);;)if(D=R,R=B.times(D.plus(O(F,D,j,1))),m(D.c).slice(0,P)===(T=m(R.c)).slice(0,P))if(R.e<N&&--P,T=T.slice(P-3,P+1),T=="9999"||!M&&T=="4999"){if(!M&&(de(D,D.e+z+2,0),D.times(D).eq(F))){R=D;break}j+=4,P+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(de(R,R.e+z+2,1),A=!R.times(R).eq(F));break}}return de(R,R.e+z+1,te,A)},U.toExponential=function(A,T){return A!=null&&(C(A,0,h),A++),Ee(this,A,T,1)},U.toFixed=function(A,T){return A!=null&&(C(A,0,h),A=A+this.e+1),Ee(this,A,T)},U.toFormat=function(A,T,R){var M,D=this;if(R==null)A!=null&&T&&typeof T=="object"?(R=T,T=null):A&&typeof A=="object"?(R=A,A=T=null):R=ae;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(M=D.toFixed(A,T),D.c){var F,L=M.split("."),P=+R.groupSize,N=+R.secondaryGroupSize,j=R.groupSeparator||"",B=L[0],K=L[1],ie=D.s<0,ue=ie?B.slice(1):B,be=ue.length;if(N&&(F=P,P=N,N=F,be-=F),P>0&&be>0){for(F=be%P||P,B=ue.substr(0,F);F<be;F+=P)B+=j+ue.substr(F,P);N>0&&(B+=j+ue.slice(F)),ie&&(B="-"+B)}M=K?B+(R.decimalSeparator||"")+((N=+R.fractionGroupSize)?K.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):K):B}return(R.prefix||"")+M+(R.suffix||"")},U.toFraction=function(A){var T,R,M,D,F,L,P,N,j,B,K,ie,ue=this,be=ue.c;if(A!=null&&(P=new H(A),!P.isInteger()&&(P.c||P.s!==1)||P.lt(ee)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+ce(P));if(!be)return new H(ue);for(T=new H(ee),j=R=new H(ee),M=N=new H(ee),ie=m(be),F=T.e=ie.length-ue.e-1,T.c[0]=f[(L=F%u)<0?u+L:L],A=!A||P.comparedTo(T)>0?F>0?T:j:P,L=Te,Te=1/0,P=new H(ie),N.c[0]=0;B=O(P,T,0,1),D=R.plus(B.times(M)),D.comparedTo(A)!=1;)R=M,M=D,j=N.plus(B.times(D=j)),N=D,T=P.minus(B.times(D=T)),P=D;return D=O(A.minus(R),M,0,1),N=N.plus(D.times(j)),R=R.plus(D.times(M)),N.s=j.s=ue.s,F=F*2,K=O(j,M,F,te).minus(ue).abs().comparedTo(O(N,R,F,te).minus(ue).abs())<1?[j,M]:[N,R],Te=L,K},U.toNumber=function(){return+ce(this)},U.toPrecision=function(A,T){return A!=null&&C(A,1,h),Ee(this,A,T,2)},U.toString=function(A){var T,R=this,M=R.s,D=R.e;return D===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(A==null?T=D<=Q||D>=_e?k(m(R.c),D):E(m(R.c),D,"0"):A===10&&we?(R=de(new H(R),z+D+1,te),T=E(m(R.c),R.e,"0")):(C(A,2,Ie.length,"Base"),T=q(E(m(R.c),D,"0"),10,A,M,!0)),M<0&&R.c[0]&&(T="-"+T)),T},U.valueOf=U.toJSON=function(){return ce(this)},U._isBigNumber=!0,x!=null&&H.set(x),H}function b(x){var O=x|0;return x>0||x===O?O:O-1}function m(x){for(var O,q,V=1,U=x.length,ee=x[0]+"";V<U;){for(O=x[V++]+"",q=u-O.length;q--;O="0"+O);ee+=O}for(U=ee.length;ee.charCodeAt(--U)===48;);return ee.slice(0,U+1||1)}function w(x,O){var q,V,U=x.c,ee=O.c,z=x.s,te=O.s,Q=x.e,_e=O.e;if(!z||!te)return null;if(q=U&&!U[0],V=ee&&!ee[0],q||V)return q?V?0:-te:z;if(z!=te)return z;if(q=z<0,V=Q==_e,!U||!ee)return V?0:!U^q?1:-1;if(!V)return Q>_e^q?1:-1;for(te=(Q=U.length)<(_e=ee.length)?Q:_e,z=0;z<te;z++)if(U[z]!=ee[z])return U[z]>ee[z]^q?1:-1;return Q==_e?0:Q>_e^q?1:-1}function C(x,O,q,V){if(x<O||x>q||x!==o(x))throw Error(s+(V||"Argument")+(typeof x=="number"?x<O||x>q?" out of range: ":" not an integer: ":" not a primitive number: ")+String(x))}function S(x){var O=x.c.length-1;return b(x.e/u)==O&&x.c[O]%2!=0}function k(x,O){return(x.length>1?x.charAt(0)+"."+x.slice(1):x)+(O<0?"e":"e+")+O}function E(x,O,q){var V,U;if(O<0){for(U=q+".";++O;U+=q);x=U+x}else if(V=x.length,++O>V){for(U=q,O-=V;--O;U+=q);x+=U}else O<V&&(x=x.slice(0,O)+"."+x.slice(O));return x}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof gl<"u"&&gl.exports?gl.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(uE)});var pE=G((r5,fE)=>{var lE=jg(),dE=fE.exports;(function(){"use strict";function t(d){return d<10?"0"+d:d}var e=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,r,o,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},i;function a(d){return n.lastIndex=0,n.test(d)?'"'+d.replace(n,function(f){var p=s[f];return typeof p=="string"?p:"\\u"+("0000"+f.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+d+'"'}function u(d,f){var p,h,g,b,m=r,w,C=f[d],S=C!=null&&(C instanceof lE||lE.isBigNumber(C));switch(C&&typeof C=="object"&&typeof C.toJSON=="function"&&(C=C.toJSON(d)),typeof i=="function"&&(C=i.call(f,d,C)),typeof C){case"string":return S?C:a(C);case"number":return isFinite(C)?String(C):"null";case"boolean":case"null":case"bigint":return String(C);case"object":if(!C)return"null";if(r+=o,w=[],Object.prototype.toString.apply(C)==="[object Array]"){for(b=C.length,p=0;p<b;p+=1)w[p]=u(p,C)||"null";return g=w.length===0?"[]":r?`[
95
95
  `+r+w.join(`,
96
96
  `+r)+`
97
97
  `+m+"]":"["+w.join(",")+"]",r=m,g}if(i&&typeof i=="object")for(b=i.length,p=0;p<b;p+=1)typeof i[p]=="string"&&(h=i[p],g=u(h,C),g&&w.push(a(h)+(r?": ":":")+g));else Object.keys(C).forEach(function(k){var E=u(k,C);E&&w.push(a(k)+(r?": ":":")+E)});return g=w.length===0?"{}":r?`{
98
98
  `+r+w.join(`,
99
99
  `+r)+`
100
- `+m+"}":"{"+w.join(",")+"}",r=m,g}}typeof dE.stringify!="function"&&(dE.stringify=function(d,f,p){var h;if(r="",o="",typeof p=="number")for(h=0;h<p;h+=1)o+=" ";else typeof p=="string"&&(o=p);if(i=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return u("",{"":d})})})()});var gE=G((t5,hE)=>{var ml=null,IN=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,FN=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,NN=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
101
- `,r:"\r",t:" "},s,i=function(m){throw{name:"SyntaxError",message:m,at:n,text:s}},a=function(m){return m&&m!==r&&i("Expected '"+m+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},u=function(){var m,w="";for(r==="-"&&(w="-",a("-"));r>="0"&&r<="9";)w+=r,a();if(r===".")for(w+=".";a()&&r>="0"&&r<="9";)w+=r;if(r==="e"||r==="E")for(w+=r,a(),(r==="-"||r==="+")&&(w+=r,a());r>="0"&&r<="9";)w+=r,a();if(m=+w,!isFinite(m))i("Bad number");else return ml==null&&(ml=jg()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new ml(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new ml(m):m},d=function(){var m,w,C="",A;if(r==='"')for(var k=n;a();){if(r==='"')return n-1>k&&(C+=s.substring(k,n-1)),a(),C;if(r==="\\"){if(n-1>k&&(C+=s.substring(k,n-1)),a(),r==="u"){for(A=0,w=0;w<4&&(m=parseInt(a(),16),!!isFinite(m));w+=1)A=A*16+m;C+=String.fromCharCode(A)}else if(typeof o[r]=="string")C+=o[r];else break;k=n}}i("Bad string")},f=function(){for(;r&&r<=" ";)a()},p=function(){switch(r){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}i("Unexpected '"+r+"'")},h,g=function(){var m=[];if(r==="["){if(a("["),f(),r==="]")return a("]"),m;for(;r;){if(m.push(h()),f(),r==="]")return a("]"),m;a(","),f()}}i("Bad array")},b=function(){var m,w=Object.create(null);if(r==="{"){if(a("{"),f(),r==="}")return a("}"),w;for(;r;){if(m=d(),f(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(w,m)&&i('Duplicate key "'+m+'"'),IN.test(m)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():w[m]=h():FN.test(m)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():w[m]=h():w[m]=h(),f(),r==="}")return a("}"),w;a(","),f()}}i("Bad object")};return h=function(){switch(f(),r){case"{":return b();case"[":return g();case'"':return d();case"-":return u();default:return r>="0"&&r<="9"?u():p()}},function(m,w){var C;return s=m+"",n=0,r=" ",C=h(),f(),r&&i("Syntax error"),typeof w=="function"?(function A(k,E){var x,O,q=k[E];return q&&typeof q=="object"&&Object.keys(q).forEach(function(V){O=A(q,V),O!==void 0?q[V]=O:delete q[V]}),w.call(k,E,q)})({"":C},""):C}};hE.exports=NN});var _E=G((n5,yl)=>{var mE=pE().stringify,yE=gE();yl.exports=function(t){return{parse:yE(t),stringify:mE}};yl.exports.parse=yE();yl.exports.stringify=mE});var Lg=G(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.GCE_LINUX_BIOS_PATHS=void 0;on.isGoogleCloudServerless=wE;on.isGoogleComputeEngineLinux=kE;on.isGoogleComputeEngineMACAddress=SE;on.isGoogleComputeEngine=AE;on.detectGCPResidency=BN;var bE=re("fs"),CE=re("os");on.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var MN=/^42:01/;function wE(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function kE(){if((0,CE.platform)()!=="linux")return!1;try{(0,bE.statSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,bE.readFileSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function SE(){let t=(0,CE.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(MN.test(n))return!0}return!1}function AE(){return kE()||SE()}function BN(){return wE()||AE()}});var EE=G(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.Colours=void 0;var _l=class t{static enabled=!1;static reset="";static bright="";static dim="";static red="";static green="";static yellow="";static blue="";static magenta="";static cyan="";static white="";static grey="";static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process?.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};bl.Colours=_l;_l.refresh()});var TE=G(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.LogSeverity=void 0;var vE;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(vE||(Cl.LogSeverity=vE={}))});var OE=G($e=>{"use strict";var UN=$e&&$e.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),jN=$e&&$e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xE=$e&&$e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&UN(n,e,r[o]);return jN(n,e),n}})();Object.defineProperty($e,"__esModule",{value:!0});$e.env=$e.DebugLogBackendBase=$e.placeholder=$e.AdhocDebugLogger=void 0;$e.getNodeBackend=qg;$e.getDebugBackend=$N;$e.getStructuredBackend=qN;$e.setBackend=HN;$e.log=DE;var LN=re("events"),fa=xE(re("process")),RE=xE(re("util")),Ft=EE(),gr=TE(),pa=class extends LN.EventEmitter{namespace;upstream;func;constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(gr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(gr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(gr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(gr.LogSeverity.ERROR,...r),this.func.sublog=r=>DE(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};$e.AdhocDebugLogger=pa;$e.placeholder=new pa("",()=>{}).func;var Is=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=fa.env[$e.env.nodeEnables]??"*";e==="all"&&(e="*"),this.filters=e.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};$e.DebugLogBackendBase=Is;var $g=class extends Is{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${Ft.Colours.green}${e}${Ft.Colours.reset}`,s=`${Ft.Colours.yellow}${fa.pid}${Ft.Colours.reset}`,i;switch(n.severity){case gr.LogSeverity.ERROR:i=`${Ft.Colours.red}${n.severity}${Ft.Colours.reset}`;break;case gr.LogSeverity.INFO:i=`${Ft.Colours.magenta}${n.severity}${Ft.Colours.reset}`;break;case gr.LogSeverity.WARNING:i=`${Ft.Colours.yellow}${n.severity}${Ft.Colours.reset}`;break;default:i=n.severity??gr.LogSeverity.DEFAULT;break}let a=RE.formatWithOptions({colors:Ft.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${Ft.Colours.grey}${d}${Ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,i,a,d?` ${f}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function qg(){return new $g}var Hg=class extends Is{debugPkg;constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){let e=fa.env.NODE_DEBUG??"";fa.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function $N(t){return new Hg(t)}var zg=class extends Is{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??gr.LogSeverity.INFO,i=Object.assign({severity:s,message:RE.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function qN(t){return new zg(t)}$e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Wg=new Map,sn;function HN(t){sn=t,Wg.clear()}function DE(t,e){if(!sn&&!fa.env[$e.env.nodeEnables]||!t)return $e.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Wg.get(t);if(n)return n.func;if(sn===null)return $e.placeholder;sn===void 0&&(sn=qg());let r=(()=>{let o;return new pa(t,(i,...a)=>{if(o!==sn){if(sn===null)return;sn===void 0&&(sn=qg()),o=sn}sn?.log(t,i,...a)})})();return Wg.set(t,r),r.func}});var Gg=G(Po=>{"use strict";var zN=Po&&Po.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WN=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&zN(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});WN(OE(),Po)});var ga=G(pe=>{"use strict";var IE=pe&&pe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GN=pe&&pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),JN=pe&&pe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&IE(n,e,r[o]);return GN(n,e),n}})(),KN=pe&&pe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&IE(e,t,n)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=eM;pe.project=tM;pe.universe=nM;pe.bulk=rM;pe.isAvailable=sM;pe.resetIsAvailableCache=iM;pe.getGCPResidency=Vg;pe.setGCPResidency=FE;pe.requestTimeout=NE;var Jg=lt(),VN=_E(),YN=Lg(),XN=JN(Gg());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var PE=XN.log("gcp-metadata");pe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Kg(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function QN(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ha(t,e={},n=3,r=!1){let o=new Headers(pe.HEADERS),s="",i={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>o.set(g,h)),s=p.metadataKey,i=p.params||i,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(QN(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?ZN:Jg.request,u={url:`${Kg()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:NE()};PE.info("instance request %j",u);let d=await a(u);PE.info("instance metadata is %s",d.data);let f=d.headers.get(pe.HEADER_NAME);if(f!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return VN.parse(d.data)}catch{}return d.data}async function ZN(t){let e={...t,url:t.url?.toString().replace(Kg(),Kg(pe.SECONDARY_HOST_ADDRESS))},n=(0,Jg.request)(t),r=(0,Jg.request)(e);return Promise.any([n,r])}function eM(t){return ha("instance",t)}function tM(t){return ha("project",t)}function nM(t){return ha("universe",t)}async function rM(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ha(n),o=n.metadataKey;e[o]=r})())),e}function oM(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var wl;async function sM(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Vg();case"ping-only":}}try{return wl===void 0&&(wl=(async()=>{try{return await ha("instance",void 0,oM(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST)),!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;{let n=t,r=i=>i?i.name==="AggregateError"&&Array.isArray(i.errors)?i.errors.flatMap(r):i.code?[i.code.toString()]:i.cause?r(i.cause):["UNKNOWN"]:["UNKNOWN"];if(!r(n).every(i=>["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(i))){let i=e.code?e.code.toString():"UNKNOWN";process.emitWarning(`received unexpected error = ${e.message} code = ${i}`,"MetadataLookupWarning")}return!1}}})()),await wl}catch{return!1}}function iM(){wl=void 0}pe.gcpResidencyCache=null;function Vg(){return pe.gcpResidencyCache===null&&FE(),pe.gcpResidencyCache}function FE(t=null){pe.gcpResidencyCache=t!==null?t:(0,YN.detectGCPResidency)()}function NE(){return Vg()?0:3e3}KN(Lg(),pe)});var UE=G(kl=>{"use strict";kl.byteLength=cM;kl.toByteArray=lM;kl.fromByteArray=pM;var Bn=[],Gt=[],aM=typeof Uint8Array<"u"?Uint8Array:Array,Yg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Io=0,ME=Yg.length;Io<ME;++Io)Bn[Io]=Yg[Io],Gt[Yg.charCodeAt(Io)]=Io;var Io,ME;Gt[45]=62;Gt[95]=63;function BE(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function cM(t){var e=BE(t),n=e[0],r=e[1];return(n+r)*3/4-r}function uM(t,e,n){return(e+n)*3/4-n}function lM(t){var e,n=BE(t),r=n[0],o=n[1],s=new aM(uM(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Gt[t.charCodeAt(u)]<<18|Gt[t.charCodeAt(u+1)]<<12|Gt[t.charCodeAt(u+2)]<<6|Gt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Gt[t.charCodeAt(u)]<<2|Gt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Gt[t.charCodeAt(u)]<<10|Gt[t.charCodeAt(u+1)]<<4|Gt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function dM(t){return Bn[t>>18&63]+Bn[t>>12&63]+Bn[t>>6&63]+Bn[t&63]}function fM(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(dM(r));return o.join("")}function pM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(fM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Bn[e>>2]+Bn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Bn[e>>10]+Bn[e>>4&63]+Bn[e<<2&63]+"=")),o.join("")}});var Qg=G(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});Xg.fromArrayBufferToHex=hM;function hM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var jE=G(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.BrowserCrypto=void 0;var Fs=UE(),gM=Qg(),Zg=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Fs.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Fs.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),i=Fs.toByteArray(t.padBase64(r)),a=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,a,Buffer.from(i),s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),i=await window.crypto.subtle.sign(r,s,o);return Fs.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Fs.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Fs.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,gM.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};Sl.BrowserCrypto=Zg});var LE=G(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.NodeCrypto=void 0;var Ns=re("crypto"),em=class{async sha256DigestBase64(e){return Ns.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Ns.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Ns.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Ns.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Ns.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:yM(e);return mM(Ns.createHmac("sha256",r).update(n).digest())}};Al.NodeCrypto=em;function mM(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0;r<t.length;++r)n[r]=t[r];return e}function yM(t){return Buffer.from(t)}});var ma=G(mr=>{"use strict";var _M=mr&&mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),bM=mr&&mr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&_M(e,t,n)};Object.defineProperty(mr,"__esModule",{value:!0});mr.createCrypto=kM;mr.hasBrowserCrypto=$E;var CM=jE(),wM=LE();bM(Qg(),mr);function kM(){return $E()?new CM.BrowserCrypto:new wM.NodeCrypto}function $E(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Ms=G((tm,HE)=>{var El=re("buffer"),Un=El.Buffer;function qE(t,e){for(var n in t)e[n]=t[n]}Un.from&&Un.alloc&&Un.allocUnsafe&&Un.allocUnsafeSlow?HE.exports=El:(qE(El,tm),tm.Buffer=Fo);function Fo(t,e,n){return Un(t,e,n)}Fo.prototype=Object.create(Un.prototype);qE(Un,Fo);Fo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Un(t,e,n)};Fo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=Un(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Fo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Un(t)};Fo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return El.SlowBuffer(t)}});var WE=G((h5,zE)=>{"use strict";function nm(t){var e=(t/8|0)+(t%8===0?0:1);return e}var SM={ES256:nm(256),ES384:nm(384),ES512:nm(521)};function AM(t){var e=SM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}zE.exports=AM});var rm=G((g5,XE)=>{"use strict";var vl=Ms().Buffer,JE=WE(),Tl=128,KE=0,EM=32,vM=16,TM=2,VE=vM|EM|KE<<6,xl=TM|KE<<6;function xM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function YE(t){if(vl.isBuffer(t))return t;if(typeof t=="string")return vl.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function RM(t,e){t=YE(t);var n=JE(e),r=n+1,o=t.length,s=0;if(t[s++]!==VE)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(Tl|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==xl)throw new Error('Could not find expected "int" for "r"');var a=t[s++];if(o-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(o-s-2)+'" available');if(r<a)throw new Error('"r" specified length of "'+a+'", max of "'+r+'" is acceptable');var u=s;if(s+=a,t[s++]!==xl)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-a,h=n-d,g=vl.allocUnsafe(p+a+h+d);for(s=0;s<p;++s)g[s]=0;t.copy(g,s,u+Math.max(-p,0),u+a),s=n;for(var b=s;s<b+h;++s)g[s]=0;return t.copy(g,s,f+Math.max(-h,0),f+d),g=g.toString("base64"),g=xM(g),g}function GE(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Tl;return o&&--r,r}function DM(t,e){t=YE(t);var n=JE(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=GE(t,0,n),s=GE(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<Tl,f=vl.allocUnsafe((d?2:3)+u),p=0;return f[p++]=VE,d?f[p++]=u:(f[p++]=Tl|1,f[p++]=u&255),f[p++]=xl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=xl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}XE.exports={derToJose:RM,joseToDer:DM}});var an=G(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.LRUCache=void 0;yr.snakeToCamel=ZE;yr.originalOrCamelOptions=FM;yr.removeUndefinedValuesInObject=NM;yr.isValidFile=MM;yr.getWellKnownCertificateConfigFileLocation=BM;var OM=re("fs"),PM=re("os"),om=re("path"),IM="certificate_config.json",QE="gcloud";function ZE(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function FM(t){function e(n){let r=t||{};return r[n]??r[ZE(n)]}return{get:e}}var sm=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};yr.LRUCache=sm;function NM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function MM(t){try{return(await OM.promises.lstat(t)).isFile()}catch{return!1}}function BM(){let t=process.env.CLOUDSDK_CONFIG||(UM()?om.join(process.env.APPDATA||"",QE):om.join(process.env.HOME||"",".config",QE));return om.join(t,IM)}function UM(){return PM.platform().startsWith("win")}});var ev=G((y5,jM)=>{jM.exports={name:"google-auth-library",version:"11.0.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=22"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"^9.0.0","google-logging-utils":"^2.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var im=G(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.USER_AGENT=Jr.PRODUCT_NAME=Jr.pkg=void 0;var tv=ev();Jr.pkg=tv;var nv="google-api-nodejs-client";Jr.PRODUCT_NAME=nv;var LM=`${nv}/${tv.version}`;Jr.USER_AGENT=LM});var Nt=G(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.AuthClient=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=cn.DEFAULT_UNIVERSE=void 0;var $M=re("events"),am=lt(),qM=an(),HM=Gg(),cm=im();cn.DEFAULT_UNIVERSE="googleapis.com";cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var um=class t extends $M.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=cn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,qM.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??cn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new am.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&am.Gaxios.mergeHeaders(s,n.headers),r&&am.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,HM.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${cm.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${cm.USER_AGENT}`):e.headers.set("User-Agent",cm.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,i):t.log.info("[%s] request %j",s,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};cn.AuthClient=um});var dm=G(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.LoginTicket=void 0;var lm=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Rl.LoginTicket=lm});var Kr=G(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.OAuth2Client=jn.ClientAuthentication=jn.CertificateFormat=jn.CodeChallengeMethod=void 0;var rv=lt(),zM=re("querystring"),WM=re("stream"),GM=rm(),ov=an(),fm=ma(),Bs=Nt(),JM=dm(),sv;(function(t){t.Plain="plain",t.S256="S256"})(sv||(jn.CodeChallengeMethod=sv={}));var _r;(function(t){t.PEM="PEM",t.JWK="JWK"})(_r||(jn.CertificateFormat=_r={}));var ya;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ya||(jn.ClientAuthentication=ya={}));var pm=class t extends Bs.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=_r.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||ya.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+zM.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,fm.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===ya.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===ya.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,ov.removeUndefinedValuesInObject)(o)),headers:r};Bs.AuthClient.setMethodName(s,"getTokenAsync");let i=await this.transporter.request(s),a=i.data;return i.data&&i.data.expires_in&&(a.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:i}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let i={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,ov.removeUndefinedValuesInObject)(r))};Bs.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof rv.GaxiosError&&i.message==="invalid_grant"&&i.response?.data&&/ReAuth/i.test(i.response.data.error_description)&&(i.message=JSON.stringify(i.response.data)),i}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let a=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(a)}}if(this.refreshHandler){let a=await this.processAndValidateRefreshHandler();if(a?.access_token){this.setCredentials(a);let u=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(u)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(a){let u=a;throw u.response&&(u.response.status===403||u.response.status===404)&&(u.message=`Could not refresh access token: ${u.message}`),u}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let i=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(i),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Bs.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=rv.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),a=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,u=o.config.data instanceof WM.Readable,d=s===401||s===403;if(!n&&d&&!u&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!u&&a){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,fm.hasBrowserCrypto)()?_r.JWK:_r.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case _r.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case _r.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Bs.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),i=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(i=Number(d)*1e3)}let a={};switch(n){case _r.PEM:a=r.data;break;case _r.JWK:for(let d of r.data.keys)a[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let u=new Date;return this.certificateExpiry=i===-1?null:new Date(u.getTime()+i),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};Bs.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let i=(0,fm.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let a=e.split(".");if(a.length!==3)throw new Error("Wrong number of segments in token: "+e);let u=a[0]+"."+a[1],d=a[2],f,p;try{f=JSON.parse(i.decodeBase64StringUtf8(a[0]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token envelope: ${a[0]}': ${k.message}`),k}if(!f)throw new Error("Can't parse token envelope: "+a[0]);try{p=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token payload '${a[0]}`),k}if(!p)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=GM.joseToDer(d,"ES256").toString("base64")),!await i.verify(h,u,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let b=Number(p.iat);if(isNaN(b))throw new Error("iat field using invalid format");let m=Number(p.exp);if(isNaN(m))throw new Error("exp field using invalid format");let w=new Date().getTime()/1e3;if(m>=w+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let C=b-t.CLOCK_SKEW_SECS_,A=m+t.CLOCK_SKEW_SECS_;if(w<C)throw new Error("Token used too early, "+w+" < "+C+": "+JSON.stringify(p));if(w>A)throw new Error("Token used too late, "+w+" > "+A+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let k=p.aud,E=!1;if(r.constructor===Array?E=r.indexOf(k)>-1:E=k===r,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new JM.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};jn.OAuth2Client=pm});var gm=G(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.Compute=void 0;var KM=lt(),iv=ga(),VM=Kr(),hm=class extends VM.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await iv.instance(o)}catch(o){throw o instanceof KM.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await iv.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Dl.Compute=hm});var ym=G(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.IdTokenClient=void 0;var YM=Kr(),mm=class extends YM.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ol.IdTokenClient=mm});var _m=G(Us=>{"use strict";Object.defineProperty(Us,"__esModule",{value:!0});Us.GCPEnv=void 0;Us.clear=XM;Us.getEnv=QM;var av=ga(),Ln;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Ln||(Us.GCPEnv=Ln={}));var _a;function XM(){_a=void 0}async function QM(){return _a||(_a=ZM(),_a)}async function ZM(){let t=Ln.NONE;return eB()?t=Ln.APP_ENGINE:tB()?t=Ln.CLOUD_FUNCTIONS:await sB()?await oB()?t=Ln.KUBERNETES_ENGINE:nB()?t=Ln.CLOUD_RUN:rB()?t=Ln.CLOUD_RUN_JOBS:t=Ln.COMPUTE_ENGINE:t=Ln.NONE,t}function eB(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function tB(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function nB(){return!!process.env.K_CONFIGURATION}function rB(){return!!process.env.CLOUD_RUN_JOB}async function oB(){try{return await av.instance("attributes/cluster-name"),!0}catch{return!1}}async function sB(){return av.isAvailable()}});var bm=G((E5,cv)=>{var Pl=Ms().Buffer,iB=re("stream"),aB=re("util");function Il(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Pl.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Pl.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}aB.inherits(Il,iB);Il.prototype.write=function(e){this.buffer=Pl.concat([this.buffer,Pl.from(e)]),this.emit("data",e)};Il.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};cv.exports=Il});var lv=G((v5,uv)=>{"use strict";var ba=re("buffer").Buffer,Cm=re("buffer").SlowBuffer;uv.exports=Fl;function Fl(t,e){if(!ba.isBuffer(t)||!ba.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Fl.install=function(){ba.prototype.equal=Cm.prototype.equal=function(e){return Fl(this,e)}};var cB=ba.prototype.equal,uB=Cm.prototype.equal;Fl.restore=function(){ba.prototype.equal=cB,Cm.prototype.equal=uB}});var Am=G((T5,bv)=>{var Ls=Ms().Buffer,Jt=re("crypto"),fv=rm(),dv=re("util"),lB=`"%s" is not a valid algorithm.
100
+ `+m+"}":"{"+w.join(",")+"}",r=m,g}}typeof dE.stringify!="function"&&(dE.stringify=function(d,f,p){var h;if(r="",o="",typeof p=="number")for(h=0;h<p;h+=1)o+=" ";else typeof p=="string"&&(o=p);if(i=f,f&&typeof f!="function"&&(typeof f!="object"||typeof f.length!="number"))throw new Error("JSON.stringify");return u("",{"":d})})})()});var gE=G((o5,hE)=>{var ml=null,FN=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,NN=/(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/,MN=function(t){"use strict";var e={strict:!1,storeAsString:!1,alwaysParseAsBig:!1,useNativeBigInt:!1,protoAction:"error",constructorAction:"error"};if(t!=null){if(t.strict===!0&&(e.strict=!0),t.storeAsString===!0&&(e.storeAsString=!0),e.alwaysParseAsBig=t.alwaysParseAsBig===!0?t.alwaysParseAsBig:!1,e.useNativeBigInt=t.useNativeBigInt===!0?t.useNativeBigInt:!1,typeof t.constructorAction<"u")if(t.constructorAction==="error"||t.constructorAction==="ignore"||t.constructorAction==="preserve")e.constructorAction=t.constructorAction;else throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${t.constructorAction}`);if(typeof t.protoAction<"u")if(t.protoAction==="error"||t.protoAction==="ignore"||t.protoAction==="preserve")e.protoAction=t.protoAction;else throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${t.protoAction}`)}var n,r,o={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
101
+ `,r:"\r",t:" "},s,i=function(m){throw{name:"SyntaxError",message:m,at:n,text:s}},a=function(m){return m&&m!==r&&i("Expected '"+m+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},u=function(){var m,w="";for(r==="-"&&(w="-",a("-"));r>="0"&&r<="9";)w+=r,a();if(r===".")for(w+=".";a()&&r>="0"&&r<="9";)w+=r;if(r==="e"||r==="E")for(w+=r,a(),(r==="-"||r==="+")&&(w+=r,a());r>="0"&&r<="9";)w+=r,a();if(m=+w,!isFinite(m))i("Bad number");else return ml==null&&(ml=jg()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new ml(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new ml(m):m},d=function(){var m,w,C="",S;if(r==='"')for(var k=n;a();){if(r==='"')return n-1>k&&(C+=s.substring(k,n-1)),a(),C;if(r==="\\"){if(n-1>k&&(C+=s.substring(k,n-1)),a(),r==="u"){for(S=0,w=0;w<4&&(m=parseInt(a(),16),!!isFinite(m));w+=1)S=S*16+m;C+=String.fromCharCode(S)}else if(typeof o[r]=="string")C+=o[r];else break;k=n}}i("Bad string")},f=function(){for(;r&&r<=" ";)a()},p=function(){switch(r){case"t":return a("t"),a("r"),a("u"),a("e"),!0;case"f":return a("f"),a("a"),a("l"),a("s"),a("e"),!1;case"n":return a("n"),a("u"),a("l"),a("l"),null}i("Unexpected '"+r+"'")},h,g=function(){var m=[];if(r==="["){if(a("["),f(),r==="]")return a("]"),m;for(;r;){if(m.push(h()),f(),r==="]")return a("]"),m;a(","),f()}}i("Bad array")},b=function(){var m,w=Object.create(null);if(r==="{"){if(a("{"),f(),r==="}")return a("}"),w;for(;r;){if(m=d(),f(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(w,m)&&i('Duplicate key "'+m+'"'),FN.test(m)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():w[m]=h():NN.test(m)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():w[m]=h():w[m]=h(),f(),r==="}")return a("}"),w;a(","),f()}}i("Bad object")};return h=function(){switch(f(),r){case"{":return b();case"[":return g();case'"':return d();case"-":return u();default:return r>="0"&&r<="9"?u():p()}},function(m,w){var C;return s=m+"",n=0,r=" ",C=h(),f(),r&&i("Syntax error"),typeof w=="function"?(function S(k,E){var x,O,q=k[E];return q&&typeof q=="object"&&Object.keys(q).forEach(function(V){O=S(q,V),O!==void 0?q[V]=O:delete q[V]}),w.call(k,E,q)})({"":C},""):C}};hE.exports=MN});var _E=G((s5,yl)=>{var mE=pE().stringify,yE=gE();yl.exports=function(t){return{parse:yE(t),stringify:mE}};yl.exports.parse=yE();yl.exports.stringify=mE});var Ug=G(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.GCE_LINUX_BIOS_PATHS=void 0;on.isGoogleCloudServerless=wE;on.isGoogleComputeEngineLinux=kE;on.isGoogleComputeEngineMACAddress=SE;on.isGoogleComputeEngine=AE;on.detectGCPResidency=jN;var bE=re("fs"),CE=re("os");on.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var BN=/^42:01/;function wE(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function kE(){if((0,CE.platform)()!=="linux")return!1;try{(0,bE.statSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,bE.readFileSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function SE(){let t=(0,CE.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(BN.test(n))return!0}return!1}function AE(){return kE()||SE()}function jN(){return wE()||AE()}});var EE=G(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.Colours=void 0;var _l=class t{static enabled=!1;static reset="";static bright="";static dim="";static red="";static green="";static yellow="";static blue="";static magenta="";static cyan="";static white="";static grey="";static isEnabled(e){return e&&e.isTTY&&(typeof e.getColorDepth=="function"?e.getColorDepth()>2:!0)}static refresh(){t.enabled=t.isEnabled(process?.stderr),this.enabled?(t.reset="\x1B[0m",t.bright="\x1B[1m",t.dim="\x1B[2m",t.red="\x1B[31m",t.green="\x1B[32m",t.yellow="\x1B[33m",t.blue="\x1B[34m",t.magenta="\x1B[35m",t.cyan="\x1B[36m",t.white="\x1B[37m",t.grey="\x1B[90m"):(t.reset="",t.bright="",t.dim="",t.red="",t.green="",t.yellow="",t.blue="",t.magenta="",t.cyan="",t.white="",t.grey="")}};bl.Colours=_l;_l.refresh()});var TE=G(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});Cl.LogSeverity=void 0;var vE;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(vE||(Cl.LogSeverity=vE={}))});var OE=G($e=>{"use strict";var UN=$e&&$e.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),LN=$e&&$e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xE=$e&&$e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&UN(n,e,r[o]);return LN(n,e),n}})();Object.defineProperty($e,"__esModule",{value:!0});$e.env=$e.DebugLogBackendBase=$e.placeholder=$e.AdhocDebugLogger=void 0;$e.getNodeBackend=$g;$e.getDebugBackend=qN;$e.getStructuredBackend=HN;$e.setBackend=zN;$e.log=DE;var $N=re("events"),fa=xE(re("process")),RE=xE(re("util")),Ft=EE(),gr=TE(),pa=class extends $N.EventEmitter{namespace;upstream;func;constructor(e,n){super(),this.namespace=e,this.upstream=n,this.func=Object.assign(this.invoke.bind(this),{instance:this,on:(r,o)=>this.on(r,o)}),this.func.debug=(...r)=>this.invokeSeverity(gr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(gr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(gr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(gr.LogSeverity.ERROR,...r),this.func.sublog=r=>DE(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};$e.AdhocDebugLogger=pa;$e.placeholder=new pa("",()=>{}).func;var Is=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=fa.env[$e.env.nodeEnables]??"*";e==="all"&&(e="*"),this.filters=e.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};$e.DebugLogBackendBase=Is;var Lg=class extends Is{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${Ft.Colours.green}${e}${Ft.Colours.reset}`,s=`${Ft.Colours.yellow}${fa.pid}${Ft.Colours.reset}`,i;switch(n.severity){case gr.LogSeverity.ERROR:i=`${Ft.Colours.red}${n.severity}${Ft.Colours.reset}`;break;case gr.LogSeverity.INFO:i=`${Ft.Colours.magenta}${n.severity}${Ft.Colours.reset}`;break;case gr.LogSeverity.WARNING:i=`${Ft.Colours.yellow}${n.severity}${Ft.Colours.reset}`;break;default:i=n.severity??gr.LogSeverity.DEFAULT;break}let a=RE.formatWithOptions({colors:Ft.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${Ft.Colours.grey}${d}${Ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,i,a,d?` ${f}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function $g(){return new Lg}var qg=class extends Is{debugPkg;constructor(e){super(),this.debugPkg=e}makeLogger(e){let n=this.debugPkg(e);return(r,...o)=>{n(o[0],...o.slice(1))}}setFilters(){let e=fa.env.NODE_DEBUG??"";fa.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function qN(t){return new qg(t)}var Hg=class extends Is{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??gr.LogSeverity.INFO,i=Object.assign({severity:s,message:RE.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function HN(t){return new Hg(t)}$e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var zg=new Map,sn;function zN(t){sn=t,zg.clear()}function DE(t,e){if(!sn&&!fa.env[$e.env.nodeEnables]||!t)return $e.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=zg.get(t);if(n)return n.func;if(sn===null)return $e.placeholder;sn===void 0&&(sn=$g());let r=(()=>{let o;return new pa(t,(i,...a)=>{if(o!==sn){if(sn===null)return;sn===void 0&&(sn=$g()),o=sn}sn?.log(t,i,...a)})})();return zg.set(t,r),r.func}});var Wg=G(Po=>{"use strict";var WN=Po&&Po.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),GN=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WN(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});GN(OE(),Po)});var ga=G(pe=>{"use strict";var IE=pe&&pe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),JN=pe&&pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),KN=pe&&pe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&IE(n,e,r[o]);return JN(n,e),n}})(),VN=pe&&pe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&IE(e,t,n)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=tM;pe.project=nM;pe.universe=rM;pe.bulk=oM;pe.isAvailable=iM;pe.resetIsAvailableCache=aM;pe.getGCPResidency=Kg;pe.setGCPResidency=FE;pe.requestTimeout=NE;var Gg=lt(),YN=_E(),XN=Ug(),QN=KN(Wg());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var PE=QN.log("gcp-metadata");pe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Jg(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function ZN(t){Object.keys(t).forEach(e=>{switch(e){case"params":case"property":case"headers":break;case"qs":throw new Error("'qs' is not a valid configuration option. Please use 'params' instead.");default:throw new Error(`'${e}' is not a valid configuration option.`)}})}async function ha(t,e={},n=3,r=!1){let o=new Headers(pe.HEADERS),s="",i={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>o.set(g,h)),s=p.metadataKey,i=p.params||i,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(ZN(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?eM:Gg.request,u={url:`${Jg()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:NE()};PE.info("instance request %j",u);let d=await a(u);PE.info("instance metadata is %s",d.data);let f=d.headers.get(pe.HEADER_NAME);if(f!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return YN.parse(d.data)}catch{}return d.data}async function eM(t){let e={...t,url:t.url?.toString().replace(Jg(),Jg(pe.SECONDARY_HOST_ADDRESS))},n=(0,Gg.request)(t),r=(0,Gg.request)(e);return Promise.any([n,r])}function tM(t){return ha("instance",t)}function nM(t){return ha("project",t)}function rM(t){return ha("universe",t)}async function oM(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await ha(n),o=n.metadataKey;e[o]=r})())),e}function sM(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var wl;async function iM(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Kg();case"ping-only":}}try{return wl===void 0&&(wl=(async()=>{try{return await ha("instance",void 0,sM(),!(process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST)),!0}catch(t){let e=t;if(process.env.DEBUG_AUTH&&console.info(e),e.type==="request-timeout"||e.response&&e.response.status===404)return!1;{let n=t,r=i=>i?i.name==="AggregateError"&&Array.isArray(i.errors)?i.errors.flatMap(r):i.code?[i.code.toString()]:i.cause?r(i.cause):["UNKNOWN"]:["UNKNOWN"];if(!r(n).every(i=>["EHOSTDOWN","EHOSTUNREACH","ENETUNREACH","ENOENT","ENOTFOUND","ECONNREFUSED"].includes(i))){let i=e.code?e.code.toString():"UNKNOWN";process.emitWarning(`received unexpected error = ${e.message} code = ${i}`,"MetadataLookupWarning")}return!1}}})()),await wl}catch{return!1}}function aM(){wl=void 0}pe.gcpResidencyCache=null;function Kg(){return pe.gcpResidencyCache===null&&FE(),pe.gcpResidencyCache}function FE(t=null){pe.gcpResidencyCache=t!==null?t:(0,XN.detectGCPResidency)()}function NE(){return Kg()?0:3e3}VN(Ug(),pe)});var jE=G(kl=>{"use strict";kl.byteLength=uM;kl.toByteArray=dM;kl.fromByteArray=hM;var Bn=[],Gt=[],cM=typeof Uint8Array<"u"?Uint8Array:Array,Vg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Io=0,ME=Vg.length;Io<ME;++Io)Bn[Io]=Vg[Io],Gt[Vg.charCodeAt(Io)]=Io;var Io,ME;Gt[45]=62;Gt[95]=63;function BE(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function uM(t){var e=BE(t),n=e[0],r=e[1];return(n+r)*3/4-r}function lM(t,e,n){return(e+n)*3/4-n}function dM(t){var e,n=BE(t),r=n[0],o=n[1],s=new cM(lM(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Gt[t.charCodeAt(u)]<<18|Gt[t.charCodeAt(u+1)]<<12|Gt[t.charCodeAt(u+2)]<<6|Gt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Gt[t.charCodeAt(u)]<<2|Gt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Gt[t.charCodeAt(u)]<<10|Gt[t.charCodeAt(u+1)]<<4|Gt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function fM(t){return Bn[t>>18&63]+Bn[t>>12&63]+Bn[t>>6&63]+Bn[t&63]}function pM(t,e,n){for(var r,o=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),o.push(fM(r));return o.join("")}function hM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(pM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Bn[e>>2]+Bn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Bn[e>>10]+Bn[e>>4&63]+Bn[e<<2&63]+"=")),o.join("")}});var Xg=G(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});Yg.fromArrayBufferToHex=gM;function gM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var UE=G(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.BrowserCrypto=void 0;var Fs=jE(),mM=Xg(),Qg=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Fs.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Fs.fromByteArray(n)}static padBase64(e){for(;e.length%4!==0;)e+="=";return e}async verify(e,n,r){let o={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},s=new TextEncoder().encode(n),i=Fs.toByteArray(t.padBase64(r)),a=await window.crypto.subtle.importKey("jwk",e,o,!0,["verify"]);return await window.crypto.subtle.verify(o,a,Buffer.from(i),s)}async sign(e,n){let r={name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},o=new TextEncoder().encode(n),s=await window.crypto.subtle.importKey("jwk",e,r,!0,["sign"]),i=await window.crypto.subtle.sign(r,s,o);return Fs.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Fs.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Fs.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,mM.fromArrayBufferToHex)(r)}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:String.fromCharCode(...new Uint16Array(e)),o=new TextEncoder,s=await window.crypto.subtle.importKey("raw",o.encode(r),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return window.crypto.subtle.sign("HMAC",s,o.encode(n))}};Sl.BrowserCrypto=Qg});var LE=G(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.NodeCrypto=void 0;var Ns=re("crypto"),Zg=class{async sha256DigestBase64(e){return Ns.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Ns.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Ns.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Ns.createSign("RSA-SHA256");return r.update(n),r.end(),r.sign(e,"base64")}decodeBase64StringUtf8(e){return Buffer.from(e,"base64").toString("utf-8")}encodeBase64StringUtf8(e){return Buffer.from(e,"utf-8").toString("base64")}async sha256DigestHex(e){return Ns.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:_M(e);return yM(Ns.createHmac("sha256",r).update(n).digest())}};Al.NodeCrypto=Zg;function yM(t){let e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let r=0;r<t.length;++r)n[r]=t[r];return e}function _M(t){return Buffer.from(t)}});var ma=G(mr=>{"use strict";var bM=mr&&mr.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),CM=mr&&mr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bM(e,t,n)};Object.defineProperty(mr,"__esModule",{value:!0});mr.createCrypto=SM;mr.hasBrowserCrypto=$E;var wM=UE(),kM=LE();CM(Xg(),mr);function SM(){return $E()?new wM.BrowserCrypto:new kM.NodeCrypto}function $E(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Ms=G((em,HE)=>{var El=re("buffer"),jn=El.Buffer;function qE(t,e){for(var n in t)e[n]=t[n]}jn.from&&jn.alloc&&jn.allocUnsafe&&jn.allocUnsafeSlow?HE.exports=El:(qE(El,em),em.Buffer=Fo);function Fo(t,e,n){return jn(t,e,n)}Fo.prototype=Object.create(jn.prototype);qE(jn,Fo);Fo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return jn(t,e,n)};Fo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=jn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Fo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return jn(t)};Fo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return El.SlowBuffer(t)}});var WE=G((y5,zE)=>{"use strict";function tm(t){var e=(t/8|0)+(t%8===0?0:1);return e}var AM={ES256:tm(256),ES384:tm(384),ES512:tm(521)};function EM(t){var e=AM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}zE.exports=EM});var nm=G((_5,XE)=>{"use strict";var vl=Ms().Buffer,JE=WE(),Tl=128,KE=0,vM=32,TM=16,xM=2,VE=TM|vM|KE<<6,xl=xM|KE<<6;function RM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function YE(t){if(vl.isBuffer(t))return t;if(typeof t=="string")return vl.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function DM(t,e){t=YE(t);var n=JE(e),r=n+1,o=t.length,s=0;if(t[s++]!==VE)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(Tl|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==xl)throw new Error('Could not find expected "int" for "r"');var a=t[s++];if(o-s-2<a)throw new Error('"r" specified length of "'+a+'", only "'+(o-s-2)+'" available');if(r<a)throw new Error('"r" specified length of "'+a+'", max of "'+r+'" is acceptable');var u=s;if(s+=a,t[s++]!==xl)throw new Error('Could not find expected "int" for "s"');var d=t[s++];if(o-s!==d)throw new Error('"s" specified length of "'+d+'", expected "'+(o-s)+'"');if(r<d)throw new Error('"s" specified length of "'+d+'", max of "'+r+'" is acceptable');var f=s;if(s+=d,s!==o)throw new Error('Expected to consume entire buffer, but "'+(o-s)+'" bytes remain');var p=n-a,h=n-d,g=vl.allocUnsafe(p+a+h+d);for(s=0;s<p;++s)g[s]=0;t.copy(g,s,u+Math.max(-p,0),u+a),s=n;for(var b=s;s<b+h;++s)g[s]=0;return t.copy(g,s,f+Math.max(-h,0),f+d),g=g.toString("base64"),g=RM(g),g}function GE(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Tl;return o&&--r,r}function OM(t,e){t=YE(t);var n=JE(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=GE(t,0,n),s=GE(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<Tl,f=vl.allocUnsafe((d?2:3)+u),p=0;return f[p++]=VE,d?f[p++]=u:(f[p++]=Tl|1,f[p++]=u&255),f[p++]=xl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=xl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}XE.exports={derToJose:DM,joseToDer:OM}});var an=G(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.LRUCache=void 0;yr.snakeToCamel=ZE;yr.originalOrCamelOptions=NM;yr.removeUndefinedValuesInObject=MM;yr.isValidFile=BM;yr.getWellKnownCertificateConfigFileLocation=jM;var PM=re("fs"),IM=re("os"),rm=re("path"),FM="certificate_config.json",QE="gcloud";function ZE(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function NM(t){function e(n){let r=t||{};return r[n]??r[ZE(n)]}return{get:e}}var om=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};yr.LRUCache=om;function MM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function BM(t){try{return(await PM.promises.lstat(t)).isFile()}catch{return!1}}function jM(){let t=process.env.CLOUDSDK_CONFIG||(UM()?rm.join(process.env.APPDATA||"",QE):rm.join(process.env.HOME||"",".config",QE));return rm.join(t,FM)}function UM(){return IM.platform().startsWith("win")}});var ev=G((C5,LM)=>{LM.exports={name:"google-auth-library",version:"11.0.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=22"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"^9.0.0","google-logging-utils":"^2.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var sm=G(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.USER_AGENT=Jr.PRODUCT_NAME=Jr.pkg=void 0;var tv=ev();Jr.pkg=tv;var nv="google-api-nodejs-client";Jr.PRODUCT_NAME=nv;var $M=`${nv}/${tv.version}`;Jr.USER_AGENT=$M});var Nt=G(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.AuthClient=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=cn.DEFAULT_UNIVERSE=void 0;var qM=re("events"),im=lt(),HM=an(),zM=Wg(),am=sm();cn.DEFAULT_UNIVERSE="googleapis.com";cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var cm=class t extends qM.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=cn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,HM.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??cn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new im.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&im.Gaxios.mergeHeaders(s,n.headers),r&&im.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,zM.log)("auth");static DEFAULT_REQUEST_INTERCEPTOR={resolved:async e=>{if(!e.headers.has("x-goog-api-client")){let r=process.version.replace(/^v/,"");e.headers.set("x-goog-api-client",`gl-node/${r}`)}let n=e.headers.get("User-Agent");n?n.includes(`${am.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${am.USER_AGENT}`):e.headers.set("User-Agent",am.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,i):t.log.info("[%s] request %j",s,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};cn.AuthClient=cm});var lm=G(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.LoginTicket=void 0;var um=class{envelope;payload;constructor(e,n){this.envelope=e,this.payload=n}getEnvelope(){return this.envelope}getPayload(){return this.payload}getUserId(){let e=this.getPayload();return e&&e.sub?e.sub:null}getAttributes(){return{envelope:this.getEnvelope(),payload:this.getPayload()}}};Rl.LoginTicket=um});var Kr=G(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.OAuth2Client=Un.ClientAuthentication=Un.CertificateFormat=Un.CodeChallengeMethod=void 0;var rv=lt(),WM=re("querystring"),GM=re("stream"),JM=nm(),ov=an(),dm=ma(),Bs=Nt(),KM=lm(),sv;(function(t){t.Plain="plain",t.S256="S256"})(sv||(Un.CodeChallengeMethod=sv={}));var _r;(function(t){t.PEM="PEM",t.JWK="JWK"})(_r||(Un.CertificateFormat=_r={}));var ya;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ya||(Un.ClientAuthentication=ya={}));var fm=class t extends Bs.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=_r.PEM;refreshTokenPromises=new Map;endpoints;issuers;clientAuthentication;_clientId;_clientSecret;refreshHandler;constructor(e={},n,r){super(typeof e=="object"?e:{}),typeof e!="object"&&(e={clientId:e,clientSecret:n,redirectUri:r}),this._clientId=e.clientId||e.client_id,this._clientSecret=e.clientSecret||e.client_secret,this.redirectUri=e.redirectUri||e.redirect_uris?.[0],this.endpoints={tokenInfoUrl:"https://oauth2.googleapis.com/tokeninfo",oauth2AuthBaseUrl:"https://accounts.google.com/o/oauth2/v2/auth",oauth2TokenUrl:"https://oauth2.googleapis.com/token",oauth2RevokeUrl:"https://oauth2.googleapis.com/revoke",oauth2FederatedSignonPemCertsUrl:"https://www.googleapis.com/oauth2/v1/certs",oauth2FederatedSignonJwkCertsUrl:"https://www.googleapis.com/oauth2/v3/certs",oauth2IapPublicKeyUrl:"https://www.gstatic.com/iap/verify/public_key",...e.endpoints},this.clientAuthentication=e.clientAuthentication||ya.ClientSecretPost,this.issuers=e.issuers||["accounts.google.com","https://accounts.google.com",this.universeDomain]}static GOOGLE_TOKEN_INFO_URL="https://oauth2.googleapis.com/tokeninfo";static CLOCK_SKEW_SECS_=300;static DEFAULT_MAX_TOKEN_LIFETIME_SECS_=86400;generateAuthUrl(e={}){if(e.code_challenge_method&&!e.code_challenge)throw new Error("If a code_challenge_method is provided, code_challenge must be included.");return e.response_type=e.response_type||"code",e.client_id=e.client_id||this._clientId,e.redirect_uri=e.redirect_uri||this.redirectUri,Array.isArray(e.scope)&&(e.scope=e.scope.join(" ")),this.endpoints.oauth2AuthBaseUrl.toString()+"?"+WM.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,dm.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===ya.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===ya.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,ov.removeUndefinedValuesInObject)(o)),headers:r};Bs.AuthClient.setMethodName(s,"getTokenAsync");let i=await this.transporter.request(s),a=i.data;return i.data&&i.data.expires_in&&(a.expiry_date=new Date().getTime()+i.data.expires_in*1e3,delete a.expires_in),this.emit("tokens",a),{tokens:a,res:i}}async refreshToken(e){if(!e)return this.refreshTokenNoCache(e);if(this.refreshTokenPromises.has(e))return this.refreshTokenPromises.get(e);let n=this.refreshTokenNoCache(e).then(r=>(this.refreshTokenPromises.delete(e),r),r=>{throw this.refreshTokenPromises.delete(e),r});return this.refreshTokenPromises.set(e,n),n}async refreshTokenNoCache(e){if(!e)throw new Error("No refresh token is set.");let n=this.endpoints.oauth2TokenUrl.toString(),r={refresh_token:e,client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token"},o;try{let i={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,ov.removeUndefinedValuesInObject)(r))};Bs.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof rv.GaxiosError&&i.message==="invalid_grant"&&i.response?.data&&/ReAuth/i.test(i.response.data.error_description)&&(i.message=JSON.stringify(i.response.data)),i}let s=o.data;return o.data&&o.data.expires_in&&(s.expiry_date=new Date().getTime()+o.data.expires_in*1e3,delete s.expires_in),this.emit("tokens",s),{tokens:s,res:o}}refreshAccessToken(e){if(e)this.refreshAccessTokenAsync().then(n=>e(null,n.credentials,n.res),e);else return this.refreshAccessTokenAsync()}async refreshAccessTokenAsync(){let e=await this.refreshToken(this.credentials.refresh_token),n=e.tokens;return n.refresh_token=this.credentials.refresh_token,this.credentials=n,{credentials:this.credentials,res:e.res}}getAccessToken(e){if(e)this.getAccessTokenAsync().then(n=>e(null,n.token,n.res),e);else return this.getAccessTokenAsync()}async getAccessTokenAsync(){if(!this.credentials.access_token||this.isTokenExpiring()){if(!this.credentials.refresh_token)if(this.refreshHandler){let r=await this.processAndValidateRefreshHandler();if(r?.access_token)return this.setCredentials(r),{token:this.credentials.access_token}}else throw new Error("No refresh token or refresh handler callback is set.");let n=await this.refreshAccessTokenAsync();if(!n.credentials||n.credentials&&!n.credentials.access_token)throw new Error("Could not refresh access token.");return{token:n.credentials.access_token,res:n.res}}else return{token:this.credentials.access_token}}async getRequestHeaders(e){return(await this.getRequestMetadataAsync(e)).headers}async getRequestMetadataAsync(e){let n=this.credentials;if(!n.access_token&&!n.refresh_token&&!this.apiKey&&!this.refreshHandler)throw new Error("No access, refresh token, API key or refresh handler callback is set.");if(n.access_token&&!this.isTokenExpiring()){n.token_type=n.token_type||"Bearer";let a=new Headers({authorization:n.token_type+" "+n.access_token});return{headers:this.addSharedMetadataHeaders(a)}}if(this.refreshHandler){let a=await this.processAndValidateRefreshHandler();if(a?.access_token){this.setCredentials(a);let u=new Headers({authorization:"Bearer "+this.credentials.access_token});return{headers:this.addSharedMetadataHeaders(u)}}}if(this.apiKey)return{headers:new Headers({"X-Goog-Api-Key":this.apiKey})};let r=null,o=null;try{r=await this.refreshToken(n.refresh_token),o=r.tokens}catch(a){let u=a;throw u.response&&(u.response.status===403||u.response.status===404)&&(u.message=`Could not refresh access token: ${u.message}`),u}let s=this.credentials;s.token_type=s.token_type||"Bearer",o.refresh_token=s.refresh_token,this.credentials=o;let i=new Headers({authorization:s.token_type+" "+o.access_token});return{headers:this.addSharedMetadataHeaders(i),res:r.res}}static getRevokeTokenUrl(e){return new t().getRevokeTokenURL(e).toString()}getRevokeTokenURL(e){let n=new URL(this.endpoints.oauth2RevokeUrl);return n.searchParams.append("token",e),n}revokeToken(e,n){let r={...t.RETRY_CONFIG,url:this.getRevokeTokenURL(e).toString(),method:"POST"};if(Bs.AuthClient.setMethodName(r,"revokeToken"),n)this.transporter.request(r).then(o=>n(null,o),n);else return this.transporter.request(r)}revokeCredentials(e){if(e)this.revokeCredentialsAsync().then(n=>e(null,n),e);else return this.revokeCredentialsAsync()}async revokeCredentialsAsync(){let e=this.credentials.access_token;if(this.credentials={},e)return this.revokeToken(e);throw new Error("No access token to revoke.")}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){try{let r=await this.getRequestMetadataAsync();return e.headers=rv.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,r.headers),this.apiKey&&e.headers.set("X-Goog-Api-Key",this.apiKey),await this.transporter.request(e)}catch(r){let o=r.response;if(o){let s=o.status,i=this.credentials&&this.credentials.access_token&&this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure),a=this.credentials&&this.credentials.access_token&&!this.credentials.refresh_token&&(!this.credentials.expiry_date||this.forceRefreshOnFailure)&&this.refreshHandler,u=o.config.data instanceof GM.Readable,d=s===401||s===403;if(!n&&d&&!u&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!u&&a){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,dm.hasBrowserCrypto)()?_r.JWK:_r.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case _r.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case _r.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Bs.AuthClient.setMethodName(d,"getFederatedSignonCertsAsync"),r=await this.transporter.request(d)}catch(d){throw d instanceof Error&&(d.message=`Failed to retrieve verification certificates: ${d.message}`),d}let s=r?.headers.get("cache-control"),i=-1;if(s){let d=/max-age=(?<maxAge>[0-9]+)/.exec(s)?.groups?.maxAge;d&&(i=Number(d)*1e3)}let a={};switch(n){case _r.PEM:a=r.data;break;case _r.JWK:for(let d of r.data.keys)a[d.kid]=d;break;default:throw new Error(`Unsupported certificate format ${n}`)}let u=new Date;return this.certificateExpiry=i===-1?null:new Date(u.getTime()+i),this.certificateCache=a,this.certificateCacheFormat=n,{certs:a,format:n,res:r}}getIapPublicKeys(e){if(e)this.getIapPublicKeysAsync().then(n=>e(null,n.pubkeys,n.res),e);else return this.getIapPublicKeysAsync()}async getIapPublicKeysAsync(){let e,n=this.endpoints.oauth2IapPublicKeyUrl.toString();try{let r={...t.RETRY_CONFIG,url:n};Bs.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let i=(0,dm.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let a=e.split(".");if(a.length!==3)throw new Error("Wrong number of segments in token: "+e);let u=a[0]+"."+a[1],d=a[2],f,p;try{f=JSON.parse(i.decodeBase64StringUtf8(a[0]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token envelope: ${a[0]}': ${k.message}`),k}if(!f)throw new Error("Can't parse token envelope: "+a[0]);try{p=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(k){throw k instanceof Error&&(k.message=`Can't parse token payload '${a[0]}`),k}if(!p)throw new Error("Can't parse token payload: "+a[1]);if(!Object.prototype.hasOwnProperty.call(n,f.kid))throw new Error("No pem found for envelope: "+JSON.stringify(f));let h=n[f.kid];if(f.alg==="ES256"&&(d=JM.joseToDer(d,"ES256").toString("base64")),!await i.verify(h,u,d))throw new Error("Invalid token signature: "+e);if(!p.iat)throw new Error("No issue time in token: "+JSON.stringify(p));if(!p.exp)throw new Error("No expiration time in token: "+JSON.stringify(p));let b=Number(p.iat);if(isNaN(b))throw new Error("iat field using invalid format");let m=Number(p.exp);if(isNaN(m))throw new Error("exp field using invalid format");let w=new Date().getTime()/1e3;if(m>=w+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let C=b-t.CLOCK_SKEW_SECS_,S=m+t.CLOCK_SKEW_SECS_;if(w<C)throw new Error("Token used too early, "+w+" < "+C+": "+JSON.stringify(p));if(w>S)throw new Error("Token used too late, "+w+" > "+S+": "+JSON.stringify(p));if(o&&o.indexOf(p.iss)<0)throw new Error("Invalid issuer, expected one of ["+o+"], but got "+p.iss);if(typeof r<"u"&&r!==null){let k=p.aud,E=!1;if(r.constructor===Array?E=r.indexOf(k)>-1:E=k===r,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new KM.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Un.OAuth2Client=fm});var hm=G(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.Compute=void 0;var VM=lt(),iv=ga(),YM=Kr(),pm=class extends YM.OAuth2Client{serviceAccountEmail;scopes;constructor(e={}){super(e),this.credentials={expiry_date:1,refresh_token:"compute-placeholder"},this.serviceAccountEmail=e.serviceAccountEmail||"default",this.scopes=Array.isArray(e.scopes)?e.scopes:e.scopes?[e.scopes]:[]}async refreshTokenNoCache(){let e=`service-accounts/${this.serviceAccountEmail}/token`,n;try{let o={property:e};this.scopes.length>0&&(o.params={scopes:this.scopes.join(",")}),n=await iv.instance(o)}catch(o){throw o instanceof VM.GaxiosError&&(o.message=`Could not refresh access token: ${o.message}`,this.wrapError(o)),o}let r=n;return n&&n.expires_in&&(r.expiry_date=new Date().getTime()+n.expires_in*1e3,delete r.expires_in),this.emit("tokens",r),{tokens:r,res:null}}async fetchIdToken(e){let n=`service-accounts/${this.serviceAccountEmail}/identity?format=full&audience=${e}`,r;try{let o={property:n};r=await iv.instance(o)}catch(o){throw o instanceof Error&&(o.message=`Could not fetch ID token: ${o.message}`),o}return r}wrapError(e){let n=e.response;n&&n.status&&(e.status=n.status,n.status===403?e.message="A Forbidden error was returned while attempting to retrieve an access token for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have the correct permission scopes specified: "+e.message:n.status===404&&(e.message="A Not Found error was returned while attempting to retrieve an accesstoken for the Compute Engine built-in service account. This may be because the Compute Engine instance does not have any permission scopes specified: "+e.message))}};Dl.Compute=pm});var mm=G(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.IdTokenClient=void 0;var XM=Kr(),gm=class extends XM.OAuth2Client{targetAudience;idTokenProvider;constructor(e){super(e),this.targetAudience=e.targetAudience,this.idTokenProvider=e.idTokenProvider}async getRequestMetadataAsync(){if(!this.credentials.id_token||!this.credentials.expiry_date||this.isTokenExpiring()){let n=await this.idTokenProvider.fetchIdToken(this.targetAudience);this.credentials={id_token:n,expiry_date:this.getIdTokenExpiryDate(n)}}return{headers:new Headers({authorization:"Bearer "+this.credentials.id_token})}}getIdTokenExpiryDate(e){let n=e.split(".")[1];if(n)return JSON.parse(Buffer.from(n,"base64").toString("ascii")).exp*1e3}};Ol.IdTokenClient=gm});var ym=G(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.GCPEnv=void 0;js.clear=QM;js.getEnv=ZM;var av=ga(),Ln;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Ln||(js.GCPEnv=Ln={}));var _a;function QM(){_a=void 0}async function ZM(){return _a||(_a=eB(),_a)}async function eB(){let t=Ln.NONE;return tB()?t=Ln.APP_ENGINE:nB()?t=Ln.CLOUD_FUNCTIONS:await iB()?await sB()?t=Ln.KUBERNETES_ENGINE:rB()?t=Ln.CLOUD_RUN:oB()?t=Ln.CLOUD_RUN_JOBS:t=Ln.COMPUTE_ENGINE:t=Ln.NONE,t}function tB(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function nB(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function rB(){return!!process.env.K_CONFIGURATION}function oB(){return!!process.env.CLOUD_RUN_JOB}async function sB(){try{return await av.instance("attributes/cluster-name"),!0}catch{return!1}}async function iB(){return av.isAvailable()}});var _m=G((x5,cv)=>{var Pl=Ms().Buffer,aB=re("stream"),cB=re("util");function Il(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Pl.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Pl.alloc(0),t.pipe(this),this;if(t.length||typeof t=="object")return this.buffer=t,this.writable=!1,process.nextTick(function(){this.emit("end",t),this.readable=!1,this.emit("close")}.bind(this)),this;throw new TypeError("Unexpected data type ("+typeof t+")")}cB.inherits(Il,aB);Il.prototype.write=function(e){this.buffer=Pl.concat([this.buffer,Pl.from(e)]),this.emit("data",e)};Il.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};cv.exports=Il});var lv=G((R5,uv)=>{"use strict";var ba=re("buffer").Buffer,bm=re("buffer").SlowBuffer;uv.exports=Fl;function Fl(t,e){if(!ba.isBuffer(t)||!ba.isBuffer(e)||t.length!==e.length)return!1;for(var n=0,r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}Fl.install=function(){ba.prototype.equal=bm.prototype.equal=function(e){return Fl(this,e)}};var uB=ba.prototype.equal,lB=bm.prototype.equal;Fl.restore=function(){ba.prototype.equal=uB,bm.prototype.equal=lB}});var Sm=G((D5,bv)=>{var Ls=Ms().Buffer,Jt=re("crypto"),fv=nm(),dv=re("util"),dB=`"%s" is not a valid algorithm.
102
102
  Supported algorithms are:
103
- "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ca="secret must be a string or buffer",js="key must be a string or a buffer",dB="key must be a string, a buffer or an object",km=typeof Jt.createPublicKey=="function";km&&(js+=" or a KeyObject",Ca+="or a KeyObject");function pv(t){if(!Ls.isBuffer(t)&&typeof t!="string"&&(!km||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw un(js)}function hv(t){if(!Ls.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw un(dB)}function fB(t){if(!Ls.isBuffer(t)){if(typeof t=="string")return t;if(!km||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw un(Ca)}}function Sm(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function gv(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function un(t){var e=[].slice.call(arguments,1),n=dv.format.bind(dv,t).apply(null,e);return new TypeError(n)}function pB(t){return Ls.isBuffer(t)||typeof t=="string"}function wa(t){return pB(t)||(t=JSON.stringify(t)),t}function mv(t){return function(n,r){fB(r),n=wa(n);var o=Jt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Sm(s)}}var wm,hB="timingSafeEqual"in Jt?function(e,n){return e.byteLength!==n.byteLength?!1:Jt.timingSafeEqual(e,n)}:function(e,n){return wm||(wm=lv()),wm(e,n)};function gB(t){return function(n,r,o){var s=mv(t)(n,o);return hB(Ls.from(r),Ls.from(s))}}function yv(t){return function(n,r){hv(r),n=wa(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Sm(s)}}function _v(t){return function(n,r,o){pv(o),n=wa(n),r=gv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function mB(t){return function(n,r){hv(r),n=wa(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Sm(s)}}function yB(t){return function(n,r,o){pv(o),n=wa(n),r=gv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function _B(t){var e=yv(t);return function(){var r=e.apply(null,arguments);return r=fv.derToJose(r,"ES"+t),r}}function bB(t){var e=_v(t);return function(r,o,s){o=fv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function CB(){return function(){return""}}function wB(){return function(e,n){return n===""}}bv.exports=function(e){var n={hs:mv,rs:yv,ps:mB,es:_B,none:CB},r={hs:gB,rs:_v,ps:yB,es:bB,none:wB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw un(lB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var Em=G((x5,Cv)=>{var kB=re("buffer").Buffer;Cv.exports=function(e){return typeof e=="string"?e:typeof e=="number"||kB.isBuffer(e)?e.toString():JSON.stringify(e)}});var vv=G((R5,Ev)=>{var SB=Ms().Buffer,wv=bm(),AB=Am(),EB=re("stream"),kv=Em(),vm=re("util");function Sv(t,e){return SB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function vB(t,e,n){n=n||"utf8";var r=Sv(kv(t),"binary"),o=Sv(kv(e),n);return vm.format("%s.%s",r,o)}function Av(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=AB(e.alg),i=vB(e,n,o),a=s.sign(i,r);return vm.format("%s.%s",i,a)}function Nl(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new wv(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new wv(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}vm.inherits(Nl,EB);Nl.prototype.sign=function(){try{var e=Av({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Nl.sign=Av;Ev.exports=Nl});var Mv=G((D5,Nv)=>{var xv=Ms().Buffer,Tv=bm(),TB=Am(),xB=re("stream"),Rv=Em(),RB=re("util"),DB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function OB(t){return Object.prototype.toString.call(t)==="[object Object]"}function PB(t){if(OB(t))return t;try{return JSON.parse(t)}catch{return}}function Dv(t){var e=t.split(".",1)[0];return PB(xv.from(e,"base64").toString("binary"))}function IB(t){return t.split(".",2).join(".")}function Ov(t){return t.split(".")[2]}function FB(t,e){e=e||"utf8";var n=t.split(".")[1];return xv.from(n,"base64").toString(e)}function Pv(t){return DB.test(t)&&!!Dv(t)}function Iv(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Rv(t);var o=Ov(t),s=IB(t),i=TB(e);return i.verify(s,o,n)}function Fv(t,e){if(e=e||{},t=Rv(t),!Pv(t))return null;var n=Dv(t);if(!n)return null;var r=FB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Ov(t)}}function $s(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new Tv(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Tv(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}RB.inherits($s,xB);$s.prototype.verify=function(){try{var e=Iv(this.signature.buffer,this.algorithm,this.key.buffer),n=Fv(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};$s.decode=Fv;$s.isValid=Pv;$s.verify=Iv;Nv.exports=$s});var Tm=G(Vr=>{var Bv=vv(),Ml=Mv(),NB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Vr.ALGORITHMS=NB;Vr.sign=Bv.sign;Vr.verify=Ml.verify;Vr.decode=Ml.decode;Vr.isValid=Ml.isValid;Vr.createSign=function(e){return new Bv(e)};Vr.createVerify=function(e){return new Ml(e)}});var jv=G(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.buildPayloadForJwsSign=Uv;Bl.getJwsSign=jB;var MB=Tm(),BB="RS256",UB="https://oauth2.googleapis.com/token";function Uv(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:UB,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function jB(t){let e=Uv(t);return(0,MB.sign)({header:{alg:BB},payload:e,secret:t.key})}});var Lv=G(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});xm.getToken=zB;var LB=jv(),$B="https://oauth2.googleapis.com/token",qB="urn:ietf:params:oauth:grant-type:jwt-bearer",HB=t=>({method:"POST",url:$B,data:new URLSearchParams({grant_type:qB,assertion:(0,LB.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function zB(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=HB(t);return(await t.transporter.request(e)).data}catch(e){let n=e,r=n.response?.data;throw r?.error&&(n.message=`${r.error}: ${r.error_description}`),n}}});var $v=G(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});Ul.ErrorWithCode=void 0;var Rm=class extends Error{code;constructor(e,n){super(e),this.code=n}};Ul.ErrorWithCode=Rm});var Nm=G(Fm=>{"use strict";Object.defineProperty(Fm,"__esModule",{value:!0});Fm.getCredentials=JB;var WB=re("path"),qv=re("fs"),GB=re("util"),jl=$v(),Hv=qv.readFile?(0,GB.promisify)(qv.readFile):async()=>{throw new jl.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Yr;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Yr||(Yr={}));var Dm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Hv(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let i=s;throw new Error(`Invalid JSON key file: ${i.message}`)}let r=n.private_key,o=n.client_email;if(!r||!o)throw new jl.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},Om=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Hv(this.keyFilePath,"utf8")}}},Pm=class{async getCredentials(){throw new jl.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},Im=class{static create(e){switch(WB.extname(e)){case Yr.JSON:return new Dm(e);case Yr.DER:case Yr.CRT:case Yr.PEM:return new Om(e);case Yr.P12:case Yr.PFX:return new Pm;default:throw new jl.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function JB(t){return Im.create(t).getCredentials()}});var zv=G(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.TokenHandler=void 0;var KB=Lv(),VB=Nm(),Mm=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,VB.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,KB.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};Ll.TokenHandler=Mm});var Wv=G(Bm=>{"use strict";Object.defineProperty(Bm,"__esModule",{value:!0});Bm.revokeToken=QB;var YB="https://oauth2.googleapis.com/revoke?token=",XB=!0;async function QB(t,e){let n=YB+t;return await e.request({url:n,retry:XB})}});var jm=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.GoogleToken=void 0;var ZB=lt(),Gv=zv(),eU=Wv(),Um=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,ZB.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new Gv.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let r;typeof e=="function"?r=e:typeof e=="object"&&(n=e);let o=this.tokenHandler.getToken(n.forceRefresh??!1);return r&&o.then(s=>r(null,s),r),o}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,eU.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Gv.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};$l.GoogleToken=Um});var $m=G(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});ql.JWTAccess=void 0;var tU=Tm(),nU=an(),Jv={alg:"RS256",typ:"JWT"},Lm=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new nU.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),i=Date.now();if(s&&s.expiration-i>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let a=Math.floor(Date.now()/1e3),u=t.getExpirationTime(a),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:u,iat:a}:d={iss:this.email,sub:this.email,aud:e,exp:u,iat:a},n){for(let b in d)if(n[b])throw new Error(`The '${b}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Jv,kid:this.keyId}:Jv,p=Object.assign(d,n),h=tU.sign({header:f,payload:p,secret:this.key}),g=new Headers({authorization:`Bearer ${h}`});return this.cache.set(o,{expiration:u*1e3,headers:g}),g}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ql.JWTAccess=Lm});var Hm=G(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});zl.JWT=void 0;var Kv=jm(),rU=Nm(),oU=$m(),sU=Kr(),Hl=Nt(),qm=class t extends sU.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Hl.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Hl.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Hl.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new oU.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Hl.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Kv.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new Kv.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,rU.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};zl.JWT=qm});var Wm=G(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.UserRefreshClient=qs.USER_REFRESH_ACCOUNT_TYPE=void 0;var iU=Kr(),aU=Nt();qs.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var zm=class t extends iU.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let i=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(i),this._refreshToken=i.refreshToken,this.credentials.refresh_token=i.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return aU.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};qs.UserRefreshClient=zm});var Jm=G(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.Impersonated=Hs.IMPERSONATED_ACCOUNT_TYPE=void 0;var Vv=Kr(),cU=lt(),uU=an();Hs.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Gm=class t extends Vv.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Vv.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,uU.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof cU.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Hs.Impersonated=Gm});var Vm=G(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.OAuthClientAuthHandler=void 0;ka.getErrorFromOAuthErrorResponse=fU;var zs=lt(),lU=ma(),dU=["PUT","POST","PATCH"],Km=class{#e=(0,lU.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new zs.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new zs.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=zs.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=zs.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=zs.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);zs.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!dU.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};ka.OAuthClientAuthHandler=Km;function fU(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let i=new Error(s);if(e){let a=Object.keys(e);e.stack&&a.push("stack"),a.forEach(u=>{u!=="message"&&Object.defineProperty(i,u,{value:e[u],writable:!1,enumerable:!0})})}return i}});var Gl=G(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.StsCredentials=void 0;var pU=lt(),hU=Nt(),Yv=Vm(),gU=an(),Ym=class t extends Yv.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,gU.removeUndefinedValuesInObject)(o)),responseType:"json"};hU.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let i=await this.transporter.request(s),a=i.data;return a.res=i,a}catch(i){throw i instanceof pU.GaxiosError&&i.response?(0,Yv.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};Wl.StsCredentials=Ym});var Xr=G(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.BaseExternalAccountClient=Kt.CLOUD_RESOURCE_MANAGER=Kt.EXTERNAL_ACCOUNT_TYPE=Kt.EXPIRATION_TIME_OFFSET=void 0;var mU=lt(),yU=re("stream"),Xm=Nt(),_U=Gl(),Xv=an(),bU=im(),CU="urn:ietf:params:oauth:grant-type:token-exchange",wU="urn:ietf:params:oauth:token-type:access_token",Qm="https://www.googleapis.com/auth/cloud-platform",kU=3600;Kt.EXPIRATION_TIME_OFFSET=300*1e3;Kt.EXTERNAL_ACCOUNT_TYPE="external_account";Kt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var SU="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",AU="https://sts.{universeDomain}/v1/token",Zm=class t extends Xm.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Xv.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Kt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Kt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??AU.replace("{universeDomain}",this.universeDomain);let i=n.get("subject_token_type"),a=n.get("workforce_pool_user_project"),u=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,Xv.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new _U.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Qm],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(SU);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=u,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=kU),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Xm.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=mU.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof yU.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:CU,audience:this.audience,requestedTokenType:wU,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Qm]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Xm.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Qm]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${bU.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Kt.BaseExternalAccountClient=Zm});var Qv=G(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});Jl.FileSubjectTokenSupplier=void 0;var ty=re("util"),ny=re("fs"),EU=(0,ty.promisify)(ny.readFile??(()=>{})),vU=(0,ty.promisify)(ny.realpath??(()=>{})),TU=(0,ty.promisify)(ny.lstat??(()=>{})),ey=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await vU(e),!(await TU(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await EU(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Jl.FileSubjectTokenSupplier=ey});var Zv=G(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.UrlSubjectTokenSupplier=void 0;var xU=Nt(),ry=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};xU.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Kl.UrlSubjectTokenSupplier=ry});var eT=G(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.CertificateSubjectTokenSupplier=Mt.InvalidConfigurationError=Mt.CertificateSourceUnavailableError=Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Vl=an(),Yl=re("fs"),Xl=re("crypto"),RU=re("https");Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var $n=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Mt.CertificateSourceUnavailableError=$n;var Vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Mt.InvalidConfigurationError=Vt;var oy=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Vt("Cannot create mTLS Agent with missing certificate or key");return new RU.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Vl.isValidFile)(e))return e;throw new $n(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Vl.isValidFile)(n))return n;throw new $n(`Path from environment variable "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Vl.getWellKnownCertificateConfigFileLocation)();if(await(0,Vl.isValidFile)(r))return r;throw new $n(`Could not find certificate configuration file. Searched override path, the "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Yl.promises.readFile(e,"utf8")}catch{throw new $n(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Vt?r:new Vt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Yl.promises.readFile(e),new Xl.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read certificate file at ${e}: ${i}`)}try{o=await Yl.promises.readFile(n),(0,Xl.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new Xl.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Yl.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new Xl.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Vt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),i=s.findIndex(u=>n.raw.equals(u.raw)),a;if(i===-1)a=[n,...s];else if(i===0)a=s;else throw new Vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(a.map(u=>u.raw.toString("base64")))}catch(r){if(r instanceof Vt)throw r;let o=r instanceof Error?r.message:String(r);throw new $n(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Mt.CertificateSubjectTokenSupplier=oy});var ay=G(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.IdentityPoolClient=void 0;var DU=Xr(),sy=an(),OU=Qv(),PU=Zv(),tT=eT(),IU=Gl(),nT=lt(),iy=class t extends DU.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,sy.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,sy.originalOrCamelOptions)(r),i=(0,sy.originalOrCamelOptions)(s.get("format")),a=i.get("type")||"text",u=i.get("subject_token_field_name");if(a!=="json"&&a!=="text")throw new Error(`Invalid credential_source format "${a}"`);if(a==="json"&&!u)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=s.get("file"),f=s.get("url"),p=s.get("certificate"),h=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new OU.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new PU.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new tT.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=g}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof tT.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new IU.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new nT.Gaxios({agent:n})}),this.transporter=new nT.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ql.IdentityPoolClient=iy});var uy=G(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});ed.AwsRequestSigner=void 0;var Zl=lt(),oT=ma(),rT="AWS4-HMAC-SHA256",FU="aws4_request",cy=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,oT.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,i=e.headers,a=await this.getCredentials(),u=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await MU({crypto:this.crypto,host:u.host,canonicalUri:u.pathname,canonicalQuerystring:u.search.slice(1),method:o,region:this.region,securityCredentials:a,requestPayload:s,additionalAmzHeaders:i}),f=Zl.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&Zl.Gaxios.mergeHeaders(f,{"x-amz-security-token":a.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};ed.AwsRequestSigner=cy;async function Sa(t,e,n){return await t.signWithHmacSha256(e,n)}async function NU(t,e,n,r,o){let s=await Sa(t,`AWS4${e}`,n),i=await Sa(t,s,r),a=await Sa(t,i,o);return await Sa(t,a,"aws4_request")}async function MU(t){let e=Zl.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),i=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let a=Zl.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),u="",d=[...a.keys()].sort();d.forEach(A=>{u+=`${A}:${a.get(A)}
103
+ "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".`,Ca="secret must be a string or buffer",Us="key must be a string or a buffer",fB="key must be a string, a buffer or an object",wm=typeof Jt.createPublicKey=="function";wm&&(Us+=" or a KeyObject",Ca+="or a KeyObject");function pv(t){if(!Ls.isBuffer(t)&&typeof t!="string"&&(!wm||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw un(Us)}function hv(t){if(!Ls.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw un(fB)}function pB(t){if(!Ls.isBuffer(t)){if(typeof t=="string")return t;if(!wm||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw un(Ca)}}function km(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function gv(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function un(t){var e=[].slice.call(arguments,1),n=dv.format.bind(dv,t).apply(null,e);return new TypeError(n)}function hB(t){return Ls.isBuffer(t)||typeof t=="string"}function wa(t){return hB(t)||(t=JSON.stringify(t)),t}function mv(t){return function(n,r){pB(r),n=wa(n);var o=Jt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return km(s)}}var Cm,gB="timingSafeEqual"in Jt?function(e,n){return e.byteLength!==n.byteLength?!1:Jt.timingSafeEqual(e,n)}:function(e,n){return Cm||(Cm=lv()),Cm(e,n)};function mB(t){return function(n,r,o){var s=mv(t)(n,o);return gB(Ls.from(r),Ls.from(s))}}function yv(t){return function(n,r){hv(r),n=wa(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return km(s)}}function _v(t){return function(n,r,o){pv(o),n=wa(n),r=gv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function yB(t){return function(n,r){hv(r),n=wa(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return km(s)}}function _B(t){return function(n,r,o){pv(o),n=wa(n),r=gv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function bB(t){var e=yv(t);return function(){var r=e.apply(null,arguments);return r=fv.derToJose(r,"ES"+t),r}}function CB(t){var e=_v(t);return function(r,o,s){o=fv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function wB(){return function(){return""}}function kB(){return function(e,n){return n===""}}bv.exports=function(e){var n={hs:mv,rs:yv,ps:yB,es:bB,none:wB},r={hs:mB,rs:_v,ps:_B,es:CB,none:kB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw un(dB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var Am=G((O5,Cv)=>{var SB=re("buffer").Buffer;Cv.exports=function(e){return typeof e=="string"?e:typeof e=="number"||SB.isBuffer(e)?e.toString():JSON.stringify(e)}});var vv=G((P5,Ev)=>{var AB=Ms().Buffer,wv=_m(),EB=Sm(),vB=re("stream"),kv=Am(),Em=re("util");function Sv(t,e){return AB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function TB(t,e,n){n=n||"utf8";var r=Sv(kv(t),"binary"),o=Sv(kv(e),n);return Em.format("%s.%s",r,o)}function Av(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=EB(e.alg),i=TB(e,n,o),a=s.sign(i,r);return Em.format("%s.%s",i,a)}function Nl(t){var e=t.secret;if(e=e??t.privateKey,e=e??t.key,/^hs/i.test(t.header.alg)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new wv(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new wv(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Em.inherits(Nl,vB);Nl.prototype.sign=function(){try{var e=Av({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});return this.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(n){this.readable=!1,this.emit("error",n),this.emit("close")}};Nl.sign=Av;Ev.exports=Nl});var Mv=G((I5,Nv)=>{var xv=Ms().Buffer,Tv=_m(),xB=Sm(),RB=re("stream"),Rv=Am(),DB=re("util"),OB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function PB(t){return Object.prototype.toString.call(t)==="[object Object]"}function IB(t){if(PB(t))return t;try{return JSON.parse(t)}catch{return}}function Dv(t){var e=t.split(".",1)[0];return IB(xv.from(e,"base64").toString("binary"))}function FB(t){return t.split(".",2).join(".")}function Ov(t){return t.split(".")[2]}function NB(t,e){e=e||"utf8";var n=t.split(".")[1];return xv.from(n,"base64").toString(e)}function Pv(t){return OB.test(t)&&!!Dv(t)}function Iv(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Rv(t);var o=Ov(t),s=FB(t),i=xB(e);return i.verify(s,o,n)}function Fv(t,e){if(e=e||{},t=Rv(t),!Pv(t))return null;var n=Dv(t);if(!n)return null;var r=NB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:Ov(t)}}function $s(t){t=t||{};var e=t.secret;if(e=e??t.publicKey,e=e??t.key,/^hs/i.test(t.algorithm)===!0&&e==null)throw new TypeError("secret must be a string or buffer or a KeyObject");var n=new Tv(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Tv(t.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}DB.inherits($s,RB);$s.prototype.verify=function(){try{var e=Iv(this.signature.buffer,this.algorithm,this.key.buffer),n=Fv(this.signature.buffer,this.encoding);return this.emit("done",e,n),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(r){this.readable=!1,this.emit("error",r),this.emit("close")}};$s.decode=Fv;$s.isValid=Pv;$s.verify=Iv;Nv.exports=$s});var vm=G(Vr=>{var Bv=vv(),Ml=Mv(),MB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Vr.ALGORITHMS=MB;Vr.sign=Bv.sign;Vr.verify=Ml.verify;Vr.decode=Ml.decode;Vr.isValid=Ml.isValid;Vr.createSign=function(e){return new Bv(e)};Vr.createVerify=function(e){return new Ml(e)}});var Uv=G(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.buildPayloadForJwsSign=jv;Bl.getJwsSign=LB;var BB=vm(),jB="RS256",UB="https://oauth2.googleapis.com/token";function jv(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:UB,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function LB(t){let e=jv(t);return(0,BB.sign)({header:{alg:jB},payload:e,secret:t.key})}});var Lv=G(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.getToken=WB;var $B=Uv(),qB="https://oauth2.googleapis.com/token",HB="urn:ietf:params:oauth:grant-type:jwt-bearer",zB=t=>({method:"POST",url:qB,data:new URLSearchParams({grant_type:HB,assertion:(0,$B.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function WB(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=zB(t);return(await t.transporter.request(e)).data}catch(e){let n=e,r=n.response?.data;throw r?.error&&(n.message=`${r.error}: ${r.error_description}`),n}}});var $v=G(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.ErrorWithCode=void 0;var xm=class extends Error{code;constructor(e,n){super(e),this.code=n}};jl.ErrorWithCode=xm});var Fm=G(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});Im.getCredentials=KB;var GB=re("path"),qv=re("fs"),JB=re("util"),Ul=$v(),Hv=qv.readFile?(0,JB.promisify)(qv.readFile):async()=>{throw new Ul.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Yr;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Yr||(Yr={}));var Rm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Hv(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let i=s;throw new Error(`Invalid JSON key file: ${i.message}`)}let r=n.private_key,o=n.client_email;if(!r||!o)throw new Ul.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},Dm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Hv(this.keyFilePath,"utf8")}}},Om=class{async getCredentials(){throw new Ul.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},Pm=class{static create(e){switch(GB.extname(e)){case Yr.JSON:return new Rm(e);case Yr.DER:case Yr.CRT:case Yr.PEM:return new Dm(e);case Yr.P12:case Yr.PFX:return new Om;default:throw new Ul.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function KB(t){return Pm.create(t).getCredentials()}});var zv=G(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.TokenHandler=void 0;var VB=Lv(),YB=Fm(),Nm=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,YB.getCredentials)(this.tokenOptions.keyFile);this.tokenOptions.key=e.privateKey,this.tokenOptions.email=e.clientEmail}}isTokenExpiring(){if(!this.token||!this.tokenExpiresAt)return!0;let e=new Date().getTime(),n=this.tokenOptions.eagerRefreshThresholdMillis??0;return this.tokenExpiresAt<=e+n}hasExpired(){let e=new Date().getTime();return this.token&&this.tokenExpiresAt?new Date().getTime()>=this.tokenExpiresAt:!0}async getToken(e){if(await this.processCredentials(),this.inFlightRequest&&!e)return this.inFlightRequest;if(this.token&&!this.isTokenExpiring()&&!e)return this.token;try{this.inFlightRequest=(0,VB.getToken)(this.tokenOptions);let n=await this.inFlightRequest;return this.token=n,this.tokenExpiresAt=new Date().getTime()+(n.expires_in??0)*1e3,n}finally{this.inFlightRequest=void 0}}};Ll.TokenHandler=Nm});var Wv=G(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});Mm.revokeToken=ZB;var XB="https://oauth2.googleapis.com/revoke?token=",QB=!0;async function ZB(t,e){let n=XB+t;return await e.request({url:n,retry:QB})}});var jm=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.GoogleToken=void 0;var ej=lt(),Gv=zv(),tj=Wv(),Bm=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,ej.request)(n)},this.tokenOptions.iss||(this.tokenOptions.iss=this.tokenOptions.email),typeof this.tokenOptions.scope=="object"&&(this.tokenOptions.scope=this.tokenOptions.scope.join(" ")),this.tokenHandler=new Gv.TokenHandler(this.tokenOptions)}get expiresAt(){return this.tokenHandler.tokenExpiresAt}get accessToken(){return this.tokenHandler.token?.access_token}get idToken(){return this.tokenHandler.token?.id_token}get tokenType(){return this.tokenHandler.token?.token_type}get refreshToken(){return this.tokenHandler.token?.refresh_token}hasExpired(){return this.tokenHandler.hasExpired()}isTokenExpiring(){return this.tokenHandler.isTokenExpiring()}getToken(e,n={forceRefresh:!1}){let r;typeof e=="function"?r=e:typeof e=="object"&&(n=e);let o=this.tokenHandler.getToken(n.forceRefresh??!1);return r&&o.then(s=>r(null,s),r),o}revokeToken(e){if(!this.accessToken)return Promise.reject(new Error("No token to revoke."));let n=(0,tj.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Gv.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};$l.GoogleToken=Bm});var Lm=G(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});ql.JWTAccess=void 0;var nj=vm(),rj=an(),Jv={alg:"RS256",typ:"JWT"},Um=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new rj.LRUCache({capacity:500,maxAge:3600*1e3});constructor(e,n,r,o){this.email=e,this.key=n,this.keyId=r,this.eagerRefreshThresholdMillis=o??300*1e3}getCachedKey(e,n){let r=e;if(n&&Array.isArray(n)&&n.length?r=e?`${e}_${n.join("_")}`:`${n.join("_")}`:typeof n=="string"&&(r=e?`${e}_${n}`:n),!r)throw Error("Scopes or url must be provided");return r}getRequestHeaders(e,n,r){let o=this.getCachedKey(e,r),s=this.cache.get(o),i=Date.now();if(s&&s.expiration-i>this.eagerRefreshThresholdMillis)return new Headers(s.headers);let a=Math.floor(Date.now()/1e3),u=t.getExpirationTime(a),d;if(Array.isArray(r)&&(r=r.join(" ")),r?d={iss:this.email,sub:this.email,scope:r,exp:u,iat:a}:d={iss:this.email,sub:this.email,aud:e,exp:u,iat:a},n){for(let b in d)if(n[b])throw new Error(`The '${b}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...Jv,kid:this.keyId}:Jv,p=Object.assign(d,n),h=nj.sign({header:f,payload:p,secret:this.key}),g=new Headers({authorization:`Bearer ${h}`});return this.cache.set(o,{expiration:u*1e3,headers:g}),g}static getExpirationTime(e){return e+3600}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{e||r(new Error("Must pass in a stream containing the service account auth settings."));let o="";e.setEncoding("utf8").on("data",s=>o+=s).on("error",r).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}};ql.JWTAccess=Um});var qm=G(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});zl.JWT=void 0;var Kv=jm(),oj=Fm(),sj=Lm(),ij=Kr(),Hl=Nt(),$m=class t extends ij.OAuth2Client{email;keyFile;key;keyId;defaultScopes;scopes;scope;subject;gtoken;additionalClaims;useJWTAccessWithScope;defaultServicePath;access;constructor(e={}){super(e),this.email=e.email,this.keyFile=e.keyFile,this.key=e.key,this.keyId=e.keyId,this.scopes=e.scopes,this.subject=e.subject,this.additionalClaims=e.additionalClaims,this.credentials={refresh_token:"jwt-placeholder",expiry_date:1}}createScoped(e){let n=new t(this);return n.scopes=e,n}async getRequestMetadataAsync(e){e=this.defaultServicePath?`https://${this.defaultServicePath}/`:e;let n=!this.hasUserScopes()&&e||this.useJWTAccessWithScope&&this.hasAnyScopes()||this.universeDomain!==Hl.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Hl.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Hl.DEFAULT_UNIVERSE}`);if(!this.apiKey&&n)if(this.additionalClaims&&this.additionalClaims.target_audience){let{tokens:r}=await this.refreshToken();return{headers:this.addSharedMetadataHeaders(new Headers({authorization:`Bearer ${r.id_token}`}))}}else{this.access||(this.access=new sj.JWTAccess(this.email,this.key,this.keyId,this.eagerRefreshThresholdMillis));let r;this.hasUserScopes()?r=this.scopes:e||(r=this.defaultScopes);let o=this.useJWTAccessWithScope||this.universeDomain!==Hl.DEFAULT_UNIVERSE,s=await this.access.getRequestHeaders(e??void 0,this.additionalClaims,o?r:void 0);return{headers:this.addSharedMetadataHeaders(s)}}else return this.hasAnyScopes()||this.apiKey?super.getRequestMetadataAsync(e):{headers:new Headers}}async fetchIdToken(e){let n=new Kv.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:{target_audience:e},transporter:this.transporter});if(await n.getToken({forceRefresh:!0}),!n.idToken)throw new Error("Unknown error: Failed to fetch ID token");return n.idToken}hasUserScopes(){return this.scopes?this.scopes.length>0:!1}hasAnyScopes(){return!!(this.scopes&&this.scopes.length>0||this.defaultScopes&&this.defaultScopes.length>0)}authorize(e){if(e)this.authorizeAsync().then(n=>e(null,n),e);else return this.authorizeAsync()}async authorizeAsync(){let e=await this.refreshToken();if(!e)throw new Error("No result returned");return this.credentials=e.tokens,this.credentials.refresh_token="jwt-placeholder",this.key=this.gtoken.googleTokenOptions?.key,this.email=this.gtoken.googleTokenOptions?.iss,e.tokens}async refreshTokenNoCache(){let e=this.createGToken(),r={access_token:(await e.getToken({forceRefresh:this.isTokenExpiring()})).access_token,token_type:"Bearer",expiry_date:e.expiresAt,id_token:e.idToken};return this.emit("tokens",r),{res:null,tokens:r}}createGToken(){return this.gtoken||(this.gtoken=new Kv.GoogleToken({iss:this.email,sub:this.subject,scope:this.scopes||this.defaultScopes,keyFile:this.keyFile,key:this.key,additionalClaims:this.additionalClaims,transporter:this.transporter})),this.gtoken}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the service account auth settings.");if(!e.client_email)throw new Error("The incoming JSON object does not contain a client_email field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");this.email=e.client_email,this.key=e.private_key,this.keyId=e.private_key_id,this.projectId=e.project_id,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}fromStreamAsync(e){return new Promise((n,r)=>{if(!e)throw new Error("Must pass in a stream containing the service account auth settings.");let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);this.fromJSON(s),n()}catch(s){r(s)}})})}fromAPIKey(e){if(typeof e!="string")throw new Error("Must provide an API Key string.");this.apiKey=e}async getCredentials(){if(this.key)return{private_key:this.key,client_email:this.email};if(this.keyFile){let e=this.createGToken(),n=await(0,oj.getCredentials)(this.keyFile);return{private_key:n.privateKey,client_email:n.clientEmail}}throw new Error("A key or a keyFile must be provided to getCredentials.")}};zl.JWT=$m});var zm=G(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.UserRefreshClient=qs.USER_REFRESH_ACCOUNT_TYPE=void 0;var aj=Kr(),cj=Nt();qs.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Hm=class t extends aj.OAuth2Client{_refreshToken;constructor(e,n,r,o,s){let i=e&&typeof e=="object"?e:{clientId:e,clientSecret:n,refreshToken:r,eagerRefreshThresholdMillis:o,forceRefreshOnFailure:s};super(i),this._refreshToken=i.refreshToken,this.credentials.refresh_token=i.refreshToken}async refreshTokenNoCache(){return super.refreshTokenNoCache(this._refreshToken)}async fetchIdToken(e){let n={...t.RETRY_CONFIG,url:this.endpoints.oauth2TokenUrl,method:"POST",data:new URLSearchParams({client_id:this._clientId,client_secret:this._clientSecret,grant_type:"refresh_token",refresh_token:this._refreshToken,target_audience:e}),responseType:"json"};return cj.AuthClient.setMethodName(n,"fetchIdToken"),(await this.transporter.request(n)).data.id_token}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the user refresh token");if(e.type!=="authorized_user")throw new Error('The incoming JSON object does not have the "authorized_user" type');if(!e.client_id)throw new Error("The incoming JSON object does not contain a client_id field");if(!e.client_secret)throw new Error("The incoming JSON object does not contain a client_secret field");if(!e.refresh_token)throw new Error("The incoming JSON object does not contain a refresh_token field");this._clientId=e.client_id,this._clientSecret=e.client_secret,this._refreshToken=e.refresh_token,this.credentials.refresh_token=e.refresh_token,this.quotaProjectId=e.quota_project_id,this.universeDomain=e.universe_domain||this.universeDomain}fromStream(e,n){if(n)this.fromStreamAsync(e).then(()=>n(),n);else return this.fromStreamAsync(e)}async fromStreamAsync(e){return new Promise((n,r)=>{if(!e)return r(new Error("Must pass in a stream containing the user refresh token."));let o="";e.setEncoding("utf8").on("error",r).on("data",s=>o+=s).on("end",()=>{try{let s=JSON.parse(o);return this.fromJSON(s),n()}catch(s){return r(s)}})})}static fromJSON(e){let n=new t;return n.fromJSON(e),n}};qs.UserRefreshClient=Hm});var Gm=G(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.Impersonated=Hs.IMPERSONATED_ACCOUNT_TYPE=void 0;var Vv=Kr(),uj=lt(),lj=an();Hs.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Wm=class t extends Vv.OAuth2Client{sourceClient;targetPrincipal;targetScopes;delegates;lifetime;endpoint;constructor(e={}){if(super(e),this.credentials={expiry_date:1,refresh_token:"impersonated-placeholder"},this.sourceClient=e.sourceClient??new Vv.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,lj.originalOrCamelOptions)(e).get("universe_domain"))this.universeDomain=this.sourceClient.universeDomain;else if(this.sourceClient.universeDomain!==this.universeDomain)throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`);this.endpoint=e.endpoint??`https://iamcredentials.${this.universeDomain}`}async sign(e){await this.sourceClient.getAccessToken();let n=`projects/-/serviceAccounts/${this.targetPrincipal}`,r=`${this.endpoint}/v1/${n}:signBlob`,o={delegates:this.delegates,payload:Buffer.from(e).toString("base64")};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:r,data:o,method:"POST"})).data}getTargetPrincipal(){return this.targetPrincipal}async refreshToken(){try{await this.sourceClient.getAccessToken();let e="projects/-/serviceAccounts/"+this.targetPrincipal,n=`${this.endpoint}/v1/${e}:generateAccessToken`,r={delegates:this.delegates,scope:this.targetScopes,lifetime:this.lifetime+"s"},o=await this.sourceClient.request({...t.RETRY_CONFIG,url:n,data:r,method:"POST"}),s=o.data;return this.credentials.access_token=s.accessToken,this.credentials.expiry_date=Date.parse(s.expireTime),{tokens:this.credentials,res:o}}catch(e){if(!(e instanceof Error))throw e;let n=0,r="";throw e instanceof uj.GaxiosError&&(n=e?.response?.data?.error?.status,r=e?.response?.data?.error?.message),n&&r?(e.message=`${n}: unable to impersonate: ${r}`,e):(e.message=`unable to impersonate: ${e}`,e)}}async fetchIdToken(e,n){await this.sourceClient.getAccessToken();let r=`projects/-/serviceAccounts/${this.targetPrincipal}`,o=`${this.endpoint}/v1/${r}:generateIdToken`,s={delegates:this.delegates,audience:e,includeEmail:n?.includeEmail??!0,useEmailAzp:n?.includeEmail??!0};return(await this.sourceClient.request({...t.RETRY_CONFIG,url:o,data:s,method:"POST"})).data.token}};Hs.Impersonated=Wm});var Km=G(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.OAuthClientAuthHandler=void 0;ka.getErrorFromOAuthErrorResponse=pj;var zs=lt(),dj=ma(),fj=["PUT","POST","PATCH"],Jm=class{#e=(0,dj.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new zs.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new zs.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=zs.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=zs.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=zs.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);zs.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!fj.includes(n))throw new Error(`${n} HTTP method does not support ${this.#t.confidentialClientType} client authentication`);let o=new Headers(e.headers).get("content-type");if(o?.startsWith("application/x-www-form-urlencoded")||e.data instanceof URLSearchParams){let s=new URLSearchParams(e.data??"");s.append("client_id",this.#t.clientId),s.append("client_secret",this.#t.clientSecret||""),e.data=s}else if(o?.startsWith("application/json"))e.data=e.data||{},Object.assign(e.data,{client_id:this.#t.clientId,client_secret:this.#t.clientSecret||""});else throw new Error(`${o} content-types are not supported with ${this.#t.confidentialClientType} client authentication`)}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};ka.OAuthClientAuthHandler=Jm;function pj(t,e){let n=t.error,r=t.error_description,o=t.error_uri,s=`Error code ${n}`;typeof r<"u"&&(s+=`: ${r}`),typeof o<"u"&&(s+=` - ${o}`);let i=new Error(s);if(e){let a=Object.keys(e);e.stack&&a.push("stack"),a.forEach(u=>{u!=="message"&&Object.defineProperty(i,u,{value:e[u],writable:!1,enumerable:!0})})}return i}});var Gl=G(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.StsCredentials=void 0;var hj=lt(),gj=Nt(),Yv=Km(),mj=an(),Vm=class t extends Yv.OAuthClientAuthHandler{#e;constructor(e={tokenExchangeEndpoint:""},n){(typeof e!="object"||e instanceof URL)&&(e={tokenExchangeEndpoint:e,clientAuthentication:n}),super(e),this.#e=e.tokenExchangeEndpoint}async exchangeToken(e,n,r){let o={grant_type:e.grantType,resource:e.resource,audience:e.audience,scope:e.scope?.join(" "),requested_token_type:e.requestedTokenType,subject_token:e.subjectToken,subject_token_type:e.subjectTokenType,actor_token:e.actingParty?.actorToken,actor_token_type:e.actingParty?.actorTokenType,options:r&&JSON.stringify(r)},s={...t.RETRY_CONFIG,url:this.#e.toString(),method:"POST",headers:n,data:new URLSearchParams((0,mj.removeUndefinedValuesInObject)(o)),responseType:"json"};gj.AuthClient.setMethodName(s,"exchangeToken"),this.applyClientAuthenticationOptions(s);try{let i=await this.transporter.request(s),a=i.data;return a.res=i,a}catch(i){throw i instanceof hj.GaxiosError&&i.response?(0,Yv.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};Wl.StsCredentials=Vm});var Xr=G(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.BaseExternalAccountClient=Kt.CLOUD_RESOURCE_MANAGER=Kt.EXTERNAL_ACCOUNT_TYPE=Kt.EXPIRATION_TIME_OFFSET=void 0;var yj=lt(),_j=re("stream"),Ym=Nt(),bj=Gl(),Xv=an(),Cj=sm(),wj="urn:ietf:params:oauth:grant-type:token-exchange",kj="urn:ietf:params:oauth:token-type:access_token",Xm="https://www.googleapis.com/auth/cloud-platform",Sj=3600;Kt.EXPIRATION_TIME_OFFSET=300*1e3;Kt.EXTERNAL_ACCOUNT_TYPE="external_account";Kt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var Aj="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",Ej="https://sts.{universeDomain}/v1/token",Qm=class t extends Ym.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Xv.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Kt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Kt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??Ej.replace("{universeDomain}",this.universeDomain);let i=n.get("subject_token_type"),a=n.get("workforce_pool_user_project"),u=n.get("service_account_impersonation_url"),d=n.get("service_account_impersonation"),f=(0,Xv.originalOrCamelOptions)(d).get("token_lifetime_seconds");this.cloudResourceManagerURL=new URL(n.get("cloud_resource_manager_url")||`https://cloudresourcemanager.${this.universeDomain}/v1/projects/`),o&&(this.clientAuth={confidentialClientType:"basic",clientId:o,clientSecret:s}),this.stsCredential=new bj.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Xm],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(Aj);if(this.workforcePoolUserProject&&!this.audience.match(p))throw new Error("workforcePoolUserProject should not be set for non-workforce pool credentials.");this.serviceAccountImpersonationUrl=u,this.serviceAccountImpersonationLifetime=f,this.serviceAccountImpersonationLifetime?this.configLifetimeRequested=!0:(this.configLifetimeRequested=!1,this.serviceAccountImpersonationLifetime=Sj),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Ym.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=yj.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof _j.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:wj,audience:this.audience,requestedTokenType:kj,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Xm]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Ym.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Xm]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${Cj.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Kt.BaseExternalAccountClient=Qm});var Qv=G(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});Jl.FileSubjectTokenSupplier=void 0;var ey=re("util"),ty=re("fs"),vj=(0,ey.promisify)(ty.readFile??(()=>{})),Tj=(0,ey.promisify)(ty.realpath??(()=>{})),xj=(0,ey.promisify)(ty.lstat??(()=>{})),Zm=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await Tj(e),!(await xj(e)).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let n,r=await vj(e,{encoding:"utf8"});if(this.formatType==="text"?n=r:this.formatType==="json"&&this.subjectTokenFieldName&&(n=JSON.parse(r)[this.subjectTokenFieldName]),!n)throw new Error("Unable to parse the subject_token from the credential_source file");return n}};Jl.FileSubjectTokenSupplier=Zm});var Zv=G(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});Kl.UrlSubjectTokenSupplier=void 0;var Rj=Nt(),ny=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};Rj.AuthClient.setMethodName(n,"getSubjectToken");let r;if(this.formatType==="text"?r=(await e.transporter.request(n)).data:this.formatType==="json"&&this.subjectTokenFieldName&&(r=(await e.transporter.request(n)).data[this.subjectTokenFieldName]),!r)throw new Error("Unable to parse the subject_token from the credential_source URL");return r}};Kl.UrlSubjectTokenSupplier=ny});var eT=G(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.CertificateSubjectTokenSupplier=Mt.InvalidConfigurationError=Mt.CertificateSourceUnavailableError=Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Vl=an(),Yl=re("fs"),Xl=re("crypto"),Dj=re("https");Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var $n=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Mt.CertificateSourceUnavailableError=$n;var Vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Mt.InvalidConfigurationError=Vt;var ry=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Vt("Cannot create mTLS Agent with missing certificate or key");return new Dj.Agent({key:this.key,cert:this.cert})}async getSubjectToken(){this.certificateConfigPath=await this.#e();let{certPath:e,keyPath:n}=await this.#t();return{cert:this.cert,key:this.key}=await this.#n(e,n),await this.#r(this.cert)}async#e(){let e=this.certificateConfigPath;if(e){if(await(0,Vl.isValidFile)(e))return e;throw new $n(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Vl.isValidFile)(n))return n;throw new $n(`Path from environment variable "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Vl.getWellKnownCertificateConfigFileLocation)();if(await(0,Vl.isValidFile)(r))return r;throw new $n(`Could not find certificate configuration file. Searched override path, the "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Yl.promises.readFile(e,"utf8")}catch{throw new $n(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Vt?r:new Vt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Yl.promises.readFile(e),new Xl.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read certificate file at ${e}: ${i}`)}try{o=await Yl.promises.readFile(n),(0,Xl.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new Xl.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Yl.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new Xl.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Vt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),i=s.findIndex(u=>n.raw.equals(u.raw)),a;if(i===-1)a=[n,...s];else if(i===0)a=s;else throw new Vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(a.map(u=>u.raw.toString("base64")))}catch(r){if(r instanceof Vt)throw r;let o=r instanceof Error?r.message:String(r);throw new $n(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Mt.CertificateSubjectTokenSupplier=ry});var iy=G(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.IdentityPoolClient=void 0;var Oj=Xr(),oy=an(),Pj=Qv(),Ij=Zv(),tT=eT(),Fj=Gl(),nT=lt(),sy=class t extends Oj.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,oy.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,oy.originalOrCamelOptions)(r),i=(0,oy.originalOrCamelOptions)(s.get("format")),a=i.get("type")||"text",u=i.get("subject_token_field_name");if(a!=="json"&&a!=="text")throw new Error(`Invalid credential_source format "${a}"`);if(a==="json"&&!u)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=s.get("file"),f=s.get("url"),p=s.get("certificate"),h=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new Pj.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new Ij.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new tT.CertificateSubjectTokenSupplier({useDefaultCertificateConfig:p.use_default_certificate_config,certificateConfigLocation:p.certificate_config_location,trustChainPath:p.trust_chain_path});this.subjectTokenSupplier=g}else throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.')}}async retrieveSubjectToken(){let e=await this.subjectTokenSupplier.getSubjectToken(this.supplierContext);if(this.subjectTokenSupplier instanceof tT.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Fj.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new nT.Gaxios({agent:n})}),this.transporter=new nT.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Ql.IdentityPoolClient=sy});var cy=G(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});ed.AwsRequestSigner=void 0;var Zl=lt(),oT=ma(),rT="AWS4-HMAC-SHA256",Nj="aws4_request",ay=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,oT.createCrypto)()}async getRequestOptions(e){if(!e.url)throw new RangeError('"url" is required in "amzOptions"');let n=typeof e.data=="object"?JSON.stringify(e.data):e.data,r=e.url,o=e.method||"GET",s=e.body||n,i=e.headers,a=await this.getCredentials(),u=new URL(r);if(typeof s!="string"&&s!==void 0)throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${s}`);let d=await Bj({crypto:this.crypto,host:u.host,canonicalUri:u.pathname,canonicalQuerystring:u.search.slice(1),method:o,region:this.region,securityCredentials:a,requestPayload:s,additionalAmzHeaders:i}),f=Zl.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&Zl.Gaxios.mergeHeaders(f,{"x-amz-security-token":a.token});let p={url:r,method:o,headers:f};return s!==void 0&&(p.body=s),p}};ed.AwsRequestSigner=ay;async function Sa(t,e,n){return await t.signWithHmacSha256(e,n)}async function Mj(t,e,n,r,o){let s=await Sa(t,`AWS4${e}`,n),i=await Sa(t,s,r),a=await Sa(t,i,o);return await Sa(t,a,"aws4_request")}async function Bj(t){let e=Zl.Gaxios.mergeHeaders(t.additionalAmzHeaders),n=t.requestPayload||"",r=t.host.split(".")[0],o=new Date,s=o.toISOString().replace(/[-:]/g,"").replace(/\.[0-9]+/,""),i=o.toISOString().replace(/[-]/g,"").replace(/T.*/,"");t.securityCredentials.token&&e.set("x-amz-security-token",t.securityCredentials.token);let a=Zl.Gaxios.mergeHeaders({host:t.host},e.has("date")?{}:{"x-amz-date":s},e),u="",d=[...a.keys()].sort();d.forEach(S=>{u+=`${S}:${a.get(S)}
104
104
  `});let f=d.join(";"),p=await t.crypto.sha256DigestHex(n),h=`${t.method.toUpperCase()}
105
105
  ${t.canonicalUri}
106
106
  ${t.canonicalQuerystring}
107
107
  ${u}
108
108
  ${f}
109
- ${p}`,g=`${i}/${t.region}/${r}/${FU}`,b=`${rT}
109
+ ${p}`,g=`${i}/${t.region}/${r}/${Nj}`,b=`${rT}
110
110
  ${s}
111
111
  ${g}
112
- `+await t.crypto.sha256DigestHex(h),m=await NU(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),w=await Sa(t.crypto,m,b),C=`${rT} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,oT.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:C,canonicalQuerystring:t.canonicalQuerystring}}});var sT=G(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.DefaultAwsSecurityCredentialsSupplier=void 0;var td=Nt(),ly=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};td.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return td.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return td.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return td.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};nd.DefaultAwsSecurityCredentialsSupplier=ly});var fy=G(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.AwsClient=void 0;var BU=uy(),UU=Xr(),jU=sT(),iT=an(),LU=lt(),dy=class t extends UU.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,iT.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,iT.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let i=s.get("region_url"),a=s.get("url"),u=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new jU.DefaultAwsSecurityCredentialsSupplier({regionUrl:i,securityCredentialsUrl:a,imdsV2SessionTokenUrl:u}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new BU.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return LU.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};rd.AwsClient=dy});var yy=G(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.InvalidSubjectTokenError=Qe.InvalidMessageFieldError=Qe.InvalidCodeFieldError=Qe.InvalidTokenTypeFieldError=Qe.InvalidExpirationTimeFieldError=Qe.InvalidSuccessFieldError=Qe.InvalidVersionFieldError=Qe.ExecutableResponseError=Qe.ExecutableResponse=void 0;var od="urn:ietf:params:oauth:token-type:saml2",py="urn:ietf:params:oauth:token-type:id_token",hy="urn:ietf:params:oauth:token-type:jwt",gy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new sd("Executable response must contain a 'version' field.");if(e.success===void 0)throw new id("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==od&&this.tokenType!==py&&this.tokenType!==hy)throw new ad(`Executable response must contain a 'token_type' field when successful and it must be one of ${py}, ${hy}, or ${od}.`);if(this.tokenType===od){if(!e.saml_response)throw new Aa(`Executable response must contain a 'saml_response' field when token_type=${od}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Aa(`Executable response must contain a 'id_token' field when token_type=${py} or ${hy}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new cd("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ud("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Qe.ExecutableResponse=gy;var qn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Qe.ExecutableResponseError=qn;var sd=class extends qn{};Qe.InvalidVersionFieldError=sd;var id=class extends qn{};Qe.InvalidSuccessFieldError=id;var my=class extends qn{};Qe.InvalidExpirationTimeFieldError=my;var ad=class extends qn{};Qe.InvalidTokenTypeFieldError=ad;var cd=class extends qn{};Qe.InvalidCodeFieldError=cd;var ud=class extends qn{};Qe.InvalidMessageFieldError=ud;var Aa=class extends qn{};Qe.InvalidSubjectTokenError=Aa});var Cy=G(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.PluggableAuthHandler=Ws.ExecutableError=void 0;var No=yy(),$U=re("child_process"),_y=re("fs"),ld=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};Ws.ExecutableError=ld;var by=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=$U.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",a=>{s+=a}),o.stderr.on("data",a=>{s+=a});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",a=>{if(clearTimeout(i),a===0)try{let u=JSON.parse(s),d=new No.ExecutableResponse(u);return n(d)}catch(u){return u instanceof No.ExecutableResponseError?r(u):r(new No.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new ld(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await _y.promises.realpath(this.outputFile)}catch{return}if(!(await _y.promises.lstat(e)).isFile())return;let n=await _y.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new No.ExecutableResponse(r).isValid()?new No.ExecutableResponse(r):void 0}catch(r){throw r instanceof No.ExecutableResponseError?r:new No.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};Ws.PluggableAuthHandler=by});var ky=G(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.PluggableAuthClient=Gs.ExecutableError=void 0;var qU=Xr(),HU=yy(),aT=Cy(),zU=Cy();Object.defineProperty(Gs,"ExecutableError",{enumerable:!0,get:function(){return zU.ExecutableError}});var WU=30*1e3,cT=5*1e3,uT=120*1e3,GU="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",lT=1,wy=class extends qU.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=WU;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<cT||this.timeoutMillis>uT)throw new Error(`Timeout must be between ${cT} and ${uT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new aT.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[GU]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>lT)throw new Error(`Version of executable is not currently supported, maximum supported version is ${lT}.`);if(!e.success)throw new aT.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new HU.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};Gs.PluggableAuthClient=wy});var Ay=G(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.ExternalAccountClient=void 0;var JU=Xr(),KU=ay(),VU=fy(),YU=ky(),Sy=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===JU.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new VU.AwsClient(e):e.credential_source?.executable?new YU.PluggableAuthClient(e):new KU.IdentityPoolClient(e):null}};dd.ExternalAccountClient=Sy});var Ty=G(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.ExternalAccountAuthorizedUserClient=Js.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var fT=Nt(),dT=Vm(),pT=lt(),XU=re("stream"),QU=Xr();Js.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var ZU="https://sts.{universeDomain}/v1/oauthtoken",Ey=class t extends dT.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};fT.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof pT.GaxiosError&&o.response?(0,dT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},vy=class extends fT.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ey({tokenRefreshEndpoint:e.token_url??ZU.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=QU.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=pT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof XU.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Js.ExternalAccountAuthorizedUserClient=vy});var Ry=G(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.GdchClient=Qr.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var ej=re("crypto"),tj=re("fs"),nj=re("https"),rj=Kr(),oj=3600;Qr.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var xy=class t extends rj.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||oj,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Qr.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Qr.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(r.agent=await this.getCaAgent());try{let o=await this.transporter.request(r),s=o.data;if(!s.access_token)throw new Error("Token response did not contain an access_token.");if(!s.expires_in)throw new Error("Token response did not contain an expires_in field.");let i={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1e3};return this.emit("tokens",i),{res:o,tokens:i}}catch(o){if(o&&o.config&&o.config.data)try{if(typeof o.config.data=="string"){let s=JSON.parse(o.config.data);s.subject_token&&(s.subject_token="***REDACTED***",o.config.data=JSON.stringify(s))}else typeof o.config.data=="object"&&o.config.data.subject_token&&(o.config.data.subject_token="***REDACTED***")}catch{}throw o instanceof Error&&(o.message=`Error getting access token for GDCH service account: ${o.message}, iss: ${this.serviceIdentityName}`),o}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1e3),o={iss:n,sub:n,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},s=this.base64UrlEncode(JSON.stringify(e)),i=this.base64UrlEncode(JSON.stringify(o)),a=`${s}.${i}`,u=ej.sign("sha256",Buffer.from(a),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(u);return`${a}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();!r.includes("googleapis.com")&&!r.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let o=await tj.promises.readFile(r);return new nj.Agent({ca:o})}catch(o){throw this.cachedCaCertPath===r&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),o instanceof Error&&(o.message=`Error reading certificate file from CA cert path, value '${r}': ${o.message}`),o}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Qr.GdchClient=xy});var yT=G(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.GoogleAuth=ln.GoogleAuthExceptionMessages=void 0;var sj=re("child_process"),Ea=re("fs"),ij=lt(),va=ga(),aj=re("os"),fd=re("path"),cj=ma(),uj=gm(),lj=ym(),dj=_m(),Ks=Hm(),hT=Wm(),Vs=Jm(),fj=Ay(),Ta=Xr(),Dy=Nt(),gT=Ty(),Oy=Ry(),mT=an();ln.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
112
+ `+await t.crypto.sha256DigestHex(h),m=await Mj(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),w=await Sa(t.crypto,m,b),C=`${rT} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,oT.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:C,canonicalQuerystring:t.canonicalQuerystring}}});var sT=G(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.DefaultAwsSecurityCredentialsSupplier=void 0;var td=Nt(),uy=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};td.AuthClient.setMethodName(r,"getAwsRegion");let o=await e.transporter.request(r);return o.data.substr(0,o.data.length-1)}async getAwsSecurityCredentials(e){if(this.#o)return this.#o;let n=new Headers;this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter));let r=await this.#t(n,e.transporter),o=await this.#n(r,n,e.transporter);return{accessKeyId:o.AccessKeyId,secretAccessKey:o.SecretAccessKey,token:o.Token}}async#e(e){let n={...this.additionalGaxiosOptions,url:this.imdsV2SessionTokenUrl,method:"PUT",responseType:"text",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"300"}};return td.AuthClient.setMethodName(n,"#getImdsV2SessionToken"),(await e.request(n)).data}async#t(e,n){if(!this.securityCredentialsUrl)throw new Error('Unable to determine AWS role name due to missing "options.credential_source.url"');let r={...this.additionalGaxiosOptions,url:this.securityCredentialsUrl,method:"GET",responseType:"text",headers:e};return td.AuthClient.setMethodName(r,"#getAwsRoleName"),(await n.request(r)).data}async#n(e,n,r){let o={...this.additionalGaxiosOptions,url:`${this.securityCredentialsUrl}/${e}`,headers:n,responseType:"json"};return td.AuthClient.setMethodName(o,"#retrieveAwsSecurityCredentials"),(await r.request(o)).data}get#r(){return process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||null}get#o(){return process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY?{accessKeyId:process.env.AWS_ACCESS_KEY_ID,secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY,token:process.env.AWS_SESSION_TOKEN}:null}};nd.DefaultAwsSecurityCredentialsSupplier=uy});var dy=G(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});rd.AwsClient=void 0;var jj=cy(),Uj=Xr(),Lj=sT(),iT=an(),$j=lt(),ly=class t extends Uj.BaseExternalAccountClient{environmentId;awsSecurityCredentialsSupplier;regionalCredVerificationUrl;awsRequestSigner;region;static#e="https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15";static AWS_EC2_METADATA_IPV4_ADDRESS="169.254.169.254";static AWS_EC2_METADATA_IPV6_ADDRESS="fd00:ec2::254";constructor(e){super(e);let n=(0,iT.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("aws_security_credentials_supplier");if(!r&&!o)throw new Error("A credential source or AWS security credentials supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or AWS security credentials supplier can be specified.");if(o)this.awsSecurityCredentialsSupplier=o,this.regionalCredVerificationUrl=t.#e,this.credentialSourceType="programmatic";else{let s=(0,iT.originalOrCamelOptions)(r);this.environmentId=s.get("environment_id");let i=s.get("region_url"),a=s.get("url"),u=s.get("imdsv2_session_token_url");this.awsSecurityCredentialsSupplier=new Lj.DefaultAwsSecurityCredentialsSupplier({regionUrl:i,securityCredentialsUrl:a,imdsV2SessionTokenUrl:u}),this.regionalCredVerificationUrl=s.get("regional_cred_verification_url"),this.credentialSourceType="aws",this.validateEnvironmentId()}this.awsRequestSigner=null,this.region=""}validateEnvironmentId(){let e=this.environmentId?.match(/^(aws)(\d+)$/);if(!e||!this.regionalCredVerificationUrl)throw new Error('No valid AWS "credential_source" provided');if(parseInt(e[2],10)!==1)throw new Error(`aws version "${e[2]}" is not supported in the current build.`)}async retrieveSubjectToken(){this.awsRequestSigner||(this.region=await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext),this.awsRequestSigner=new jj.AwsRequestSigner(async()=>this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext),this.region));let e=await this.awsRequestSigner.getRequestOptions({...t.RETRY_CONFIG,url:this.regionalCredVerificationUrl.replace("{region}",this.region),method:"POST"}),n=[];return $j.Gaxios.mergeHeaders({"x-goog-cloud-target-resource":this.audience},e.headers).forEach((o,s)=>n.push({key:s,value:o})),encodeURIComponent(JSON.stringify({url:e.url,method:e.method,headers:n}))}};rd.AwsClient=ly});var my=G(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.InvalidSubjectTokenError=Qe.InvalidMessageFieldError=Qe.InvalidCodeFieldError=Qe.InvalidTokenTypeFieldError=Qe.InvalidExpirationTimeFieldError=Qe.InvalidSuccessFieldError=Qe.InvalidVersionFieldError=Qe.ExecutableResponseError=Qe.ExecutableResponse=void 0;var od="urn:ietf:params:oauth:token-type:saml2",fy="urn:ietf:params:oauth:token-type:id_token",py="urn:ietf:params:oauth:token-type:jwt",hy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new sd("Executable response must contain a 'version' field.");if(e.success===void 0)throw new id("Executable response must contain a 'success' field.");if(this.version=e.version,this.success=e.success,this.success){if(this.expirationTime=e.expiration_time,this.tokenType=e.token_type,this.tokenType!==od&&this.tokenType!==fy&&this.tokenType!==py)throw new ad(`Executable response must contain a 'token_type' field when successful and it must be one of ${fy}, ${py}, or ${od}.`);if(this.tokenType===od){if(!e.saml_response)throw new Aa(`Executable response must contain a 'saml_response' field when token_type=${od}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Aa(`Executable response must contain a 'id_token' field when token_type=${fy} or ${py}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new cd("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new ud("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Qe.ExecutableResponse=hy;var qn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Qe.ExecutableResponseError=qn;var sd=class extends qn{};Qe.InvalidVersionFieldError=sd;var id=class extends qn{};Qe.InvalidSuccessFieldError=id;var gy=class extends qn{};Qe.InvalidExpirationTimeFieldError=gy;var ad=class extends qn{};Qe.InvalidTokenTypeFieldError=ad;var cd=class extends qn{};Qe.InvalidCodeFieldError=cd;var ud=class extends qn{};Qe.InvalidMessageFieldError=ud;var Aa=class extends qn{};Qe.InvalidSubjectTokenError=Aa});var by=G(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.PluggableAuthHandler=Ws.ExecutableError=void 0;var No=my(),qj=re("child_process"),yy=re("fs"),ld=class extends Error{code;constructor(e,n){super(`The executable failed with exit code: ${n} and error message: ${e}.`),this.code=n,Object.setPrototypeOf(this,new.target.prototype)}};Ws.ExecutableError=ld;var _y=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=qj.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",a=>{s+=a}),o.stderr.on("data",a=>{s+=a});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",a=>{if(clearTimeout(i),a===0)try{let u=JSON.parse(s),d=new No.ExecutableResponse(u);return n(d)}catch(u){return u instanceof No.ExecutableResponseError?r(u):r(new No.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new ld(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await yy.promises.realpath(this.outputFile)}catch{return}if(!(await yy.promises.lstat(e)).isFile())return;let n=await yy.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new No.ExecutableResponse(r).isValid()?new No.ExecutableResponse(r):void 0}catch(r){throw r instanceof No.ExecutableResponseError?r:new No.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};Ws.PluggableAuthHandler=_y});var wy=G(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.PluggableAuthClient=Gs.ExecutableError=void 0;var Hj=Xr(),zj=my(),aT=by(),Wj=by();Object.defineProperty(Gs,"ExecutableError",{enumerable:!0,get:function(){return Wj.ExecutableError}});var Gj=30*1e3,cT=5*1e3,uT=120*1e3,Jj="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",lT=1,Cy=class extends Hj.BaseExternalAccountClient{command;timeoutMillis;outputFile;handler;constructor(e){if(super(e),!e.credential_source.executable)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(this.command=e.credential_source.executable.command,!this.command)throw new Error('No valid Pluggable Auth "credential_source" provided.');if(e.credential_source.executable.timeout_millis===void 0)this.timeoutMillis=Gj;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<cT||this.timeoutMillis>uT)throw new Error(`Timeout must be between ${cT} and ${uT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new aT.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Jj]!=="1")throw new Error("Pluggable Auth executables need to be explicitly allowed to run by setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment Variable to 1.");let e;if(this.outputFile&&(e=await this.handler.retrieveCachedResponse()),!e){let n=new Map;n.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE",this.audience),n.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE",this.subjectTokenType),n.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE","0"),this.outputFile&&n.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE",this.outputFile);let r=this.getServiceAccountEmail();r&&n.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL",r),e=await this.handler.retrieveResponseFromExecutable(n)}if(e.version>lT)throw new Error(`Version of executable is not currently supported, maximum supported version is ${lT}.`);if(!e.success)throw new aT.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new zj.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.");if(e.isExpired())throw new Error("Executable response is expired.");return e.subjectToken}};Gs.PluggableAuthClient=Cy});var Sy=G(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.ExternalAccountClient=void 0;var Kj=Xr(),Vj=iy(),Yj=dy(),Xj=wy(),ky=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===Kj.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new Yj.AwsClient(e):e.credential_source?.executable?new Xj.PluggableAuthClient(e):new Vj.IdentityPoolClient(e):null}};dd.ExternalAccountClient=ky});var vy=G(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.ExternalAccountAuthorizedUserClient=Js.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var fT=Nt(),dT=Km(),pT=lt(),Qj=re("stream"),Zj=Xr();Js.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var eU="https://sts.{universeDomain}/v1/oauthtoken",Ay=class t extends dT.OAuthClientAuthHandler{#e;constructor(e){super(e),this.#e=e.tokenRefreshEndpoint}async refreshToken(e,n){let r={...t.RETRY_CONFIG,url:this.#e,method:"POST",headers:n,data:new URLSearchParams({grant_type:"refresh_token",refresh_token:e}),responseType:"json"};fT.AuthClient.setMethodName(r,"refreshToken"),this.applyClientAuthenticationOptions(r);try{let o=await this.transporter.request(r),s=o.data;return s.res=o,s}catch(o){throw o instanceof pT.GaxiosError&&o.response?(0,dT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Ey=class extends fT.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ay({tokenRefreshEndpoint:e.token_url??eU.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Zj.EXPIRATION_TIME_OFFSET:this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis,this.forceRefreshOnFailure=!!e?.forceRefreshOnFailure}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=pT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof Qj.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken);return this.cachedAccessToken={access_token:e.access_token,expiry_date:new Date().getTime()+e.expires_in*1e3,res:e.res},e.refresh_token!==void 0&&(this.refreshToken=e.refresh_token),this.cachedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Js.ExternalAccountAuthorizedUserClient=Ey});var xy=G(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.GdchClient=Qr.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var tU=re("crypto"),nU=re("fs"),rU=re("https"),oU=Kr(),sU=3600;Qr.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var Ty=class t extends oU.OAuth2Client{projectId;privateKeyId;privateKey;serviceIdentityName;tokenServerUri;caCertPath;apiAudience;lifetime;gdchOptions;caAgentPromise;cachedCaCertPath;lastCaCertReadTime=0;CA_CERT_TTL_MS=300*1e3;constructor(e={}){super(e),this.gdchOptions=e,this.projectId=e.projectId||void 0,this.privateKeyId=e.privateKeyId,this.privateKey=e.privateKey,this.serviceIdentityName=e.serviceIdentityName,this.tokenServerUri=e.tokenServerUri,this.caCertPath=e.caCertPath,this.apiAudience=e.apiAudience,this.lifetime=e.lifetime||sU,this.credentials={refresh_token:"gdch-placeholder",expiry_date:1}}createWithGdchAudience(e){if(!e)throw new Error("Audience cannot be null or empty for GDCH service account credentials.");return new t({...this.gdchOptions,projectId:this.projectId,privateKeyId:this.privateKeyId,privateKey:this.privateKey,serviceIdentityName:this.serviceIdentityName,tokenServerUri:this.tokenServerUri,caCertPath:this.caCertPath,lifetime:this.lifetime,apiAudience:e})}fromJSON(e){if(!e)throw new Error("Must pass in a JSON object containing the GDCH credentials settings.");if(e.type!==Qr.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Qr.GDCH_SERVICE_ACCOUNT_TYPE}" type`);if(e.format_version!=="1")throw new Error("Only format version 1 is supported.");if(!e.project)throw new Error("The incoming JSON object does not contain a project field");if(!e.private_key_id)throw new Error("The incoming JSON object does not contain a private_key_id field");if(!e.private_key)throw new Error("The incoming JSON object does not contain a private_key field");if(!e.name)throw new Error("The incoming JSON object does not contain a name field");if(!e.token_uri)throw new Error("The incoming JSON object does not contain a token_uri field");this.projectId=e.project,this.privateKeyId=e.private_key_id,this.privateKey=e.private_key,this.serviceIdentityName=e.name,this.tokenServerUri=e.token_uri,this.caCertPath=e.ca_cert_path,this.gdchOptions={...this.gdchOptions,projectId:e.project,privateKeyId:e.private_key_id,privateKey:e.private_key,serviceIdentityName:e.name,tokenServerUri:e.token_uri,caCertPath:e.ca_cert_path}}async refreshTokenNoCache(){if(!this.apiAudience)throw new Error("Audience cannot be null or empty for GDCH service account credentials. Specify the audience by calling createWithGdchAudience.");if(!this.privateKey)throw new Error("Private key is not configured for GDCH credentials.");if(!this.privateKeyId)throw new Error("Private key ID is not configured for GDCH credentials.");if(!this.projectId)throw new Error("Project is not configured for GDCH credentials.");if(!this.serviceIdentityName)throw new Error("Service identity name is not configured for GDCH credentials.");if(!this.tokenServerUri)throw new Error("Token server URI is not configured for GDCH credentials.");let e=this.createAssertion(),n={audience:this.apiAudience,grant_type:"urn:ietf:params:oauth:token-type:token-exchange",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,subject_token_type:"urn:k8s:params:oauth:token-type:serviceaccount"},r={url:this.tokenServerUri,method:"POST",headers:{"Content-Type":"application/json"},data:n,responseType:"json",timeout:1e4,retry:!0,retryConfig:{httpMethodsToRetry:["POST"],statusCodesToRetry:[[500,599]],noResponseRetries:3}};this.caCertPath&&(r.agent=await this.getCaAgent());try{let o=await this.transporter.request(r),s=o.data;if(!s.access_token)throw new Error("Token response did not contain an access_token.");if(!s.expires_in)throw new Error("Token response did not contain an expires_in field.");let i={access_token:s.access_token,token_type:"STS-Bearer",expiry_date:Date.now()+s.expires_in*1e3};return this.emit("tokens",i),{res:o,tokens:i}}catch(o){if(o&&o.config&&o.config.data)try{if(typeof o.config.data=="string"){let s=JSON.parse(o.config.data);s.subject_token&&(s.subject_token="***REDACTED***",o.config.data=JSON.stringify(s))}else typeof o.config.data=="object"&&o.config.data.subject_token&&(o.config.data.subject_token="***REDACTED***")}catch{}throw o instanceof Error&&(o.message=`Error getting access token for GDCH service account: ${o.message}, iss: ${this.serviceIdentityName}`),o}}createAssertion(){let e={alg:"ES256",typ:"JWT",kid:this.privateKeyId},n=`system:serviceaccount:${this.projectId}:${this.serviceIdentityName}`,r=Math.floor(Date.now()/1e3),o={iss:n,sub:n,iat:r,exp:r+this.lifetime,aud:this.tokenServerUri},s=this.base64UrlEncode(JSON.stringify(e)),i=this.base64UrlEncode(JSON.stringify(o)),a=`${s}.${i}`,u=tU.sign("sha256",Buffer.from(a),{key:this.privateKey,dsaEncoding:"ieee-p1363"}),d=this.base64UrlEncode(u);return`${a}.${d}`}async requestAsync(e,n=!1){if(this.caCertPath&&!e.agent){let r=(e.url||"").toString();!r.includes("googleapis.com")&&!r.includes("google.com")&&(e.agent=await this.getCaAgent())}return super.requestAsync(e,n)}getCaAgent(){if(!this.caCertPath){this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0;return}let e=Date.now(),n=e-this.lastCaCertReadTime>this.CA_CERT_TTL_MS;if(this.caAgentPromise&&this.caCertPath===this.cachedCaCertPath&&!n)return this.caAgentPromise;this.cachedCaCertPath=this.caCertPath,this.lastCaCertReadTime=e;let r=this.caCertPath;return this.caAgentPromise=(async()=>{try{let o=await nU.promises.readFile(r);return new rU.Agent({ca:o})}catch(o){throw this.cachedCaCertPath===r&&(this.caAgentPromise=void 0,this.cachedCaCertPath=void 0,this.lastCaCertReadTime=0),o instanceof Error&&(o.message=`Error reading certificate file from CA cert path, value '${r}': ${o.message}`),o}})(),this.caAgentPromise}toJSON(){return{...this,privateKey:this.privateKey?"***REDACTED***":void 0,_clientSecret:this._clientSecret?"***REDACTED***":void 0,apiKey:this.apiKey?"***REDACTED***":void 0,gdchOptions:this.gdchOptions?{...this.gdchOptions,privateKey:this.gdchOptions.privateKey?"***REDACTED***":void 0,clientSecret:this.gdchOptions.clientSecret?"***REDACTED***":void 0,client_secret:this.gdchOptions.client_secret?"***REDACTED***":void 0,apiKey:this.gdchOptions.apiKey?"***REDACTED***":void 0,credentials:this.gdchOptions.credentials?{...this.gdchOptions.credentials,access_token:this.gdchOptions.credentials.access_token?"***REDACTED***":void 0,refresh_token:this.gdchOptions.credentials.refresh_token?"***REDACTED***":void 0}:void 0}:void 0,credentials:{...this.credentials,access_token:this.credentials?.access_token?"***REDACTED***":void 0,refresh_token:this.credentials?.refresh_token?"***REDACTED***":void 0}}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toJSON()}base64UrlEncode(e){return(typeof e=="string"?Buffer.from(e):e).toString("base64url")}};Qr.GdchClient=Ty});var yT=G(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.GoogleAuth=ln.GoogleAuthExceptionMessages=void 0;var iU=re("child_process"),Ea=re("fs"),aU=lt(),va=ga(),cU=re("os"),fd=re("path"),uU=ma(),lU=hm(),dU=mm(),fU=ym(),Ks=qm(),hT=zm(),Vs=Gm(),pU=Sy(),Ta=Xr(),Ry=Nt(),gT=vy(),Dy=xy(),mT=an();ln.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
113
113
  To learn more about authentication and Google APIs, visit:
114
114
  https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
115
115
  To learn more about authentication and Google APIs, visit:
116
116
  https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
117
117
  To learn more about Universe Domain retrieval, visit:
118
- https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Py=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ln.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await va.universe("universe-domain"),e||=Dy.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Dy.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,mT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Dy.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof Ks.JWT?n.scopes=this.scopes:n instanceof Ta.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Ks.JWT?n.scopes=this.scopes:n instanceof Ta.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new uj.Compute(e));throw new Error(ln.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=va.getGCPResidency()||await va.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=fd.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=fd.join(s,".config","gcloud"))}if(!n)return null;let r=fd.join(n,"application_default_credentials.json");return Ea.existsSync(r)?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ea.realpathSync(e),!Ea.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=Ea.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Vs.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Vs.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new Vs.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,mT.originalOrCamelOptions)(n).get("universe_domain");return e.type===hT.USER_REFRESH_ACCOUNT_TYPE?(r=new hT.UserRefreshClient(n),r.fromJSON(e)):e.type===Vs.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ta.EXTERNAL_ACCOUNT_TYPE?(r=fj.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===gT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new gT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Oy.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Oy.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Ks.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){let o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",i=>s.push(i)).on("end",()=>{try{try{let i=JSON.parse(s.join("")),a=this._cacheClientFromJSON(i,n);return r(a)}catch(i){if(!this.keyFilename)throw i;let a=new Ks.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),r(a)}}catch(i){return o(i)}})})}fromAPIKey(e,n={}){return new Ks.JWT({...n,apiKey:e})}_isWindows(){let e=aj.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,sj.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Ta.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await va.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Vs.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ta.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([va.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(ln.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Oy.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),i=e.createWithGdchAudience(s);return this.cachedCredential=i,i}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=fd.resolve(this.keyFilename),n=Ea.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new lj.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=ij.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,dj.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof Vs.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,cj.createCrypto)();if(r instanceof Ks.JWT&&r.key)return await s.sign(r.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,i.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ln.GoogleAuth=Py});var _T=G(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.IAMAuth=void 0;var Iy=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};pd.IAMAuth=Iy});var bT=G(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.DownscopedClient=Hn.EXPIRATION_TIME_OFFSET=Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var pj=lt(),hj=re("stream"),Fy=Nt(),gj=Gl(),mj="urn:ietf:params:oauth:grant-type:token-exchange",yj="urn:ietf:params:oauth:token-type:access_token",_j="urn:ietf:params:oauth:token-type:access_token";Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Hn.EXPIRATION_TIME_OFFSET=300*1e3;var Ny=class extends Fy.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Fy.AuthClient?{}:e),e instanceof Fy.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new gj.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=pj.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof hj.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:mj,requestedTokenType:yj,subjectToken:e,subjectTokenType:_j},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Hn.DownscopedClient=Ny});var CT=G(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.PassThroughClient=void 0;var bj=Nt(),My=class extends bj.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};hd.PassThroughClient=My});var gd=G(oe=>{"use strict";var Cj=oe&&oe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),wj=oe&&oe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Cj(e,t,n)};Object.defineProperty(oe,"__esModule",{value:!0});oe.GoogleAuth=oe.auth=oe.GDCH_SERVICE_ACCOUNT_TYPE=oe.GdchClient=oe.PassThroughClient=oe.ExternalAccountAuthorizedUserClient=oe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=oe.ExecutableError=oe.PluggableAuthClient=oe.DownscopedClient=oe.BaseExternalAccountClient=oe.ExternalAccountClient=oe.IdentityPoolClient=oe.AwsRequestSigner=oe.AwsClient=oe.UserRefreshClient=oe.LoginTicket=oe.ClientAuthentication=oe.OAuth2Client=oe.CodeChallengeMethod=oe.Impersonated=oe.JWT=oe.JWTAccess=oe.IdTokenClient=oe.IAMAuth=oe.GCPEnv=oe.Compute=oe.DEFAULT_UNIVERSE=oe.AuthClient=oe.gaxios=oe.gcpMetadata=void 0;var wT=yT();Object.defineProperty(oe,"GoogleAuth",{enumerable:!0,get:function(){return wT.GoogleAuth}});oe.gcpMetadata=ga();oe.gaxios=lt();var kT=Nt();Object.defineProperty(oe,"AuthClient",{enumerable:!0,get:function(){return kT.AuthClient}});Object.defineProperty(oe,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return kT.DEFAULT_UNIVERSE}});var kj=gm();Object.defineProperty(oe,"Compute",{enumerable:!0,get:function(){return kj.Compute}});var Sj=_m();Object.defineProperty(oe,"GCPEnv",{enumerable:!0,get:function(){return Sj.GCPEnv}});var Aj=_T();Object.defineProperty(oe,"IAMAuth",{enumerable:!0,get:function(){return Aj.IAMAuth}});var Ej=ym();Object.defineProperty(oe,"IdTokenClient",{enumerable:!0,get:function(){return Ej.IdTokenClient}});var vj=$m();Object.defineProperty(oe,"JWTAccess",{enumerable:!0,get:function(){return vj.JWTAccess}});var Tj=Hm();Object.defineProperty(oe,"JWT",{enumerable:!0,get:function(){return Tj.JWT}});var xj=Jm();Object.defineProperty(oe,"Impersonated",{enumerable:!0,get:function(){return xj.Impersonated}});var By=Kr();Object.defineProperty(oe,"CodeChallengeMethod",{enumerable:!0,get:function(){return By.CodeChallengeMethod}});Object.defineProperty(oe,"OAuth2Client",{enumerable:!0,get:function(){return By.OAuth2Client}});Object.defineProperty(oe,"ClientAuthentication",{enumerable:!0,get:function(){return By.ClientAuthentication}});var Rj=dm();Object.defineProperty(oe,"LoginTicket",{enumerable:!0,get:function(){return Rj.LoginTicket}});var Dj=Wm();Object.defineProperty(oe,"UserRefreshClient",{enumerable:!0,get:function(){return Dj.UserRefreshClient}});var Oj=fy();Object.defineProperty(oe,"AwsClient",{enumerable:!0,get:function(){return Oj.AwsClient}});var Pj=uy();Object.defineProperty(oe,"AwsRequestSigner",{enumerable:!0,get:function(){return Pj.AwsRequestSigner}});var Ij=ay();Object.defineProperty(oe,"IdentityPoolClient",{enumerable:!0,get:function(){return Ij.IdentityPoolClient}});var Fj=Ay();Object.defineProperty(oe,"ExternalAccountClient",{enumerable:!0,get:function(){return Fj.ExternalAccountClient}});var Nj=Xr();Object.defineProperty(oe,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Nj.BaseExternalAccountClient}});var Mj=bT();Object.defineProperty(oe,"DownscopedClient",{enumerable:!0,get:function(){return Mj.DownscopedClient}});var ST=ky();Object.defineProperty(oe,"PluggableAuthClient",{enumerable:!0,get:function(){return ST.PluggableAuthClient}});Object.defineProperty(oe,"ExecutableError",{enumerable:!0,get:function(){return ST.ExecutableError}});var AT=Ty();Object.defineProperty(oe,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return AT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(oe,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return AT.ExternalAccountAuthorizedUserClient}});var Bj=CT();Object.defineProperty(oe,"PassThroughClient",{enumerable:!0,get:function(){return Bj.PassThroughClient}});var ET=Ry();Object.defineProperty(oe,"GdchClient",{enumerable:!0,get:function(){return ET.GdchClient}});Object.defineProperty(oe,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return ET.GDCH_SERVICE_ACCOUNT_TYPE}});wj(jm(),oe);var Uj=new wT.GoogleAuth;oe.auth=Uj});var qa,e0=Br(()=>{"use strict";qa=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:i}=n||{},a="";if(o){let u=new Date().toISOString();a+=this.config.colors?`${this.colors.cyan}[${u}]${this.colors.reset} `:`[${u}] `}switch(s&&(a+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":a+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?a+=this.toMarkdown(e):a+=String(e);break;default:typeof e=="object"?a+=JSON.stringify(e,null,2):a+=String(e);break}return i&&Object.keys(i).length>0&&(a+=`
118
+ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Oy=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ln.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await va.universe("universe-domain"),e||=Ry.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ry.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,mT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ry.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof Ks.JWT?n.scopes=this.scopes:n instanceof Ta.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Ks.JWT?n.scopes=this.scopes:n instanceof Ta.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new lU.Compute(e));throw new Error(ln.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=va.getGCPResidency()||await va.isAvailable()),this.checkIsGCE}async _tryGetApplicationCredentialsFromEnvironmentVariable(e){let n=process.env.GOOGLE_APPLICATION_CREDENTIALS||process.env.google_application_credentials;if(!n||n.length===0)return null;try{return await this._getApplicationCredentialsFromFilePath(n,e)}catch(r){throw r instanceof Error&&(r.message=`Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${r.message}`),r}}async _tryGetApplicationCredentialsFromWellKnownFile(e){let n=process.env.CLOUDSDK_CONFIG;if(!n)if(this._isWindows())process.env.APPDATA&&(n=fd.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=fd.join(s,".config","gcloud"))}if(!n)return null;let r=fd.join(n,"application_default_credentials.json");return Ea.existsSync(r)?await this._getApplicationCredentialsFromFilePath(r,e):null}async _getApplicationCredentialsFromFilePath(e,n={}){if(!e||e.length===0)throw new Error("The file path is invalid.");try{if(e=Ea.realpathSync(e),!Ea.lstatSync(e).isFile())throw new Error}catch(o){throw o instanceof Error&&(o.message=`The file at ${e} does not exist, or it is not a file. ${o.message}`),o}let r=Ea.createReadStream(e);return this.fromStream(r,n)}fromImpersonatedJSON(e){if(!e)throw new Error("Must pass in a JSON object containing an impersonated refresh token");if(e.type!==Vs.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Vs.IMPERSONATED_ACCOUNT_TYPE}" type`);if(!e.source_credentials)throw new Error("The incoming JSON object does not contain a source_credentials field");if(!e.service_account_impersonation_url)throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field");let n=this.fromJSON(e.source_credentials);if(e.service_account_impersonation_url?.length>256)throw new RangeError(`Target principal is too long: ${e.service_account_impersonation_url}`);let r=/(?<target>[^/]+):(generateAccessToken|generateIdToken)$/.exec(e.service_account_impersonation_url)?.groups?.target;if(!r)throw new RangeError(`Cannot extract target principal from ${e.service_account_impersonation_url}`);let o=(this.scopes||e.scopes||this.defaultScopes)??[];return new Vs.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,mT.originalOrCamelOptions)(n).get("universe_domain");return e.type===hT.USER_REFRESH_ACCOUNT_TYPE?(r=new hT.UserRefreshClient(n),r.fromJSON(e)):e.type===Vs.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ta.EXTERNAL_ACCOUNT_TYPE?(r=pU.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===gT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new gT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Dy.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Dy.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Ks.JWT(n),this.setGapicJWTValues(r),r.fromJSON(e)),o&&(r.universeDomain=o),r}_cacheClientFromJSON(e,n){let r=this.fromJSON(e,n);return this.jsonContent=e,this.cachedCredential=r,r}fromStream(e,n={},r){let o={};if(typeof n=="function"?r=n:o=n,r)this.fromStreamAsync(e,o).then(s=>r(null,s),r);else return this.fromStreamAsync(e,o)}fromStreamAsync(e,n){return new Promise((r,o)=>{if(!e)throw new Error("Must pass in a stream containing the Google auth settings.");let s=[];e.setEncoding("utf8").on("error",o).on("data",i=>s.push(i)).on("end",()=>{try{try{let i=JSON.parse(s.join("")),a=this._cacheClientFromJSON(i,n);return r(a)}catch(i){if(!this.keyFilename)throw i;let a=new Ks.JWT({...this.clientOptions,keyFile:this.keyFilename});return this.cachedCredential=a,this.setGapicJWTValues(a),r(a)}}catch(i){return o(i)}})})}fromAPIKey(e,n={}){return new Ks.JWT({...n,apiKey:e})}_isWindows(){let e=cU.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,iU.exec)("gcloud config config-helper --format json",(n,r)=>{if(!n&&r)try{let o=JSON.parse(r).configuration.properties.core.project;e(o);return}catch{}e(null)})})}getProductionProjectId(){return process.env.GCLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT||process.env.gcloud_project||process.env.google_cloud_project}async getFileProjectId(){if(this.cachedCredential)return this.cachedCredential.projectId;if(this.keyFilename){let n=await this.getClient();if(n&&n.projectId)return n.projectId}let e=await this._tryGetApplicationCredentialsFromEnvironmentVariable();return e?e.projectId:null}async getExternalAccountClientProjectId(){return!this.jsonContent||this.jsonContent.type!==Ta.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await va.project("project-id")}catch{return null}}getCredentials(e){if(e)this.getCredentialsAsync().then(n=>e(null,n),e);else return this.getCredentialsAsync()}async getCredentialsAsync(){let e=await this.getClient();if(e instanceof Vs.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ta.BaseExternalAccountClient){let n=e.getServiceAccountEmail();if(n)return{client_email:n,universe_domain:e.universeDomain}}if(this.jsonContent)return{client_email:this.jsonContent.client_email,private_key:this.jsonContent.private_key,universe_domain:this.jsonContent.universe_domain};if(await this._checkIsGCE()){let[n,r]=await Promise.all([va.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(ln.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Dy.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),i=e.createWithGdchAudience(s);return this.cachedCredential=i,i}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=fd.resolve(this.keyFilename),n=Ea.createReadStream(e);return await this.fromStreamAsync(n,this.clientOptions)}else if(this.apiKey){let e=await this.fromAPIKey(this.apiKey,this.clientOptions);e.scopes=this.scopes;let{credential:n}=await this.#t(e);return n}else{let{credential:e}=await this.getApplicationDefaultAsync(this.clientOptions);return e}}async getIdTokenClient(e){let n=await this.getClient();if(!("fetchIdToken"in n))throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.");return new dU.IdTokenClient({targetAudience:e,idTokenProvider:n})}async getAccessToken(){return(await(await this.getClient()).getAccessToken()).token}async getRequestHeaders(e){return(await this.getClient()).getRequestHeaders(e)}async authorizeRequest(e={}){let n=e.url,o=await(await this.getClient()).getRequestHeaders(n);return e.headers=aU.Gaxios.mergeHeaders(e.headers,o),e}async fetch(...e){return(await this.getClient()).fetch(...e)}async request(e){return(await this.getClient()).request(e)}getEnv(){return(0,fU.getEnv)()}async sign(e,n){let r=await this.getClient(),o=await this.getUniverseDomain();if(n=n||`https://iamcredentials.${o}/v1/projects/-/serviceAccounts/`,r instanceof Vs.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,uU.createCrypto)();if(r instanceof Ks.JWT&&r.key)return await s.sign(r.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,i.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ln.GoogleAuth=Oy});var _T=G(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.IAMAuth=void 0;var Py=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};pd.IAMAuth=Py});var bT=G(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.DownscopedClient=Hn.EXPIRATION_TIME_OFFSET=Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var hU=lt(),gU=re("stream"),Iy=Nt(),mU=Gl(),yU="urn:ietf:params:oauth:grant-type:token-exchange",_U="urn:ietf:params:oauth:token-type:access_token",bU="urn:ietf:params:oauth:token-type:access_token";Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Hn.EXPIRATION_TIME_OFFSET=300*1e3;var Fy=class extends Iy.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Iy.AuthClient?{}:e),e instanceof Iy.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new mU.StsCredentials({tokenExchangeEndpoint:`https://sts.${this.universeDomain}/v1/token`}),this.cachedDownscopedAccessToken=null}setCredentials(e){if(!e.expiry_date)throw new Error("The access token expiry_date field is missing in the provided credentials.");super.setCredentials(e),this.cachedDownscopedAccessToken=e}async getAccessToken(){return(!this.cachedDownscopedAccessToken||this.isExpired(this.cachedDownscopedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedDownscopedAccessToken.access_token,expirationTime:this.cachedDownscopedAccessToken.expiry_date,res:this.cachedDownscopedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=hU.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof gU.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){let e=(await this.authClient.getAccessToken()).token,n={grantType:yU,requestedTokenType:_U,subjectToken:e,subjectTokenType:bU},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Hn.DownscopedClient=Fy});var CT=G(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.PassThroughClient=void 0;var CU=Nt(),Ny=class extends CU.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};hd.PassThroughClient=Ny});var gd=G(oe=>{"use strict";var wU=oe&&oe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),kU=oe&&oe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&wU(e,t,n)};Object.defineProperty(oe,"__esModule",{value:!0});oe.GoogleAuth=oe.auth=oe.GDCH_SERVICE_ACCOUNT_TYPE=oe.GdchClient=oe.PassThroughClient=oe.ExternalAccountAuthorizedUserClient=oe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=oe.ExecutableError=oe.PluggableAuthClient=oe.DownscopedClient=oe.BaseExternalAccountClient=oe.ExternalAccountClient=oe.IdentityPoolClient=oe.AwsRequestSigner=oe.AwsClient=oe.UserRefreshClient=oe.LoginTicket=oe.ClientAuthentication=oe.OAuth2Client=oe.CodeChallengeMethod=oe.Impersonated=oe.JWT=oe.JWTAccess=oe.IdTokenClient=oe.IAMAuth=oe.GCPEnv=oe.Compute=oe.DEFAULT_UNIVERSE=oe.AuthClient=oe.gaxios=oe.gcpMetadata=void 0;var wT=yT();Object.defineProperty(oe,"GoogleAuth",{enumerable:!0,get:function(){return wT.GoogleAuth}});oe.gcpMetadata=ga();oe.gaxios=lt();var kT=Nt();Object.defineProperty(oe,"AuthClient",{enumerable:!0,get:function(){return kT.AuthClient}});Object.defineProperty(oe,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return kT.DEFAULT_UNIVERSE}});var SU=hm();Object.defineProperty(oe,"Compute",{enumerable:!0,get:function(){return SU.Compute}});var AU=ym();Object.defineProperty(oe,"GCPEnv",{enumerable:!0,get:function(){return AU.GCPEnv}});var EU=_T();Object.defineProperty(oe,"IAMAuth",{enumerable:!0,get:function(){return EU.IAMAuth}});var vU=mm();Object.defineProperty(oe,"IdTokenClient",{enumerable:!0,get:function(){return vU.IdTokenClient}});var TU=Lm();Object.defineProperty(oe,"JWTAccess",{enumerable:!0,get:function(){return TU.JWTAccess}});var xU=qm();Object.defineProperty(oe,"JWT",{enumerable:!0,get:function(){return xU.JWT}});var RU=Gm();Object.defineProperty(oe,"Impersonated",{enumerable:!0,get:function(){return RU.Impersonated}});var My=Kr();Object.defineProperty(oe,"CodeChallengeMethod",{enumerable:!0,get:function(){return My.CodeChallengeMethod}});Object.defineProperty(oe,"OAuth2Client",{enumerable:!0,get:function(){return My.OAuth2Client}});Object.defineProperty(oe,"ClientAuthentication",{enumerable:!0,get:function(){return My.ClientAuthentication}});var DU=lm();Object.defineProperty(oe,"LoginTicket",{enumerable:!0,get:function(){return DU.LoginTicket}});var OU=zm();Object.defineProperty(oe,"UserRefreshClient",{enumerable:!0,get:function(){return OU.UserRefreshClient}});var PU=dy();Object.defineProperty(oe,"AwsClient",{enumerable:!0,get:function(){return PU.AwsClient}});var IU=cy();Object.defineProperty(oe,"AwsRequestSigner",{enumerable:!0,get:function(){return IU.AwsRequestSigner}});var FU=iy();Object.defineProperty(oe,"IdentityPoolClient",{enumerable:!0,get:function(){return FU.IdentityPoolClient}});var NU=Sy();Object.defineProperty(oe,"ExternalAccountClient",{enumerable:!0,get:function(){return NU.ExternalAccountClient}});var MU=Xr();Object.defineProperty(oe,"BaseExternalAccountClient",{enumerable:!0,get:function(){return MU.BaseExternalAccountClient}});var BU=bT();Object.defineProperty(oe,"DownscopedClient",{enumerable:!0,get:function(){return BU.DownscopedClient}});var ST=wy();Object.defineProperty(oe,"PluggableAuthClient",{enumerable:!0,get:function(){return ST.PluggableAuthClient}});Object.defineProperty(oe,"ExecutableError",{enumerable:!0,get:function(){return ST.ExecutableError}});var AT=vy();Object.defineProperty(oe,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return AT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(oe,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return AT.ExternalAccountAuthorizedUserClient}});var jU=CT();Object.defineProperty(oe,"PassThroughClient",{enumerable:!0,get:function(){return jU.PassThroughClient}});var ET=xy();Object.defineProperty(oe,"GdchClient",{enumerable:!0,get:function(){return ET.GdchClient}});Object.defineProperty(oe,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return ET.GDCH_SERVICE_ACCOUNT_TYPE}});kU(jm(),oe);var UU=new wT.GoogleAuth;oe.auth=UU});var qa,e0=Br(()=>{"use strict";qa=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:i}=n||{},a="";if(o){let u=new Date().toISOString();a+=this.config.colors?`${this.colors.cyan}[${u}]${this.colors.reset} `:`[${u}] `}switch(s&&(a+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":a+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?a+=this.toMarkdown(e):a+=String(e);break;default:typeof e=="object"?a+=JSON.stringify(e,null,2):a+=String(e);break}return i&&Object.keys(i).length>0&&(a+=`
119
119
  `+(this.config.colors?`${this.colors.dim}`:""),a+="Metadata: "+JSON.stringify(i,null,2),this.config.colors&&(a+=this.colors.reset)),a}toMarkdown(e,n=0){let r=" ".repeat(n);return Array.isArray(e)?e.map(o=>typeof o=="object"?`${r}-
120
120
  ${this.toMarkdown(o,n+1)}`:`${r}- ${o}`).join(`
121
121
  `):typeof e=="object"&&e!==null?Object.entries(e).map(([o,s])=>typeof s=="object"&&s!==null?`${r}${o}:
122
122
  ${this.toMarkdown(s,n+1)}`:`${r}${o}: ${s}`).join(`
123
- `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var Ha,t0=Br(()=>{"use strict";Ha=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{timestamp:r=!0,prefix:o,metadata:s}=n||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),o&&(i.prefix=o),s&&Object.keys(s).length>0&&(i.metadata=s),i}async sendRequest(e,n,r,o,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let u=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(a),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return u}catch(u){throw clearTimeout(a),u}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,i){let a=null;for(let u=1;u<=i.maxAttempts;u++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(a=d,u===i.maxAttempts)break;let f=i.backoffMs*Math.pow(2,u-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${u}/${i.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw a}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n);return await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry),!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`,{cause:o})}}}});import{writeFileSync as V6,existsSync as Y6,mkdirSync as X6}from"fs";import{join as GR}from"path";import{tmpdir as Q6}from"os";var za,n0=Br(()=>{"use strict";za=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=Q6();this.baseDir=GR(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{Y6(this.baseDir)||X6(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return GR(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return V6(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var r0,ui,JR=Br(()=>{"use strict";e0();t0();n0();r0=class{handlers=new Map;defaultOptions={};logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){(this.logger?.error??console.error)(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){let n;switch(e.type){case"console":n=new qa(e.config);break;case"webhook":n=new Ha(e.config);break;case"temp-file":n=new za(e.config);break;default:throw new Error(`Unknown output handler type: ${e.type}`)}return this.logger&&typeof n.setLogger=="function"&&n.setLogger(this.logger),n}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([i,a])=>{try{await a.output(e,r)?o.success.push(i):o.failed.push(i)}catch(u){(this.logger?.error??console.error)(`[OutputManager] Handler ${i} failed:`,u),o.failed.push(i)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},i=e.map(async a=>{let u=this.handlers.get(a);if(!u){(this.logger?.warn??console.warn)(`[OutputManager] Handler ${a} not found`),s.failed.push(a);return}try{await u.output(n,o)?s.success.push(a):s.failed.push(a)}catch(d){(this.logger?.error??console.error)(`[OutputManager] Handler ${a} failed:`,d),s.failed.push(a)}});return await Promise.all(i),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,i])=>i.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},ui=new r0});var ZR=nr(MC(),1);import Z6 from"fastify";import eH from"@fastify/cors";import{RATE_LIMIT_CONFIG as tH}from"@caeliq/ccr-shared";var VC=nr(sh(),1);import{readFileSync as TO,existsSync as JC}from"fs";import{join as KC}from"path";import{config as xO}from"dotenv";var Qo=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:KC(process.cwd(),this.options.jsonPath);if(JC(e))try{let n=TO(e,"utf-8"),r=VC.default.parse(n);this.config={...this.config,...r},(this.logger?.info??console.log)(`Loaded JSON config from: ${e}`)}catch(n){(this.logger?.warn??console.warn)(`Failed to load JSON config from ${e}:`,n)}else(this.logger?.warn??console.warn)(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:KC(process.cwd(),this.options.envPath);if(JC(e))try{let n=xO({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){(this.logger?.warn??console.warn)(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};var ah="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Ge(t){return t.replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi,"[redacted-url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ah})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"').replace(/\b(?:authorization|x-api-key|api-key|api_key|access_token|token)\s*[:=]\s*["']?[^\s,;"']+/gi,e=>`${e.split(/\s*[:=]/,1)[0]}=[redacted]`).replace(/\[[0-9a-f:]+\](?::\d+)?/gi,"[redacted-address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[redacted-address]").replace(/\b(connect(?:ing)?(?:\s+to)?|from|to)\s+(?:localhost|(?:[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.)+[a-z]{2,63})(?::\d+)?\b/gi,"$1 [redacted-address]").replace(/([?&](?:api_?key|key|token|access_token|auth)=)[^&\s]+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,240)}var RO=new RegExp(`^(?:${ah})$`,"i"),DO=6,OO=20;function Zo(t,e=0){if(t==null)return t;if(!(e>DO)){if(typeof t=="string")return Ge(t);if(Array.isArray(t))return t.slice(0,OO).map(n=>Zo(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=RO.test(r)?"[redacted]":Zo(o,e+1);return n}return t}}var Lc=32768;function ch(t,e=Lc){let n=t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ah})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"'),r=Math.max(0,e);if(n.length<=r)return n;let o=n.length-r;return`${n.slice(0,r)}\u2026[truncated ${o} bytes]`}function PO(t,e){return t.split(`
123
+ `):`${r}${e}`}async output(e,n={}){try{let r=this.formatData(e,n);switch(this.config.level||"log"){case"info":console.info(r);break;case"warn":console.warn(r);break;case"error":console.error(r);break;case"debug":console.debug(r);break;default:console.log(r);break}return!0}catch(r){return console.error("[ConsoleOutputHandler] Output failed:",r),!1}}}});var Ha,t0=Br(()=>{"use strict";Ha=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{timestamp:r=!0,prefix:o,metadata:s}=n||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),o&&(i.prefix=o),s&&Object.keys(s).length>0&&(i.metadata=s),i}async sendRequest(e,n,r,o,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let u=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(a),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return u}catch(u){throw clearTimeout(a),u}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,i){let a=null;for(let u=1;u<=i.maxAttempts;u++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(a=d,u===i.maxAttempts)break;let f=i.backoffMs*Math.pow(2,u-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${u}/${i.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw a}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n);return await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry),!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`,{cause:o})}}}});import{writeFileSync as Q6,existsSync as Z6,mkdirSync as eH}from"fs";import{join as JR}from"path";import{tmpdir as tH}from"os";var za,n0=Br(()=>{"use strict";za=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=tH();this.baseDir=JR(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{Z6(this.baseDir)||eH(this.baseDir,{recursive:!0})}catch{}}extractSessionId(e){try{let n=e.match(/_session_([a-f0-9-]+)/i);return n?n[1]:null}catch{return null}}getFilePath(e){let n=this.config.prefix||"session",r=this.config.extension?`.${this.config.extension}`:"",o;if(this.config.includeTimestamp){let s=Date.now();o=`${n}-${e}-${s}${r}`}else o=`${n}-${e}${r}`;return JR(this.baseDir,o)}async output(e,n={}){try{let r=n.metadata?.sessionId;if(!r)return!1;let o={...e,timestamp:Date.now(),sessionId:r},s=this.getFilePath(r);return Q6(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var r0,ui,KR=Br(()=>{"use strict";e0();t0();n0();r0=class{handlers=new Map;defaultOptions={};logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}registerHandler(e,n){this.handlers.set(e,n)}registerHandlers(e){for(let n of e)if(n.enabled!==!1)try{let r=this.createHandler(n),o=n.type+"_"+Date.now();this.registerHandler(o,r)}catch(r){(this.logger?.error??console.error)(`[OutputManager] Failed to register ${n.type} handler:`,r)}}createHandler(e){let n;switch(e.type){case"console":n=new qa(e.config);break;case"webhook":n=new Ha(e.config);break;case"temp-file":n=new za(e.config);break;default:throw new Error(`Unknown output handler type: ${e.type}`)}return this.logger&&typeof n.setLogger=="function"&&n.setLogger(this.logger),n}unregisterHandler(e){return this.handlers.delete(e)}getHandler(e){return this.handlers.get(e)}getAllHandlers(){return new Map(this.handlers)}clearHandlers(){this.handlers.clear()}setDefaultOptions(e){this.defaultOptions={...this.defaultOptions,...e}}getDefaultOptions(){return{...this.defaultOptions}}async output(e,n){let r={...this.defaultOptions,...n},o={success:[],failed:[]},s=Array.from(this.handlers.entries()).map(async([i,a])=>{try{await a.output(e,r)?o.success.push(i):o.failed.push(i)}catch(u){(this.logger?.error??console.error)(`[OutputManager] Handler ${i} failed:`,u),o.failed.push(i)}});return await Promise.all(s),o}async outputTo(e,n,r){let o={...this.defaultOptions,...r},s={success:[],failed:[]},i=e.map(async a=>{let u=this.handlers.get(a);if(!u){(this.logger?.warn??console.warn)(`[OutputManager] Handler ${a} not found`),s.failed.push(a);return}try{await u.output(n,o)?s.success.push(a):s.failed.push(a)}catch(d){(this.logger?.error??console.error)(`[OutputManager] Handler ${a} failed:`,d),s.failed.push(a)}});return await Promise.all(i),s}async outputToType(e,n,r){let o=Array.from(this.handlers.entries()).filter(([s,i])=>i.type===e).map(([s])=>s);return this.outputTo(o,n,r)}},ui=new r0});var eD=nr(MC(),1);import nH from"fastify";import rH from"@fastify/cors";import{RATE_LIMIT_CONFIG as oH}from"@caeliq/ccr-shared";var VC=nr(oh(),1);import{readFileSync as xO,existsSync as JC}from"fs";import{join as KC}from"path";import{config as RO}from"dotenv";var Qo=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:KC(process.cwd(),this.options.jsonPath);if(JC(e))try{let n=xO(e,"utf-8"),r=VC.default.parse(n);this.config={...this.config,...r},(this.logger?.info??console.log)(`Loaded JSON config from: ${e}`)}catch(n){(this.logger?.warn??console.warn)(`Failed to load JSON config from ${e}:`,n)}else(this.logger?.warn??console.warn)(`JSON config file not found: ${e}`)}loadEnvConfig(){let e=this.isAbsolutePath(this.options.envPath)?this.options.envPath:KC(process.cwd(),this.options.envPath);if(JC(e))try{let n=RO({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){(this.logger?.warn??console.warn)(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};var ih="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Ge(t){return t.replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi,"[redacted-url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ih})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"').replace(/\b(?:authorization|x-api-key|api-key|api_key|access_token|token)\s*[:=]\s*["']?[^\s,;"']+/gi,e=>`${e.split(/\s*[:=]/,1)[0]}=[redacted]`).replace(/\[[0-9a-f:]+\](?::\d+)?/gi,"[redacted-address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[redacted-address]").replace(/\b(connect(?:ing)?(?:\s+to)?|from|to)\s+(?:localhost|(?:[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.)+[a-z]{2,63})(?::\d+)?\b/gi,"$1 [redacted-address]").replace(/([?&](?:api_?key|key|token|access_token|auth)=)[^&\s]+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,240)}var DO=new RegExp(`^(?:${ih})$`,"i"),OO=6,PO=20;function Zo(t,e=0){if(t==null)return t;if(!(e>OO)){if(typeof t=="string")return Ge(t);if(Array.isArray(t))return t.slice(0,PO).map(n=>Zo(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=DO.test(r)?"[redacted]":Zo(o,e+1);return n}return t}}var Lc=32768;function ah(t,e=Lc){let n=t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ih})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"'),r=Math.max(0,e);if(n.length<=r)return n;let o=n.length-r;return`${n.slice(0,r)}\u2026[truncated ${o} bytes]`}function IO(t,e){return t.split(`
124
124
  `).map(n=>Ge(n)).filter(Boolean).join(`
125
- `).slice(0,e)}function En(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:Ge(n)||"Unknown error",code:typeof e?.code=="string"?e.code:void 0,type:typeof e?.type=="string"?e.type:void 0,name:typeof e?.name=="string"?e.name:void 0,statusCode:typeof e?.statusCode=="number"?e.statusCode:void 0,stack:typeof e?.stack=="string"?PO(e.stack,4e3):void 0,cause:r?Ge(r):void 0}}var IO=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function FO(t){return IO.test(t)}function NO(t){if(t==null)return;if(Array.isArray(t)){let n=t.filter(r=>r!=null&&String(r).length>0).map(r=>String(r));return n.length?n.join(", "):void 0}let e=String(t);return e.length?e:void 0}function ih(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=NO(o);if(s!=null){if(FO(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function MO(t,e){let n=ih(t),r=ih(e),o=new Map(Object.entries(n).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),s=new Map(Object.entries(r).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),i={},a={},u={},d=0;for(let[f,{key:p,value:h}]of o){let g=s.get(f);if(!g){i[p]=h;continue}g.value===h?d+=1:u[p]={from:h,to:g.value}}for(let[f,{key:p,value:h}]of s)o.has(f)||(a[p]=h);return{onlyInLeft:i,onlyInRight:a,changed:u,sameCount:d}}var St="client disconnected";function es(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"})):new Promise((n,r)=>{let o=setTimeout(()=>{e&&e.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),r(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"}))};e&&e.addEventListener("abort",s,{once:!0})})}function QC(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(a=St)=>{n.signal.aborted||n.abort(a)},i=()=>{if(!o&&(o=!0,!!r)){if(uh(r)){s(`${St} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&uh(r)&&s(`${St} (response close)`)}),r.on("error",a=>{(a?.code==="EPIPE"||a?.code==="ECONNRESET"||a?.code==="ERR_STREAM_PREMATURE_CLOSE"||Je(a))&&s(`${St} (response error)`)})}};return{signal:n.signal,arm:i}}function BO(t){let e=t?.trim();if(!e)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(n*1e3,6e4);let r=Date.parse(e);if(Number.isFinite(r))return Math.min(Math.max(0,r-Date.now()),6e4)}function UO(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function lh(t,e){let n=BO(e);return n!==void 0&&n>0?n:UO(t)}function ZC(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var YC=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CONNECT"]);function ew(t){let e=t;if(!e)return!1;if(e.name==="TimeoutError"||e.code==="TIMEOUT_ERR"||e.code===23||e.cause&&(e.cause.name==="TimeoutError"||e.cause.code==="TIMEOUT_ERR"||e.cause.code===23))return!0;let n=String(e.message||"");return/aborted due to timeout|operation was aborted due to timeout/i.test(n)}function vn(t=St){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:St;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function XC(t){let e=t.toLowerCase();if(e.includes("socket hang up"))return!0;let n=e.indexOf("client");if(n===-1)return!1;let r=e.slice(n);return r.includes("closed")||r.includes("disconnect")}function Je(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(St)||XC(t);let e=t;if(ew(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(St)||typeof e.message=="string"&&e.message.startsWith(St)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return XC(r)}function uh(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function tw(t){return uh(t.raw)}function ar(t){if(!t||Je(t))return!1;if(ew(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&YC.has(e.code)||e.cause?.code&&YC.has(String(e.cause.code)))return!0;let n=String(e.message||"");return/fetch failed|network|socket|ECONNRESET|ENOTFOUND|ETIMEDOUT|other side closed/i.test(n)}function dh(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function fh(t){let e=t;if(!e||Je(e))return!1;if(ar(e))return!0;let n=typeof e.statusCode=="number"?e.statusCode:typeof e.upstream?.status=="number"?e.upstream.status:void 0;return n!==void 0?dh(n):e.code==="provider_response_error"}function Hi(t,e,n,r,o="invalid_request_error"){switch(t){case"openai_chat_completions":case"openai_responses":return{statusCode:n,body:{error:{message:e,type:o,param:null,code:r}}};default:return{statusCode:n,body:{error:{message:e,type:o==="invalid_request_error"?"invalid_request_error":o,code:r},type:"error"}}}}function J(t,e=500,n="internal_error",r="api_error",o){let s=new Error(Ge(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function nw(t,e,n){if(Je(t)||n.raw.destroyed||n.sent)return e.log.debug(En(t),"request aborted or already closed"),!n.sent&&!n.raw.destroyed&&!n.raw.headersSent?(n.type("application/json"),n.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):void 0;e.log.error(En(t),"request error");let r=t.statusCode||500,o=Ge(t.message||"Internal error")||"Internal error",s=t.code||"internal_error",i=t.type||(r>=400&&r<500?"invalid_request_error":"api_error"),a=e.clientProtocol,u=t.protocolBody,d=t.upstream?.body;if(!u&&d&&typeof d=="object"){let f=d.error;(a==="anthropic_messages"||!a)&&d.type==="error"&&f&&typeof f=="object"?u={type:"error",error:{type:typeof f.type=="string"?f.type:i,message:typeof f.message=="string"?f.message:o,...typeof f.code=="string"?{code:f.code}:{}}}:(a==="openai_chat_completions"||a==="openai_responses")&&f&&typeof f=="object"&&(u={error:{message:typeof f.message=="string"?f.message:o,type:typeof f.type=="string"?f.type:i,param:f.param??null,code:typeof f.code=="string"?f.code:s}})}return u||(u=Hi(a,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}import{Readable as v1}from"stream";import{ProxyAgent as jO}from"undici";function LO(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function $O(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function rw(t){let e=t.split(".");if(e.length!==4)return null;let n=0;for(let r of e){let o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>255)return null;n=n<<8|o}return n>>>0}function qO(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=rw(t),i=rw(n);if(s===null||i===null)return!1;let a=o===0?0:-1<<32-o>>>0;return(s&a)===(i&a)}function HO(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=LO(e.hostname);if(n==="localhost"||n==="127.0.0.1"||n.startsWith("127.")||n==="0.0.0.0"||n==="::1"||n==="0:0:0:0:0:0:0:1")return!0;let r=process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;let o=r.split(",").map(s=>s.trim()).filter(Boolean);for(let s of o){let i=s.toLowerCase();if(i==="*")return!0;let a=zO(i);if(a.startsWith(".")){if(n.endsWith(a)||n===a.slice(1))return!0;continue}if(a.includes("/")&&$O(n)){if(qO(n,a))return!0;continue}if(n===a)return!0;if(a.startsWith("*.")){let u=a.slice(1);if(n.endsWith(u)||n===u.slice(1))return!0}}return!1}function zO(t){if(t.startsWith("[")&&t.includes("]"))return t.slice(1,t.indexOf("]"));if(t.split(":").length-1===1){let[n,r]=t.split(":");if(/^\d+$/.test(r))return n}return t}async function ts(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([p,h])=>{h&&s.set(p,h)});let i=AbortSignal.timeout(n.TIMEOUT??60*1e3*60),a=n.signal?AbortSignal.any([n.signal,i]):i,u={method:"POST",headers:s,body:JSON.stringify(e),signal:a},d=typeof t=="string"?t:t.toString();n.httpsProxy&&!HO(d)&&(u.dispatcher=new jO(new URL(n.httpsProxy).toString()));try{return await fetch(d,u)}catch(p){if(Je(p))throw typeof p=="string"?vn(p):p;if(n.signal?.aborted&&Je(n.signal.reason??St))throw vn(n.signal.reason??p);if(ar(p)){let h=J(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var ph;function WO(t){ph=t}function ow(){if(ph)try{return ph()}catch{return}}var sw="1.0.63";import{createHash as JO}from"crypto";var hh={type:"ephemeral"};function Ve(t){return t.map(e=>{let n={...e};return Array.isArray(n.content)&&(n.content=n.content.map(r=>{if(r.cache_control){let{cache_control:o,...s}=r;return s}return r})),n.cache_control&&delete n.cache_control,Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{let{cache_control:o,...s}=r;return s})),n})}function Ye(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function iw(t){return`ccr_${JO("sha256").update(t).digest("hex").slice(0,48)}`}function KO(t){if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}return t}function VO(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
126
- `):""}function en(t,e){let n=t?.req?.sessionId||KO(e?.metadata?.user_id);if(typeof n=="string"&&n)return iw(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?VO(r.content):"",s=[e.model||"",o].join(`
127
- `);return s.trim()?iw(s):void 0}function $c(t,e={}){let n=e.maxBreakpoints??4,r=JSON.parse(JSON.stringify(t)),o=[],s=d=>{d&&typeof d=="object"&&d.cache_control&&o.push(d)};(Array.isArray(r.tools)?r.tools:[]).forEach(s),Array.isArray(r.system)?r.system.forEach(s):s(r.system),(Array.isArray(r.messages)?r.messages:[]).forEach(d=>{s(d),Array.isArray(d?.content)&&d.content.forEach(s)});let i=!!r.cache_control,a=Math.max(0,n-(i?1:0));if(o.length>a)for(let d of o.slice(0,o.length-a))delete d.cache_control;let u=Math.min(o.length,a);if(!i&&u<n){let d=o[o.length-1]?.cache_control;r.cache_control=d?.ttl?{type:"ephemeral",ttl:d.ttl}:hh}return r}function yo(t){let e=Ve(t.messages||[]),n=Ye(t.tools);for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o.content=="string"&&o.content){o.content=[{type:"text",text:o.content,cache_control:hh}];break}if(Array.isArray(o.content))for(let s=o.content.length-1;s>=0;s-=1){let i=o.content[s];if(i?.type==="text"&&i.text)return o.content[s]={...i,cache_control:hh},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function qc(t){let e=[];for(let n=0;n<t.length;n++){let r={...t[n]};if(r.role==="assistant"&&r.tool_calls){let o=[],s=[],i=[],a=n+1;for(;a<t.length&&t[a].role==="tool";)i.push(t[a]),a++;r.tool_calls.forEach(u=>{i.some(f=>f.tool_call_id===u.id)?o.push(u):s.push(u.id)}),o.length>0?r.tool_calls=o:delete r.tool_calls,(r.content||r.tool_calls)&&e.push(r)}else if(r.role==="tool"){let o=!1;if(n>0){let s=t[n-1];if(s.role==="assistant"&&s.tool_calls)o=s.tool_calls.some(i=>i.id===r.tool_call_id);else if(s.role==="tool"){for(let i=n-1;i>=0;i--)if(t[i].role!=="tool"){t[i].role==="assistant"&&t[i].tool_calls&&(o=t[i].tool_calls.some(a=>a.id===r.tool_call_id));break}}}o&&e.push(r)}else e.push(r)}return e}function aw(t){let n=(t||"").toLowerCase().match(/(?:^|\/)gpt-(\d+)(?:\.(\d+))?/);if(!n)return!1;let r=Number(n[1]),o=Number(n[2]||0);return r>5||r===5&&o>=6}function cw(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function YO(t){for(let e=t.length-1;e>=0;e-=1)if(cw(t[e]))return e;return-1}function zi(t,e,n){let r={...t,messages:(t.messages||[]).map(s=>({...s,content:Array.isArray(s.content)?s.content.map(i=>({...i})):s.content})),tools:Array.isArray(t.tools)?t.tools.map(s=>s?.function?{...s,function:{...s.function,parameters:{...s.function.parameters}}}:{...s}):t.tools},o=en(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),aw(r.model)){let s=[];r.messages.forEach((i,a)=>{if(i.cache_control){if(typeof i.content=="string"&&i.content)s.push({messageIndex:a});else if(Array.isArray(i.content)){let u=YO(i.content);u>=0&&s.push({messageIndex:a,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,d)=>{u?.cache_control&&cw(u)&&s.push({messageIndex:a,contentIndex:d})})});for(let i of s.slice(-3)){let a=r.messages[i.messageIndex];typeof a.content=="string"?a.content=[{type:"text",text:a.content,prompt_cache_breakpoint:{mode:"explicit"}}]:Array.isArray(a.content)&&i.contentIndex!==void 0&&(a.content[i.contentIndex].prompt_cache_breakpoint={mode:"explicit"})}}return r.messages=Ve(r.messages),r.tools=Ye(r.tools),r}function Hc(t,e){return aw(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function XO(t){return String(t?.name||"").trim().toLowerCase()}function QO(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function gh(t,e){let n={...t,messages:Ve(t.messages||[]),tools:Ye(t.tools)},r=en(e,t);return r&&(n.prompt_cache_key=r),n}function zc(t,e,n){let r=XO(e),o=QO(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?zi(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?yo(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?gh(t,n):{...t,messages:Ve(t.messages||[]),tools:Ye(t.tools)}}function Dt(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e||void 0}function Ot(t,e){return e?.type==="disabled"||t?.enabled===!1||Dt(t?.effort)==="none"}function ns(t,e){let n=Dt(t);if(!(!n&&e===void 0))return{...n?{effort:n}:{},enabled:n==="none"?!1:e??!0}}function Wc(t){if(!t.reasoning)return t;let e=Ot(t.reasoning,t.thinking)?"none":Dt(t.reasoning.effort);return e&&(t.reasoning_effort=e),delete t.reasoning,t}function uw(t){let e=Dt(t);if(!(!e||e==="none"))return e==="minimal"?"low":e==="ultra"?"max":e}var Tn=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
128
- `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};function lw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function Gc(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=lw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var ZO=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function Jc(t){let e={};return t&&t.forEach((n,r)=>{ZO.has(r.toLowerCase())||(e[r]=n)}),e}var eP=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),tP=["anthropic-ratelimit-","x-ratelimit-"];function mh(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){if(typeof o!="string"||!o)continue;let s=r.toLowerCase();!(eP.has(s)||tP.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function dw(t,e){let n={};for(let[r,o]of Object.entries(t||{})){if(o===void 0||o==="undefined")continue;let s=r.toLowerCase(),i=s==="authorization"?"Authorization":s==="x-api-key"?"x-api-key":s,a=lw(n,i);a&&delete n[a],n[i]=o}return n["x-api-key"]?delete n.Authorization:!n.Authorization&&e&&(n.Authorization=`Bearer ${e}`),Object.fromEntries(Object.entries(n).filter(r=>typeof r[1]=="string"))}import{createHash as nP}from"crypto";var rP=512,oP=16,sP=4,_o=new Map;function yw(t){let e=JSON.stringify(yh(t))??"";return{hash:nP("sha256").update(e).digest("hex").slice(0,oP),approxTokens:Math.ceil(e.length/sP)}}function _w(t){return yw(t).hash}function yh(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(yh);let e={};for(let n of Object.keys(t).sort())e[n]=yh(t[n]);return e}function bw(t){if(!t||typeof t!="object")return!1;let e=t.cache_control;return!!(e&&typeof e=="object"&&e.type==="ephemeral")}function Cw(t){return!!(t&&typeof t=="object"&&t.prompt_cache_breakpoint)}function _h(t){if(!t||typeof t!="object")return 0;let e=0;if((bw(t)||Cw(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=_h(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=_h(n));return e}function Wi(t,e,n){if(!(!t||typeof t!="object")){if((bw(t)||Cw(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>Wi(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&Wi(o,`${e}.${r}`,n)}}function fw(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=String(n.type||"");r&&e[e.length-1]!==r&&e.push(r)}return e.length?e:void 0}function pw(t){if(!t||typeof t!="object")return;if(t.type==="reasoning"&&typeof t.id=="string"&&t.id)return t.id;let e=t.thinking?.id;return typeof e=="string"&&e?e:void 0}function iP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function bh(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)bh(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&iP(o)?e.add(String(o)):o&&typeof o=="object"&&bh(o,e,n+1)}}function Kc(t,e,n){let r=e,{hash:o,approxTokens:s}=yw(e);return{path:t,...n?.role?{role:n.role}:{},...n?.type?{type:n.type}:{},...typeof r?.role=="string"&&!n?.role?{role:r.role}:{},...typeof r?.type=="string"&&!n?.type?{type:r.type}:{},hash:o,approxTokens:s,breakpoints:_h(e),...pw(r)?{reasoningId:pw(r)}:{}}}function aP(t,e){for(_o.has(t)&&_o.delete(t),_o.set(t,e);_o.size>rP;){let n=_o.keys().next().value;if(n===void 0)break;_o.delete(n)}}function cP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=Kc("system",t.system,{type:"system"});o=p.hash,n.push(p),Wi(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=Kc("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=Kc("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),Wi(t.tools,"tools",r)}let i=Array.isArray(t.messages)?{key:"messages",items:t.messages}:Array.isArray(t.input)?{key:"input",items:t.input}:Array.isArray(t.contents)?{key:"contents",items:t.contents}:void 0,a;i&&i.items.forEach((p,h)=>{let g=`${i.key}[${h}]`;n.push(Kc(g,p)),Wi(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=fw(p.content)||fw(p.parts)||a)});let u=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:typeof t.session_id=="string"&&t.session_id?t.session_id:void 0,d=e?Object.fromEntries(Object.entries(e).filter(([,p])=>typeof p=="string"&&p)):void 0;if(n.length===0&&!u&&!(d&&Object.keys(d).length))return null;let f=new Set;return bh(i?.items,f),{createdAt:Date.now(),...typeof t.model=="string"?{model:t.model}:{},...u?{prompt_cache_key:u}:{},...typeof t.session_id=="string"?{session_id:t.session_id}:{},...d&&Object.keys(d).length?{affinity:d}:{},...a?{lastAssistantBlockOrder:a}:{},breakpointPaths:r,...o?{systemHash:o}:{},...s?{toolsHash:s}:{},approxTokens:n.reduce((p,h)=>p+h.approxTokens,0),unstableIds:[...f],segments:n}}function hw(t){if(t)return{path:t.path,...t.role?{role:t.role}:{},...t.type?{type:t.type}:{},approxTokens:t.approxTokens,breakpoints:t.breakpoints,...t.reasoningId?{reasoningId:t.reasoningId}:{}}}function gw(t){return t?_w(t):""}function mw(t){return t.reduce((e,n)=>e+n.approxTokens,0)}function uP(t,e,n,r){let o=r?.stage??"wire",s=r?.conversationIdSource??"session",i=n.unstableIds.length?{unstableIds:n.unstableIds.slice(0,8)}:{};if(!e)return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!0,prefixIntact:!0,change:"none",unchangedPrefixCount:n.segments.length,previousSegmentCount:0,currentSegmentCount:n.segments.length,unchangedPrefixApproxTokens:n.approxTokens,approxPrefixTokensLost:0,prompt_cache_keyChanged:!1,affinityChanged:!1,lastAssistantBlockOrderChanged:!1,modelChanged:!1,systemHashChanged:!1,toolsHashChanged:!1,breakpointsMoved:!1,...i};let a=(e.prompt_cache_key||"")!==(n.prompt_cache_key||""),u=gw(e.affinity)!==gw(n.affinity),d=JSON.stringify(e.lastAssistantBlockOrder||[])!==JSON.stringify(n.lastAssistantBlockOrder||[]),f=(e.model||"")!==(n.model||""),p=(e.systemHash||"")!==(n.systemHash||""),h=(e.toolsHash||"")!==(n.toolsHash||""),g=JSON.stringify(e.breakpointPaths)!==JSON.stringify(n.breakpointPaths),b=e.segments,m=n.segments,w=Math.min(b.length,m.length),C=0;for(;C<w&&b[C].path===m[C].path&&b[C].hash===m[C].hash;)C+=1;let A=C===b.length&&m.length>=b.length,k="none",E,x,O,q;C<w?(k="modified",E=m[C]?.path||b[C]?.path,q={previous:hw(b[C]),current:hw(m[C])}):m.length>b.length?(k="appended",x=m.slice(C).map(j=>j.path)):m.length<b.length&&(k="removed",O=b.slice(C).map(j=>j.path),E=b[C]?.path),k==="none"&&(a||u||d||f||g)&&(k="modified"),E||(a?E="prompt_cache_key":u?E="affinity":f?E="model":d?E="lastAssistantBlockOrder":g&&(E="breakpointPaths"));let V=k==="modified"||k==="removed"?mw(b.slice(C)):0;return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!1,prefixIntact:A&&!a&&!u&&!f,change:k,unchangedPrefixCount:C,previousSegmentCount:b.length,currentSegmentCount:m.length,unchangedPrefixApproxTokens:mw(m.slice(0,C)),approxPrefixTokensLost:V,msSinceLastTurn:Math.max(0,n.createdAt-e.createdAt),prompt_cache_keyChanged:a,affinityChanged:u,lastAssistantBlockOrderChanged:d,modelChanged:f,systemHashChanged:p,toolsHashChanged:h,breakpointsMoved:g,...i,...E?{firstDivergencePath:E}:{},...q?{firstDivergence:q}:{},...x?{appendedPaths:x}:{},...O?{removedPaths:O}:{},...a?{prompt_cache_key:{previous:e.prompt_cache_key,current:n.prompt_cache_key}}:{},...u?{affinity:{previous:e.affinity,current:n.affinity}}:{},...d?{lastAssistantBlockOrder:{previous:e.lastAssistantBlockOrder,current:n.lastAssistantBlockOrder}}:{}}}function lP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${_w([t.systemHash||"",t.toolsHash||"",e?.hash||""])}`}function dP(t,e){return typeof t=="string"&&t?{id:t,source:"session"}:e.prompt_cache_key?{id:e.prompt_cache_key,source:"cache_key"}:{id:lP(e),source:"fingerprint"}}function ww(t,e,n,r){let o=cP(e,n);if(!o)return null;let s=r?.stage??"wire",{id:i,source:a}=dP(t,o),u=[s,r?.provider||"-",r?.model||o.model||"-",i].join("|"),d=_o.get(u),f=uP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&aP(u,o),f}function Ch(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function wh(t){if(!t||typeof t.debug!="function")return!1;if(typeof t.isLevelEnabled=="function")try{return t.isLevelEnabled("debug")===!0}catch{return!1}let e=typeof t.level=="string"?t.level.toLowerCase():"";return e==="debug"||e==="trace"?!0:typeof t.levelVal=="number"?t.levelVal<=20:!("level"in t)&&!("levelVal"in t)}function kw(t,e){let n=Jc(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function fP(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function Vc(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??Lc,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:ch(e,o)}),n!==void 0&&r.debug({...s,response:Zo(n),tppe:"Original Response"})}function At(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Sw(t,e){if(!e||typeof e!="object")return t;let n=e,r=[n.usage,n.message?.usage,n.response?.usage,n.usageMetadata].filter(s=>s&&typeof s=="object"),o=t;for(let s of r){let i=$t($t(At(s.cache_read_input_tokens),At(s.prompt_tokens_details?.cached_tokens)),$t($t(At(s.input_tokens_details?.cached_tokens),At(s.cachedContentTokenCount)),At(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||At(s.cache_read_input_tokens)!==void 0||At(s.cache_creation_input_tokens)!==void 0,promptTokens:$t(o.promptTokens,$t($t(At(s.input_tokens),At(s.prompt_tokens)),At(s.promptTokenCount))),cachedTokens:$t(o.cachedTokens,i),cacheWriteTokens:$t(o.cacheWriteTokens,At(s.cache_creation_input_tokens)),outputTokens:$t(o.outputTokens,$t($t(At(s.output_tokens),At(s.completion_tokens)),At(s.candidatesTokenCount)))}}return o}function pP(t,e){return e===void 0?"unknown":!t||t.firstTurn?e>0?"warm-start":"cold":t.prefixIntact?e>0?"hit":"unexpected-miss":e>0?"partial":"expected-miss"}function kh(t,e){if(!wh(t.logger))return;let n=t.cacheDiff,r=e.cachedTokens,o=e.promptTokens,s=o===void 0?void 0:e.cachedExcludedFromPrompt?o+(r||0)+(e.cacheWriteTokens||0):o,i=r===void 0||!s?void 0:Math.round(r/s*1e3)/1e3;if(r===void 0&&o===void 0&&!n)return;let a=n?Ch(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:pP(n,i),...t.model?{model:t.model}:{},...t.responseStatus?{status:t.responseStatus}:{},...n?{conversationId:n.conversationId,conversationIdSource:n.conversationIdSource,predictedChange:n.change,prefixIntact:n.prefixIntact,...n.firstDivergencePath?{firstDivergencePath:n.firstDivergencePath}:{},approxPrefixTokensLost:n.approxPrefixTokensLost,...n.msSinceLastTurn!==void 0?{msSinceLastTurn:n.msSinceLastTurn}:{},...a?{divergenceStage:a}:{}}:{},...s!==void 0?{promptTokens:s}:{},...r!==void 0?{cachedTokens:r}:{},...e.cacheWriteTokens!==void 0?{cacheWriteTokens:e.cacheWriteTokens}:{},...e.outputTokens!==void 0?{outputTokens:e.outputTokens}:{},...i!==void 0?{cacheHitRatio:i}:{}})}function hP(t,e){(async()=>{let r=t.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader(),o={cachedExcludedFromPrompt:!1},s=()=>new Promise(i=>setImmediate(i));try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(!a||typeof a!="object")continue;let u=a;if(u.data==null)continue;if(typeof u.data=="object"&&u.data.type==="done"){Vc(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);Vc(e,f),await s();continue}o=Sw(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}Vc(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}kh(e,o)}})()}async function gP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return Vc(e,n,r),kh(e,Sw({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:kw(t.headers,"application/json")})}async function Aw(t,e){if(!wh(e.logger)||!t.body)return t;let n=fP(t);if(n.includes("application/json"))try{return await gP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return kh(e,{cachedExcludedFromPrompt:!1}),t;try{let r=mP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:kw(t.headers,"text/event-stream")})}catch{return t}}function mP(t,e){let n=new TransformStream(void 0,{highWaterMark:1/0},{highWaterMark:1}),r=n.writable.getWriter();hP(n.readable,e);let o=!0,s=()=>{o&&(o=!1,r.close().catch(()=>{}))};return t.pipeThrough(new TransformStream({transform(i,a){a.enqueue(i),o&&r.write(i.slice()).catch(()=>{s()})},flush(){s()},cancel(){s()}}))}function Gi(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function yP(t){return Array.isArray(t)?t.reduce((e,n)=>e+Gi(n),0):0}function _P(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=String(n.type||"");r&&e[e.length-1]!==r&&e.push(r)}return e.length?e:void 0}function bP(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=Gi(i);else t.system&&typeof t.system=="object"&&(e+=Gi(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=Gi(i),n+=yP(i.content),i.role==="assistant"&&(r=_P(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=Gi(i);let s=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:void 0;return e===0&&n===0&&o===0&&!s&&!r?null:{systemBreakpoints:e,messageBreakpoints:n,toolBreakpoints:o,...s?{prompt_cache_key:s}:{},...r?{lastAssistantBlockOrder:r}:{}}}function Sh(t,e){if(!wh(e.logger))return null;let n=bP(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=ww(e.conversationId,t,e.cacheAffinity,{stage:e.stage??"wire",provider:e.provider,model:e.model,commit:r===void 0||r>=200&&r<300});if(!o)return null;let s=Ch(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var CP=new TextEncoder().encode(`: keepalive
125
+ `).slice(0,e)}function En(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:Ge(n)||"Unknown error",code:typeof e?.code=="string"?e.code:void 0,type:typeof e?.type=="string"?e.type:void 0,name:typeof e?.name=="string"?e.name:void 0,statusCode:typeof e?.statusCode=="number"?e.statusCode:void 0,stack:typeof e?.stack=="string"?IO(e.stack,4e3):void 0,cause:r?Ge(r):void 0}}var FO=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function NO(t){return FO.test(t)}function MO(t){if(t==null)return;if(Array.isArray(t)){let n=t.filter(r=>r!=null&&String(r).length>0).map(r=>String(r));return n.length?n.join(", "):void 0}let e=String(t);return e.length?e:void 0}function sh(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=MO(o);if(s!=null){if(NO(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function BO(t,e){let n=sh(t),r=sh(e),o=new Map(Object.entries(n).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),s=new Map(Object.entries(r).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),i={},a={},u={},d=0;for(let[f,{key:p,value:h}]of o){let g=s.get(f);if(!g){i[p]=h;continue}g.value===h?d+=1:u[p]={from:h,to:g.value}}for(let[f,{key:p,value:h}]of s)o.has(f)||(a[p]=h);return{onlyInLeft:i,onlyInRight:a,changed:u,sameCount:d}}var St="client disconnected";function es(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"})):new Promise((n,r)=>{let o=setTimeout(()=>{e&&e.removeEventListener("abort",s),n()},t),s=()=>{clearTimeout(o),r(Object.assign(new Error("Aborted"),{name:"AbortError",code:"ABORT_ERR"}))};e&&e.addEventListener("abort",s,{once:!0})})}function QC(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(a=St)=>{n.signal.aborted||n.abort(a)},i=()=>{if(!o&&(o=!0,!!r)){if(ch(r)){s(`${St} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&ch(r)&&s(`${St} (response close)`)}),r.on("error",a=>{(a?.code==="EPIPE"||a?.code==="ECONNRESET"||a?.code==="ERR_STREAM_PREMATURE_CLOSE"||Je(a))&&s(`${St} (response error)`)})}};return{signal:n.signal,arm:i}}function jO(t){let e=t?.trim();if(!e)return;let n=Number(e);if(Number.isFinite(n)&&n>=0)return Math.min(n*1e3,6e4);let r=Date.parse(e);if(Number.isFinite(r))return Math.min(Math.max(0,r-Date.now()),6e4)}function UO(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function uh(t,e){let n=jO(e);return n!==void 0&&n>0?n:UO(t)}function ZC(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var YC=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_SOCKET","UND_ERR_CONNECT"]);function ew(t){let e=t;if(!e)return!1;if(e.name==="TimeoutError"||e.code==="TIMEOUT_ERR"||e.code===23||e.cause&&(e.cause.name==="TimeoutError"||e.cause.code==="TIMEOUT_ERR"||e.cause.code===23))return!0;let n=String(e.message||"");return/aborted due to timeout|operation was aborted due to timeout/i.test(n)}function vn(t=St){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:St;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function XC(t){let e=t.toLowerCase();if(e.includes("socket hang up"))return!0;let n=e.indexOf("client");if(n===-1)return!1;let r=e.slice(n);return r.includes("closed")||r.includes("disconnect")}function Je(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(St)||XC(t);let e=t;if(ew(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(St)||typeof e.message=="string"&&e.message.startsWith(St)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return XC(r)}function ch(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function tw(t){return ch(t.raw)}function ar(t){if(!t||Je(t))return!1;if(ew(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&YC.has(e.code)||e.cause?.code&&YC.has(String(e.cause.code)))return!0;let n=String(e.message||"");return/fetch failed|network|socket|ECONNRESET|ENOTFOUND|ETIMEDOUT|other side closed/i.test(n)}function lh(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function dh(t){let e=t;if(!e||Je(e))return!1;if(ar(e))return!0;let n=typeof e.statusCode=="number"?e.statusCode:typeof e.upstream?.status=="number"?e.upstream.status:void 0;return n!==void 0?lh(n):e.code==="provider_response_error"}function Hi(t,e,n,r,o="invalid_request_error"){switch(t){case"openai_chat_completions":case"openai_responses":return{statusCode:n,body:{error:{message:e,type:o,param:null,code:r}}};default:return{statusCode:n,body:{error:{message:e,type:o==="invalid_request_error"?"invalid_request_error":o,code:r},type:"error"}}}}function J(t,e=500,n="internal_error",r="api_error",o){let s=new Error(Ge(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function nw(t,e,n){if(Je(t)||n.raw.destroyed||n.sent)return e.log.debug(En(t),"request aborted or already closed"),!n.sent&&!n.raw.destroyed&&!n.raw.headersSent?(n.type("application/json"),n.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):void 0;e.log.error(En(t),"request error");let r=t.statusCode||500,o=Ge(t.message||"Internal error")||"Internal error",s=t.code||"internal_error",i=t.type||(r>=400&&r<500?"invalid_request_error":"api_error"),a=e.clientProtocol,u=t.protocolBody,d=t.upstream?.body;if(!u&&d&&typeof d=="object"){let f=d.error;(a==="anthropic_messages"||!a)&&d.type==="error"&&f&&typeof f=="object"?u={type:"error",error:{type:typeof f.type=="string"?f.type:i,message:typeof f.message=="string"?f.message:o,...typeof f.code=="string"?{code:f.code}:{}}}:(a==="openai_chat_completions"||a==="openai_responses")&&f&&typeof f=="object"&&(u={error:{message:typeof f.message=="string"?f.message:o,type:typeof f.type=="string"?f.type:i,param:f.param??null,code:typeof f.code=="string"?f.code:s}})}return u||(u=Hi(a,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}import{Readable as T1}from"stream";import{ProxyAgent as LO}from"undici";function $O(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function qO(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function rw(t){let e=t.split(".");if(e.length!==4)return null;let n=0;for(let r of e){let o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>255)return null;n=n<<8|o}return n>>>0}function HO(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=rw(t),i=rw(n);if(s===null||i===null)return!1;let a=o===0?0:-1<<32-o>>>0;return(s&a)===(i&a)}function zO(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=$O(e.hostname);if(n==="localhost"||n==="127.0.0.1"||n.startsWith("127.")||n==="0.0.0.0"||n==="::1"||n==="0:0:0:0:0:0:0:1")return!0;let r=process.env.NO_PROXY||process.env.no_proxy;if(!r)return!1;let o=r.split(",").map(s=>s.trim()).filter(Boolean);for(let s of o){let i=s.toLowerCase();if(i==="*")return!0;let a=WO(i);if(a.startsWith(".")){if(n.endsWith(a)||n===a.slice(1))return!0;continue}if(a.includes("/")&&qO(n)){if(HO(n,a))return!0;continue}if(n===a)return!0;if(a.startsWith("*.")){let u=a.slice(1);if(n.endsWith(u)||n===u.slice(1))return!0}}return!1}function WO(t){if(t.startsWith("[")&&t.includes("]"))return t.slice(1,t.indexOf("]"));if(t.split(":").length-1===1){let[n,r]=t.split(":");if(/^\d+$/.test(r))return n}return t}async function ts(t,e,n,r,o){let s=new Headers({"Content-Type":"application/json"});n.headers&&Object.entries(n.headers).forEach(([p,h])=>{h&&s.set(p,h)});let i=AbortSignal.timeout(n.TIMEOUT??60*1e3*60),a=n.signal?AbortSignal.any([n.signal,i]):i,u={method:"POST",headers:s,body:JSON.stringify(e),signal:a},d=typeof t=="string"?t:t.toString();n.httpsProxy&&!zO(d)&&(u.dispatcher=new LO(new URL(n.httpsProxy).toString()));try{return await fetch(d,u)}catch(p){if(Je(p))throw typeof p=="string"?vn(p):p;if(n.signal?.aborted&&Je(n.signal.reason??St))throw vn(n.signal.reason??p);if(ar(p)){let h=J(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var fh;function GO(t){fh=t}function ow(){if(fh)try{return fh()}catch{return}}var sw="1.0.64";import{createHash as KO}from"crypto";var ph={type:"ephemeral"};function Ve(t){return t.map(e=>{let n={...e};return Array.isArray(n.content)&&(n.content=n.content.map(r=>{if(r.cache_control){let{cache_control:o,...s}=r;return s}return r})),n.cache_control&&delete n.cache_control,Array.isArray(n.tool_calls)&&(n.tool_calls=n.tool_calls.map(r=>{let{cache_control:o,...s}=r;return s})),n})}function Ye(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function iw(t){return`ccr_${KO("sha256").update(t).digest("hex").slice(0,48)}`}function VO(t){if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}return t}function YO(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
126
+ `):""}function en(t,e){let n=t?.req?.sessionId||VO(e?.metadata?.user_id);if(typeof n=="string"&&n)return iw(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?YO(r.content):"",s=[e.model||"",o].join(`
127
+ `);return s.trim()?iw(s):void 0}function $c(t,e={}){let n=e.maxBreakpoints??4,r=JSON.parse(JSON.stringify(t)),o=[],s=d=>{d&&typeof d=="object"&&d.cache_control&&o.push(d)};(Array.isArray(r.tools)?r.tools:[]).forEach(s),Array.isArray(r.system)?r.system.forEach(s):s(r.system),(Array.isArray(r.messages)?r.messages:[]).forEach(d=>{s(d),Array.isArray(d?.content)&&d.content.forEach(s)});let i=!!r.cache_control,a=Math.max(0,n-(i?1:0));if(o.length>a)for(let d of o.slice(0,o.length-a))delete d.cache_control;let u=Math.min(o.length,a);if(!i&&u<n){let d=o[o.length-1]?.cache_control;r.cache_control=d?.ttl?{type:"ephemeral",ttl:d.ttl}:ph}return r}function yo(t){let e=Ve(t.messages||[]),n=Ye(t.tools);for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o.content=="string"&&o.content){o.content=[{type:"text",text:o.content,cache_control:ph}];break}if(Array.isArray(o.content))for(let s=o.content.length-1;s>=0;s-=1){let i=o.content[s];if(i?.type==="text"&&i.text)return o.content[s]={...i,cache_control:ph},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function qc(t){let e=[];for(let n=0;n<t.length;n++){let r={...t[n]};if(r.role==="assistant"&&r.tool_calls){let o=[],s=[],i=[],a=n+1;for(;a<t.length&&t[a].role==="tool";)i.push(t[a]),a++;r.tool_calls.forEach(u=>{i.some(f=>f.tool_call_id===u.id)?o.push(u):s.push(u.id)}),o.length>0?r.tool_calls=o:delete r.tool_calls,(r.content||r.tool_calls)&&e.push(r)}else if(r.role==="tool"){let o=!1;if(n>0){let s=t[n-1];if(s.role==="assistant"&&s.tool_calls)o=s.tool_calls.some(i=>i.id===r.tool_call_id);else if(s.role==="tool"){for(let i=n-1;i>=0;i--)if(t[i].role!=="tool"){t[i].role==="assistant"&&t[i].tool_calls&&(o=t[i].tool_calls.some(a=>a.id===r.tool_call_id));break}}}o&&e.push(r)}else e.push(r)}return e}function aw(t){let n=(t||"").toLowerCase().match(/(?:^|\/)gpt-(\d+)(?:\.(\d+))?/);if(!n)return!1;let r=Number(n[1]),o=Number(n[2]||0);return r>5||r===5&&o>=6}function cw(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function XO(t){for(let e=t.length-1;e>=0;e-=1)if(cw(t[e]))return e;return-1}function zi(t,e,n){let r={...t,messages:(t.messages||[]).map(s=>({...s,content:Array.isArray(s.content)?s.content.map(i=>({...i})):s.content})),tools:Array.isArray(t.tools)?t.tools.map(s=>s?.function?{...s,function:{...s.function,parameters:{...s.function.parameters}}}:{...s}):t.tools},o=en(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),aw(r.model)){let s=[];r.messages.forEach((i,a)=>{if(i.cache_control){if(typeof i.content=="string"&&i.content)s.push({messageIndex:a});else if(Array.isArray(i.content)){let u=XO(i.content);u>=0&&s.push({messageIndex:a,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,d)=>{u?.cache_control&&cw(u)&&s.push({messageIndex:a,contentIndex:d})})});for(let i of s.slice(-3)){let a=r.messages[i.messageIndex];typeof a.content=="string"?a.content=[{type:"text",text:a.content,prompt_cache_breakpoint:{mode:"explicit"}}]:Array.isArray(a.content)&&i.contentIndex!==void 0&&(a.content[i.contentIndex].prompt_cache_breakpoint={mode:"explicit"})}}return r.messages=Ve(r.messages),r.tools=Ye(r.tools),r}function Hc(t,e){return aw(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function QO(t){return String(t?.name||"").trim().toLowerCase()}function ZO(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function hh(t,e){let n={...t,messages:Ve(t.messages||[]),tools:Ye(t.tools)},r=en(e,t);return r&&(n.prompt_cache_key=r),n}function zc(t,e,n){let r=QO(e),o=ZO(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?zi(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?yo(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?hh(t,n):{...t,messages:Ve(t.messages||[]),tools:Ye(t.tools)}}function Dt(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e||void 0}function Ot(t,e){return e?.type==="disabled"||t?.enabled===!1||Dt(t?.effort)==="none"}function ns(t,e){let n=Dt(t);if(!(!n&&e===void 0))return{...n?{effort:n}:{},enabled:n==="none"?!1:e??!0}}function Wc(t){if(!t.reasoning)return t;let e=Ot(t.reasoning,t.thinking)?"none":Dt(t.reasoning.effort);return e&&(t.reasoning_effort=e),delete t.reasoning,t}function uw(t){let e=Dt(t);if(!(!e||e==="none"))return e==="minimal"?"low":e==="ultra"?"max":e}var Tn=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
128
+ `);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};function lw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function Gc(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=lw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var eP=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function Jc(t){let e={};return t&&t.forEach((n,r)=>{eP.has(r.toLowerCase())||(e[r]=n)}),e}var tP=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),nP=["anthropic-ratelimit-","x-ratelimit-"];function gh(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){if(typeof o!="string"||!o)continue;let s=r.toLowerCase();!(tP.has(s)||nP.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function dw(t,e){let n={};for(let[r,o]of Object.entries(t||{})){if(o===void 0||o==="undefined")continue;let s=r.toLowerCase(),i=s==="authorization"?"Authorization":s==="x-api-key"?"x-api-key":s,a=lw(n,i);a&&delete n[a],n[i]=o}return n["x-api-key"]?delete n.Authorization:!n.Authorization&&e&&(n.Authorization=`Bearer ${e}`),Object.fromEntries(Object.entries(n).filter(r=>typeof r[1]=="string"))}import{createHash as rP}from"crypto";var oP=512,sP=16,iP=4,_o=new Map;function yw(t){let e=JSON.stringify(mh(t))??"";return{hash:rP("sha256").update(e).digest("hex").slice(0,sP),approxTokens:Math.ceil(e.length/iP)}}function _w(t){return yw(t).hash}function mh(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(mh);let e={};for(let n of Object.keys(t).sort())e[n]=mh(t[n]);return e}function bw(t){if(!t||typeof t!="object")return!1;let e=t.cache_control;return!!(e&&typeof e=="object"&&e.type==="ephemeral")}function Cw(t){return!!(t&&typeof t=="object"&&t.prompt_cache_breakpoint)}function yh(t){if(!t||typeof t!="object")return 0;let e=0;if((bw(t)||Cw(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=yh(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=yh(n));return e}function Wi(t,e,n){if(!(!t||typeof t!="object")){if((bw(t)||Cw(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>Wi(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&Wi(o,`${e}.${r}`,n)}}function fw(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=String(n.type||"");r&&e[e.length-1]!==r&&e.push(r)}return e.length?e:void 0}function pw(t){if(!t||typeof t!="object")return;if(t.type==="reasoning"&&typeof t.id=="string"&&t.id)return t.id;let e=t.thinking?.id;return typeof e=="string"&&e?e:void 0}function aP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function _h(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)_h(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&aP(o)?e.add(String(o)):o&&typeof o=="object"&&_h(o,e,n+1)}}function Kc(t,e,n){let r=e,{hash:o,approxTokens:s}=yw(e);return{path:t,...n?.role?{role:n.role}:{},...n?.type?{type:n.type}:{},...typeof r?.role=="string"&&!n?.role?{role:r.role}:{},...typeof r?.type=="string"&&!n?.type?{type:r.type}:{},hash:o,approxTokens:s,breakpoints:yh(e),...pw(r)?{reasoningId:pw(r)}:{}}}function cP(t,e){for(_o.has(t)&&_o.delete(t),_o.set(t,e);_o.size>oP;){let n=_o.keys().next().value;if(n===void 0)break;_o.delete(n)}}function uP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=Kc("system",t.system,{type:"system"});o=p.hash,n.push(p),Wi(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=Kc("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=Kc("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),Wi(t.tools,"tools",r)}let i=Array.isArray(t.messages)?{key:"messages",items:t.messages}:Array.isArray(t.input)?{key:"input",items:t.input}:Array.isArray(t.contents)?{key:"contents",items:t.contents}:void 0,a;i&&i.items.forEach((p,h)=>{let g=`${i.key}[${h}]`;n.push(Kc(g,p)),Wi(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=fw(p.content)||fw(p.parts)||a)});let u=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:typeof t.session_id=="string"&&t.session_id?t.session_id:void 0,d=e?Object.fromEntries(Object.entries(e).filter(([,p])=>typeof p=="string"&&p)):void 0;if(n.length===0&&!u&&!(d&&Object.keys(d).length))return null;let f=new Set;return _h(i?.items,f),{createdAt:Date.now(),...typeof t.model=="string"?{model:t.model}:{},...u?{prompt_cache_key:u}:{},...typeof t.session_id=="string"?{session_id:t.session_id}:{},...d&&Object.keys(d).length?{affinity:d}:{},...a?{lastAssistantBlockOrder:a}:{},breakpointPaths:r,...o?{systemHash:o}:{},...s?{toolsHash:s}:{},approxTokens:n.reduce((p,h)=>p+h.approxTokens,0),unstableIds:[...f],segments:n}}function hw(t){if(t)return{path:t.path,...t.role?{role:t.role}:{},...t.type?{type:t.type}:{},approxTokens:t.approxTokens,breakpoints:t.breakpoints,...t.reasoningId?{reasoningId:t.reasoningId}:{}}}function gw(t){return t?_w(t):""}function mw(t){return t.reduce((e,n)=>e+n.approxTokens,0)}function lP(t,e,n,r){let o=r?.stage??"wire",s=r?.conversationIdSource??"session",i=n.unstableIds.length?{unstableIds:n.unstableIds.slice(0,8)}:{};if(!e)return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!0,prefixIntact:!0,change:"none",unchangedPrefixCount:n.segments.length,previousSegmentCount:0,currentSegmentCount:n.segments.length,unchangedPrefixApproxTokens:n.approxTokens,approxPrefixTokensLost:0,prompt_cache_keyChanged:!1,affinityChanged:!1,lastAssistantBlockOrderChanged:!1,modelChanged:!1,systemHashChanged:!1,toolsHashChanged:!1,breakpointsMoved:!1,...i};let a=(e.prompt_cache_key||"")!==(n.prompt_cache_key||""),u=gw(e.affinity)!==gw(n.affinity),d=JSON.stringify(e.lastAssistantBlockOrder||[])!==JSON.stringify(n.lastAssistantBlockOrder||[]),f=(e.model||"")!==(n.model||""),p=(e.systemHash||"")!==(n.systemHash||""),h=(e.toolsHash||"")!==(n.toolsHash||""),g=JSON.stringify(e.breakpointPaths)!==JSON.stringify(n.breakpointPaths),b=e.segments,m=n.segments,w=Math.min(b.length,m.length),C=0;for(;C<w&&b[C].path===m[C].path&&b[C].hash===m[C].hash;)C+=1;let S=C===b.length&&m.length>=b.length,k="none",E,x,O,q;C<w?(k="modified",E=m[C]?.path||b[C]?.path,q={previous:hw(b[C]),current:hw(m[C])}):m.length>b.length?(k="appended",x=m.slice(C).map(U=>U.path)):m.length<b.length&&(k="removed",O=b.slice(C).map(U=>U.path),E=b[C]?.path),k==="none"&&(a||u||d||f||g)&&(k="modified"),E||(a?E="prompt_cache_key":u?E="affinity":f?E="model":d?E="lastAssistantBlockOrder":g&&(E="breakpointPaths"));let V=k==="modified"||k==="removed"?mw(b.slice(C)):0;return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!1,prefixIntact:S&&!a&&!u&&!f,change:k,unchangedPrefixCount:C,previousSegmentCount:b.length,currentSegmentCount:m.length,unchangedPrefixApproxTokens:mw(m.slice(0,C)),approxPrefixTokensLost:V,msSinceLastTurn:Math.max(0,n.createdAt-e.createdAt),prompt_cache_keyChanged:a,affinityChanged:u,lastAssistantBlockOrderChanged:d,modelChanged:f,systemHashChanged:p,toolsHashChanged:h,breakpointsMoved:g,...i,...E?{firstDivergencePath:E}:{},...q?{firstDivergence:q}:{},...x?{appendedPaths:x}:{},...O?{removedPaths:O}:{},...a?{prompt_cache_key:{previous:e.prompt_cache_key,current:n.prompt_cache_key}}:{},...u?{affinity:{previous:e.affinity,current:n.affinity}}:{},...d?{lastAssistantBlockOrder:{previous:e.lastAssistantBlockOrder,current:n.lastAssistantBlockOrder}}:{}}}function dP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${_w([t.systemHash||"",t.toolsHash||"",e?.hash||""])}`}function fP(t,e){return typeof t=="string"&&t?{id:t,source:"session"}:e.prompt_cache_key?{id:e.prompt_cache_key,source:"cache_key"}:{id:dP(e),source:"fingerprint"}}function ww(t,e,n,r){let o=uP(e,n);if(!o)return null;let s=r?.stage??"wire",{id:i,source:a}=fP(t,o),u=[s,r?.provider||"-",r?.model||o.model||"-",i].join("|"),d=_o.get(u),f=lP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&cP(u,o),f}function bh(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function Ch(t){if(!t||typeof t.debug!="function")return!1;if(typeof t.isLevelEnabled=="function")try{return t.isLevelEnabled("debug")===!0}catch{return!1}let e=typeof t.level=="string"?t.level.toLowerCase():"";return e==="debug"||e==="trace"?!0:typeof t.levelVal=="number"?t.levelVal<=20:!("level"in t)&&!("levelVal"in t)}function kw(t,e){let n=Jc(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function pP(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function Vc(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??Lc,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:ah(e,o)}),n!==void 0&&r.debug({...s,response:Zo(n),tppe:"Original Response"})}function At(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Sw(t,e){if(!e||typeof e!="object")return t;let n=e,r=[n.usage,n.message?.usage,n.response?.usage,n.usageMetadata].filter(s=>s&&typeof s=="object"),o=t;for(let s of r){let i=$t($t(At(s.cache_read_input_tokens),At(s.prompt_tokens_details?.cached_tokens)),$t($t(At(s.input_tokens_details?.cached_tokens),At(s.cachedContentTokenCount)),At(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||At(s.cache_read_input_tokens)!==void 0||At(s.cache_creation_input_tokens)!==void 0,promptTokens:$t(o.promptTokens,$t($t(At(s.input_tokens),At(s.prompt_tokens)),At(s.promptTokenCount))),cachedTokens:$t(o.cachedTokens,i),cacheWriteTokens:$t(o.cacheWriteTokens,At(s.cache_creation_input_tokens)),outputTokens:$t(o.outputTokens,$t($t(At(s.output_tokens),At(s.completion_tokens)),At(s.candidatesTokenCount)))}}return o}function hP(t,e){return e===void 0?"unknown":!t||t.firstTurn?e>0?"warm-start":"cold":t.prefixIntact?e>0?"hit":"unexpected-miss":e>0?"partial":"expected-miss"}function wh(t,e){if(!Ch(t.logger))return;let n=t.cacheDiff,r=e.cachedTokens,o=e.promptTokens,s=o===void 0?void 0:e.cachedExcludedFromPrompt?o+(r||0)+(e.cacheWriteTokens||0):o,i=r===void 0||!s?void 0:Math.round(r/s*1e3)/1e3;if(r===void 0&&o===void 0&&!n)return;let a=n?bh(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:hP(n,i),...t.model?{model:t.model}:{},...t.responseStatus?{status:t.responseStatus}:{},...n?{conversationId:n.conversationId,conversationIdSource:n.conversationIdSource,predictedChange:n.change,prefixIntact:n.prefixIntact,...n.firstDivergencePath?{firstDivergencePath:n.firstDivergencePath}:{},approxPrefixTokensLost:n.approxPrefixTokensLost,...n.msSinceLastTurn!==void 0?{msSinceLastTurn:n.msSinceLastTurn}:{},...a?{divergenceStage:a}:{}}:{},...s!==void 0?{promptTokens:s}:{},...r!==void 0?{cachedTokens:r}:{},...e.cacheWriteTokens!==void 0?{cacheWriteTokens:e.cacheWriteTokens}:{},...e.outputTokens!==void 0?{outputTokens:e.outputTokens}:{},...i!==void 0?{cacheHitRatio:i}:{}})}function gP(t,e){(async()=>{let r=t.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader(),o={cachedExcludedFromPrompt:!1},s=()=>new Promise(i=>setImmediate(i));try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(!a||typeof a!="object")continue;let u=a;if(u.data==null)continue;if(typeof u.data=="object"&&u.data.type==="done"){Vc(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);Vc(e,f),await s();continue}o=Sw(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}Vc(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}wh(e,o)}})()}async function mP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return Vc(e,n,r),wh(e,Sw({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:kw(t.headers,"application/json")})}async function Aw(t,e){if(!Ch(e.logger)||!t.body)return t;let n=pP(t);if(n.includes("application/json"))try{return await mP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return wh(e,{cachedExcludedFromPrompt:!1}),t;try{let r=yP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:kw(t.headers,"text/event-stream")})}catch{return t}}function yP(t,e){let n=new TransformStream(void 0,{highWaterMark:1/0},{highWaterMark:1}),r=n.writable.getWriter();gP(n.readable,e);let o=!0,s=()=>{o&&(o=!1,r.close().catch(()=>{}))};return t.pipeThrough(new TransformStream({transform(i,a){a.enqueue(i),o&&r.write(i.slice()).catch(()=>{s()})},flush(){s()},cancel(){s()}}))}function Gi(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function _P(t){return Array.isArray(t)?t.reduce((e,n)=>e+Gi(n),0):0}function bP(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(!n||typeof n!="object")continue;let r=String(n.type||"");r&&e[e.length-1]!==r&&e.push(r)}return e.length?e:void 0}function CP(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=Gi(i);else t.system&&typeof t.system=="object"&&(e+=Gi(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=Gi(i),n+=_P(i.content),i.role==="assistant"&&(r=bP(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=Gi(i);let s=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:void 0;return e===0&&n===0&&o===0&&!s&&!r?null:{systemBreakpoints:e,messageBreakpoints:n,toolBreakpoints:o,...s?{prompt_cache_key:s}:{},...r?{lastAssistantBlockOrder:r}:{}}}function kh(t,e){if(!Ch(e.logger))return null;let n=CP(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=ww(e.conversationId,t,e.cacheAffinity,{stage:e.stage??"wire",provider:e.provider,model:e.model,commit:r===void 0||r>=200&&r<300});if(!o)return null;let s=bh(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var wP=new TextEncoder().encode(`: keepalive
129
129
 
130
- `);function Ah(t,e){let n=e?.idleMs??1e4;if(!(n>0))return t;let r=null,o=null,s=!1,i=()=>{r&&(clearTimeout(r),r=null)};return new ReadableStream({async start(a){o=t.getReader();let u=()=>{i(),!s&&(r=setTimeout(()=>{if(r=null,!s){try{a.enqueue(CP)}catch{s=!0;return}u()}},n))};u();try{for(;!s;){let{done:d,value:f}=await o.read();if(d)break;f&&f.byteLength>0&&(a.enqueue(f),u())}i(),s||a.close()}catch(d){if(i(),!s)try{a.error(d)}catch{}}finally{i();try{o?.releaseLock()}catch{}}},cancel(a){s=!0,i();let u=o;return o=null,u?u.cancel(a).catch(()=>{}):t.cancel(a).catch(()=>{})}})}function Yc(t){if(/^\s*\[DONE\]/.test(t)&&!t.includes("data:"))return["data: [DONE]",""];let e=t.indexOf("data:");if(e<0)return[t];let n=t.slice(0,e),r=t.slice(e+5).trim();if(!r)return[t];if(r.startsWith("[DONE]"))return[`${n}data: [DONE]`,""];let o=wP(r);if(o<0)return[t];let s=r.slice(0,o).trimEnd();return s?[`${n}data: ${s}`,"",`${n}data: [DONE]`,""]:[`${n}data: [DONE]`,""]}function wP(t){let e="[DONE]",n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r<0)return-1;let o=t.slice(0,r).trimEnd();if(!o)return r;try{return JSON.parse(o),r}catch{n=r+e.length}}return-1}function Xc(t){return/^data:\s*\[DONE\]\s*$/.test(t)||/^\s*\[DONE\]\s*$/.test(t)}function Qc(t){t.push(""),t.push("data: [DONE]"),t.push("")}function Eh(t){let e=new TextDecoder,n=new TextEncoder,r="",o=!1,s=null,i=(a,u=!1)=>{if(o)return"";r+=a;let d=r.split(/\r?\n/);r=u?"":d.pop()||"";let f=[],p=h=>{if(!o)for(let g of Yc(h)){if(o)return;if(Xc(g)){Qc(f),o=!0;return}f.push(g)}};for(let h of d)p(h);return u&&r&&(p(r),r=""),f.length?`${f.join(`
130
+ `);function Sh(t,e){let n=e?.idleMs??1e4;if(!(n>0))return t;let r=null,o=null,s=!1,i=()=>{r&&(clearTimeout(r),r=null)};return new ReadableStream({async start(a){o=t.getReader();let u=()=>{i(),!s&&(r=setTimeout(()=>{if(r=null,!s){try{a.enqueue(wP)}catch{s=!0;return}u()}},n))};u();try{for(;!s;){let{done:d,value:f}=await o.read();if(d)break;f&&f.byteLength>0&&(a.enqueue(f),u())}i(),s||a.close()}catch(d){if(i(),!s)try{a.error(d)}catch{}}finally{i();try{o?.releaseLock()}catch{}}},cancel(a){s=!0,i();let u=o;return o=null,u?u.cancel(a).catch(()=>{}):t.cancel(a).catch(()=>{})}})}function Yc(t){if(/^\s*\[DONE\]/.test(t)&&!t.includes("data:"))return["data: [DONE]",""];let e=t.indexOf("data:");if(e<0)return[t];let n=t.slice(0,e),r=t.slice(e+5).trim();if(!r)return[t];if(r.startsWith("[DONE]"))return[`${n}data: [DONE]`,""];let o=kP(r);if(o<0)return[t];let s=r.slice(0,o).trimEnd();return s?[`${n}data: ${s}`,"",`${n}data: [DONE]`,""]:[`${n}data: [DONE]`,""]}function kP(t){let e="[DONE]",n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r<0)return-1;let o=t.slice(0,r).trimEnd();if(!o)return r;try{return JSON.parse(o),r}catch{n=r+e.length}}return-1}function Xc(t){return/^data:\s*\[DONE\]\s*$/.test(t)||/^\s*\[DONE\]\s*$/.test(t)}function Qc(t){t.push(""),t.push("data: [DONE]"),t.push("")}function Ah(t){let e=new TextDecoder,n=new TextEncoder,r="",o=!1,s=null,i=(a,u=!1)=>{if(o)return"";r+=a;let d=r.split(/\r?\n/);r=u?"":d.pop()||"";let f=[],p=h=>{if(!o)for(let g of Yc(h)){if(o)return;if(Xc(g)){Qc(f),o=!0;return}f.push(g)}};for(let h of d)p(h);return u&&r&&(p(r),r=""),f.length?`${f.join(`
131
131
  `)}
132
- `:""};return new ReadableStream({async start(a){s=t.getReader();try{for(;!o;){let{done:u,value:d}=await s.read();if(u){let p=i(e.decode(),!0);p&&a.enqueue(n.encode(p)),a.close();return}let f=i(e.decode(d,{stream:!0}));f&&a.enqueue(n.encode(f))}await s.cancel(),a.close()}catch(u){try{a.error(u)}catch{}}finally{try{s?.releaseLock()}catch{}}},cancel(a){let u=s;return s=null,u?u.cancel(a).catch(()=>{}):t.cancel(a).catch(()=>{})}})}async function Ew(t,e,n){let r=await t(e);if(r.status!==401||typeof n!="function")return r;let o=await n();if(!o)return r;try{await r.body?.cancel()}catch{}return Object.assign(e,o),t(e)}import{RATE_LIMIT_CONFIG as hs}from"@caeliq/ccr-shared";var vw=[{protocol:"anthropic_messages",canonicalPath:"/v1/messages",aliases:[],ownerTransformerName:"Anthropic"},{protocol:"openai_chat_completions",canonicalPath:"/v1/chat/completions",aliases:["/chat/completions"],ownerTransformerName:"OpenAI"},{protocol:"openai_responses",canonicalPath:"/v1/responses",aliases:["/responses"],ownerTransformerName:"openai-responses"}],kP=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],SP=/^\/preset\/[^/]+/;function AP(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function EP(t){let e=t.match(SP);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function vP(t){return kP.some(e=>t===e)}function TP(t){for(let e of vw){let n=[e.canonicalPath,...e.aliases];for(let r of n)if(t===r)return{protocol:e.protocol,canonicalPath:e.canonicalPath,matchedPath:r,ownerTransformerName:e.ownerTransformerName,isAlias:r!==e.canonicalPath,stream:!!e.defaultStream}}return null}function cr(t,e){if(t.toUpperCase()!=="POST")return null;let n=AP(e),{suffix:r,presetPrefix:o}=EP(n);if(vP(r))return null;let s=TP(r);return s?{...s,presetPrefix:o}:null}function xP(t,e){return cr(t,e)!==null}function vh(){let t=[];for(let e of vw){t.push({path:e.canonicalPath,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!0});for(let n of e.aliases)t.push({path:n,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!1})}return t}function Tw(t,e){return{protocol:t.protocol,pathname:t.matchedPath,canonicalPath:t.canonicalPath,matchedPath:t.matchedPath,originalModel:e?.originalModel,stream:e?.stream??t.stream,scenarioType:e?.scenarioType,ownerTransformerName:t.ownerTransformerName}}import{createHash as IP}from"crypto";import{createHash as RP}from"crypto";var xw=/^[a-zA-Z0-9_-]+$/,Rw=/[^a-zA-Z0-9_-]+/g,Dw=256;function DP(t){return t.length>0&&t.length<=Dw&&xw.test(t)}function Th(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function ur(t){if(typeof t!="string"||t.length===0)return;if(DP(t))return t;let e=Th(t.replace(Rw,"_").slice(0,Dw));return e.length?e:void 0}var Ow=64,Pw=20,OP=Ow-Pw-1;function PP(t){return t.length>0&&t.length<=Ow&&xw.test(t)}function _t(t){if(typeof t!="string"||t.length===0)return;if(PP(t))return t;let e=Th(t.replace(Rw,"_")),n=Th(e.slice(0,OP))||"call",r=RP("sha256").update(t,"utf8").digest("base64url").slice(0,Pw);return`${n}_${r}`}function rs(){return{forward:new Map,reverse:new Map}}function bo(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=_t(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=_t(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=_t(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function Zc(t,e=rs(),n=new Set){if(!t||typeof t!="object")throw J("Invalid Responses body",400,"invalid_body");if(typeof t.model!="string"||!t.model.trim())throw J("Responses requires model",400,"invalid_body","invalid_request_error");if(FP(t),t.stream!==void 0&&typeof t.stream!="boolean")throw J("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.instructions!==void 0&&typeof t.instructions!="string")throw J("instructions must be a string",400,"invalid_instructions","invalid_request_error");if(t.max_tokens!==void 0)throw J("Responses uses max_output_tokens, not max_tokens",400,"unsupported_field","invalid_request_error");if(t.max_output_tokens!=null){let f=Number(t.max_output_tokens);if(!Number.isInteger(f)||f<=0)throw J("max_output_tokens must be a positive integer",400,"invalid_token_limit","invalid_request_error")}if(t.reasoning!==void 0&&(t.reasoning===null||typeof t.reasoning!="object"||Array.isArray(t.reasoning)))throw J("reasoning must be an object",400,"invalid_reasoning","invalid_request_error");if(t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw J("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");if(t.prompt_cache_key!==void 0&&typeof t.prompt_cache_key!="string")throw J("prompt_cache_key must be a string",400,"invalid_prompt_cache_key","invalid_request_error");let r;if(t.text?.format&&t.text.format.type!=="text"){let f=t.text.format;if(f.type==="json_schema")r={type:"json_schema",json_schema:{name:f.name,schema:f.schema,...f.strict!==void 0?{strict:f.strict}:{}}};else if(f.type==="json_object")r={type:"json_object"};else throw J(`Structured text formats are not supported without a verified mapping (received text.format.type=${JSON.stringify(f.type)})`,400,"unsupported_response_format","invalid_request_error")}for(let f of["metadata","max_tool_calls","service_tier","safety_identifier","top_logprobs","truncation"])if(t[f]!==void 0&&t[f]!==null)throw J(`Responses field '${f}' is not supported`,400,"unsupported_field","invalid_request_error");let o=[];typeof t.instructions=="string"&&t.instructions&&o.push({role:"system",content:t.instructions});let s=t.input;if(typeof s=="string")o.push({role:"user",content:s});else if(Array.isArray(s)){if(s.length===0)throw J("Responses input[] must not be empty",400,"invalid_input","invalid_request_error");for(let f of s)jP(o,f,e)}else throw J("Responses requires string input or input[]",400,"invalid_input","invalid_request_error");if(o.length===0)throw J("Responses input did not contain a supported item",400,"invalid_input","invalid_request_error");let i=$P(t.tools,n),a=qP(t.tool_choice),u=t.reasoning&&typeof t.reasoning=="object"?{...ns(t.reasoning.effort,!0),summary:t.reasoning.summary}:void 0,d={model:t.model,messages:o,tools:i,tool_choice:a,stream:t.stream===!0,temperature:t.temperature,top_p:t.top_p,max_tokens:t.max_output_tokens??t.max_tokens,reasoning:u,parallel_tool_calls:t.parallel_tool_calls};return typeof t.prompt_cache_key=="string"&&(d.prompt_cache_key=t.prompt_cache_key),r&&(d.response_format=r),d}function FP(t){if(t.store===!0)throw J("store: true is not supported; CCR does not own Responses state",400,"unsupported_store","invalid_request_error");if(t.previous_response_id)throw J("previous_response_id is not supported",400,"unsupported_previous_response_id","invalid_request_error");if(t.conversation)throw J("conversation is not supported",400,"unsupported_conversation","invalid_request_error");if(t.background===!0)throw J("background: true is not supported",400,"unsupported_background","invalid_request_error");if(Array.isArray(t.tools))for(let e of t.tools){let n=e?.type;if(typeof n!="string"||!n)throw J("Responses tools require a type",400,"invalid_tool","invalid_request_error")}}function NP(t){return t?.content===null||t?.content===void 0||t?.content===""}function Iw(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"&&NP(n)){if(Array.isArray(n.tool_calls)&&n.tool_calls.length>0){n.tool_calls.push(e);return}if(n.thinking&&!n.tool_calls){n.tool_calls=[e];return}}t.push({role:"assistant",content:null,tool_calls:[e]})}function MP(t){return typeof t?.content=="string"&&t.content?t.content:typeof t?.reasoning=="string"&&t.reasoning?t.reasoning:Array.isArray(t?.summary)?t.summary.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
133
- `):""}var BP=/^rs_[A-Za-z0-9]+$/;function lr(t){return typeof t=="string"&&BP.test(t)}function os(t){if(!(typeof t!="string"||!t)&&!lr(t))return t}function ss(t){let e=typeof t?.signature=="string"?t.signature:"";if(!(!e||lr(e)))return e}function is(t){if(!t||typeof t!="object")return;let e=MP(t),n=os(t.encrypted_content),r=typeof t.id=="string"&&t.id?t.id:lr(t.encrypted_content)?t.encrypted_content:void 0;if(!(!e&&!n&&!r))return{content:e,...n?{encrypted_content:n}:{},...r?{id:r}:{}}}function eu(t,e,n){typeof e!="string"||!e||typeof n!="string"||!n||t.set(e,(t.get(e)||"")+n)}function as(t,e){let n=is(t);if(!n)return;let r=typeof t?.id=="string"&&t.id||n.id;return r&&e.get(r)?!n.encrypted_content&&!n.id?void 0:{content:"",...n.encrypted_content?{encrypted_content:n.encrypted_content}:{},...n.id?{id:n.id}:{}}:(r&&n.content&&e.set(r,n.content),n)}function tu(t){if(!(!t||typeof t!="object")){if(t.type==="json_schema")return{type:"json_schema",name:t.json_schema?.name,schema:t.json_schema?.schema,...t.json_schema?.strict!==void 0?{strict:t.json_schema.strict}:{}};if(typeof t.type=="string"&&t.type)return{type:t.type}}}function Rn(t){if(!t||typeof t!="object")return;let e=typeof t.thinking?.content=="string"?t.thinking.content:"",n=typeof t.reasoning_content=="string"?t.reasoning_content:"",r=e||n,o=typeof t.thinking?.signature=="string"&&t.thinking.signature?t.thinking.signature:void 0,s=os(t.thinking?.encrypted_content),i=typeof t.thinking?.id=="string"&&t.thinking.id||(lr(o)?o:void 0)||(lr(t.thinking?.encrypted_content)?t.thinking.encrypted_content:void 0),a=o&&!lr(o)?o:void 0;if(!(!r&&!a&&!s&&!i))return{content:r,...a?{signature:a}:{},...s?{encrypted_content:s}:{},...i?{id:i}:{}}}function cs(t){let e=[],n=[];if(typeof t?.content=="string"&&t.content)e.push({text:t.content});else if(Array.isArray(t?.content))for(let r of t.content)!r||typeof r!="object"||((r.type==="text"||r.type==="output_text"||r.type==="input_text")&&r.text?e.push({text:r.text,...r.cache_control?{cache_control:r.cache_control}:{}}):(r.type==="image_url"||r.type==="input_image"||r.type==="output_image")&&n.push(r));return{thinking:Rn(t),texts:e,images:n,toolCalls:Array.isArray(t?.tool_calls)?t.tool_calls:[]}}function Ji(t){return t.texts.some(e=>e.text.length>0)}function us(t,e){if(!t||typeof t!="object")return null;let n=typeof t.content=="string"?t.content:"",r=os(t.encrypted_content),o=typeof t.id=="string"&&t.id?t.id:void 0;if(!n&&!r&&!o)return null;let s={type:"reasoning",id:o||e||(n?`rs_${IP("sha256").update(n).digest("hex").slice(0,24)}`:"rs_anon"),summary:n?[{type:"summary_text",text:n}]:[]};return r&&(s.encrypted_content=r),s}function UP(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"){n.thinking=e;return}t.push({role:"assistant",content:null,thinking:e})}function jP(t,e,n){if(!e||typeof e!="object")throw J("Invalid Responses input item",400,"invalid_input_item","invalid_request_error");if(e.type==="reasoning"){let r=is(e);r&&UP(t,r);return}if(e.type==="function_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("function_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="function_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("function_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("function_call requires name",400,"invalid_function_call","invalid_request_error");Iw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:typeof e.arguments=="string"?e.arguments:JSON.stringify(e.arguments??{})}});return}if(e.type==="custom_tool_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("custom_tool_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="custom_tool_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("custom_tool_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("custom_tool_call requires name",400,"invalid_function_call","invalid_request_error");if(typeof e.input!="string")throw J("custom_tool_call requires string input",400,"invalid_custom_tool_input","invalid_request_error");Iw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:JSON.stringify({[xn]:e.input})}});return}if(e.type==="message"||e.role){let r=e.role==="assistant"?"assistant":e.role==="system"||e.role==="developer"?"system":e.role==="user"?"user":void 0;if(!r)throw J(`Unsupported Responses message role '${e.role}'`,400,"unsupported_role","invalid_request_error");if(typeof e.content!="string"&&!Array.isArray(e.content))throw J("Responses message items require string or array content",400,"invalid_content","invalid_request_error");t.push({role:r,content:LP(e.content)});return}if(e.type==="input_text"||e.type==="output_text"){t.push({role:e.type==="output_text"?"assistant":"user",content:String(e.text??"")});return}if(e.type==="input_image"){if(e.file_id)throw J("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=e.image_url||e.url;if(typeof r!="string"||!r)throw J("input_image requires image_url",400,"invalid_image","invalid_request_error");t.push({role:"user",content:[{type:"image_url",image_url:{url:r,...e.detail?{detail:e.detail}:{}}}]});return}throw J(`Unsupported Responses input item type '${e.type||"unknown"}'`,400,"unsupported_input_item","invalid_request_error")}function LP(t){if(typeof t=="string")return t;if(!Array.isArray(t))return t==null?"":JSON.stringify(t);let e=[];for(let n of t){if(typeof n=="string"){e.push({type:"text",text:n});continue}if(!(!n||typeof n!="object"))if(n.type==="input_text"||n.type==="output_text"||n.type==="text")e.push({type:"text",text:String(n.text??"")});else if(n.type==="input_image"||n.type==="image_url"){if(n.file_id)throw J("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=n.image_url?.url||n.image_url||n.url;if(typeof r!="string"||!r)throw J("input_image requires image_url",400,"invalid_image","invalid_request_error");e.push({type:"image_url",image_url:{url:r,...n.detail?{detail:n.detail}:{}}})}else throw J(`Unsupported Responses content part '${n.type||"unknown"}'`,400,"unsupported_content_part","invalid_request_error")}return e.length===1&&e[0].type==="text"?e[0].text:e.length>0?e:""}var xn="input";function Fw(t){let e=t.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return e?e[2]:t}function nu(t){return!t.includes("*** Begin Patch ***")&&!t.includes("*** End Patch ***")?t:t.split("*** Begin Patch ***").join("*** Begin Patch").split("*** End Patch ***").join("*** End Patch")}function Nw(t,e){if(t!=="exec")return e;let n=e.trim();if(!n.startsWith("{")||!n.endsWith("}"))return e;let r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object"||Array.isArray(r))return e;let o="cmd"in r?"cmd":"command"in r?"command":null;if(!o)return e;let s=r[o];return typeof s!="string"||!s?e:(delete r[o],r.cmd=s,`await tools.exec_command(${JSON.stringify(r)});`)}function Mw(t,e){if(t!=="exec")return e;let n=e.match(/^apply_patch\s*<<\s*['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return n?`await tools.apply_patch(${JSON.stringify(n[2])});`:e}function xh(t,e,n){if(!Bw(n)||t!=="exec")return e;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.input=="string")return r.input=Mw(t,Nw(t,r.input)),JSON.stringify(r)}catch{}return e}function Rh(t){if(!t)return"";try{let n=JSON.parse(t)?.[xn];if(typeof n=="string")return Fw(n)}catch{}return Fw(t)}function Bw(t){return t?.codexIsolateConventions!==!1}function Dh(t,e,n){let r=Rh(e);return Bw(n)&&(r=Mw(t,Nw(t,r))),nu(r)}function $P(t,e){if(t!=null){if(!Array.isArray(t))throw J("Responses tools must be an array",400,"invalid_tools","invalid_request_error");return t.map(n=>{let r=typeof n?.type=="string"?n.type:"",o=n?.name||n?.function?.name;if(r==="web_search"||r==="web_search_preview"?o="web_search":!o&&r&&r!=="function"&&r!=="custom"&&(o=r),typeof o!="string"||!o)throw J("Responses function tools require a name",400,"invalid_tool","invalid_request_error");if(r==="custom"){e?.add(o);let s=n.description||n.function?.description||"";return{type:"function",function:{name:o,description:s&&`${s}
132
+ `:""};return new ReadableStream({async start(a){s=t.getReader();try{for(;!o;){let{done:u,value:d}=await s.read();if(u){let p=i(e.decode(),!0);p&&a.enqueue(n.encode(p)),a.close();return}let f=i(e.decode(d,{stream:!0}));f&&a.enqueue(n.encode(f))}await s.cancel(),a.close()}catch(u){try{a.error(u)}catch{}}finally{try{s?.releaseLock()}catch{}}},cancel(a){let u=s;return s=null,u?u.cancel(a).catch(()=>{}):t.cancel(a).catch(()=>{})}})}async function Ew(t,e,n){let r=await t(e);if(r.status!==401||typeof n!="function")return r;let o=await n();if(!o)return r;try{await r.body?.cancel()}catch{}return Object.assign(e,o),t(e)}import{RATE_LIMIT_CONFIG as hs}from"@caeliq/ccr-shared";var vw=[{protocol:"anthropic_messages",canonicalPath:"/v1/messages",aliases:[],ownerTransformerName:"Anthropic"},{protocol:"openai_chat_completions",canonicalPath:"/v1/chat/completions",aliases:["/chat/completions"],ownerTransformerName:"OpenAI"},{protocol:"openai_responses",canonicalPath:"/v1/responses",aliases:["/responses"],ownerTransformerName:"openai-responses"}],SP=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],AP=/^\/preset\/[^/]+/;function EP(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function vP(t){let e=t.match(AP);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function TP(t){return SP.some(e=>t===e)}function xP(t){for(let e of vw){let n=[e.canonicalPath,...e.aliases];for(let r of n)if(t===r)return{protocol:e.protocol,canonicalPath:e.canonicalPath,matchedPath:r,ownerTransformerName:e.ownerTransformerName,isAlias:r!==e.canonicalPath,stream:!!e.defaultStream}}return null}function cr(t,e){if(t.toUpperCase()!=="POST")return null;let n=EP(e),{suffix:r,presetPrefix:o}=vP(n);if(TP(r))return null;let s=xP(r);return s?{...s,presetPrefix:o}:null}function RP(t,e){return cr(t,e)!==null}function Eh(){let t=[];for(let e of vw){t.push({path:e.canonicalPath,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!0});for(let n of e.aliases)t.push({path:n,protocol:e.protocol,ownerTransformerName:e.ownerTransformerName,isCanonical:!1})}return t}function Tw(t,e){return{protocol:t.protocol,pathname:t.matchedPath,canonicalPath:t.canonicalPath,matchedPath:t.matchedPath,originalModel:e?.originalModel,stream:e?.stream??t.stream,scenarioType:e?.scenarioType,ownerTransformerName:t.ownerTransformerName}}import{createHash as FP}from"crypto";import{createHash as DP}from"crypto";var xw=/^[a-zA-Z0-9_-]+$/,Rw=/[^a-zA-Z0-9_-]+/g,Dw=256;function OP(t){return t.length>0&&t.length<=Dw&&xw.test(t)}function vh(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function ur(t){if(typeof t!="string"||t.length===0)return;if(OP(t))return t;let e=vh(t.replace(Rw,"_").slice(0,Dw));return e.length?e:void 0}var Ow=64,Pw=20,PP=Ow-Pw-1;function IP(t){return t.length>0&&t.length<=Ow&&xw.test(t)}function _t(t){if(typeof t!="string"||t.length===0)return;if(IP(t))return t;let e=vh(t.replace(Rw,"_")),n=vh(e.slice(0,PP))||"call",r=DP("sha256").update(t,"utf8").digest("base64url").slice(0,Pw);return`${n}_${r}`}function rs(){return{forward:new Map,reverse:new Map}}function bo(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=_t(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=_t(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=_t(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function Zc(t,e=rs(),n=new Set){if(!t||typeof t!="object")throw J("Invalid Responses body",400,"invalid_body");if(typeof t.model!="string"||!t.model.trim())throw J("Responses requires model",400,"invalid_body","invalid_request_error");if(NP(t),t.stream!==void 0&&typeof t.stream!="boolean")throw J("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.instructions!==void 0&&typeof t.instructions!="string")throw J("instructions must be a string",400,"invalid_instructions","invalid_request_error");if(t.max_tokens!==void 0)throw J("Responses uses max_output_tokens, not max_tokens",400,"unsupported_field","invalid_request_error");if(t.max_output_tokens!=null){let f=Number(t.max_output_tokens);if(!Number.isInteger(f)||f<=0)throw J("max_output_tokens must be a positive integer",400,"invalid_token_limit","invalid_request_error")}if(t.reasoning!==void 0&&(t.reasoning===null||typeof t.reasoning!="object"||Array.isArray(t.reasoning)))throw J("reasoning must be an object",400,"invalid_reasoning","invalid_request_error");if(t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw J("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");if(t.prompt_cache_key!==void 0&&typeof t.prompt_cache_key!="string")throw J("prompt_cache_key must be a string",400,"invalid_prompt_cache_key","invalid_request_error");let r;if(t.text?.format&&t.text.format.type!=="text"){let f=t.text.format;if(f.type==="json_schema")r={type:"json_schema",json_schema:{name:f.name,schema:f.schema,...f.strict!==void 0?{strict:f.strict}:{}}};else if(f.type==="json_object")r={type:"json_object"};else throw J(`Structured text formats are not supported without a verified mapping (received text.format.type=${JSON.stringify(f.type)})`,400,"unsupported_response_format","invalid_request_error")}for(let f of["metadata","max_tool_calls","service_tier","safety_identifier","top_logprobs","truncation"])if(t[f]!==void 0&&t[f]!==null)throw J(`Responses field '${f}' is not supported`,400,"unsupported_field","invalid_request_error");let o=[];typeof t.instructions=="string"&&t.instructions&&o.push({role:"system",content:t.instructions});let s=t.input;if(typeof s=="string")o.push({role:"user",content:s});else if(Array.isArray(s)){if(s.length===0)throw J("Responses input[] must not be empty",400,"invalid_input","invalid_request_error");for(let f of s)LP(o,f,e)}else throw J("Responses requires string input or input[]",400,"invalid_input","invalid_request_error");if(o.length===0)throw J("Responses input did not contain a supported item",400,"invalid_input","invalid_request_error");let i=qP(t.tools,n),a=HP(t.tool_choice),u=t.reasoning&&typeof t.reasoning=="object"?{...ns(t.reasoning.effort,!0),summary:t.reasoning.summary}:void 0,d={model:t.model,messages:o,tools:i,tool_choice:a,stream:t.stream===!0,temperature:t.temperature,top_p:t.top_p,max_tokens:t.max_output_tokens??t.max_tokens,reasoning:u,parallel_tool_calls:t.parallel_tool_calls};return typeof t.prompt_cache_key=="string"&&(d.prompt_cache_key=t.prompt_cache_key),r&&(d.response_format=r),d}function NP(t){if(t.store===!0)throw J("store: true is not supported; CCR does not own Responses state",400,"unsupported_store","invalid_request_error");if(t.previous_response_id)throw J("previous_response_id is not supported",400,"unsupported_previous_response_id","invalid_request_error");if(t.conversation)throw J("conversation is not supported",400,"unsupported_conversation","invalid_request_error");if(t.background===!0)throw J("background: true is not supported",400,"unsupported_background","invalid_request_error");if(Array.isArray(t.tools))for(let e of t.tools){let n=e?.type;if(typeof n!="string"||!n)throw J("Responses tools require a type",400,"invalid_tool","invalid_request_error")}}function MP(t){return t?.content===null||t?.content===void 0||t?.content===""}function Iw(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"&&MP(n)){if(Array.isArray(n.tool_calls)&&n.tool_calls.length>0){n.tool_calls.push(e);return}if(n.thinking&&!n.tool_calls){n.tool_calls=[e];return}}t.push({role:"assistant",content:null,tool_calls:[e]})}function BP(t){return typeof t?.content=="string"&&t.content?t.content:typeof t?.reasoning=="string"&&t.reasoning?t.reasoning:Array.isArray(t?.summary)?t.summary.map(e=>typeof e=="string"?e:typeof e?.text=="string"?e.text:"").filter(Boolean).join(`
133
+ `):""}var jP=/^rs_[A-Za-z0-9]+$/;function lr(t){return typeof t=="string"&&jP.test(t)}function os(t){if(!(typeof t!="string"||!t)&&!lr(t))return t}function ss(t){let e=typeof t?.signature=="string"?t.signature:"";if(!(!e||lr(e)))return e}function is(t){if(!t||typeof t!="object")return;let e=BP(t),n=os(t.encrypted_content),r=typeof t.id=="string"&&t.id?t.id:lr(t.encrypted_content)?t.encrypted_content:void 0;if(!(!e&&!n&&!r))return{content:e,...n?{encrypted_content:n}:{},...r?{id:r}:{}}}function eu(t,e,n){typeof e!="string"||!e||typeof n!="string"||!n||t.set(e,(t.get(e)||"")+n)}function as(t,e){let n=is(t);if(!n)return;let r=typeof t?.id=="string"&&t.id||n.id;return r&&e.get(r)?!n.encrypted_content&&!n.id?void 0:{content:"",...n.encrypted_content?{encrypted_content:n.encrypted_content}:{},...n.id?{id:n.id}:{}}:(r&&n.content&&e.set(r,n.content),n)}function tu(t){if(!(!t||typeof t!="object")){if(t.type==="json_schema")return{type:"json_schema",name:t.json_schema?.name,schema:t.json_schema?.schema,...t.json_schema?.strict!==void 0?{strict:t.json_schema.strict}:{}};if(typeof t.type=="string"&&t.type)return{type:t.type}}}function Rn(t){if(!t||typeof t!="object")return;let e=typeof t.thinking?.content=="string"?t.thinking.content:"",n=typeof t.reasoning_content=="string"?t.reasoning_content:"",r=typeof t.reasoning=="string"?t.reasoning:"",o=e||n||r,s=typeof t.thinking?.signature=="string"&&t.thinking.signature?t.thinking.signature:void 0,i=os(t.thinking?.encrypted_content),a=typeof t.thinking?.id=="string"&&t.thinking.id||(lr(s)?s:void 0)||(lr(t.thinking?.encrypted_content)?t.thinking.encrypted_content:void 0),u=s&&!lr(s)?s:void 0;if(!(!o&&!u&&!i&&!a))return{content:o,...u?{signature:u}:{},...i?{encrypted_content:i}:{},...a?{id:a}:{}}}function cs(t){let e=[],n=[];if(typeof t?.content=="string"&&t.content)e.push({text:t.content});else if(Array.isArray(t?.content))for(let r of t.content)!r||typeof r!="object"||((r.type==="text"||r.type==="output_text"||r.type==="input_text")&&r.text?e.push({text:r.text,...r.cache_control?{cache_control:r.cache_control}:{}}):(r.type==="image_url"||r.type==="input_image"||r.type==="output_image")&&n.push(r));return{thinking:Rn(t),texts:e,images:n,toolCalls:Array.isArray(t?.tool_calls)?t.tool_calls:[]}}function Ji(t){return t.texts.some(e=>e.text.length>0)}function us(t,e){if(!t||typeof t!="object")return null;let n=typeof t.content=="string"?t.content:"",r=os(t.encrypted_content),o=typeof t.id=="string"&&t.id?t.id:void 0;if(!n&&!r&&!o)return null;let s={type:"reasoning",id:o||e||(n?`rs_${FP("sha256").update(n).digest("hex").slice(0,24)}`:"rs_anon"),summary:n?[{type:"summary_text",text:n}]:[]};return r&&(s.encrypted_content=r),s}function UP(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"){n.thinking=e;return}t.push({role:"assistant",content:null,thinking:e})}function LP(t,e,n){if(!e||typeof e!="object")throw J("Invalid Responses input item",400,"invalid_input_item","invalid_request_error");if(e.type==="reasoning"){let r=is(e);r&&UP(t,r);return}if(e.type==="function_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("function_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="function_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("function_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("function_call requires name",400,"invalid_function_call","invalid_request_error");Iw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:typeof e.arguments=="string"?e.arguments:JSON.stringify(e.arguments??{})}});return}if(e.type==="custom_tool_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("custom_tool_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="custom_tool_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("custom_tool_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("custom_tool_call requires name",400,"invalid_function_call","invalid_request_error");if(typeof e.input!="string")throw J("custom_tool_call requires string input",400,"invalid_custom_tool_input","invalid_request_error");Iw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:JSON.stringify({[xn]:e.input})}});return}if(e.type==="message"||e.role){let r=e.role==="assistant"?"assistant":e.role==="system"||e.role==="developer"?"system":e.role==="user"?"user":void 0;if(!r)throw J(`Unsupported Responses message role '${e.role}'`,400,"unsupported_role","invalid_request_error");if(typeof e.content!="string"&&!Array.isArray(e.content))throw J("Responses message items require string or array content",400,"invalid_content","invalid_request_error");t.push({role:r,content:$P(e.content)});return}if(e.type==="input_text"||e.type==="output_text"){t.push({role:e.type==="output_text"?"assistant":"user",content:String(e.text??"")});return}if(e.type==="input_image"){if(e.file_id)throw J("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=e.image_url||e.url;if(typeof r!="string"||!r)throw J("input_image requires image_url",400,"invalid_image","invalid_request_error");t.push({role:"user",content:[{type:"image_url",image_url:{url:r,...e.detail?{detail:e.detail}:{}}}]});return}throw J(`Unsupported Responses input item type '${e.type||"unknown"}'`,400,"unsupported_input_item","invalid_request_error")}function $P(t){if(typeof t=="string")return t;if(!Array.isArray(t))return t==null?"":JSON.stringify(t);let e=[];for(let n of t){if(typeof n=="string"){e.push({type:"text",text:n});continue}if(!(!n||typeof n!="object"))if(n.type==="input_text"||n.type==="output_text"||n.type==="text")e.push({type:"text",text:String(n.text??"")});else if(n.type==="input_image"||n.type==="image_url"){if(n.file_id)throw J("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=n.image_url?.url||n.image_url||n.url;if(typeof r!="string"||!r)throw J("input_image requires image_url",400,"invalid_image","invalid_request_error");e.push({type:"image_url",image_url:{url:r,...n.detail?{detail:n.detail}:{}}})}else throw J(`Unsupported Responses content part '${n.type||"unknown"}'`,400,"unsupported_content_part","invalid_request_error")}return e.length===1&&e[0].type==="text"?e[0].text:e.length>0?e:""}var xn="input";function Fw(t){let e=t.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return e?e[2]:t}function nu(t){return!t.includes("*** Begin Patch ***")&&!t.includes("*** End Patch ***")?t:t.split("*** Begin Patch ***").join("*** Begin Patch").split("*** End Patch ***").join("*** End Patch")}function Nw(t,e){if(t!=="exec")return e;let n=e.trim();if(!n.startsWith("{")||!n.endsWith("}"))return e;let r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object"||Array.isArray(r))return e;let o="cmd"in r?"cmd":"command"in r?"command":null;if(!o)return e;let s=r[o];return typeof s!="string"||!s?e:(delete r[o],r.cmd=s,`await tools.exec_command(${JSON.stringify(r)});`)}function Mw(t,e){if(t!=="exec")return e;let n=e.match(/^apply_patch\s*<<\s*['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return n?`await tools.apply_patch(${JSON.stringify(n[2])});`:e}function Th(t,e,n){if(!Bw(n)||t!=="exec")return e;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.input=="string")return r.input=Mw(t,Nw(t,r.input)),JSON.stringify(r)}catch{}return e}function xh(t){if(!t)return"";try{let n=JSON.parse(t)?.[xn];if(typeof n=="string")return Fw(n)}catch{}return Fw(t)}function Bw(t){return t?.codexIsolateConventions!==!1}function Rh(t,e,n){let r=xh(e);return Bw(n)&&(r=Mw(t,Nw(t,r))),nu(r)}function qP(t,e){if(t!=null){if(!Array.isArray(t))throw J("Responses tools must be an array",400,"invalid_tools","invalid_request_error");return t.map(n=>{let r=typeof n?.type=="string"?n.type:"",o=n?.name||n?.function?.name;if(r==="web_search"||r==="web_search_preview"?o="web_search":!o&&r&&r!=="function"&&r!=="custom"&&(o=r),typeof o!="string"||!o)throw J("Responses function tools require a name",400,"invalid_tool","invalid_request_error");if(r==="custom"){e?.add(o);let s=n.description||n.function?.description||"";return{type:"function",function:{name:o,description:s&&`${s}
134
134
 
135
- Note: this tool takes freeform text, not JSON. Call it with a single "${xn}" argument whose value is the complete text described above, as a plain string \u2014 do not add markdown code fences, a shell heredoc (e.g. "<<EOF"), or any other wrapping around it.`,parameters:{type:"object",properties:{[xn]:{type:"string",description:"The complete freeform text/code input for this tool, exactly as described in the tool description \u2014 as a plain string, with no markdown code fences or shell heredoc wrapping."}},required:[xn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function qP(t){if(t!=null){if(typeof t=="string"){if(["auto","none","required"].includes(t))return t;throw J(`Unsupported Responses tool_choice '${t}'`,400,"unsupported_tool_choice","invalid_request_error")}if(t?.name&&(t?.type==="function"||t?.type==="custom"))return{type:"function",function:{name:t.name}};throw t?.type==="allowed_tools"?J("allowed_tools tool_choice is not supported",400,"unsupported_tool_choice","invalid_request_error"):J("Unsupported Responses tool_choice",400,"unsupported_tool_choice","invalid_request_error")}}function Uw(t,e){let n=e?.callIdMap??rs(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=us(Rn(s),t?.id?`rs_${t.id}`:void 0);a&&i.push(a);let u=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(f=>f?.type==="text").map(f=>f.text).join(""):"";if(u||!s.tool_calls?.length){let f=`msg_${t.id||Date.now()}`;i.push({type:"message",id:f,status:"completed",role:"assistant",content:[{type:"output_text",text:u||"",annotations:[],logprobs:s?.logprobs?.content||[]}]})}if(Array.isArray(s.tool_calls))for(let f of s.tool_calls){if(!f?.function)continue;let p=bo(n,f.id,"unified_to_client")??f.id,h=typeof f.function.arguments=="string"?f.function.arguments:JSON.stringify(f.function.arguments??{});if(e?.customToolNames?.has(f.function.name)){i.push({type:"custom_tool_call",id:p,call_id:p,name:f.function.name,input:Dh(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:nu(xh(f.function.name,h,r)),status:"completed"})}let d=Ww(t?.usage);return{id:t?.id||`resp_${Date.now()}`,object:"response",created_at:t?.created||Math.floor(Date.now()/1e3),status:"completed",model:e?.originalModel||t?.model,output:i,usage:d}}function jw(t){let e=`resp_${Date.now()}`;return{responseId:e,model:t?.model,textItemId:`msg_${e}`,textStarted:!1,textClosed:!1,textContent:"",closedTextItems:[],toolCalls:new Map,nextOutputIndex:0,finished:!1,created:!1,sequenceNumber:0,finishReasonSeen:!1,callIdMap:t?.callIdMap??rs(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function Lw(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function $w(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:zw(t,"in_progress")}))}function qw(t,e){!t.textStarted||t.textClosed||(t.textClosed=!0,e.push({type:"response.output_text.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,text:t.textContent,logprobs:[]}),e.push({type:"response.content_part.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,part:{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}}),e.push({type:"response.output_item.done",output_index:t.textOutputIndex,item:{type:"message",id:t.textItemId,status:"completed",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}}),t.closedTextItems.push({id:t.textItemId,outputIndex:t.textOutputIndex??0,content:t.textContent}))}function Hw(t,e){if(!t||typeof t!="object")return[];if(e.finished)return[];let n=[],r=t.choices?.[0],o=r?.delta||{};!e.model&&t.model&&(e.model=t.model),t.id&&(e.responseId=t.id.startsWith("resp_")?t.id:`resp_${t.id}`),t.usage&&(e.usage=t.usage);let s=Rn(o);!e.textStarted&&e.toolCalls.size===0&&(typeof o.content=="string"||Array.isArray(o.tool_calls)||s?.content||s?.encrypted_content||s?.id||r?.finish_reason)&&$w(e,n),s?.content&&(e.thinkingContent+=s.content);let i=os(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:lr(o.thinking?.signature)&&(e.thinkingId=o.thinking.signature),typeof o.content=="string"&&o.content.length>0&&(e.textClosed&&(e.textStarted=!1,e.textClosed=!1,e.textContent="",e.textItemId=`msg_${e.responseId}_${e.nextOutputIndex}`,e.textOutputIndex=void 0),e.textStarted||(e.textStarted=!0,e.textOutputIndex=e.nextOutputIndex++,n.push({type:"response.output_item.added",output_index:e.textOutputIndex,item:{type:"message",id:e.textItemId,status:"in_progress",role:"assistant",content:[]}}),n.push({type:"response.content_part.added",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,part:{type:"output_text",text:"",annotations:[]}})),e.textContent+=o.content,n.push({type:"response.output_text.delta",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,delta:o.content,logprobs:[]})),Array.isArray(o.tool_calls)&&o.tool_calls.length>0&&qw(e,n),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let u=typeof a.index=="number"?a.index:0,d=e.toolCalls.get(u);if(!d){let f=bo(e.callIdMap,a.id||`call_${e.responseId}_${u}`,"unified_to_client")||`call_${u}`,p=a.function?.name||"";d={id:f,name:p,arguments:"",added:!1,outputIndex:e.nextOutputIndex++,emittedArgumentsLength:0,isCustom:e.customToolNames.has(p)},e.toolCalls.set(u,d)}if(a.id&&!d.added&&(d.id=bo(e.callIdMap,a.id,"unified_to_client")||d.id),a.function?.name&&(d.name=a.function.name,d.isCustom=e.customToolNames.has(d.name)),typeof a.function?.arguments=="string"&&(d.arguments+=a.function.arguments),!d.added&&d.name&&(d.added=!0,n.push({type:"response.output_item.added",output_index:d.outputIndex,item:d.isCustom?{type:"custom_tool_call",id:d.id,call_id:d.id,name:d.name,input:""}:{type:"function_call",id:d.id,call_id:d.id,name:d.name,arguments:"",status:"in_progress"}})),d.added&&d.arguments.length>d.emittedArgumentsLength){if(!d.isCustom){let f=d.arguments.slice(d.emittedArgumentsLength);n.push({type:"response.function_call_arguments.delta",item_id:d.id,output_index:d.outputIndex,delta:f})}d.emittedArgumentsLength=d.arguments.length}}return r?.finish_reason&&(e.finishReasonSeen=!0),Lw(e,n)}function Oh(t,e){if(t.finished)return[];t.finished=!0;let n=[];$w(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};qw(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=Dh(s.name,s.arguments,r);n.push({type:"response.custom_tool_call_input.delta",item_id:s.id,output_index:s.outputIndex,delta:a}),n.push({type:"response.custom_tool_call_input.done",item_id:s.id,output_index:s.outputIndex,input:a}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"custom_tool_call",id:s.id,call_id:s.id,name:s.name,input:a}});continue}let i=nu(xh(s.name,s.arguments,r));n.push({type:"response.function_call_arguments.done",item_id:s.id,output_index:s.outputIndex,name:s.name,arguments:i}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"function_call",id:s.id,call_id:s.id,name:s.name,arguments:i,status:"completed"}})}let o=zw(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),Lw(t,n)}function zw(t,e,n){let r=[];for(let i of t.closedTextItems)r.push({index:i.outputIndex,item:{type:"message",id:i.id,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:i.content,annotations:[],logprobs:[]}]}});(t.textStarted||t.textContent)&&!t.closedTextItems.some(i=>i.id===t.textItemId)&&r.push({index:t.textOutputIndex??0,item:{type:"message",id:t.textItemId,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}});for(let i of t.toolCalls.values()){let a={codexIsolateConventions:t.codexIsolateConventions};r.push({index:i.outputIndex,item:i.isCustom?{type:"custom_tool_call",id:i.id,call_id:i.id,name:i.name,input:Dh(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:nu(xh(i.name,i.arguments,a)),status:e==="completed"?"completed":"in_progress"}})}let o=r.sort((i,a)=>i.index-a.index).map(({item:i})=>i),s=us({content:t.thinkingContent,encrypted_content:t.thinkingEncryptedContent,id:t.thinkingId},t.thinkingId||`rs_${t.responseId}`);return s&&o.unshift(s),{id:t.responseId,object:"response",created_at:Math.floor(Date.now()/1e3),status:e,model:t.model,output:o,usage:Ww(n)}}function Ww(t){if(!t||typeof t!="object")return;let e={input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0},n=t.prompt_tokens_details;return n&&typeof n=="object"&&(e.input_tokens_details={},n.cached_tokens!=null&&(e.input_tokens_details.cached_tokens=n.cached_tokens),n.cache_write_tokens!=null&&(e.input_tokens_details.cache_write_tokens=n.cache_write_tokens)),e}function Ki(t,e){let n={type:"response.failed",response:{id:e?.responseId||`resp_${Date.now()}`,object:"response",status:"failed",error:{message:t,type:"api_error",code:"provider_response_error"},output:[]}};return e?{...n,sequence_number:e.sequenceNumber++}:n}function Gw(t,e,n){let r=e&&typeof e=="object"?jr(e):{},o=t.stream,s=typeof r.model=="string"?r.model:void 0;(t.protocol==="openai_chat_completions"||t.protocol==="openai_responses"||t.protocol==="anthropic_messages")&&(o=r.stream===!0);let i=Tw(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function Jw(t,e,n,r){if(typeof n.transformRequestOut=="function"){let o=await n.transformRequestOut(e,r);return o&&typeof o=="object"&&"body"in o&&o.body?o.body:o}if(t==="openai_chat_completions")return HP(e);if(t==="openai_responses")return Zc(e);throw t==="anthropic_messages"?J("Anthropic transformRequestOut is required",500,"transformer_misconfigured"):J(`Client protocol '${t}' normalization is not implemented yet`,501,"protocol_not_implemented")}function HP(t){if(!t||typeof t!="object")throw J("Invalid Chat Completions body",400,"invalid_body");if(!Array.isArray(t.messages))throw J("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model)throw J("Chat Completions requires model",400,"invalid_body","invalid_request_error");return t}function jr(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var zP=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie","host","content-length","content-encoding","accept-encoding","connection","keep-alive","transfer-encoding","upgrade","te","trailer","expect","via","proxy-authenticate","proxy-authentication-info","x-auth-token","openai-secret","x-claude-desktop-no-iap-inject"]),WP=["proxy-","x-forwarded-","x-real-ip"];function Kw(t){let e={};if(!t)return e;let n=t instanceof Headers?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=r.toLowerCase();if(zP.has(s)||WP.some(a=>s.startsWith(a)))continue;let i=Array.isArray(o)?o.filter(a=>a!=null).map(String).join(", "):o;typeof i=="string"&&i&&(e[s]=i)}return e}function Vw(t,e,n,r){let o=t.transformer?.use;if(!Array.isArray(o)||o.length!==1||o[0]?.name!==e.name)return!1;let s=r?t.transformer?.[r]?.use:void 0;if(Array.isArray(s)&&s.length>0&&(s.length!==1||s[0]?.name!==e.name))return!1;let i={anthropic_messages:"Anthropic",openai_chat_completions:"OpenAI",openai_responses:"openai-responses"};return e.name===i[n]}import{get_encoding as GP}from"tiktoken";var Ph=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Ih=new Ph(100);import{readFile as Yw}from"fs/promises";import{opendir as JP,stat as Xw}from"fs/promises";import{join as Nh,resolve as ru,relative as ek,basename as ou}from"path";import{CLAUDE_PROJECTS_DIR as Fh,HOME_DIR as KP}from"@caeliq/ccr-shared";import{LRUCache as VP}from"lru-cache";var YP=GP("cl100k_base"),dr=t=>YP.encode(t,void 0,[]),Qw="<CCR-SUBAGENT-MODEL>",Zw="</CCR-SUBAGENT-MODEL>",ls="x-anthropic-billing-header",ds=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function tk(t){let e=t?.trim();if(!e)return;if(e.includes(","))return e;let n=e.indexOf("/");return n>0?`${e.slice(0,n)},${e.slice(n+1)}`:e}function XP(t){let e=`${ls}:`;if(!t.startsWith(e))return!1;let n=t.slice(e.length).trim();if(!n)return!1;if(n.startsWith("{"))try{let o=JSON.parse(n);return ds(o)&&o.cc_is_subagent===!0}catch{return!1}let r=n.split(";").map(o=>o.trim()).filter(Boolean).flatMap(o=>{let s=o.indexOf("=");return s<0||o.slice(0,s).trim()!=="cc_is_subagent"?[]:[o.slice(s+1).trim()]});return r.length===1&&r[0]==="true"}function su(t,e){let n=t.indexOf(Qw);if(n<0)return;let r=n+Qw.length,o=t.indexOf(Zw,r);if(o<0)return;let s=tk(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Zw.length)}`),s}function nk(t,e){if(typeof t=="string")return su(t,e);if(!(!ds(t)||typeof t.text!="string"))return su(t.text,e)}function QP(t){let e=t?.system;if(typeof e=="string")return su(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=nk(r,s=>{typeof r=="string"?e[n]=s:ds(r)&&(r.text=s)});if(o)return o}}function ZP(t){if(typeof t.content=="string")return su(t.content,n=>{t.content=n});if(!Array.isArray(t.content))return;let e=t.content;for(let n=0;n<e.length;n+=1){let r=e[n],o=nk(r,s=>{typeof r=="string"?e[n]=s:ds(r)&&(r.text=s)});if(o)return o}}function e1(t){if(!Array.isArray(t?.messages))return;let e=Math.min(t.messages.length,2);for(let n=0;n<e;n+=1){let r=t.messages[n];if(!ds(r)||r.role!=="user")continue;let o=ZP(r);if(o)return o}}function rk(t){return QP(t)||e1(t)}function ok(t){let e=t?.system;if(!Array.isArray(e)||e.length===0)return{present:!1,isSubagent:!1};let n=e[0],r=typeof n=="string"?n:ds(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(ls)?{present:!0,isSubagent:XP(r)}:{present:!1,isSubagent:!1}}var sk=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=dr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=dr(s.text).length:s.type==="tool_use"?r+=dr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=dr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=dr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=dr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=dr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=dr(o.name+o.description).length),o.input_schema&&(r+=dr(JSON.stringify(o.input_schema)).length)}),r},t1=async(t,e)=>{if(t.sessionId){let n=await ak(t.sessionId);if(n){let r=ru(KP),o=ru(r,ou(n)),s=ek(r,o);if(!s||s.startsWith(".."))return;let i=`${ou(String(t.sessionId))}.json`,a=Nh(o,"config.json"),u=Nh(o,i);try{let d=JSON.parse(await Yw(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await Yw(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function ik(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function n1(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function r1(t){return Array.isArray(t)?t.some(e=>{if(!e||typeof e!="object")return!1;if(typeof e.type=="string"&&(e.type==="web_search"||e.type.startsWith("web_search")))return!0;let n=e.function?.name||e.name||e.function?.function?.name;return typeof n=="string"&&(n==="web_search"||n.toLowerCase()==="websearch")}):!1}function o1(t){if(Ot(t?.reasoning,t?.thinking))return!1;if(t?.thinking)return!0;let e=t?.reasoning;return!!(e&&typeof e=="object"&&(e.enabled===!0||typeof e.effort=="string"&&e.effort.trim().length>0))}var s1=async(t,e,n,r)=>{let o=await t1(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=ik(t),u=typeof a?.model=="string"?a.model:String(a?.model??"");if(u.includes(",")){let[h,g]=u.split(","),b=s.find(w=>w.name.toLowerCase()===h.toLowerCase()),m=b?.models?.find(w=>w.toLowerCase()===g.toLowerCase());return b&&m?{model:`${b.name},${m}`,scenarioType:"default"}:{model:u,scenarioType:"default"}}let d=i?.longContextThreshold||6e4,f=r&&r.input_tokens>d&&e>2e4,p=e>d;if(n1(t)){let h=t.protocolContext?.taggedSubagentModel,g=t.protocolContext?.claudeCodeSubagent===!0;if(h)return t.log.info(`Using CCR subagent tag model: ${h}`),{model:h,scenarioType:"subagent"};if(g){let m=tk(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(m)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${m}`),{model:m,scenarioType:"subagent"}}let b=n.get("Router");if(u?.includes("claude")&&u?.includes("haiku")&&b?.background)return t.log.info(`Using background model for ${u}`),{model:b.background,scenarioType:"background"}}return r1(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:o1(a)&&i?.think?(t.log.info("Using think model for reasoning/thinking request"),{model:i.think,scenarioType:"think"}):(f||p)&&i?.longContext?(t.log.info(`Using long context model due to token count: ${e}, threshold: ${d}`),{model:i.longContext,scenarioType:"longContext"}):{model:i?.default||u,scenarioType:"default"}},i1=t=>{if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}},Mh=async(t,e,n)=>{let{configService:r,event:o}=n,s=ik(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=i1(i);let a=Ih.get(t.sessionId),u=s.messages||[],d=s.system??[],f=s.tools||[];try{let p=typeof s.model=="string"?s.model:String(s.model??""),[h,g]=p.split(","),b=n.tokenizerService?.getTokenizerConfigForModel(h,g),m;n.tokenizerService?m=(await n.tokenizerService.countTokens({messages:u,system:d,tools:f},b)).tokenCount:m=sk(u,d,f),t.tokenCount=m;let w,C=r.get("CUSTOM_ROUTER_PATH");if(C)try{w=await re(C)(t,r.getAll(),{event:o})}catch(A){t.log.error(`failed to load custom router: ${A.message}`)}if(w)t.scenarioType="default";else{let A=await s1(t,m,r,a);w=A.model,t.scenarioType=A.scenarioType}s.model=w,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=w)}catch(p){t.log.error(`Error in router middleware: ${p.message}`);let g=r.get("Router")?.default||s.model;s.model=g,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=g),t.scenarioType="default"}},Lr=new VP({max:1e3}),ak=async(t,e)=>{if(Lr.has(t)){let n=Lr.get(t);return!n||n===""?null:n}try{if(!(await Xw(Fh)).isDirectory())return Lr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Lr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Lr.set(t,""),null)}try{let n=await JP(Fh),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=ru(Fh),s=`${ou(String(t))}.jsonl`,i=r.map(async u=>{let d=ru(o,ou(u)),f=ek(o,d);if(!f||f.startsWith(".."))return null;let p=Nh(d,s);try{return(await Xw(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return Lr.set(t,u),u;return Lr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Lr.set(t,""),null}};import{readFile as y1}from"fs/promises";import{createHash as a1}from"crypto";var c1="59cf53e54c78",Bh=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",u1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",ck=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Co="You are Claude Code, Anthropic's official CLI for Claude.";function l1(t){return typeof t=="string"?t:Array.isArray(t)?t.find(n=>n.type==="text")?.text??"":""}function d1(t){let e=t?.find(n=>n.role==="user");return e?l1(e.content):""}function f1(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return a1("sha256").update(c1+n+e).digest("hex").slice(0,3)}function p1(){return"00000"}function h1(t,e=Bh,n=u1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=f1(d1(t),e);return`${ls}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${p1()};`}function iu(t){let e=[],n=r=>{if(typeof r=="string"){r&&e.push({type:"text",text:r});return}if(Array.isArray(r)){for(let o of r)if(o?.type==="text"&&o.text){let s={type:"text",text:o.text};o.cache_control!==void 0&&(s.cache_control=o.cache_control),e.push(s)}}};if((typeof t.system=="string"||Array.isArray(t.system))&&n(t.system),Array.isArray(t.messages)){let r=[];for(let o of t.messages)o.role==="system"||o.role==="developer"?n(o.content):r.push(o);t.messages=r}return t.system=e,e}function au(t,e){for(let r=t.length-1;r>=0;r--)t[r].text.startsWith(ls)&&t.splice(r,1);let n=h1(e);n&&t.unshift({type:"text",text:n})}function cu(t){let e=t.findIndex(o=>o.text.startsWith(ls)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Co){if(r?.text.startsWith(Co)&&r.text.length>Co.length){let o={type:"text",text:r.text.slice(Co.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Co},o);return}t.splice(n,0,{type:"text",text:Co})}}function uu(t,e){let n=t.findIndex(i=>i.text===Co);if(n<0||t.length<=n+1||!Array.isArray(e))return;let r=e.find(i=>i.role==="user");if(!r)return;let s=t.splice(n+1).map(i=>i.text).filter(i=>i.length>0).join(`
135
+ Note: this tool takes freeform text, not JSON. Call it with a single "${xn}" argument whose value is the complete text described above, as a plain string \u2014 do not add markdown code fences, a shell heredoc (e.g. "<<EOF"), or any other wrapping around it.`,parameters:{type:"object",properties:{[xn]:{type:"string",description:"The complete freeform text/code input for this tool, exactly as described in the tool description \u2014 as a plain string, with no markdown code fences or shell heredoc wrapping."}},required:[xn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function HP(t){if(t!=null){if(typeof t=="string"){if(["auto","none","required"].includes(t))return t;throw J(`Unsupported Responses tool_choice '${t}'`,400,"unsupported_tool_choice","invalid_request_error")}if(t?.name&&(t?.type==="function"||t?.type==="custom"))return{type:"function",function:{name:t.name}};throw t?.type==="allowed_tools"?J("allowed_tools tool_choice is not supported",400,"unsupported_tool_choice","invalid_request_error"):J("Unsupported Responses tool_choice",400,"unsupported_tool_choice","invalid_request_error")}}function jw(t,e){let n=e?.callIdMap??rs(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=us(Rn(s),t?.id?`rs_${t.id}`:void 0);a&&i.push(a);let u=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(f=>f?.type==="text").map(f=>f.text).join(""):"";if(u||!s.tool_calls?.length){let f=`msg_${t.id||Date.now()}`;i.push({type:"message",id:f,status:"completed",role:"assistant",content:[{type:"output_text",text:u||"",annotations:[],logprobs:s?.logprobs?.content||[]}]})}if(Array.isArray(s.tool_calls))for(let f of s.tool_calls){if(!f?.function)continue;let p=bo(n,f.id,"unified_to_client")??f.id,h=typeof f.function.arguments=="string"?f.function.arguments:JSON.stringify(f.function.arguments??{});if(e?.customToolNames?.has(f.function.name)){i.push({type:"custom_tool_call",id:p,call_id:p,name:f.function.name,input:Rh(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:nu(Th(f.function.name,h,r)),status:"completed"})}let d=Ww(t?.usage);return{id:t?.id||`resp_${Date.now()}`,object:"response",created_at:t?.created||Math.floor(Date.now()/1e3),status:"completed",model:e?.originalModel||t?.model,output:i,usage:d}}function Uw(t){let e=`resp_${Date.now()}`;return{responseId:e,model:t?.model,textItemId:`msg_${e}`,textStarted:!1,textClosed:!1,textContent:"",closedTextItems:[],toolCalls:new Map,nextOutputIndex:0,finished:!1,created:!1,sequenceNumber:0,finishReasonSeen:!1,callIdMap:t?.callIdMap??rs(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function Lw(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function $w(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:zw(t,"in_progress")}))}function qw(t,e){!t.textStarted||t.textClosed||(t.textClosed=!0,e.push({type:"response.output_text.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,text:t.textContent,logprobs:[]}),e.push({type:"response.content_part.done",item_id:t.textItemId,output_index:t.textOutputIndex,content_index:0,part:{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}}),e.push({type:"response.output_item.done",output_index:t.textOutputIndex,item:{type:"message",id:t.textItemId,status:"completed",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}}),t.closedTextItems.push({id:t.textItemId,outputIndex:t.textOutputIndex??0,content:t.textContent}))}function Hw(t,e){if(!t||typeof t!="object")return[];if(e.finished)return[];let n=[],r=t.choices?.[0],o=r?.delta||{};!e.model&&t.model&&(e.model=t.model),t.id&&(e.responseId=t.id.startsWith("resp_")?t.id:`resp_${t.id}`),t.usage&&(e.usage=t.usage);let s=Rn(o);!e.textStarted&&e.toolCalls.size===0&&(typeof o.content=="string"||Array.isArray(o.tool_calls)||s?.content||s?.encrypted_content||s?.id||r?.finish_reason)&&$w(e,n),s?.content&&(e.thinkingContent+=s.content);let i=os(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:lr(o.thinking?.signature)&&(e.thinkingId=o.thinking.signature),typeof o.content=="string"&&o.content.length>0&&(e.textClosed&&(e.textStarted=!1,e.textClosed=!1,e.textContent="",e.textItemId=`msg_${e.responseId}_${e.nextOutputIndex}`,e.textOutputIndex=void 0),e.textStarted||(e.textStarted=!0,e.textOutputIndex=e.nextOutputIndex++,n.push({type:"response.output_item.added",output_index:e.textOutputIndex,item:{type:"message",id:e.textItemId,status:"in_progress",role:"assistant",content:[]}}),n.push({type:"response.content_part.added",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,part:{type:"output_text",text:"",annotations:[]}})),e.textContent+=o.content,n.push({type:"response.output_text.delta",item_id:e.textItemId,output_index:e.textOutputIndex,content_index:0,delta:o.content,logprobs:[]})),Array.isArray(o.tool_calls)&&o.tool_calls.length>0&&qw(e,n),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let u=typeof a.index=="number"?a.index:0,d=e.toolCalls.get(u);if(!d){let f=bo(e.callIdMap,a.id||`call_${e.responseId}_${u}`,"unified_to_client")||`call_${u}`,p=a.function?.name||"";d={id:f,name:p,arguments:"",added:!1,outputIndex:e.nextOutputIndex++,emittedArgumentsLength:0,isCustom:e.customToolNames.has(p)},e.toolCalls.set(u,d)}if(a.id&&!d.added&&(d.id=bo(e.callIdMap,a.id,"unified_to_client")||d.id),a.function?.name&&(d.name=a.function.name,d.isCustom=e.customToolNames.has(d.name)),typeof a.function?.arguments=="string"&&(d.arguments+=a.function.arguments),!d.added&&d.name&&(d.added=!0,n.push({type:"response.output_item.added",output_index:d.outputIndex,item:d.isCustom?{type:"custom_tool_call",id:d.id,call_id:d.id,name:d.name,input:""}:{type:"function_call",id:d.id,call_id:d.id,name:d.name,arguments:"",status:"in_progress"}})),d.added&&d.arguments.length>d.emittedArgumentsLength){if(!d.isCustom){let f=d.arguments.slice(d.emittedArgumentsLength);n.push({type:"response.function_call_arguments.delta",item_id:d.id,output_index:d.outputIndex,delta:f})}d.emittedArgumentsLength=d.arguments.length}}return r?.finish_reason&&(e.finishReasonSeen=!0),Lw(e,n)}function Dh(t,e){if(t.finished)return[];t.finished=!0;let n=[];$w(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};qw(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=Rh(s.name,s.arguments,r);n.push({type:"response.custom_tool_call_input.delta",item_id:s.id,output_index:s.outputIndex,delta:a}),n.push({type:"response.custom_tool_call_input.done",item_id:s.id,output_index:s.outputIndex,input:a}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"custom_tool_call",id:s.id,call_id:s.id,name:s.name,input:a}});continue}let i=nu(Th(s.name,s.arguments,r));n.push({type:"response.function_call_arguments.done",item_id:s.id,output_index:s.outputIndex,name:s.name,arguments:i}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"function_call",id:s.id,call_id:s.id,name:s.name,arguments:i,status:"completed"}})}let o=zw(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),Lw(t,n)}function zw(t,e,n){let r=[];for(let i of t.closedTextItems)r.push({index:i.outputIndex,item:{type:"message",id:i.id,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:i.content,annotations:[],logprobs:[]}]}});(t.textStarted||t.textContent)&&!t.closedTextItems.some(i=>i.id===t.textItemId)&&r.push({index:t.textOutputIndex??0,item:{type:"message",id:t.textItemId,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}});for(let i of t.toolCalls.values()){let a={codexIsolateConventions:t.codexIsolateConventions};r.push({index:i.outputIndex,item:i.isCustom?{type:"custom_tool_call",id:i.id,call_id:i.id,name:i.name,input:Rh(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:nu(Th(i.name,i.arguments,a)),status:e==="completed"?"completed":"in_progress"}})}let o=r.sort((i,a)=>i.index-a.index).map(({item:i})=>i),s=us({content:t.thinkingContent,encrypted_content:t.thinkingEncryptedContent,id:t.thinkingId},t.thinkingId||`rs_${t.responseId}`);return s&&o.unshift(s),{id:t.responseId,object:"response",created_at:Math.floor(Date.now()/1e3),status:e,model:t.model,output:o,usage:Ww(n)}}function Ww(t){if(!t||typeof t!="object")return;let e={input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0},n=t.prompt_tokens_details;return n&&typeof n=="object"&&(e.input_tokens_details={},n.cached_tokens!=null&&(e.input_tokens_details.cached_tokens=n.cached_tokens),n.cache_write_tokens!=null&&(e.input_tokens_details.cache_write_tokens=n.cache_write_tokens)),e}function Ki(t,e){let n={type:"response.failed",response:{id:e?.responseId||`resp_${Date.now()}`,object:"response",status:"failed",error:{message:t,type:"api_error",code:"provider_response_error"},output:[]}};return e?{...n,sequence_number:e.sequenceNumber++}:n}function Gw(t,e,n){let r=e&&typeof e=="object"?Ur(e):{},o=t.stream,s=typeof r.model=="string"?r.model:void 0;(t.protocol==="openai_chat_completions"||t.protocol==="openai_responses"||t.protocol==="anthropic_messages")&&(o=r.stream===!0);let i=Tw(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function Jw(t,e,n,r){if(typeof n.transformRequestOut=="function"){let o=await n.transformRequestOut(e,r);return o&&typeof o=="object"&&"body"in o&&o.body?o.body:o}if(t==="openai_chat_completions")return zP(e);if(t==="openai_responses")return Zc(e);throw t==="anthropic_messages"?J("Anthropic transformRequestOut is required",500,"transformer_misconfigured"):J(`Client protocol '${t}' normalization is not implemented yet`,501,"protocol_not_implemented")}function zP(t){if(!t||typeof t!="object")throw J("Invalid Chat Completions body",400,"invalid_body");if(!Array.isArray(t.messages))throw J("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model)throw J("Chat Completions requires model",400,"invalid_body","invalid_request_error");return t}function Ur(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var WP=new Set(["authorization","proxy-authorization","x-api-key","cookie","set-cookie","host","content-length","content-encoding","accept-encoding","connection","keep-alive","transfer-encoding","upgrade","te","trailer","expect","via","proxy-authenticate","proxy-authentication-info","x-auth-token","openai-secret","x-claude-desktop-no-iap-inject"]),GP=["proxy-","x-forwarded-","x-real-ip"];function Kw(t){let e={};if(!t)return e;let n=t instanceof Headers?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=r.toLowerCase();if(WP.has(s)||GP.some(a=>s.startsWith(a)))continue;let i=Array.isArray(o)?o.filter(a=>a!=null).map(String).join(", "):o;typeof i=="string"&&i&&(e[s]=i)}return e}function Vw(t,e,n,r){let o=t.transformer?.use;if(!Array.isArray(o)||o.length!==1||o[0]?.name!==e.name)return!1;let s=r?t.transformer?.[r]?.use:void 0;if(Array.isArray(s)&&s.length>0&&(s.length!==1||s[0]?.name!==e.name))return!1;let i={anthropic_messages:"Anthropic",openai_chat_completions:"OpenAI",openai_responses:"openai-responses"};return e.name===i[n]}import{get_encoding as JP}from"tiktoken";var Oh=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Ph=new Oh(100);import{readFile as Yw}from"fs/promises";import{opendir as KP,stat as Xw}from"fs/promises";import{join as Fh,resolve as ru,relative as ek,basename as ou}from"path";import{CLAUDE_PROJECTS_DIR as Ih,HOME_DIR as VP}from"@caeliq/ccr-shared";import{LRUCache as YP}from"lru-cache";var XP=JP("cl100k_base"),dr=t=>XP.encode(t,void 0,[]),Qw="<CCR-SUBAGENT-MODEL>",Zw="</CCR-SUBAGENT-MODEL>",ls="x-anthropic-billing-header",ds=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function tk(t){let e=t?.trim();if(!e)return;if(e.includes(","))return e;let n=e.indexOf("/");return n>0?`${e.slice(0,n)},${e.slice(n+1)}`:e}function QP(t){let e=`${ls}:`;if(!t.startsWith(e))return!1;let n=t.slice(e.length).trim();if(!n)return!1;if(n.startsWith("{"))try{let o=JSON.parse(n);return ds(o)&&o.cc_is_subagent===!0}catch{return!1}let r=n.split(";").map(o=>o.trim()).filter(Boolean).flatMap(o=>{let s=o.indexOf("=");return s<0||o.slice(0,s).trim()!=="cc_is_subagent"?[]:[o.slice(s+1).trim()]});return r.length===1&&r[0]==="true"}function su(t,e){let n=t.indexOf(Qw);if(n<0)return;let r=n+Qw.length,o=t.indexOf(Zw,r);if(o<0)return;let s=tk(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Zw.length)}`),s}function nk(t,e){if(typeof t=="string")return su(t,e);if(!(!ds(t)||typeof t.text!="string"))return su(t.text,e)}function ZP(t){let e=t?.system;if(typeof e=="string")return su(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=nk(r,s=>{typeof r=="string"?e[n]=s:ds(r)&&(r.text=s)});if(o)return o}}function e1(t){if(typeof t.content=="string")return su(t.content,n=>{t.content=n});if(!Array.isArray(t.content))return;let e=t.content;for(let n=0;n<e.length;n+=1){let r=e[n],o=nk(r,s=>{typeof r=="string"?e[n]=s:ds(r)&&(r.text=s)});if(o)return o}}function t1(t){if(!Array.isArray(t?.messages))return;let e=Math.min(t.messages.length,2);for(let n=0;n<e;n+=1){let r=t.messages[n];if(!ds(r)||r.role!=="user")continue;let o=e1(r);if(o)return o}}function rk(t){return ZP(t)||t1(t)}function ok(t){let e=t?.system;if(!Array.isArray(e)||e.length===0)return{present:!1,isSubagent:!1};let n=e[0],r=typeof n=="string"?n:ds(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(ls)?{present:!0,isSubagent:QP(r)}:{present:!1,isSubagent:!1}}var sk=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=dr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=dr(s.text).length:s.type==="tool_use"?r+=dr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=dr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=dr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=dr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=dr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=dr(o.name+o.description).length),o.input_schema&&(r+=dr(JSON.stringify(o.input_schema)).length)}),r},n1=async(t,e)=>{if(t.sessionId){let n=await ak(t.sessionId);if(n){let r=ru(VP),o=ru(r,ou(n)),s=ek(r,o);if(!s||s.startsWith(".."))return;let i=`${ou(String(t.sessionId))}.json`,a=Fh(o,"config.json"),u=Fh(o,i);try{let d=JSON.parse(await Yw(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await Yw(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function ik(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function r1(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function o1(t){return Array.isArray(t)?t.some(e=>{if(!e||typeof e!="object")return!1;if(typeof e.type=="string"&&(e.type==="web_search"||e.type.startsWith("web_search")))return!0;let n=e.function?.name||e.name||e.function?.function?.name;return typeof n=="string"&&(n==="web_search"||n.toLowerCase()==="websearch")}):!1}function s1(t){if(Ot(t?.reasoning,t?.thinking))return!1;if(t?.thinking)return!0;let e=t?.reasoning;return!!(e&&typeof e=="object"&&(e.enabled===!0||typeof e.effort=="string"&&e.effort.trim().length>0))}var i1=async(t,e,n,r)=>{let o=await n1(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=ik(t),u=typeof a?.model=="string"?a.model:String(a?.model??"");if(u.includes(",")){let[h,g]=u.split(","),b=s.find(w=>w.name.toLowerCase()===h.toLowerCase()),m=b?.models?.find(w=>w.toLowerCase()===g.toLowerCase());return b&&m?{model:`${b.name},${m}`,scenarioType:"default"}:{model:u,scenarioType:"default"}}let d=i?.longContextThreshold||6e4,f=r&&r.input_tokens>d&&e>2e4,p=e>d;if(r1(t)){let h=t.protocolContext?.taggedSubagentModel,g=t.protocolContext?.claudeCodeSubagent===!0;if(h)return t.log.info(`Using CCR subagent tag model: ${h}`),{model:h,scenarioType:"subagent"};if(g){let m=tk(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(m)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${m}`),{model:m,scenarioType:"subagent"}}let b=n.get("Router");if(u?.includes("claude")&&u?.includes("haiku")&&b?.background)return t.log.info(`Using background model for ${u}`),{model:b.background,scenarioType:"background"}}return o1(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:s1(a)&&i?.think?(t.log.info("Using think model for reasoning/thinking request"),{model:i.think,scenarioType:"think"}):(f||p)&&i?.longContext?(t.log.info(`Using long context model due to token count: ${e}, threshold: ${d}`),{model:i.longContext,scenarioType:"longContext"}):{model:i?.default||u,scenarioType:"default"}},a1=t=>{if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}},Nh=async(t,e,n)=>{let{configService:r,event:o}=n,s=ik(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=a1(i);let a=Ph.get(t.sessionId),u=s.messages||[],d=s.system??[],f=s.tools||[];try{let p=typeof s.model=="string"?s.model:String(s.model??""),[h,g]=p.split(","),b=n.tokenizerService?.getTokenizerConfigForModel(h,g),m;n.tokenizerService?m=(await n.tokenizerService.countTokens({messages:u,system:d,tools:f},b)).tokenCount:m=sk(u,d,f),t.tokenCount=m;let w,C=r.get("CUSTOM_ROUTER_PATH");if(C)try{w=await re(C)(t,r.getAll(),{event:o})}catch(S){t.log.error(`failed to load custom router: ${S.message}`)}if(w)t.scenarioType="default";else{let S=await i1(t,m,r,a);w=S.model,t.scenarioType=S.scenarioType}s.model=w,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=w)}catch(p){t.log.error(`Error in router middleware: ${p.message}`);let g=r.get("Router")?.default||s.model;s.model=g,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=g),t.scenarioType="default"}},Lr=new YP({max:1e3}),ak=async(t,e)=>{if(Lr.has(t)){let n=Lr.get(t);return!n||n===""?null:n}try{if(!(await Xw(Ih)).isDirectory())return Lr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Lr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Lr.set(t,""),null)}try{let n=await KP(Ih),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=ru(Ih),s=`${ou(String(t))}.jsonl`,i=r.map(async u=>{let d=ru(o,ou(u)),f=ek(o,d);if(!f||f.startsWith(".."))return null;let p=Fh(d,s);try{return(await Xw(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return Lr.set(t,u),u;return Lr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Lr.set(t,""),null}};import{readFile as _1}from"fs/promises";import{createHash as c1}from"crypto";var u1="59cf53e54c78",Mh=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",l1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",ck=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Co="You are Claude Code, Anthropic's official CLI for Claude.";function d1(t){return typeof t=="string"?t:Array.isArray(t)?t.find(n=>n.type==="text")?.text??"":""}function f1(t){let e=t?.find(n=>n.role==="user");return e?d1(e.content):""}function p1(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return c1("sha256").update(u1+n+e).digest("hex").slice(0,3)}function h1(){return"00000"}function g1(t,e=Mh,n=l1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=p1(f1(t),e);return`${ls}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${h1()};`}function iu(t){let e=[],n=r=>{if(typeof r=="string"){r&&e.push({type:"text",text:r});return}if(Array.isArray(r)){for(let o of r)if(o?.type==="text"&&o.text){let s={type:"text",text:o.text};o.cache_control!==void 0&&(s.cache_control=o.cache_control),e.push(s)}}};if((typeof t.system=="string"||Array.isArray(t.system))&&n(t.system),Array.isArray(t.messages)){let r=[];for(let o of t.messages)o.role==="system"||o.role==="developer"?n(o.content):r.push(o);t.messages=r}return t.system=e,e}function au(t,e){for(let r=t.length-1;r>=0;r--)t[r].text.startsWith(ls)&&t.splice(r,1);let n=g1(e);n&&t.unshift({type:"text",text:n})}function cu(t){let e=t.findIndex(o=>o.text.startsWith(ls)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Co){if(r?.text.startsWith(Co)&&r.text.length>Co.length){let o={type:"text",text:r.text.slice(Co.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Co},o);return}t.splice(n,0,{type:"text",text:Co})}}function uu(t,e){let n=t.findIndex(i=>i.text===Co);if(n<0||t.length<=n+1||!Array.isArray(e))return;let r=e.find(i=>i.role==="user");if(!r)return;let s=t.splice(n+1).map(i=>i.text).filter(i=>i.length>0).join(`
136
136
 
137
137
  `);s&&(typeof r.content=="string"?r.content=r.content?`${s}
138
138
 
139
- ${r.content}`:s:Array.isArray(r.content)?r.content.unshift({type:"text",text:s}):r.content=s)}function g1(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function m1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function lu(t,e){let n=r=>{let o=g1(r);return e?.set(o,r),o};if(Array.isArray(t.tools))for(let r of t.tools)r?.function?.name&&(r.function.name=n(r.function.name));if(Array.isArray(t.messages))for(let r of t.messages)for(let o of r.tool_calls??[])o?.function?.name&&(o.function.name=n(o.function.name));typeof t.tool_choice=="string"?["auto","none","required"].includes(t.tool_choice)||(t.tool_choice=n(t.tool_choice)):t.tool_choice?.type==="function"&&t.tool_choice.function?.name&&(t.tool_choice.function.name=n(t.tool_choice.function.name))}function fs(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??m1(o))};for(let r of t?.choices??[]){for(let o of r?.message?.tool_calls??[])n(o);for(let o of r?.delta?.tool_calls??[])n(o)}}function wo(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n||o==null)continue;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a));return i.length?i.map(String).join(", "):void 0}return String(o)||void 0}}function _1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function b1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&(n.text.startsWith("You are Claude Code, Anthropic's official CLI for Claude.")||n.text.startsWith("You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.")||n.text.startsWith("You are a Claude agent, built on Anthropic's Claude Agent SDK.")))}function uk(t,e){let n=Uh(t,e),r=n.desktopMarker&&n.desktopUserAgent&&Array.isArray(e?.messages),o=n.cliUserAgent&&n.cliApp&&n.cliSession&&n.stainlessPackage&&n.billingSystem&&n.identitySystem&&Array.isArray(e?.messages),s=n.cliUserAgent||n.cliApp||n.cliSession;return r&&s?"other":r||n.desktopAgentSdkUserAgent&&o?"claude_desktop":o?"claude_code":"other"}function Uh(t,e){let n=wo(t,"user-agent")||"",r=wo(t,"anthropic-desktop-topbar"),s=(/^claude-cli\/[^\s()]+\s+\(([^)]*)\)$/i.exec(n)?.[1]||"").split(",").map(a=>a.trim().toLowerCase()),i=s.some(a=>["claude-desktop","claude-desktop-3p"].includes(a))&&s.some(a=>/^agent-sdk\/[^\s,]+$/.test(a));return{desktopMarker:r==="1",desktopUserAgent:/^Anthropic\/JS\s+/i.test(n),desktopAgentSdkUserAgent:i,cliUserAgent:/^claude-cli\//i.test(n),cliApp:["cli","cli-bg"].includes(wo(t,"x-app")||""),cliSession:!!wo(t,"x-claude-code-session-id"),stainlessPackage:!!wo(t,"x-stainless-package-version"),billingSystem:_1(e),identitySystem:b1(e)}}function du(t,e="Anthropic"){let r=(Array.isArray(t?.transformer?.use)?t.transformer.use:[]).map(o=>o?.name);return r.length===1&&r[0]===e?"api_key":r.length===2&&r[0]==="claude-auth"&&r[1]===e?"claude_oauth":"out_of_scope"}function fu(t){return t==="claude_desktop"||t==="claude_code"}async function pu(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=iu(t);au(r,t.messages),cu(r);let o=n?.get?.("REWRITE_SYSTEM_PROMPT");if(o&&Array.isArray(t.system))for(let i of t.system){if(typeof i?.text!="string"||!i.text.includes("<env>"))continue;let a=await y1(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}uu(r,t.messages);let s=new Map;lu(t,s),C1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function C1(t,e){let n={type:"ephemeral",...e==="claude_oauth"?{ttl:"1h"}:{}};delete t.cache_control;for(let i of t.tools||[])delete i.cache_control;for(let i of t.system||[])i&&typeof i.text=="string"&&!i.text.startsWith("x-anthropic-billing-header")?i.cache_control={...n}:i&&delete i.cache_control;for(let i of t.messages||[]){delete i.cache_control;for(let a of i.tool_calls||[])delete a.cache_control;if(Array.isArray(i.content))for(let a of i.content)delete a.cache_control}let r=t.messages||[],o=-1;for(let i=r.length-1;i>=0;i-=1){let a=r[i];if(a.role!=="assistant"){o=i;break}if(typeof a.content=="string"){o=i;break}if(Array.isArray(a.content)){let u=a.content.at(-1);if(u&&!["thinking","redacted_thinking","fallback"].includes(u.type)){o=i;break}}}let s=r[o];if(s){if(typeof s.content=="string"){s.content=[{type:"text",text:s.content,cache_control:{...n}}];return}if(Array.isArray(s.content))for(let i=s.content.length-1;i>=0;i-=1){let a=s.content[i];if(!(s.role==="assistant"&&["thinking","redacted_thinking","fallback"].includes(a?.type))&&a&&typeof a=="object"){a.cache_control={...n};return}}}}var w1={"claude-3-5-haiku":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-haiku-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-3-5-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-3-7-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:32e3,upper:64e3},capabilities:[]},"claude-sonnet-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-sonnet-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management"]},"claude-opus-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-1":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-opus-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-opus-4-7":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"xhigh",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","context_management","fast_mode"]},"claude-opus-4-8":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt"]},"claude-opus-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt","refusal_fallback","opus_5_prompt_bundle"]},"claude-fable-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","rejects_disabled_thinking","mid_conv_system","context_management","lean_prompt","fable_5_mitigations","refusal_fallback"]},"claude-mythos-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},capabilities:[]}},lk=/\[1m\]$/i;function Dn(t){let e=t||"",n=lk.test(e);return{modelId:e.replace(lk,""),requestedOneMillion:n}}function k1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=Dn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function ps(t){let e=k1(t);if(e)return w1[e]}function jh(t,e){return t?.capabilities.includes(e)??!1}function dk(t){return(t?.capabilities.length??0)>0}import{decodeClaudeModelAlias as S1}from"@caeliq/ccr-shared";async function pk(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||cr(t.method,s)||cr("POST",o);if(!i)throw J(`No inbound protocol match for ${s}`,404,"protocol_not_found");t.protocolMatch=i,t.clientProtocol=i.protocol,i.ownerTransformerName!==r.name&&t.log?.warn?.({expected:i.ownerTransformerName,actual:r.name,path:s},"endpoint transformer name differs from protocol owner");let a=t.body,u=t.query||{},{normalizationInput:d,context:f}=Gw(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=uk(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:Uh(t.headers,d)},"classified Anthropic client"),await A1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await Jw(i.protocol,d,r,p);h.model=fk(h.model,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"";let g=t;t.protocolContext=f,t.unifiedBody=h,t.originalClientBody=a;let b=n.configService.get("CUSTOM_ROUTER_PATH"),m=g.body;g.body=i.protocol==="anthropic_messages"&&b?a:h;try{await Mh(g,e,{configService:n.configService,tokenizerService:n.tokenizerService})}finally{g.body=m??a}let w=typeof h.model=="string"?h.model:f.originalModel;h.model=fk(w,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"",f.scenarioType=g.scenarioType,f.originalModel=f.originalModel??(typeof a?.model=="string"?a.model:void 0),g.unifiedBody=h,g.protocolContext=f;let C=E1(h.model,i.protocol),A=Dn(C.modelName);C.modelName=A.modelId,f.requestedOneMillion=A.requestedOneMillion;let k=n.providerService.getProvider(C.providerName);k||Vi(i.protocol,`Provider '${C.providerName}' not found`,404,"provider_not_found"),h.model=C.modelName,g.provider=C.providerName,g.model=C.modelName;let E=jr(h),x=du(k);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&fu(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await pu(h,f,n.configService),f.stream=f.stream||h.stream===!0||a?.stream===!0,{match:i,protocolContext:f,originalBody:a,clientWireBody:d,unifiedBody:h,prePolicyUnifiedBody:E,providerName:C.providerName,modelName:C.modelName}}async function A1(t,e){let n=ok(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=rk(t)}function E1(t,e){let n=typeof t=="string"?t.trim():"";n||Vi(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||Vi(e,`Unresolved bare model '${n}'. Configure Router.default or send provider,model.`,400,"unresolved_model","invalid_request_error");let[r,...o]=n.split(","),s=o.join(",");return(!r||!s)&&Vi(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function fk(t,e,n){if(typeof t!="string")return t;let r=S1(t);if(!r)return t;let o=Dn(r).modelId;return e(o)||Vi(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function Vi(t,e,n,r,o="api_error"){let s=Hi(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function hu(t,e,n,r){return n?Vw(t,e,n.protocol,r):t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r||""]?.use?.length||t.transformer?.[r||""]?.use.length===1&&t.transformer?.[r||""]?.use[0].name===e.name)}function Yi(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function ko(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function T1(t,e,n,r,o){let s=QC(t,e),i=s.signal;s.arm();let a;try{a=await pk(t,e,n,r,o)}catch(d){throw Je(d)||i.aborted?typeof d=="string"?vn(d):vn(i.reason??d):d}let u=n.providerService.getProvider(a.providerName);if(!u)throw J(`Provider '${a.providerName}' not found`,404,"provider_not_found");t._preparedInbound=a;try{let d=hu(u,r,a.protocolContext,a.modelName)&&!ko(a.protocolContext),f=!ko(a.protocolContext)&&Yi(u,r,a.protocolContext),p=a.protocolContext.anthropicNativeWire?a.originalBody:a.clientWireBody??a.originalBody,h=a.protocolContext.anthropicNativeWire||d||f?{...typeof p=="object"&&p?jr(p):{},model:a.modelName}:jr(a.unifiedBody);gk(t,n,u,h);let{requestBody:g,config:b,bypass:m}=await hk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),w=await mk(g,b,u,n,m,r,{req:t,signal:i,protocolContext:a.protocolContext}),C=await yk(g,w,u,r,m,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:m});return await _k(C,e,a.originalBody,i,a.protocolContext.stream,a.protocolContext.protocol)}catch(d){if(Je(d))throw typeof d=="string"?vn(d):d;if(i.aborted)throw vn(i.reason??d);if(fh(d)){let f=await x1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw vn(i.reason??St)}throw d}}async function x1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=ZC(a,i);if(!u?.length||s?.aborted||Je(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:En(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=lh(d,o?.headers?.["Retry-After"]??o?.headers?.["retry-after"]);if(d+=1,f>0){t.log.info(`Waiting ${f}ms before first fallback attempt`);try{await es(f,s)}catch(p){if(Je(p)||s?.aborted)return null;throw p}}for(let p=0;p<u.length;p+=1){if(s?.aborted)return null;let h=u[p];try{t.log.info(`Trying fallback model: ${h}`);let g=t._preparedInbound,[b,...m]=h.split(","),w=m.join(","),C=n.providerService.getProvider(b);if(!C){t.log.warn(`Fallback provider '${b}' not found, skipping`);continue}let A=du(C),k=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:A,anthropicDestinationInScope:A!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&A!=="out_of_scope"&&fu(g.protocolContext.anthropicClientKind||"other")),anthropicPolicyApplied:!1,anthropicSystemTransformed:!1,claudeAuthToolNameMap:new Map}:g?.protocolContext,E={...jr(g?.prePolicyUnifiedBody||g?.unifiedBody||t.unifiedBody||t.body),model:w};k?.anthropicDestinationInScope&&k.anthropicClientKind==="other"&&await pu(E,k,n.configService);let x={...t,provider:b,model:w,body:g?.originalBody??t.body,unifiedBody:E,protocolContext:k,clientProtocol:k?.protocol,scenarioType:i},O=hu(C,r,k,w)&&!ko(k),q=!ko(k)&&Yi(C,r,k),V=k?.anthropicNativeWire?g?.originalBody:g?.clientWireBody??g?.originalBody,j=k?.anthropicNativeWire||O||q?{...typeof V=="object"&&V?jr(V):{},model:w}:E;gk(x,n,C,j);let{requestBody:ee,config:z,bypass:te}=await hk(j,C,r,t.headers,{req:x,provider:C,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:k,skipClientNormalization:!0}),Q=await mk(ee,z,C,n,te,r,{req:x,signal:s,protocolContext:k}),_e=await yk(ee,Q,C,r,te,{req:x,signal:s,protocolContext:k});return t.log.info(`Fallback model ${h} succeeded`),await _k(_e,e,g?.originalBody??t.body,s,k?.stream,k?.protocol)}catch(g){if(Je(g))throw g;if(s?.aborted)throw vn(s.reason??St);if(!fh(g))throw t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed`),p<u.length-1){let m=lh(d,g?.headers?.["Retry-After"]??g?.headers?.["retry-after"]);if(d+=1,m>0){t.log.info(`Waiting ${m}ms before next fallback attempt`);try{await es(m,s)}catch(w){if(Je(w)||s?.aborted)return null;throw w}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function hk(t,e,n,r,o){let s=t,i={},a=hu(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!ko(o?.protocolContext)),d=ko(o?.protocolContext),f=!d&&Yi(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Kw(r)),!u&&o?.protocolContext?.protocol==="openai_responses"&&!e.transformer?.use?.some(h=>h?.name==="openai-responses")&&delete s.prompt_cache_key,!p&&typeof n.transformRequestOut=="function"){let h=await n.transformRequestOut(s,o);h.body?(s=h.body,i=h.config||{}):s=h}if(!u&&e.transformer?.use?.length)for(let h of e.transformer.use){if(f&&h?.name===n.name||!h||typeof h.transformRequestIn!="function")continue;let g=await h.transformRequestIn(s,e,o);if(g.body){s=g.body;let b=g.config||{};i={...i,...b,headers:Gc(i.headers,b.headers)}}else s=g}if(!u&&e.transformer?.[t.model]?.use?.length)for(let h of e.transformer[t.model].use){if(f&&h?.name===n.name||!h||typeof h.transformRequestIn!="function")continue;let g=await h.transformRequestIn(s,e,o);if(g.body){s=g.body;let b=g.config||{};i={...i,...b,headers:Gc(i.headers,b.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=Wc(s),s=zc(s,e,o)),{requestBody:s,config:i,bypass:u}}function gk(t,e,n,r){t&&(t._cachePrefixClientDiff=Sh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function mk(t,e,n,r,o,s,i){let a={logger:i?.req?.log??r.log,reqId:i?.req?.id,provider:n?.name,model:t?.model,conversationId:i?.req?.sessionId},u=async w=>{let C=Sh(t,{...a,stage:"wire",responseStatus:w?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheAffinity:{sessionId:e?.headers?.["session-id"],threadId:e?.headers?.["thread-id"],clientRequestId:e?.headers?.["x-client-request-id"]}});return Aw(w,{...a,responseStatus:w?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheDiff:C})};if(e?.__providerResponse)return u(e.__providerResponse);let d=n.transformer?.use?.find(w=>typeof w?.auth=="function")||s;if((o||n.transformer?.passthrough)&&typeof d.auth=="function"){let w=await d.auth(t,n,i);if(w.body){t=w.body;let C=e.headers||{};w.config?.headers&&(C=Gc(C,w.config.headers),delete C.host,delete w.config.headers),e={...e,...w.config,headers:C}}else t=w}let f=e.url||new URL(n.baseUrl),p=dw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},m=await Ew(w=>ts(f,t,{httpsProxy:r.configService.getHttpsProxy(),...g,headers:JSON.parse(JSON.stringify(w)),signal:i?.signal??g.signal},i,r.log),p,h);if(!m.ok){let w=await m.text(),C=Ge(w)||w.slice(0,240),A;try{A=JSON.parse(w)}catch{A=void 0}let k=A&&typeof A=="object"?A.error:void 0,E=mh(m.headers),x=Object.keys(E).length>0?E:void 0;if(!x?.["retry-after"]&&m.status===429){let j=k?.details||A?.details;if(Array.isArray(j)){let ee=j.find(z=>z["@type"]==="type.googleapis.com/google.rpc.RetryInfo");if(ee?.retryDelay){let z=parseInt(ee.retryDelay,10);isNaN(z)||(x={...x||{},"retry-after":z.toString()})}}}let O=typeof k?.message=="string"?k.message:void 0,q=Ge(O||w)||C;r.log.error({status:m.status,provider:n.name,model:t.model,errorMessage:q,upstreamType:typeof k?.type=="string"?k.type:void 0,upstreamCode:typeof k?.code=="string"?k.code:void 0},`[provider_response_error] ${n.name},${t.model}: ${q}`);let V=J(`Error from provider(${n.name},${t.model}: ${m.status}): ${q}`,m.status,typeof k?.code=="string"?k.code:"provider_response_error","api_error",x);throw V.upstream={status:m.status,statusText:m.statusText,headers:x??{},body:A!==void 0?Zo(A):void 0,provider:n.name,model:t.model},V}return u(m)}async function yk(t,e,n,r,o,s){let i=e,a=ko(s?.protocolContext),u=o||!a&&Yi(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&Yi(n,r,s?.protocolContext),f={...s,provider:n};if(!o&&n.transformer?.use?.length)for(let p of Array.from(n.transformer.use).reverse())d&&p?.name===r.name||!p||typeof p.transformResponseOut!="function"||(i=await p.transformResponseOut(i,f));if(!o&&n.transformer?.[t.model]?.use?.length)for(let p of Array.from(n.transformer[t.model].use).reverse())d&&p?.name===r.name||!p||typeof p.transformResponseOut!="function"||(i=await p.transformResponseOut(i,f));return!u&&r.transformResponseIn&&(i=await r.transformResponseIn(i,s)),i}async function _k(t,e,n,r,o,s){t.ok||e.code(t.status);let i=mh(t.headers);for(let[u,d]of Object.entries(i))e.header(u,d);if((typeof o=="boolean"?o:n?.stream===!0)&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let u=s==="openai_chat_completions"?Eh(t.body):t.body,d=Ah(u),f=v1.fromWeb(d),p=!1,h=()=>{if(!p){p=!0;try{f.destroyed||f.destroy()}catch{}}},g=()=>{r&&r.removeEventListener("abort",h)};return tw(e)?(h(),!e.sent&&!e.raw.destroyed?(e.type("application/json"),e.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):e):(r?.aborted&&e.log?.warn?.({reason:String(r.reason??""),headersSent:e.raw.headersSent,writableEnded:e.raw.writableEnded},"disconnect signal fired but socket still open; continuing SSE"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&r.addEventListener("abort",h,{once:!0}),e.raw.on("error",m=>{(m?.code==="EPIPE"||m?.code==="ECONNRESET"||m?.code==="ERR_STREAM_PREMATURE_CLOSE"||Je(m))&&h()}),e.raw.on("close",()=>{e.raw.writableEnded||h()}),f.on("error",m=>{m?.code==="ERR_STREAM_PREMATURE_CLOSE"||m?.code==="ABORT_ERR"||Je(m)||e.log?.error?.(En(m),"upstream stream error")}),f.once("end",g),f.once("close",g),e.send(f))}if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),t.body&&typeof t.body.pipe=="function")return e.send(t.body);throw J("Streaming response body is not a readable stream",502,"provider_response_error")}else{let u=await t.json();return e.send(u)}}var Lh=async t=>{let e={config:{rateLimit:{...hs}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=cr(s.method,i);s.pathname=i,a&&(s.protocolMatch=a,s.clientProtocol=a.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:sw})),t.get("/health",e,async()=>{let s=ow();return{status:"ok",timestamp:new Date().toISOString(),...s?{vitals:s}:{}}});let n=t.transformerService.getAllTransformers(),r=s=>{let i=n.get(s);if(i){if(typeof i=="object")return i;try{let a=new i;return a&&typeof a=="object"&&(a.logger=t.log),a}catch{return}}},o=new Set;for(let s of vh()){let i=r(s.ownerTransformerName);if(!i){t.log.warn(`protocol route ${s.path}: owner transformer '${s.ownerTransformerName}' not found`);continue}for(let a of[s.path,`${s.path}/`])o.has(a)||(o.add(a),t.post(a,e,async(u,d)=>T1(u,d,t,i,a)))}t.post("/providers",{config:{rateLimit:{...hs}},schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(s,i)=>{let{name:a,baseUrl:u,apiKey:d,models:f}=s.body;if(!a?.trim())throw J("Provider name is required",400,"invalid_request");if(!u||!R1(u))throw J("Valid base URL is required",400,"invalid_request");if(!d?.trim())throw J("API key is required",400,"invalid_request");if(!f||!Array.isArray(f)||f.length===0)throw J("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(s.body.name))throw J(`Provider with name '${s.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(s.body)}),t.get("/providers",e,async()=>t.providerService.getProviders()),t.get("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{let i=t.providerService.getProvider(s.params.id);if(!i)throw J("Provider not found",404,"provider_not_found");return i}),t.put("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(s,i)=>{let a=t.providerService.updateProvider(s.params.id,s.body);if(!a)throw J("Provider not found",404,"provider_not_found");return a}),t.delete("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{if(!t.providerService.deleteProvider(s.params.id))throw J("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(s,i)=>{if(!t.providerService.toggleProvider(s.params.id,s.body.enabled))throw J("Provider not found",404,"provider_not_found");return{message:`Provider ${s.body.enabled?"enabled":"disabled"} successfully`}})};function R1(t){try{return new URL(t),!0}catch{return!1}}var gs=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}configService;transformerService;logger;providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let i=`${r.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let i=`${r.name},${s}`,a={provider:r.name,model:s,fullModel:i};this.modelRoutes.set(i,a),this.modelRoutes.has(s)||this.modelRoutes.set(s,a)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var ut=[];for(let t=0;t<256;++t)ut.push((t+256).toString(16).slice(1));function bk(t,e=0){return(ut[t[e+0]]+ut[t[e+1]]+ut[t[e+2]]+ut[t[e+3]]+"-"+ut[t[e+4]]+ut[t[e+5]]+"-"+ut[t[e+6]]+ut[t[e+7]]+"-"+ut[t[e+8]]+ut[t[e+9]]+"-"+ut[t[e+10]]+ut[t[e+11]]+ut[t[e+12]]+ut[t[e+13]]+ut[t[e+14]]+ut[t[e+15]]).toLowerCase()}var D1=new Uint8Array(16);function $h(){return crypto.getRandomValues(D1)}function O1(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():P1(t,e,n)}function P1(t,e,n){t=t||{};let r=t.random??t.rng?.()??$h();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return bk(r)}var On=O1;var Ck=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var qh=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function I1(t){if(typeof t!="string")return!1;let e=t.trim();return qh.some(n=>e===n)}function F1(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.filter(n=>n?.type==="text"&&typeof n.text=="string"&&n.text.length>0).map(n=>n.text).join(`
140
- `);if(e)return e}return JSON.stringify(t)??""}function N1(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function M1(t){let e={source:"anthropic",trailingToolResults:[],interruption:"none",steering:"none"};if(!Array.isArray(t)||t.length===0)return e;let n=t[t.length-1];if(n?.role!=="user")return e;if(typeof n.content=="string")return n.content.trim()&&(e.steering="meaningful"),e;if(!Array.isArray(n.content))return e;let r=n.content.some(o=>o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0);for(let o of n.content){if(o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0){e.trailingToolResults.push({toolCallId:o.tool_use_id,content:F1(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&I1(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}N1(o)&&(e.steering="meaningful")}return e}function B1(t){let e=t&&typeof t=="object"&&typeof t.user_id=="string"?t.user_id:void 0;if(!e)return;try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}return e.split("_session_")[1]||e}function wk(t){return{source:"anthropic",sourceSessionIdentity:B1(t.metadata),turnIntent:M1(t.messages)}}var ms=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
139
+ ${r.content}`:s:Array.isArray(r.content)?r.content.unshift({type:"text",text:s}):r.content=s)}function m1(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function y1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function lu(t,e){let n=r=>{let o=m1(r);return e?.set(o,r),o};if(Array.isArray(t.tools))for(let r of t.tools)r?.function?.name&&(r.function.name=n(r.function.name));if(Array.isArray(t.messages))for(let r of t.messages)for(let o of r.tool_calls??[])o?.function?.name&&(o.function.name=n(o.function.name));typeof t.tool_choice=="string"?["auto","none","required"].includes(t.tool_choice)||(t.tool_choice=n(t.tool_choice)):t.tool_choice?.type==="function"&&t.tool_choice.function?.name&&(t.tool_choice.function.name=n(t.tool_choice.function.name))}function fs(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??y1(o))};for(let r of t?.choices??[]){for(let o of r?.message?.tool_calls??[])n(o);for(let o of r?.delta?.tool_calls??[])n(o)}}function wo(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n||o==null)continue;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a));return i.length?i.map(String).join(", "):void 0}return String(o)||void 0}}function b1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function C1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&(n.text.startsWith("You are Claude Code, Anthropic's official CLI for Claude.")||n.text.startsWith("You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.")||n.text.startsWith("You are a Claude agent, built on Anthropic's Claude Agent SDK.")))}function uk(t,e){let n=Bh(t,e),r=n.desktopMarker&&n.desktopUserAgent&&Array.isArray(e?.messages),o=n.cliUserAgent&&n.cliApp&&n.cliSession&&n.stainlessPackage&&n.billingSystem&&n.identitySystem&&Array.isArray(e?.messages),s=n.cliUserAgent||n.cliApp||n.cliSession;return r&&s?"other":r||n.desktopAgentSdkUserAgent&&o?"claude_desktop":o?"claude_code":"other"}function Bh(t,e){let n=wo(t,"user-agent")||"",r=wo(t,"anthropic-desktop-topbar"),s=(/^claude-cli\/[^\s()]+\s+\(([^)]*)\)$/i.exec(n)?.[1]||"").split(",").map(a=>a.trim().toLowerCase()),i=s.some(a=>["claude-desktop","claude-desktop-3p"].includes(a))&&s.some(a=>/^agent-sdk\/[^\s,]+$/.test(a));return{desktopMarker:r==="1",desktopUserAgent:/^Anthropic\/JS\s+/i.test(n),desktopAgentSdkUserAgent:i,cliUserAgent:/^claude-cli\//i.test(n),cliApp:["cli","cli-bg"].includes(wo(t,"x-app")||""),cliSession:!!wo(t,"x-claude-code-session-id"),stainlessPackage:!!wo(t,"x-stainless-package-version"),billingSystem:b1(e),identitySystem:C1(e)}}function du(t,e="Anthropic"){let r=(Array.isArray(t?.transformer?.use)?t.transformer.use:[]).map(o=>o?.name);return r.length===1&&r[0]===e?"api_key":r.length===2&&r[0]==="claude-auth"&&r[1]===e?"claude_oauth":"out_of_scope"}function fu(t){return t==="claude_desktop"||t==="claude_code"}async function pu(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=iu(t);au(r,t.messages),cu(r);let o=n?.get?.("REWRITE_SYSTEM_PROMPT");if(o&&Array.isArray(t.system))for(let i of t.system){if(typeof i?.text!="string"||!i.text.includes("<env>"))continue;let a=await _1(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}uu(r,t.messages);let s=new Map;lu(t,s),w1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function w1(t,e){let n={type:"ephemeral",...e==="claude_oauth"?{ttl:"1h"}:{}};delete t.cache_control;for(let i of t.tools||[])delete i.cache_control;for(let i of t.system||[])i&&typeof i.text=="string"&&!i.text.startsWith("x-anthropic-billing-header")?i.cache_control={...n}:i&&delete i.cache_control;for(let i of t.messages||[]){delete i.cache_control;for(let a of i.tool_calls||[])delete a.cache_control;if(Array.isArray(i.content))for(let a of i.content)delete a.cache_control}let r=t.messages||[],o=-1;for(let i=r.length-1;i>=0;i-=1){let a=r[i];if(a.role!=="assistant"){o=i;break}if(typeof a.content=="string"){o=i;break}if(Array.isArray(a.content)){let u=a.content.at(-1);if(u&&!["thinking","redacted_thinking","fallback"].includes(u.type)){o=i;break}}}let s=r[o];if(s){if(typeof s.content=="string"){s.content=[{type:"text",text:s.content,cache_control:{...n}}];return}if(Array.isArray(s.content))for(let i=s.content.length-1;i>=0;i-=1){let a=s.content[i];if(!(s.role==="assistant"&&["thinking","redacted_thinking","fallback"].includes(a?.type))&&a&&typeof a=="object"){a.cache_control={...n};return}}}}var k1={"claude-3-5-haiku":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-haiku-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-3-5-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:8192,upper:8192},capabilities:[]},"claude-3-7-sonnet":{nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!1,maxOutputTokens:{default:32e3,upper:64e3},capabilities:[]},"claude-sonnet-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-sonnet-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-sonnet-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management"]},"claude-opus-4-0":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-1":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:32e3},capabilities:["context_management"]},"claude-opus-4-5":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!1,supportsOneMillionSuffix:!0,maxOutputTokens:{default:32e3,upper:64e3},capabilities:["context_management"]},"claude-opus-4-6":{window:2e5,nativeOneMillion:!1,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},capabilities:["effort","max_effort","adaptive_thinking","context_management"]},"claude-opus-4-7":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"xhigh",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","context_management","fast_mode"]},"claude-opus-4-8":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt"]},"claude-opus-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!0,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","mid_conv_system","context_management","fast_mode","lean_prompt","refusal_fallback","opus_5_prompt_bundle"]},"claude-fable-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},defaultEffort:"high",capabilities:["effort","max_effort","xhigh_effort","adaptive_thinking","rejects_disabled_thinking","mid_conv_system","context_management","lean_prompt","fable_5_mitigations","refusal_fallback"]},"claude-mythos-5":{window:1e6,nativeOneMillion:!0,supportsOneMillionBeta:!0,supportsOneMillionSuffix:!1,maxOutputTokens:{default:64e3,upper:128e3},capabilities:[]}},lk=/\[1m\]$/i;function Dn(t){let e=t||"",n=lk.test(e);return{modelId:e.replace(lk,""),requestedOneMillion:n}}function S1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=Dn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function ps(t){let e=S1(t);if(e)return k1[e]}function jh(t,e){return t?.capabilities.includes(e)??!1}function dk(t){return(t?.capabilities.length??0)>0}import{decodeClaudeModelAlias as A1}from"@caeliq/ccr-shared";async function pk(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||cr(t.method,s)||cr("POST",o);if(!i)throw J(`No inbound protocol match for ${s}`,404,"protocol_not_found");t.protocolMatch=i,t.clientProtocol=i.protocol,i.ownerTransformerName!==r.name&&t.log?.warn?.({expected:i.ownerTransformerName,actual:r.name,path:s},"endpoint transformer name differs from protocol owner");let a=t.body,u=t.query||{},{normalizationInput:d,context:f}=Gw(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=uk(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:Bh(t.headers,d)},"classified Anthropic client"),await E1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await Jw(i.protocol,d,r,p);h.model=fk(h.model,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"";let g=t;t.protocolContext=f,t.unifiedBody=h,t.originalClientBody=a;let b=n.configService.get("CUSTOM_ROUTER_PATH"),m=g.body;g.body=i.protocol==="anthropic_messages"&&b?a:h;try{await Nh(g,e,{configService:n.configService,tokenizerService:n.tokenizerService})}finally{g.body=m??a}let w=typeof h.model=="string"?h.model:f.originalModel;h.model=fk(w,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"",f.scenarioType=g.scenarioType,f.originalModel=f.originalModel??(typeof a?.model=="string"?a.model:void 0),g.unifiedBody=h,g.protocolContext=f;let C=v1(h.model,i.protocol),S=Dn(C.modelName);C.modelName=S.modelId,f.requestedOneMillion=S.requestedOneMillion;let k=n.providerService.getProvider(C.providerName);k||Vi(i.protocol,`Provider '${C.providerName}' not found`,404,"provider_not_found"),h.model=C.modelName,g.provider=C.providerName,g.model=C.modelName;let E=Ur(h),x=du(k);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&fu(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await pu(h,f,n.configService),f.stream=f.stream||h.stream===!0||a?.stream===!0,{match:i,protocolContext:f,originalBody:a,clientWireBody:d,unifiedBody:h,prePolicyUnifiedBody:E,providerName:C.providerName,modelName:C.modelName}}async function E1(t,e){let n=ok(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=rk(t)}function v1(t,e){let n=typeof t=="string"?t.trim():"";n||Vi(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||Vi(e,`Unresolved bare model '${n}'. Configure Router.default or send provider,model.`,400,"unresolved_model","invalid_request_error");let[r,...o]=n.split(","),s=o.join(",");return(!r||!s)&&Vi(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function fk(t,e,n){if(typeof t!="string")return t;let r=A1(t);if(!r)return t;let o=Dn(r).modelId;return e(o)||Vi(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function Vi(t,e,n,r,o="api_error"){let s=Hi(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function hu(t,e,n,r){return n?Vw(t,e,n.protocol,r):t.transformer?.use?.length===1&&t.transformer.use[0].name===e.name&&(!t.transformer?.[r||""]?.use?.length||t.transformer?.[r||""]?.use.length===1&&t.transformer?.[r||""]?.use[0].name===e.name)}function Yi(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function ko(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function x1(t,e,n,r,o){let s=QC(t,e),i=s.signal;s.arm();let a;try{a=await pk(t,e,n,r,o)}catch(d){throw Je(d)||i.aborted?typeof d=="string"?vn(d):vn(i.reason??d):d}let u=n.providerService.getProvider(a.providerName);if(!u)throw J(`Provider '${a.providerName}' not found`,404,"provider_not_found");t._preparedInbound=a;try{let d=hu(u,r,a.protocolContext,a.modelName)&&!ko(a.protocolContext),f=!ko(a.protocolContext)&&Yi(u,r,a.protocolContext),p=a.protocolContext.anthropicNativeWire?a.originalBody:a.clientWireBody??a.originalBody,h=a.protocolContext.anthropicNativeWire||d||f?{...typeof p=="object"&&p?Ur(p):{},model:a.modelName}:Ur(a.unifiedBody);gk(t,n,u,h);let{requestBody:g,config:b,bypass:m}=await hk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),w=await mk(g,b,u,n,m,r,{req:t,signal:i,protocolContext:a.protocolContext}),C=await yk(g,w,u,r,m,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:m});return await _k(C,e,a.originalBody,i,a.protocolContext.stream,a.protocolContext.protocol)}catch(d){if(Je(d))throw typeof d=="string"?vn(d):d;if(i.aborted)throw vn(i.reason??d);if(dh(d)){let f=await R1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw vn(i.reason??St)}throw d}}async function R1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=ZC(a,i);if(!u?.length||s?.aborted||Je(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:En(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=uh(d,o?.headers?.["Retry-After"]??o?.headers?.["retry-after"]);if(d+=1,f>0){t.log.info(`Waiting ${f}ms before first fallback attempt`);try{await es(f,s)}catch(p){if(Je(p)||s?.aborted)return null;throw p}}for(let p=0;p<u.length;p+=1){if(s?.aborted)return null;let h=u[p];try{t.log.info(`Trying fallback model: ${h}`);let g=t._preparedInbound,[b,...m]=h.split(","),w=m.join(","),C=n.providerService.getProvider(b);if(!C){t.log.warn(`Fallback provider '${b}' not found, skipping`);continue}let S=du(C),k=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:S,anthropicDestinationInScope:S!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&S!=="out_of_scope"&&fu(g.protocolContext.anthropicClientKind||"other")),anthropicPolicyApplied:!1,anthropicSystemTransformed:!1,claudeAuthToolNameMap:new Map}:g?.protocolContext,E={...Ur(g?.prePolicyUnifiedBody||g?.unifiedBody||t.unifiedBody||t.body),model:w};k?.anthropicDestinationInScope&&k.anthropicClientKind==="other"&&await pu(E,k,n.configService);let x={...t,provider:b,model:w,body:g?.originalBody??t.body,unifiedBody:E,protocolContext:k,clientProtocol:k?.protocol,scenarioType:i},O=hu(C,r,k,w)&&!ko(k),q=!ko(k)&&Yi(C,r,k),V=k?.anthropicNativeWire?g?.originalBody:g?.clientWireBody??g?.originalBody,U=k?.anthropicNativeWire||O||q?{...typeof V=="object"&&V?Ur(V):{},model:w}:E;gk(x,n,C,U);let{requestBody:ee,config:z,bypass:te}=await hk(U,C,r,t.headers,{req:x,provider:C,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:k,skipClientNormalization:!0}),Q=await mk(ee,z,C,n,te,r,{req:x,signal:s,protocolContext:k}),_e=await yk(ee,Q,C,r,te,{req:x,signal:s,protocolContext:k});return t.log.info(`Fallback model ${h} succeeded`),await _k(_e,e,g?.originalBody??t.body,s,k?.stream,k?.protocol)}catch(g){if(Je(g))throw g;if(s?.aborted)throw vn(s.reason??St);if(!dh(g))throw t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed`),p<u.length-1){let m=uh(d,g?.headers?.["Retry-After"]??g?.headers?.["retry-after"]);if(d+=1,m>0){t.log.info(`Waiting ${m}ms before next fallback attempt`);try{await es(m,s)}catch(w){if(Je(w)||s?.aborted)return null;throw w}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function hk(t,e,n,r,o){let s=t,i={},a=hu(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!ko(o?.protocolContext)),d=ko(o?.protocolContext),f=!d&&Yi(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Kw(r)),!u&&o?.protocolContext?.protocol==="openai_responses"&&!e.transformer?.use?.some(h=>h?.name==="openai-responses")&&delete s.prompt_cache_key,!p&&typeof n.transformRequestOut=="function"){let h=await n.transformRequestOut(s,o);h.body?(s=h.body,i=h.config||{}):s=h}if(!u&&e.transformer?.use?.length)for(let h of e.transformer.use){if(f&&h?.name===n.name||!h||typeof h.transformRequestIn!="function")continue;let g=await h.transformRequestIn(s,e,o);if(g.body){s=g.body;let b=g.config||{};i={...i,...b,headers:Gc(i.headers,b.headers)}}else s=g}if(!u&&e.transformer?.[t.model]?.use?.length)for(let h of e.transformer[t.model].use){if(f&&h?.name===n.name||!h||typeof h.transformRequestIn!="function")continue;let g=await h.transformRequestIn(s,e,o);if(g.body){s=g.body;let b=g.config||{};i={...i,...b,headers:Gc(i.headers,b.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=Wc(s),s=zc(s,e,o)),{requestBody:s,config:i,bypass:u}}function gk(t,e,n,r){t&&(t._cachePrefixClientDiff=kh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function mk(t,e,n,r,o,s,i){let a={logger:i?.req?.log??r.log,reqId:i?.req?.id,provider:n?.name,model:t?.model,conversationId:i?.req?.sessionId},u=async w=>{let C=kh(t,{...a,stage:"wire",responseStatus:w?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheAffinity:{sessionId:e?.headers?.["session-id"],threadId:e?.headers?.["thread-id"],clientRequestId:e?.headers?.["x-client-request-id"]}});return Aw(w,{...a,responseStatus:w?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheDiff:C})};if(e?.__providerResponse)return u(e.__providerResponse);let d=n.transformer?.use?.find(w=>typeof w?.auth=="function")||s;if((o||n.transformer?.passthrough)&&typeof d.auth=="function"){let w=await d.auth(t,n,i);if(w.body){t=w.body;let C=e.headers||{};w.config?.headers&&(C=Gc(C,w.config.headers),delete C.host,delete w.config.headers),e={...e,...w.config,headers:C}}else t=w}let f=e.url||new URL(n.baseUrl),p=dw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},m=await Ew(w=>ts(f,t,{httpsProxy:r.configService.getHttpsProxy(),...g,headers:JSON.parse(JSON.stringify(w)),signal:i?.signal??g.signal},i,r.log),p,h);if(!m.ok){let w=await m.text(),C=Ge(w)||w.slice(0,240),S;try{S=JSON.parse(w)}catch{S=void 0}let k=S&&typeof S=="object"?S.error:void 0,E=gh(m.headers),x=Object.keys(E).length>0?E:void 0;if(!x?.["retry-after"]&&m.status===429){let U=k?.details||S?.details;if(Array.isArray(U)){let ee=U.find(z=>z["@type"]==="type.googleapis.com/google.rpc.RetryInfo");if(ee?.retryDelay){let z=parseInt(ee.retryDelay,10);isNaN(z)||(x={...x||{},"retry-after":z.toString()})}}}let O=typeof k?.message=="string"?k.message:void 0,q=Ge(O||w)||C;r.log.error({status:m.status,provider:n.name,model:t.model,errorMessage:q,upstreamType:typeof k?.type=="string"?k.type:void 0,upstreamCode:typeof k?.code=="string"?k.code:void 0},`[provider_response_error] ${n.name},${t.model}: ${q}`);let V=J(`Error from provider(${n.name},${t.model}: ${m.status}): ${q}`,m.status,typeof k?.code=="string"?k.code:"provider_response_error","api_error",x);throw V.upstream={status:m.status,statusText:m.statusText,headers:x??{},body:S!==void 0?Zo(S):void 0,provider:n.name,model:t.model},V}return u(m)}async function yk(t,e,n,r,o,s){let i=e,a=ko(s?.protocolContext),u=o||!a&&Yi(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&Yi(n,r,s?.protocolContext),f={...s,provider:n};if(!o&&n.transformer?.use?.length)for(let p of Array.from(n.transformer.use).reverse())d&&p?.name===r.name||!p||typeof p.transformResponseOut!="function"||(i=await p.transformResponseOut(i,f));if(!o&&n.transformer?.[t.model]?.use?.length)for(let p of Array.from(n.transformer[t.model].use).reverse())d&&p?.name===r.name||!p||typeof p.transformResponseOut!="function"||(i=await p.transformResponseOut(i,f));return!u&&r.transformResponseIn&&(i=await r.transformResponseIn(i,s)),i}async function _k(t,e,n,r,o,s){t.ok||e.code(t.status);let i=gh(t.headers);for(let[u,d]of Object.entries(i))e.header(u,d);if((typeof o=="boolean"?o:n?.stream===!0)&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let u=s==="openai_chat_completions"?Ah(t.body):t.body,d=Sh(u),f=T1.fromWeb(d),p=!1,h=()=>{if(!p){p=!0;try{f.destroyed||f.destroy()}catch{}}},g=()=>{r&&r.removeEventListener("abort",h)};return tw(e)?(h(),!e.sent&&!e.raw.destroyed?(e.type("application/json"),e.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):e):(r?.aborted&&e.log?.warn?.({reason:String(r.reason??""),headersSent:e.raw.headersSent,writableEnded:e.raw.writableEnded},"disconnect signal fired but socket still open; continuing SSE"),e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),r&&r.addEventListener("abort",h,{once:!0}),e.raw.on("error",m=>{(m?.code==="EPIPE"||m?.code==="ECONNRESET"||m?.code==="ERR_STREAM_PREMATURE_CLOSE"||Je(m))&&h()}),e.raw.on("close",()=>{e.raw.writableEnded||h()}),f.on("error",m=>{m?.code==="ERR_STREAM_PREMATURE_CLOSE"||m?.code==="ABORT_ERR"||Je(m)||e.log?.error?.(En(m),"upstream stream error")}),f.once("end",g),f.once("close",g),e.send(f))}if(e.header("Content-Type","text/event-stream"),e.header("Cache-Control","no-cache"),e.header("Connection","keep-alive"),t.body&&typeof t.body.pipe=="function")return e.send(t.body);throw J("Streaming response body is not a readable stream",502,"provider_response_error")}else{let u=await t.json();return e.send(u)}}var Uh=async t=>{let e={config:{rateLimit:{...hs}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=cr(s.method,i);s.pathname=i,a&&(s.protocolMatch=a,s.clientProtocol=a.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:sw})),t.get("/health",e,async()=>{let s=ow();return{status:"ok",timestamp:new Date().toISOString(),...s?{vitals:s}:{}}});let n=t.transformerService.getAllTransformers(),r=s=>{let i=n.get(s);if(i){if(typeof i=="object")return i;try{let a=new i;return a&&typeof a=="object"&&(a.logger=t.log),a}catch{return}}},o=new Set;for(let s of Eh()){let i=r(s.ownerTransformerName);if(!i){t.log.warn(`protocol route ${s.path}: owner transformer '${s.ownerTransformerName}' not found`);continue}for(let a of[s.path,`${s.path}/`])o.has(a)||(o.add(a),t.post(a,e,async(u,d)=>x1(u,d,t,i,a)))}t.post("/providers",{config:{rateLimit:{...hs}},schema:{body:{type:"object",properties:{id:{type:"string"},name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}}},required:["id","name","type","baseUrl","apiKey","models"]}}},async(s,i)=>{let{name:a,baseUrl:u,apiKey:d,models:f}=s.body;if(!a?.trim())throw J("Provider name is required",400,"invalid_request");if(!u||!D1(u))throw J("Valid base URL is required",400,"invalid_request");if(!d?.trim())throw J("API key is required",400,"invalid_request");if(!f||!Array.isArray(f)||f.length===0)throw J("At least one model is required",400,"invalid_request");if(t.providerService.getProvider(s.body.name))throw J(`Provider with name '${s.body.name}' already exists`,400,"provider_exists");return t.providerService.registerProvider(s.body)}),t.get("/providers",e,async()=>t.providerService.getProviders()),t.get("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{let i=t.providerService.getProvider(s.params.id);if(!i)throw J("Provider not found",404,"provider_not_found");return i}),t.put("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{name:{type:"string"},type:{type:"string",enum:["openai","anthropic"]},baseUrl:{type:"string"},apiKey:{type:"string"},models:{type:"array",items:{type:"string"}},enabled:{type:"boolean"}}}}},async(s,i)=>{let a=t.providerService.updateProvider(s.params.id,s.body);if(!a)throw J("Provider not found",404,"provider_not_found");return a}),t.delete("/providers/:id",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]}}},async s=>{if(!t.providerService.deleteProvider(s.params.id))throw J("Provider not found",404,"provider_not_found");return{message:"Provider deleted successfully"}}),t.patch("/providers/:id/toggle",{config:{rateLimit:{...hs}},schema:{params:{type:"object",properties:{id:{type:"string"}},required:["id"]},body:{type:"object",properties:{enabled:{type:"boolean"}},required:["enabled"]}}},async(s,i)=>{if(!t.providerService.toggleProvider(s.params.id,s.body.enabled))throw J("Provider not found",404,"provider_not_found");return{message:`Provider ${s.body.enabled?"enabled":"disabled"} successfully`}})};function D1(t){try{return new URL(t),!0}catch{return!1}}var gs=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}configService;transformerService;logger;providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let i=`${r.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let i=`${r.name},${s}`,a={provider:r.name,model:s,fullModel:i};this.modelRoutes.set(i,a),this.modelRoutes.has(s)||this.modelRoutes.set(s,a)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var ut=[];for(let t=0;t<256;++t)ut.push((t+256).toString(16).slice(1));function bk(t,e=0){return(ut[t[e+0]]+ut[t[e+1]]+ut[t[e+2]]+ut[t[e+3]]+"-"+ut[t[e+4]]+ut[t[e+5]]+"-"+ut[t[e+6]]+ut[t[e+7]]+"-"+ut[t[e+8]]+ut[t[e+9]]+"-"+ut[t[e+10]]+ut[t[e+11]]+ut[t[e+12]]+ut[t[e+13]]+ut[t[e+14]]+ut[t[e+15]]).toLowerCase()}var O1=new Uint8Array(16);function Lh(){return crypto.getRandomValues(O1)}function P1(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():I1(t,e,n)}function I1(t,e,n){t=t||{};let r=t.random??t.rng?.()??Lh();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return bk(r)}var On=P1;var Ck=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var $h=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function F1(t){if(typeof t!="string")return!1;let e=t.trim();return $h.some(n=>e===n)}function N1(t){if(typeof t=="string")return t;if(Array.isArray(t)){let e=t.filter(n=>n?.type==="text"&&typeof n.text=="string"&&n.text.length>0).map(n=>n.text).join(`
140
+ `);if(e)return e}return JSON.stringify(t)??""}function M1(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function B1(t){let e={source:"anthropic",trailingToolResults:[],interruption:"none",steering:"none"};if(!Array.isArray(t)||t.length===0)return e;let n=t[t.length-1];if(n?.role!=="user")return e;if(typeof n.content=="string")return n.content.trim()&&(e.steering="meaningful"),e;if(!Array.isArray(n.content))return e;let r=n.content.some(o=>o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0);for(let o of n.content){if(o?.type==="tool_result"&&typeof o.tool_use_id=="string"&&o.tool_use_id.length>0){e.trailingToolResults.push({toolCallId:o.tool_use_id,content:N1(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&F1(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}M1(o)&&(e.steering="meaningful")}return e}function j1(t){let e=t&&typeof t=="object"&&typeof t.user_id=="string"?t.user_id:void 0;if(!e)return;try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}return e.split("_session_")[1]||e}function wk(t){return{source:"anthropic",sourceSessionIdentity:j1(t.metadata),turnIntent:B1(t.messages)}}var ms=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
141
141
  `),e.id&&(r+=`id: ${e.id}
142
142
  `),e.retry&&(r+=`retry: ${e.retry}
143
143
  `),e.data&&(e.data.type==="done"?r+=`data: [DONE]
@@ -148,36 +148,36 @@ ${r.content}`:s:Array.isArray(r.content)?r.content.unshift({type:"text",text:s})
148
148
  `))}}}catch(f){if(!i){let p=U1(f);gu(n?.logger,"Stream error",p);let h=!1;try{h=n?.onError?.(p,d)===!0}catch(g){gu(n?.logger,"Stream error handler failed",g)}o=!h,h||u.error(p)}}finally{if(s=null,!i)try{n?.onComplete?.(d)}catch(f){if(gu(n?.logger,"Stream completion error",f),!o){o=!0;try{u.error(f)}catch{}}}if(!o&&!i)try{u.close()}catch{}}},cancel:async u=>{i=!0;let d=s;s=null,d&&await d.cancel(u).catch(()=>{})}});return new Response(a,{status:t.status,statusText:t.statusText,headers:{...Jc(t.headers),"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function ve(t,e){return e.encode(`data: ${t}
149
149
 
150
150
  `)}function Pe(t,e){return e.encode(t+`
151
- `)}var mu=nr(Nk(),1),nI={STOP:"stop",MAX_TOKENS:"length",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter"},Hh="\u26A0\uFE0F Upstream ended the turn without a reply";function Xi(t){return t?nI[t.toUpperCase()]||t.toLowerCase():null}function zh(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${Hh} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var yu=class{constructor(e){this.emit=e}emit;_hasThinking=!1;_sigSent=!1;_contentSent=!1;_buffer="";processThinking(e,n){this._hasThinking=!0,this.emit.thinking(e,n)}processSignature(e,n){this.processSignatureWithMeta(e,n)}processSignatureWithMeta(e,n,r){if(!this._sigSent){if(this._contentSent){this._sigSent=!0;return}this._hasThinking||(this._hasThinking=!0,this.emit.thinking("(no content)",n)),this._sigSent=!0,this.emit.signature(e,n),r?.beforeFlush?.(),this.flushBufferedContent(r?.flushMeta)}}processContent(e,n,r){this._sigSent||!this._hasThinking?(this._contentSent=!0,this.emit.content(e,{chunk:n,candidate:r,mode:"direct"})):this._buffer+=e}emitContentPlaceholder(e,n){this._contentSent=!0,this.emit.content(e,{chunk:n?.chunk,candidate:n?.candidate,mode:"placeholder",finishReason:n?.finishReason})}bufferContent(e){this._buffer+=e}finalize(e,n,r){if(this._hasThinking&&!this._sigSent){this.processSignatureWithMeta(`ccr_${Date.now()}`,e,{beforeFlush:r?.beforeFlush,flushMeta:{chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Xi(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Xi(n?.finishReason)})}flushBufferedContent(e){this._buffer&&(this._contentSent=!0,this.emit.content(this._buffer,{chunk:e?.chunk,candidate:e?.candidate,mode:e?.mode||"buffered",finishReason:e?.finishReason}),this._buffer="")}shouldDeferContent(e,n){return this._hasThinking&&!this._sigSent&&!e&&!n}get hasBufferedContent(){return this._buffer.length>0}get hasThinkingContent(){return this._hasThinking}get signatureSent(){return this._sigSent}get contentSent(){return this._contentSent}get needsContentPlaceholder(){return this._sigSent&&!this._contentSent}acknowledgeSignature(){this._sigSent=!0}};function _u(t,e){return e[t]||t}function bu(t){return!t||typeof t=="string"?[]:t.filter(e=>e.type==="image_url").map(e=>({url:e.image_url.url,mediaType:e.media_type||"image/jpeg",isBase64:e.image_url.url.startsWith("data:")}))}function Cu(t,e){if(t.length===0)return[];let n=[];for(let r of t){let o=n[n.length-1];if(o&&o.role===r.role){let s=o[e],i=r[e];Array.isArray(s)&&Array.isArray(i)&&s.push(...i)}else n.push({...r})}return n}function ys(t){return t.function?.name?{name:t.function.name,description:t.function.description,parameters:t.function.parameters}:{name:t.name,description:t.description,parameters:t.input_schema}}function wu(t,e){if(e==="gemini")return t.isBase64?{inlineData:{mimeType:t.mediaType,data:t.url.split(",").pop()||t.url}}:{fileData:{mimeType:t.mediaType,fileUri:t.url}};if(e==="claude")return{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.url.startsWith("data:")&&t.url.split(",").pop()||t.url}};throw new Error(`Unsupported provider for image processing: ${e}`)}function Qi(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof mu.default=="function"?mu.default:mu.default.default;if(typeof e!="function")return t;let n=/(\$\$?[\s\S]+?\$\$?|\\\(?:[\s\S]+?\\\)|\\\[[\s\S]+?\\\]|\\(?:[a-zA-Z]+))/g;return t.replace(n,r=>{let o=r,s;do s=o,o=e(o);while(o!==s);return o.replace(/\$([^$]+)\$/g,"$1")})}catch{return t}}function Mk(t){if(!t)return"unnamed_function";let e=t.replace(/[^a-zA-Z0-9_.:-]/g,"_");return/^[^a-zA-Z_]/.test(e)&&(e="_"+e),e.substring(0,128)}function qr(t){let e=t?.input_tokens||0,n=t?.cache_read_input_tokens||0,r=t?.cache_creation_input_tokens||0,o=t?.output_tokens||0;return{completion_tokens:o,prompt_tokens:e+n+r,prompt_tokens_details:{cached_tokens:n,cache_write_tokens:r},total_tokens:e+n+r+o}}function Wh(t){switch(t){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"stop_sequence":case"pause_turn":return"stop";default:return typeof t=="string"&&t?"stop":null}}function Bk(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=_u(s.role,{assistant:"assistant"}),a=[];if(s.role==="tool"){let u=s.content;Array.isArray(u)?u=u.filter(d=>d.type==="text").map(d=>d.text).join(`
152
- `):typeof u=="object"&&u!==null&&(u=JSON.stringify(u)),a.push({type:"tool_result",tool_use_id:s.tool_call_id,content:u,...s.cache_control?{cache_control:s.cache_control}:{}})}else typeof s.content=="string"?a.push({type:"text",text:s.content,...s.cache_control?{cache_control:s.cache_control}:{}}):Array.isArray(s.content)&&(s.content.forEach(d=>{d.type==="text"&&a.push({type:"text",text:d.text||"",...d.cache_control?{cache_control:d.cache_control}:{}})}),bu(s.content).forEach(d=>{a.push(wu(d,"claude"))})),s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(u=>{a.push({type:"tool_use",id:u.id,name:u.function.name,input:JSON.parse(u.function.arguments||"{}")})});a.length>0&&e.push({role:i,content:a})}let r={anthropic_version:"vertex-2023-10-16",messages:Cu(e,"content"),max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(o=>{let s=ys(o);return{name:s.name,description:s.description,input_schema:s.parameters,...o.cache_control?{cache_control:o.cache_control}:{}}})),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),$c(r)}function Uk(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(i=>i.type==="text"?{type:"text",text:i.text||""}:i.type==="image"&&i.source?{type:"image_url",image_url:{url:i.source.data},media_type:i.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function ku(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o=Array.isArray(r.content)?r.content:[],s=o.filter(h=>h?.type==="text"&&typeof h.text=="string").map(h=>h.text),i=o.find(h=>h?.type==="thinking"&&typeof h.thinking=="string"),a,u=o.filter(h=>h?.type==="tool_use");u.length>0?a=u.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})):Array.isArray(r.tool_use)&&r.tool_use.length>0&&(a=r.tool_use.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})));let d=Wh(r.stop_reason),f={role:"assistant",content:s.length>0?s.join(""):null,...a&&{tool_calls:a}};i&&(f.thinking={content:i.thinking,signature:i.signature});let p={id:r.id,choices:[{finish_reason:d,index:0,message:f}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:qr(r.usage)};return new Response(JSON.stringify(p),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r={},o="",s="",i=new Map;return Ne(t,(u,d)=>{let{controller:f,encoder:p}=d;if(u.startsWith("data: ")){let h=u.slice(6).trim();if(h){n?.debug({chunkStr:h},`${e} chunk:`);try{let g=JSON.parse(h);if(g.type==="message_start"){r=g.message?.usage||g.usage||{},o=g.message?.id||g.id||o,s=g.message?.model||g.model||s;let b={choices:[{delta:{role:"assistant"},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:o,model:s,object:"chat.completion.chunk"};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
151
+ `)}var mu=nr(Nk(),1),rI={STOP:"stop",MAX_TOKENS:"length",SAFETY:"content_filter",RECITATION:"content_filter",BLOCKLIST:"content_filter",PROHIBITED_CONTENT:"content_filter",SPII:"content_filter",IMAGE_SAFETY:"content_filter"},qh="\u26A0\uFE0F Upstream ended the turn without a reply";function Xi(t){return t?rI[t.toUpperCase()]||t.toLowerCase():null}function Hh(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${qh} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var yu=class{constructor(e){this.emit=e}emit;_hasThinking=!1;_sigSent=!1;_contentSent=!1;_buffer="";processThinking(e,n){this._hasThinking=!0,this.emit.thinking(e,n)}processSignature(e,n){this.processSignatureWithMeta(e,n)}processSignatureWithMeta(e,n,r){if(!this._sigSent){if(this._contentSent){this._sigSent=!0;return}this._hasThinking||(this._hasThinking=!0,this.emit.thinking("(no content)",n)),this._sigSent=!0,this.emit.signature(e,n),r?.beforeFlush?.(),this.flushBufferedContent(r?.flushMeta)}}processContent(e,n,r){this._sigSent||!this._hasThinking?(this._contentSent=!0,this.emit.content(e,{chunk:n,candidate:r,mode:"direct"})):this._buffer+=e}emitContentPlaceholder(e,n){this._contentSent=!0,this.emit.content(e,{chunk:n?.chunk,candidate:n?.candidate,mode:"placeholder",finishReason:n?.finishReason})}bufferContent(e){this._buffer+=e}finalize(e,n,r){if(this._hasThinking&&!this._sigSent){this.processSignatureWithMeta(`ccr_${Date.now()}`,e,{beforeFlush:r?.beforeFlush,flushMeta:{chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Xi(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Xi(n?.finishReason)})}flushBufferedContent(e){this._buffer&&(this._contentSent=!0,this.emit.content(this._buffer,{chunk:e?.chunk,candidate:e?.candidate,mode:e?.mode||"buffered",finishReason:e?.finishReason}),this._buffer="")}shouldDeferContent(e,n){return this._hasThinking&&!this._sigSent&&!e&&!n}get hasBufferedContent(){return this._buffer.length>0}get hasThinkingContent(){return this._hasThinking}get signatureSent(){return this._sigSent}get contentSent(){return this._contentSent}get needsContentPlaceholder(){return this._sigSent&&!this._contentSent}acknowledgeSignature(){this._sigSent=!0}};function _u(t,e){return e[t]||t}function bu(t){return!t||typeof t=="string"?[]:t.filter(e=>e.type==="image_url").map(e=>({url:e.image_url.url,mediaType:e.media_type||"image/jpeg",isBase64:e.image_url.url.startsWith("data:")}))}function Cu(t,e){if(t.length===0)return[];let n=[];for(let r of t){let o=n[n.length-1];if(o&&o.role===r.role){let s=o[e],i=r[e];Array.isArray(s)&&Array.isArray(i)&&s.push(...i)}else n.push({...r})}return n}function ys(t){return t.function?.name?{name:t.function.name,description:t.function.description,parameters:t.function.parameters}:{name:t.name,description:t.description,parameters:t.input_schema}}function wu(t,e){if(e==="gemini")return t.isBase64?{inlineData:{mimeType:t.mediaType,data:t.url.split(",").pop()||t.url}}:{fileData:{mimeType:t.mediaType,fileUri:t.url}};if(e==="claude")return{type:"image",source:{type:"base64",media_type:t.mediaType,data:t.url.startsWith("data:")&&t.url.split(",").pop()||t.url}};throw new Error(`Unsupported provider for image processing: ${e}`)}function Qi(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof mu.default=="function"?mu.default:mu.default.default;if(typeof e!="function")return t;let n=/(\$\$?[\s\S]+?\$\$?|\\\(?:[\s\S]+?\\\)|\\\[[\s\S]+?\\\]|\\(?:[a-zA-Z]+))/g;return t.replace(n,r=>{let o=r,s;do s=o,o=e(o);while(o!==s);return o.replace(/\$([^$]+)\$/g,"$1")})}catch{return t}}function Mk(t){if(!t)return"unnamed_function";let e=t.replace(/[^a-zA-Z0-9_.:-]/g,"_");return/^[^a-zA-Z_]/.test(e)&&(e="_"+e),e.substring(0,128)}function qr(t){let e=t?.input_tokens||0,n=t?.cache_read_input_tokens||0,r=t?.cache_creation_input_tokens||0,o=t?.output_tokens||0;return{completion_tokens:o,prompt_tokens:e+n+r,prompt_tokens_details:{cached_tokens:n,cache_write_tokens:r},total_tokens:e+n+r+o}}function zh(t){switch(t){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"stop_sequence":case"pause_turn":return"stop";default:return typeof t=="string"&&t?"stop":null}}function Bk(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=_u(s.role,{assistant:"assistant"}),a=[];if(s.role==="tool"){let u=s.content;Array.isArray(u)?u=u.filter(d=>d.type==="text").map(d=>d.text).join(`
152
+ `):typeof u=="object"&&u!==null&&(u=JSON.stringify(u)),a.push({type:"tool_result",tool_use_id:s.tool_call_id,content:u,...s.cache_control?{cache_control:s.cache_control}:{}})}else typeof s.content=="string"?a.push({type:"text",text:s.content,...s.cache_control?{cache_control:s.cache_control}:{}}):Array.isArray(s.content)&&(s.content.forEach(d=>{d.type==="text"&&a.push({type:"text",text:d.text||"",...d.cache_control?{cache_control:d.cache_control}:{}})}),bu(s.content).forEach(d=>{a.push(wu(d,"claude"))})),s.tool_calls&&s.tool_calls.length>0&&s.tool_calls.forEach(u=>{a.push({type:"tool_use",id:u.id,name:u.function.name,input:JSON.parse(u.function.arguments||"{}")})});a.length>0&&e.push({role:i,content:a})}let r={anthropic_version:"vertex-2023-10-16",messages:Cu(e,"content"),max_tokens:t.max_tokens||1e3,stream:t.stream||!1,...t.temperature&&{temperature:t.temperature}};return t.tools&&t.tools.length>0&&(r.tools=t.tools.map(o=>{let s=ys(o);return{name:s.name,description:s.description,input_schema:s.parameters,...o.cache_control?{cache_control:o.cache_control}:{}}})),t.tool_choice&&(t.tool_choice==="auto"||t.tool_choice==="none"?r.tool_choice=t.tool_choice:typeof t.tool_choice=="string"&&(r.tool_choice={type:"tool",name:t.tool_choice})),$c(r)}function jk(t){let e=t,r={messages:e.messages.map(o=>{let s=o.content.map(i=>i.type==="text"?{type:"text",text:i.text||""}:i.type==="image"&&i.source?{type:"image_url",image_url:{url:i.source.data},media_type:i.source.media_type}:{type:"text",text:""});return{role:o.role,content:s}}),model:t.model||"claude-sonnet-4@20250514",max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream};return e.tools&&e.tools.length>0&&(r.tools=e.tools.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:{type:"object",properties:o.input_schema.properties,required:o.input_schema.required,additionalProperties:o.input_schema.additionalProperties,$schema:o.input_schema.$schema}}}))),e.tool_choice&&(typeof e.tool_choice=="string"?r.tool_choice=e.tool_choice:e.tool_choice.type==="tool"&&(r.tool_choice=e.tool_choice.name)),r}async function ku(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o=Array.isArray(r.content)?r.content:[],s=o.filter(h=>h?.type==="text"&&typeof h.text=="string").map(h=>h.text),i=o.find(h=>h?.type==="thinking"&&typeof h.thinking=="string"),a,u=o.filter(h=>h?.type==="tool_use");u.length>0?a=u.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})):Array.isArray(r.tool_use)&&r.tool_use.length>0&&(a=r.tool_use.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})));let d=zh(r.stop_reason),f={role:"assistant",content:s.length>0?s.join(""):null,...a&&{tool_calls:a}};i&&(f.thinking={content:i.thinking,signature:i.signature});let p={id:r.id,choices:[{finish_reason:d,index:0,message:f}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:qr(r.usage)};return new Response(JSON.stringify(p),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r={},o="",s="",i=new Map;return Ne(t,(u,d)=>{let{controller:f,encoder:p}=d;if(u.startsWith("data: ")){let h=u.slice(6).trim();if(h){n?.debug({chunkStr:h},`${e} chunk:`);try{let g=JSON.parse(h);if(g.type==="message_start"){r=g.message?.usage||g.usage||{},o=g.message?.id||g.id||o,s=g.message?.model||g.model||s;let b={choices:[{delta:{role:"assistant"},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:o,model:s,object:"chat.completion.chunk"};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
153
153
 
154
154
  `))}else if(g.type==="content_block_delta"&&g.delta?.type==="text_delta"){let b={choices:[{delta:{role:"assistant",content:g.delta.text||""},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
155
155
 
156
156
  `))}else if(g.type==="content_block_delta"&&g.delta?.type==="input_json_delta"){let b={choices:[{delta:{tool_calls:[{index:i.get(Number(g.index||0))??Number(g.index||0),function:{arguments:g.delta.partial_json||""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
157
157
 
158
- `))}else if(g.type==="content_block_delta"&&g.delta?.type==="thinking_delta"){let b={choices:[{delta:{thinking:{content:g.delta.thinking||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
158
+ `))}else if(g.type==="content_block_delta"&&g.delta?.type==="thinking_delta"){let b=g.delta.thinking||"";if(!b)return;let m={choices:[{delta:{thinking:{content:b}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(m)}
159
159
 
160
160
  `))}else if(g.type==="content_block_delta"&&g.delta?.type==="signature_delta"){let b={choices:[{delta:{thinking:{signature:g.delta.signature||""}},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
161
161
 
162
162
  `))}else if(g.type==="content_block_start"&&g.content_block?.type==="tool_use"){let b=Number(g.index||0),m=i.size;i.set(b,m);let w={choices:[{delta:{tool_calls:[{index:m,id:g.content_block.id,type:"function",function:{name:g.content_block.name,arguments:""}}]},finish_reason:null,index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(w)}
163
163
 
164
- `))}else if(g.type==="message_delta"){let b={choices:[{delta:{},finish_reason:Wh(g.delta?.stop_reason)||"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:qr({...r,...g.usage})};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
164
+ `))}else if(g.type==="message_delta"){let b={choices:[{delta:{},finish_reason:zh(g.delta?.stop_reason)||"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:qr({...r,...g.usage})};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
165
165
 
166
166
  `))}else if(g.type==="message_stop")f.enqueue(p.encode(`data: [DONE]
167
167
 
168
- `));else{if(g.type==="content_block_start"||g.type==="content_block_stop"||g.type==="ping")return;{let b={choices:[{delta:{role:"assistant",content:g.content?.[0]?.text||""},finish_reason:Wh(g.stop_reason),index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
168
+ `));else{if(g.type==="content_block_start"||g.type==="content_block_stop"||g.type==="ping")return;{let b={choices:[{delta:{role:"assistant",content:g.content?.[0]?.text||""},finish_reason:zh(g.stop_reason),index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:qr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
169
169
 
170
- `))}}}catch(g){n?.error(`Error parsing ${e} stream chunk`,h,g.message)}}}})}return t}import{randomUUID as Vk}from"crypto";import{existsSync as Au,readFileSync as Lk,writeFileSync as $k,mkdirSync as qk}from"fs";import{dirname as Hk,join as zk}from"path";import{homedir as Wk}from"os";import{randomBytes as rI}from"crypto";var oI=zk(Wk(),".claude-code-router","claude_auth.json"),sI=zk(Wk(),".claude-code-router","claude_device.json"),iI=/^[0-9a-f]{64}$/;function Gk(){return process.env.CCR_CLAUDE_AUTH_FILE||oI}function aI(){return process.env.CCR_CLAUDE_DEVICE_FILE||sI}var jk={client_id:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorization_endpoint:"https://claude.ai/oauth/authorize",token_endpoint:"https://platform.claude.com/v1/oauth/token",scope:"user:profile user:inference user:sessions:claude_code user:mcp_servers"},Su=null;function Gh(){try{let t=Gk();if(!Au(t))return null;let e=Lk(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function Jh(t){let e=Gk(),n=Hk(e);Au(n)||qk(n,{recursive:!0}),$k(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function cI(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function Kh(t){let e=await fetch(jk.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:jk.client_id,refresh_token:t})});if(!e.ok){let r=await e.text();throw new Error(`Token refresh failed (${e.status}): ${r}`)}let n=await e.json();return{access_token:n.access_token,refresh_token:n.refresh_token,id_token:n.id_token,token_type:n.token_type||"Bearer",scope:n.scope,expires_at:n.expires_at||Date.now()/1e3+(n.expires_in||3600),last_refresh:Date.now()/1e3}}async function Eu(t){let e=Gh();if(!e)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(t?.force||cI(e)){if(!e.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");Su||(Su=Kh(e.refresh_token).then(n=>(Jh(n),n)).finally(()=>{Su=null})),e=await Su}return e}function Jk(){let t=aI();try{if(Au(t)){let r=JSON.parse(Lk(t,"utf-8"));if(typeof r.device_id=="string"&&iI.test(r.device_id))return r.device_id}}catch{}let e=rI(32).toString("hex"),n=Hk(t);return Au(n)||qk(n,{recursive:!0}),$k(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}function Zi(t){let e=new URL(t||"https://api.anthropic.com"),n=e.pathname.replace(/\/$/,"");return n.endsWith("/v1/messages")||(e.pathname=`${n}/v1/messages`.replace(/\/+/g,"/")),e.searchParams.set("beta","true"),e.toString()}var Kk="oauth-2025-04-20";function uI(...t){let e=new Set,n=[];for(let r of t)if(r)for(let o of r.split(",")){let s=o.trim();if(!s)continue;let i=s.toLowerCase();e.has(i)||(e.add(i),n.push(s))}return n.join(",")}function Vh(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n)continue;if(o==null)return;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a).length>0);return i.length?i.map(String).join(", "):void 0}let s=String(o);return s.length?s:void 0}}function lI(t){return t?.startsWith("claude-cli/")??!1}function Yh(t){return t.clientBeta?.trim()?uI(t.clientBeta,Kk):Kk}function Qh(t,e){let{requestedOneMillion:n}=Dn(t),r=ps(t),o=u=>jh(r,u),i=Dn(t).modelId.toLowerCase().includes("haiku")?[]:["claude-code-20250219"];e?.includeOAuthBeta!==!1&&i.push("oauth-2025-04-20"),n&&i.push("context-1m-2025-08-07"),dk(r)&&i.push("interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13"),o("context_management")&&i.push("context-management-2025-06-27"),i.push("prompt-caching-scope-2026-01-05"),o("mid_conv_system")&&i.push("mid-conversation-system-2026-04-07"),e?.includeToolSearch&&i.push("advanced-tool-use-2025-11-20"),e?.includeEffort&&o("effort")&&i.push("effort-2025-11-24"),e?.includeFallbackCredit&&i.push("fallback-credit-2026-06-01");let a=e?.envBeta??process.env.ANTHROPIC_BETAS;for(let u of a?.split(",")||[]){let d=u.trim();d&&!i.includes(d)&&i.push(d)}return i.join(",")}function Zh(t,e){if(!t||!e)return t;let n=Dn(t).modelId;return ps(n)?.nativeOneMillion?n:`${n}[1m]`}function eg(t,e){let n=o=>jh(e,o),r=o=>{o&&typeof o=="object"&&!n("effort")&&delete o.effort};r(t.thinking),r(t.output_config),t.thinking&&typeof t.thinking=="object"&&t.thinking.type!=="disabled"&&(t.thinking=n("adaptive_thinking")?{type:"adaptive",display:"omitted"}:{type:"enabled",...t.thinking.budget_tokens!==void 0?{budget_tokens:t.thinking.budget_tokens}:{},display:"omitted"}),e&&typeof t.max_tokens=="number"&&(t.max_tokens=Math.min(t.max_tokens,e.maxOutputTokens.upper))}var dI="0.94.0";function fI(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function pI(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Xh;function Yk(){return Xh||(Xh=Vk()),Xh}var hI=new Set(["authorization","x-api-key","anthropic-beta","cookie","set-cookie","host","content-length","content-encoding","connection","transfer-encoding","upgrade","te","trailer"]);function gI(){let t={};for(let e of(process.env.ANTHROPIC_CUSTOM_HEADERS||"").split(/\r?\n/)){if(!e.trim())continue;let n=e.indexOf(":");if(n<0)continue;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();!r||!o||hI.has(r.toLowerCase())||(t[r]=o)}return t}function tg(){let t=[ck,process.env.CLAUDE_AGENT_SDK_VERSION?`agent-sdk/${process.env.CLAUDE_AGENT_SDK_VERSION}`:void 0,process.env.CLAUDE_AGENT_SDK_CLIENT_APP?`client-app/${process.env.CLAUDE_AGENT_SDK_CLIENT_APP}`:void 0].filter(Boolean).join(", ");return{"User-Agent":process.env.ANTHROPIC_USER_AGENT||`claude-cli/${Bh} (external, ${t})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":Yk(),"x-client-request-id":Vk(),"x-stainless-arch":fI(),"x-stainless-lang":"js","x-stainless-os":pI(),"x-stainless-package-version":dI,"x-stainless-retry-count":"0","x-stainless-runtime":"node","x-stainless-runtime-version":process.version,"x-stainless-timeout":"600",...process.env.CLAUDE_CODE_CONTAINER_ID?{"x-claude-remote-container-id":process.env.CLAUDE_CODE_CONTAINER_ID}:{},...process.env.CLAUDE_CODE_REMOTE_SESSION_ID?{"x-claude-remote-session-id":process.env.CLAUDE_CODE_REMOTE_SESSION_ID}:{},...process.env.CLAUDE_AGENT_SDK_CLIENT_APP?{"x-client-app":process.env.CLAUDE_AGENT_SDK_CLIENT_APP}:{},...process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION&&!["0","false","no","off"].includes(process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION.trim().toLowerCase())?{"x-anthropic-additional-protection":"true"}:{},...gI()}}function ng(){return{user_id:JSON.stringify({device_id:Jk(),account_uuid:"",session_id:Yk()})}}var vu=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await Eu(),s=r?.req?.headers||{},i=Vh(s,"user-agent"),a=r?.protocolContext?.anthropicClientKind||(lI(i)?"claude_code":"other"),u=a==="claude_code",d=!r?.protocolContext||r.protocolContext.anthropicDestinationInScope===!0;if(a==="other"&&d&&!r?.protocolContext?.anthropicPolicyApplied){let g=iu(e);au(g,e.messages),cu(g),uu(g,e.messages);let b=new Map;lu(e,b),r&&(r.claudeAuthToolNameMap=b,r.protocolContext&&(r.protocolContext.claudeAuthToolNameMap=b))}else if(a==="other"){let g=r?.protocolContext?.claudeAuthToolNameMap;g&&r&&(r.claudeAuthToolNameMap=g)}let f=u?Vh(s,"anthropic-beta"):void 0,p=Yh(u?{clientBeta:f}:{clientBeta:Qh(Zh(e.model,r?.protocolContext?.requestedOneMillion))}),h={Authorization:`Bearer ${o.access_token}`,"anthropic-beta":p};if(u)for(let g of["user-agent","x-app","x-claude-code-session-id","anthropic-dangerous-direct-browser-access","x-client-request-id","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout"]){let b=Vh(s,g);b&&(h[g]=b)}else{Object.assign(h,tg());let g=ps(e.model);r&&(r.claudeAuthPostBuildHook=b=>{eg(b,g),b.metadata={...b.metadata||{},...ng()}})}return{body:e,config:{headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async auth(e,n,r){let o=await Eu(),s=r?.req?.headers||{},i=wo(s,"anthropic-beta");return{body:e,config:{url:Zi(n?.baseUrl),headers:{Authorization:`Bearer ${o.access_token}`,"anthropic-beta":Yh({clientBeta:i})},__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async transformResponseOut(e,n){let r=n?.claudeAuthToolNameMap??n?.protocolContext?.claudeAuthToolNameMap;if(r?.size&&e.ok){let s=e.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await e.json();return fs(i,r),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:e.headers})}if(s.includes("text/event-stream")&&e.body)return Ne(e,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
170
+ `))}}}catch(g){n?.error(`Error parsing ${e} stream chunk`,h,g.message)}}}})}return t}import{randomUUID as Vk}from"crypto";import{existsSync as Au,readFileSync as Lk,writeFileSync as $k,mkdirSync as qk}from"fs";import{dirname as Hk,join as zk}from"path";import{homedir as Wk}from"os";import{randomBytes as oI}from"crypto";var sI=zk(Wk(),".claude-code-router","claude_auth.json"),iI=zk(Wk(),".claude-code-router","claude_device.json"),aI=/^[0-9a-f]{64}$/;function Gk(){return process.env.CCR_CLAUDE_AUTH_FILE||sI}function cI(){return process.env.CCR_CLAUDE_DEVICE_FILE||iI}var Uk={client_id:"9d1c250a-e61b-44d9-88ed-5944d1962f5e",authorization_endpoint:"https://claude.ai/oauth/authorize",token_endpoint:"https://platform.claude.com/v1/oauth/token",scope:"user:profile user:inference user:sessions:claude_code user:mcp_servers"},Su=null;function Wh(){try{let t=Gk();if(!Au(t))return null;let e=Lk(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function Gh(t){let e=Gk(),n=Hk(e);Au(n)||qk(n,{recursive:!0}),$k(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function uI(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function Jh(t){let e=await fetch(Uk.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:Uk.client_id,refresh_token:t})});if(!e.ok){let r=await e.text();throw new Error(`Token refresh failed (${e.status}): ${r}`)}let n=await e.json();return{access_token:n.access_token,refresh_token:n.refresh_token,id_token:n.id_token,token_type:n.token_type||"Bearer",scope:n.scope,expires_at:n.expires_at||Date.now()/1e3+(n.expires_in||3600),last_refresh:Date.now()/1e3}}async function Eu(t){let e=Wh();if(!e)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(t?.force||uI(e)){if(!e.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");Su||(Su=Jh(e.refresh_token).then(n=>(Gh(n),n)).finally(()=>{Su=null})),e=await Su}return e}function Jk(){let t=cI();try{if(Au(t)){let r=JSON.parse(Lk(t,"utf-8"));if(typeof r.device_id=="string"&&aI.test(r.device_id))return r.device_id}}catch{}let e=oI(32).toString("hex"),n=Hk(t);return Au(n)||qk(n,{recursive:!0}),$k(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}function Zi(t){let e=new URL(t||"https://api.anthropic.com"),n=e.pathname.replace(/\/$/,"");return n.endsWith("/v1/messages")||(e.pathname=`${n}/v1/messages`.replace(/\/+/g,"/")),e.searchParams.set("beta","true"),e.toString()}var Kk="oauth-2025-04-20";function lI(...t){let e=new Set,n=[];for(let r of t)if(r)for(let o of r.split(",")){let s=o.trim();if(!s)continue;let i=s.toLowerCase();e.has(i)||(e.add(i),n.push(s))}return n.join(",")}function Kh(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n)continue;if(o==null)return;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a).length>0);return i.length?i.map(String).join(", "):void 0}let s=String(o);return s.length?s:void 0}}function dI(t){return t?.startsWith("claude-cli/")??!1}function Vh(t){return t.clientBeta?.trim()?lI(t.clientBeta,Kk):Kk}function Xh(t,e){let{requestedOneMillion:n}=Dn(t),r=ps(t),o=u=>jh(r,u),i=Dn(t).modelId.toLowerCase().includes("haiku")?[]:["claude-code-20250219"];e?.includeOAuthBeta!==!1&&i.push("oauth-2025-04-20"),n&&i.push("context-1m-2025-08-07"),dk(r)&&i.push("interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13"),o("context_management")&&i.push("context-management-2025-06-27"),i.push("prompt-caching-scope-2026-01-05"),o("mid_conv_system")&&i.push("mid-conversation-system-2026-04-07"),e?.includeToolSearch&&i.push("advanced-tool-use-2025-11-20"),e?.includeEffort&&o("effort")&&i.push("effort-2025-11-24"),e?.includeFallbackCredit&&i.push("fallback-credit-2026-06-01");let a=e?.envBeta??process.env.ANTHROPIC_BETAS;for(let u of a?.split(",")||[]){let d=u.trim();d&&!i.includes(d)&&i.push(d)}return i.join(",")}function Qh(t,e){if(!t||!e)return t;let n=Dn(t).modelId;return ps(n)?.nativeOneMillion?n:`${n}[1m]`}function Zh(t,e){let n=o=>jh(e,o),r=o=>{o&&typeof o=="object"&&!n("effort")&&delete o.effort};r(t.thinking),r(t.output_config),t.thinking&&typeof t.thinking=="object"&&t.thinking.type!=="disabled"&&(t.thinking=n("adaptive_thinking")?{type:"adaptive",display:"summarized"}:{type:"enabled",...t.thinking.budget_tokens!==void 0?{budget_tokens:t.thinking.budget_tokens}:{},display:"summarized"}),e&&typeof t.max_tokens=="number"&&(t.max_tokens=Math.min(t.max_tokens,e.maxOutputTokens.upper))}var fI="0.94.0";function pI(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function hI(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Yh;function Yk(){return Yh||(Yh=Vk()),Yh}var gI=new Set(["authorization","x-api-key","anthropic-beta","cookie","set-cookie","host","content-length","content-encoding","connection","transfer-encoding","upgrade","te","trailer"]);function mI(){let t={};for(let e of(process.env.ANTHROPIC_CUSTOM_HEADERS||"").split(/\r?\n/)){if(!e.trim())continue;let n=e.indexOf(":");if(n<0)continue;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();!r||!o||gI.has(r.toLowerCase())||(t[r]=o)}return t}function eg(){let t=[ck,process.env.CLAUDE_AGENT_SDK_VERSION?`agent-sdk/${process.env.CLAUDE_AGENT_SDK_VERSION}`:void 0,process.env.CLAUDE_AGENT_SDK_CLIENT_APP?`client-app/${process.env.CLAUDE_AGENT_SDK_CLIENT_APP}`:void 0].filter(Boolean).join(", ");return{"User-Agent":process.env.ANTHROPIC_USER_AGENT||`claude-cli/${Mh} (external, ${t})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":Yk(),"x-client-request-id":Vk(),"x-stainless-arch":pI(),"x-stainless-lang":"js","x-stainless-os":hI(),"x-stainless-package-version":fI,"x-stainless-retry-count":"0","x-stainless-runtime":"node","x-stainless-runtime-version":process.version,"x-stainless-timeout":"600",...process.env.CLAUDE_CODE_CONTAINER_ID?{"x-claude-remote-container-id":process.env.CLAUDE_CODE_CONTAINER_ID}:{},...process.env.CLAUDE_CODE_REMOTE_SESSION_ID?{"x-claude-remote-session-id":process.env.CLAUDE_CODE_REMOTE_SESSION_ID}:{},...process.env.CLAUDE_AGENT_SDK_CLIENT_APP?{"x-client-app":process.env.CLAUDE_AGENT_SDK_CLIENT_APP}:{},...process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION&&!["0","false","no","off"].includes(process.env.CLAUDE_CODE_ADDITIONAL_PROTECTION.trim().toLowerCase())?{"x-anthropic-additional-protection":"true"}:{},...mI()}}function tg(){return{user_id:JSON.stringify({device_id:Jk(),account_uuid:"",session_id:Yk()})}}var vu=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await Eu(),s=r?.req?.headers||{},i=Kh(s,"user-agent"),a=r?.protocolContext?.anthropicClientKind||(dI(i)?"claude_code":"other"),u=a==="claude_code",d=!r?.protocolContext||r.protocolContext.anthropicDestinationInScope===!0;if(a==="other"&&d&&!r?.protocolContext?.anthropicPolicyApplied){let g=iu(e);au(g,e.messages),cu(g),uu(g,e.messages);let b=new Map;lu(e,b),r&&(r.claudeAuthToolNameMap=b,r.protocolContext&&(r.protocolContext.claudeAuthToolNameMap=b))}else if(a==="other"){let g=r?.protocolContext?.claudeAuthToolNameMap;g&&r&&(r.claudeAuthToolNameMap=g)}let f=u?Kh(s,"anthropic-beta"):void 0,p=Vh(u?{clientBeta:f}:{clientBeta:Xh(Qh(e.model,r?.protocolContext?.requestedOneMillion))}),h={Authorization:`Bearer ${o.access_token}`,"anthropic-beta":p};if(u)for(let g of["user-agent","x-app","x-claude-code-session-id","anthropic-dangerous-direct-browser-access","x-client-request-id","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout"]){let b=Kh(s,g);b&&(h[g]=b)}else{Object.assign(h,eg());let g=ps(e.model);r&&(r.claudeAuthPostBuildHook=b=>{Zh(b,g),b.metadata={...b.metadata||{},...tg()}})}return{body:e,config:{headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async auth(e,n,r){let o=await Eu(),s=r?.req?.headers||{},i=wo(s,"anthropic-beta");return{body:e,config:{url:Zi(n?.baseUrl),headers:{Authorization:`Bearer ${o.access_token}`,"anthropic-beta":Vh({clientBeta:i})},__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async transformResponseOut(e,n){let r=n?.claudeAuthToolNameMap??n?.protocolContext?.claudeAuthToolNameMap;if(r?.size&&e.ok){let s=e.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await e.json();return fs(i,r),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:e.headers})}if(s.includes("text/event-stream")&&e.body)return Ne(e,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
171
171
  `));return}try{let u=JSON.parse(i.slice(6));fs(u,r),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
172
172
 
173
173
  `))}catch{a.controller.enqueue(a.encoder.encode(i+`
174
- `))}},{logger:this.logger})}let o=e.headers.get("anthropic-ratelimit-unified-overage-in-use");return o&&this.logger?.debug?.({overageInUse:o,overageStatus:e.headers.get("anthropic-ratelimit-unified-overage-status")},"claude-auth: subscription overage in use for this request"),e}async recoverUnauthorizedAuth(e){let n=Gh();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await Kh(n.refresh_token);return Jh(r),{Authorization:`Bearer ${r.access_token}`}}};function Tu(t){let e=t?.prompt_tokens_details?.cached_tokens||0,n=t?.prompt_tokens_details?.cache_write_tokens||0;return{input_tokens:Math.max(0,(t?.prompt_tokens||0)-e-n),output_tokens:t?.completion_tokens||0,cache_creation_input_tokens:n,cache_read_input_tokens:e}}function mI(t,e){if(!t||typeof t!="object")return;let n=structuredClone(t);if(n.effort!==void 0){let r=e?void 0:uw(n.effort);r?n.effort=r:delete n.effort}return Object.keys(n).length?n:void 0}var xu=class t{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}options;name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n,r){let o={};return this.useBearer?(o.Authorization=`Bearer ${n.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=n.apiKey,o.Authorization=void 0),{body:e,config:{url:Zi(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,r);o.model=Dn(o.model).modelId;let s=r?.protocolContext,a=s?.anthropicDestinationInScope===!0&&s.anthropicClientKind==="other"&&s.anthropicPolicyApplied===!0&&s?.anthropicProviderMode==="api_key";a&&(eg(o,ps(o.model)),o.metadata={...o.metadata||{},...ng()}),r?.claudeAuthPostBuildHook?.(o);let u=Zi(n?.baseUrl),d={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return a&&Object.assign(d,tg(),{"anthropic-beta":Qh(Zh(o.model,s?.requestedOneMillion),{includeOAuthBeta:!1})}),!n?.transformer?.use?.some(p=>p?.name==="claude-auth")&&(this.useBearer?(d.Authorization=`Bearer ${n.apiKey}`,d["x-api-key"]=void 0):(d["x-api-key"]=n.apiKey,d.Authorization=void 0)),{body:o,config:{url:u,headers:d}}}async transformResponseOut(e,n){let r=await ku(e,this.name,this.logger),o=n?.protocolContext?.claudeAuthToolNameMap;if(!o?.size||!r.ok)return r;let s=r.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await r.json();return fs(i,o),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:r.headers})}return s.includes("text/event-stream")&&r.body?Ne(r,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
174
+ `))}},{logger:this.logger})}let o=e.headers.get("anthropic-ratelimit-unified-overage-in-use");return o&&this.logger?.debug?.({overageInUse:o,overageStatus:e.headers.get("anthropic-ratelimit-unified-overage-status")},"claude-auth: subscription overage in use for this request"),e}async recoverUnauthorizedAuth(e){let n=Wh();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await Jh(n.refresh_token);return Gh(r),{Authorization:`Bearer ${r.access_token}`}}};function Tu(t){let e=t?.prompt_tokens_details?.cached_tokens||0,n=t?.prompt_tokens_details?.cache_write_tokens||0;return{input_tokens:Math.max(0,(t?.prompt_tokens||0)-e-n),output_tokens:t?.completion_tokens||0,cache_creation_input_tokens:n,cache_read_input_tokens:e}}function yI(t,e){if(!t||typeof t!="object")return;let n=structuredClone(t);if(n.effort!==void 0){let r=e?void 0:uw(n.effort);r?n.effort=r:delete n.effort}return Object.keys(n).length?n:void 0}var xu=class t{constructor(e){this.options=e;this.useBearer=this.options?.UseBearer??!1}options;name="Anthropic";endPoint="/v1/messages";useBearer;logger;async auth(e,n,r){let o={};return this.useBearer?(o.Authorization=`Bearer ${n.apiKey}`,o["x-api-key"]=void 0):(o["x-api-key"]=n.apiKey,o.Authorization=void 0),{body:e,config:{url:Zi(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,r);o.model=Dn(o.model).modelId;let s=r?.protocolContext,a=s?.anthropicDestinationInScope===!0&&s.anthropicClientKind==="other"&&s.anthropicPolicyApplied===!0&&s?.anthropicProviderMode==="api_key";a&&(Zh(o,ps(o.model)),o.metadata={...o.metadata||{},...tg()}),r?.claudeAuthPostBuildHook?.(o);let u=Zi(n?.baseUrl),d={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return a&&Object.assign(d,eg(),{"anthropic-beta":Xh(Qh(o.model,s?.requestedOneMillion),{includeOAuthBeta:!1})}),!n?.transformer?.use?.some(p=>p?.name==="claude-auth")&&(this.useBearer?(d.Authorization=`Bearer ${n.apiKey}`,d["x-api-key"]=void 0):(d["x-api-key"]=n.apiKey,d.Authorization=void 0)),{body:o,config:{url:u,headers:d}}}async transformResponseOut(e,n){let r=await ku(e,this.name,this.logger),o=n?.protocolContext?.claudeAuthToolNameMap;if(!o?.size||!r.ok)return r;let s=r.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await r.json();return fs(i,o),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:r.headers})}return s.includes("text/event-stream")&&r.body?Ne(r,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
175
175
  `));return}try{let u=JSON.parse(i.slice(6));fs(u,o),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
176
176
 
177
177
  `))}catch{a.controller.enqueue(a.encoder.encode(i+`
178
178
  `))}},{logger:this.logger}):r}async transformRequestOut(e,n){n&&(n.unifiedRequest=wk(e));let r=[];if(e.system){if(typeof e.system=="string")r.push({role:"system",content:e.system});else if(Array.isArray(e.system)&&e.system.length){let f=e.system.filter(p=>p.type==="text"&&p.text).map(p=>({type:"text",text:p.text,cache_control:p.cache_control}));r.push({role:"system",content:f})}}JSON.parse(JSON.stringify(e.messages||[]))?.forEach(f=>{if(f.role==="user"||f.role==="assistant"){if(typeof f.content=="string"){r.push({role:f.role,content:f.content});return}if(Array.isArray(f.content)){if(f.role==="user"){let p=f.content.filter(g=>g.type==="tool_result"&&g.tool_use_id);p.length&&p.forEach(g=>{let b={role:"tool",content:typeof g.content=="string"?g.content:Array.isArray(g.content)&&g.content.filter(m=>m.type==="text"&&m.text).map(m=>m.text).join(`
179
179
  `)||JSON.stringify(g.content),tool_call_id:ur(g.tool_use_id)??g.tool_use_id,cache_control:g.cache_control};r.push(b)});let h=f.content.filter(g=>g.type==="text"&&g.text||g.type==="image"&&g.source);h.length&&r.push({role:"user",content:h.map(g=>g?.type==="image"?{type:"image_url",image_url:{url:g.source?.type==="base64"?Ck(g.source.data,g.source.media_type):g.source.url},media_type:g.source.media_type,cache_control:g.cache_control}:g)})}else if(f.role==="assistant"){let p={role:"assistant",content:""},h=f.content.filter(m=>m.type==="text"&&m.text);h.length&&(p.content=h.some(m=>m.cache_control)?h.map(m=>({type:"text",text:m.text,cache_control:m.cache_control})):h.map(m=>m.text).join(`
180
- `));let g=f.content.filter(m=>m.type==="tool_use"&&m.id);g.length&&(p.tool_calls=g.map(m=>({id:ur(m.id)??m.id,type:"function",function:{name:m.name,arguments:JSON.stringify(m.input||{})},cache_control:m.cache_control})));let b=f.content.find(m=>m.type==="thinking"&&m.signature);b&&(p.thinking={content:b.thinking,signature:b.signature}),r.push(p)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice,...e.cache_control?{cache_control:e.cache_control}:{}},i=Dt(e.output_config?.effort??e.effort);if(e.thinking||i){let f=e.thinking?e.thinking.type==="enabled"||e.thinking.type==="adaptive":!0;s.reasoning={...ns(i,f),...typeof e.thinking?.budget_tokens=="number"?{max_tokens:e.thinking.budget_tokens}:{}}}let a=n?.protocolContext;a?.protocol==="anthropic_messages"&&(a.anthropicSource={...e.metadata?{metadata:JSON.parse(JSON.stringify(e.metadata))}:{},...e.thinking?{thinking:JSON.parse(JSON.stringify(e.thinking))}:{},...e.output_config?{outputConfig:JSON.parse(JSON.stringify(e.output_config))}:{},...e.stop_sequences?{stopSequences:[...e.stop_sequences]}:{}}),Array.isArray(n?.provider?.transformer?.use)&&n.provider.transformer.use.some(f=>f?.name==="claude-auth")&&(e.thinking&&(s.anthropic_thinking=e.thinking),e.output_config&&(s.anthropic_output_config=e.output_config),e.metadata&&(s.anthropic_metadata=e.metadata),e.stop_sequences&&(s.anthropic_stop_sequences=e.stop_sequences)),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:e.tool_choice.type==="any"?s.tool_choice="required":s.tool_choice=e.tool_choice.type,e.tool_choice.disable_parallel_tool_use===!0&&(s.parallel_tool_calls=!1));let d=e.output_config?.format;if(d?.type==="json_schema"&&d.schema&&typeof d.schema=="object"){let f=typeof d.name=="string"&&d.name.length>0?d.name:"response";s.response_format={type:"json_schema",json_schema:{name:f,schema:d.schema,...d.strict!==void 0?{strict:d.strict}:{}}}}return s}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}static buildAnthropicBody(e,n,r){let o=[],s=w=>{if(typeof w=="string"){w&&o.push({type:"text",text:w});return}if(Array.isArray(w))for(let C of w)C?.type==="text"&&C.text&&o.push({type:"text",text:C.text,...C.cache_control?{cache_control:C.cache_control}:{}})};e.system&&s(e.system);let i=[];for(let w of e.messages){if(w.role==="system"||w.role==="developer"){s(w.content);continue}if(w.role==="tool"){let C={type:"tool_result",tool_use_id:ur(w.tool_call_id)??w.tool_call_id,content:typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.filter(k=>k?.type==="text").map(k=>({type:"text",text:k.text||"",...k.cache_control?{cache_control:k.cache_control}:{}})):JSON.stringify(w.content),...w.cache_control?{cache_control:w.cache_control}:{}},A=i[i.length-1];A?.role==="user"&&Array.isArray(A.content)?A.content.push(C):i.push({role:"user",content:[C]});continue}if(w.role==="assistant"){let C=[],A=cs(w);if(A.thinking){let k=ss(A.thinking);C.push({type:"thinking",thinking:A.thinking.content,...k?{signature:k}:{}})}for(let k of A.texts)C.push({type:"text",text:k.text,...k.cache_control?{cache_control:k.cache_control}:{}});for(let k of A.images){let E=k.image_url?.url;if(typeof E=="string"&&E.startsWith("data:")){let[x,O]=E.split(","),q=x.split(":")[1]?.split(";")[0]??"image/jpeg";C.push({type:"image",source:{type:"base64",media_type:q,data:O}})}else typeof E=="string"&&C.push({type:"image",source:{type:"url",url:E}})}if(A.toolCalls.length)for(let k of A.toolCalls){let E={};try{E=JSON.parse(k.function.arguments||"{}")}catch(x){(n?.error??console.error)("Failed to parse tool_call arguments for tool '%s': %s",k.function.name,x)}C.push({type:"tool_use",id:ur(k.id)??k.id,name:k.function.name,input:E,...k.cache_control?{cache_control:k.cache_control}:{}})}C.length>0&&i.push({role:"assistant",content:C});continue}if(w.role==="user"){let C=[];if(typeof w.content=="string")C.push({type:"text",text:w.content});else if(Array.isArray(w.content)){for(let A of w.content)if(A.type==="text"&&A.text)C.push({type:"text",text:A.text,...A.cache_control?{cache_control:A.cache_control}:{}});else if(A.type==="image_url"&&A.image_url?.url){let k=A.image_url.url;if(k.startsWith("data:")){let[E,x]=k.split(","),O=E.split(":")[1]?.split(";")[0]??"image/jpeg";C.push({type:"image",source:{type:"base64",media_type:O,data:x},...A.cache_control?{cache_control:A.cache_control}:{}})}else C.push({type:"image",source:{type:"url",url:k},...A.cache_control?{cache_control:A.cache_control}:{}})}}C.length>0&&i.push({role:"user",content:C});continue}}let a;if(e.tools?.length){let w=e.tools.find(C=>C?.type!=="function"||!C?.function);if(w)throw J(`Tool type '${w?.type||"unknown"}' cannot be represented by Anthropic Messages`,400,"unsupported_hosted_tool","invalid_request_error");a=e.tools.map(C=>({name:C.function.name,description:C.function.description||"",input_schema:C.function.parameters,...C.cache_control?{cache_control:C.cache_control}:{}}))}let u;if(e.tool_choice){let w=e.tool_choice;w==="auto"?u={type:"auto"}:w==="required"?u={type:"any"}:typeof w=="string"?u={type:"tool",name:w}:w.type==="function"&&(u={type:"tool",name:w.function?.name})}e.parallel_tool_calls===!1&&e.tool_choice!=="none"&&(!u&&a?.length&&(u={type:"auto"}),u&&typeof u=="object"&&(u.disable_parallel_tool_use=!0));let d=o.length===1&&!o[0].cache_control?o[0].text:o.length>0?o:void 0,f={model:e.model,max_tokens:e.max_tokens??8192,messages:i,stream:e.stream??!0};d!==void 0&&(f.system=d),e.temperature!==void 0&&(f.temperature=e.temperature),e.top_p!==void 0&&(f.top_p=e.top_p),e.stop!==void 0&&(f.stop_sequences=Array.isArray(e.stop)?e.stop:[e.stop]),e.tool_choice!=="none"&&a?.length&&(f.tools=a),e.tool_choice!=="none"&&u&&(f.tool_choice=u);let p=r?.protocolContext?.anthropicSource,h=Ot(e.reasoning,e.thinking);h?f.thinking={type:"disabled"}:p?.thinking?f.thinking=p.thinking:e.anthropic_thinking?f.thinking=e.anthropic_thinking:(e.reasoning?.enabled||e.reasoning?.effort)&&(f.thinking={type:"adaptive"});let g=p?.outputConfig?p.outputConfig:e.anthropic_output_config?e.anthropic_output_config:e.reasoning?.effort?{effort:e.reasoning.effort}:void 0,b=mI(g,h)||{},m=e.response_format;return m?.type==="json_schema"&&m.json_schema?.schema&&typeof m.json_schema.schema=="object"&&(b.format={type:"json_schema",schema:m.json_schema.schema}),Object.keys(b).length&&(f.output_config=b),p?.metadata?f.metadata=p.metadata:e.anthropic_metadata&&(f.metadata=e.anthropic_metadata),p?.stopSequences?f.stop_sequences=p.stopSequences:e.anthropic_stop_sequences&&(f.stop_sequences=e.anthropic_stop_sequences),e.cache_control&&(f.cache_control=e.cache_control),f}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema},...n.cache_control?{cache_control:n.cache_control}:{}}))}async convertOpenAIStreamToAnthropic(e,n){let r=null,o=null;return new ReadableStream({start:async i=>{let a=new TextEncoder,u=`msg_${Date.now()}`,d=null,f="unknown",p=!1,h=!1,g=!1,b=new Map,m=new Map,w=0,C=0,A=!1;o=()=>{A=!0};let k=!1,E=0,x=-1,O=0,q=()=>{let te=E;return E++,te},V=te=>{if(!A)try{i.enqueue(te);let Q=new TextDecoder().decode(te);this.logger.debug({reqId:n.req.id,data:Q,type:"send data"})}catch(Q){if(Q instanceof TypeError&&Q.message.includes("Controller is already closed"))A=!0;else throw this.logger.debug({reqId:n.req.id,error:Q instanceof Error?Q.message:String(Q),type:"send data error"}),Q}},j=()=>{if(!A)try{if(x>=0){let Q={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
180
+ `));let g=f.content.filter(m=>m.type==="tool_use"&&m.id);g.length&&(p.tool_calls=g.map(m=>({id:ur(m.id)??m.id,type:"function",function:{name:m.name,arguments:JSON.stringify(m.input||{})},cache_control:m.cache_control})));let b=f.content.find(m=>m.type==="thinking"&&m.signature);b&&(p.thinking={content:b.thinking,signature:b.signature}),r.push(p)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice,...e.cache_control?{cache_control:e.cache_control}:{}},i=Dt(e.output_config?.effort??e.effort);if(e.thinking||i){let f=e.thinking?e.thinking.type==="enabled"||e.thinking.type==="adaptive":!0;s.reasoning={...ns(i,f),...typeof e.thinking?.budget_tokens=="number"?{max_tokens:e.thinking.budget_tokens}:{}}}let a=n?.protocolContext;a?.protocol==="anthropic_messages"&&(a.anthropicSource={...e.metadata?{metadata:JSON.parse(JSON.stringify(e.metadata))}:{},...e.thinking?{thinking:JSON.parse(JSON.stringify(e.thinking))}:{},...e.output_config?{outputConfig:JSON.parse(JSON.stringify(e.output_config))}:{},...e.stop_sequences?{stopSequences:[...e.stop_sequences]}:{}}),Array.isArray(n?.provider?.transformer?.use)&&n.provider.transformer.use.some(f=>f?.name==="claude-auth")&&(e.thinking&&(s.anthropic_thinking=e.thinking),e.output_config&&(s.anthropic_output_config=e.output_config),e.metadata&&(s.anthropic_metadata=e.metadata),e.stop_sequences&&(s.anthropic_stop_sequences=e.stop_sequences)),e.tool_choice&&(e.tool_choice.type==="tool"?s.tool_choice={type:"function",function:{name:e.tool_choice.name}}:e.tool_choice.type==="any"?s.tool_choice="required":s.tool_choice=e.tool_choice.type,e.tool_choice.disable_parallel_tool_use===!0&&(s.parallel_tool_calls=!1));let d=e.output_config?.format;if(d?.type==="json_schema"&&d.schema&&typeof d.schema=="object"){let f=typeof d.name=="string"&&d.name.length>0?d.name:"response";s.response_format={type:"json_schema",json_schema:{name:f,schema:d.schema,...d.strict!==void 0?{strict:d.strict}:{}}}}return s}async transformResponseIn(e,n){if(e.headers.get("Content-Type")?.includes("text/event-stream")){if(!e.body)throw new Error("Stream response body is null");let o=await this.convertOpenAIStreamToAnthropic(e.body,n);return new Response(o,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else{let o=await e.json(),s=this.convertOpenAIResponseToAnthropic(o,n);return new Response(JSON.stringify(s),{headers:{"Content-Type":"application/json"}})}}static buildAnthropicBody(e,n,r){let o=[],s=w=>{if(typeof w=="string"){w&&o.push({type:"text",text:w});return}if(Array.isArray(w))for(let C of w)C?.type==="text"&&C.text&&o.push({type:"text",text:C.text,...C.cache_control?{cache_control:C.cache_control}:{}})};e.system&&s(e.system);let i=[];for(let w of e.messages){if(w.role==="system"||w.role==="developer"){s(w.content);continue}if(w.role==="tool"){let C={type:"tool_result",tool_use_id:ur(w.tool_call_id)??w.tool_call_id,content:typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.filter(k=>k?.type==="text").map(k=>({type:"text",text:k.text||"",...k.cache_control?{cache_control:k.cache_control}:{}})):JSON.stringify(w.content),...w.cache_control?{cache_control:w.cache_control}:{}},S=i[i.length-1];S?.role==="user"&&Array.isArray(S.content)?S.content.push(C):i.push({role:"user",content:[C]});continue}if(w.role==="assistant"){let C=[],S=cs(w);if(S.thinking){let k=ss(S.thinking);C.push({type:"thinking",thinking:S.thinking.content,...k?{signature:k}:{}})}for(let k of S.texts)C.push({type:"text",text:k.text,...k.cache_control?{cache_control:k.cache_control}:{}});for(let k of S.images){let E=k.image_url?.url;if(typeof E=="string"&&E.startsWith("data:")){let[x,O]=E.split(","),q=x.split(":")[1]?.split(";")[0]??"image/jpeg";C.push({type:"image",source:{type:"base64",media_type:q,data:O}})}else typeof E=="string"&&C.push({type:"image",source:{type:"url",url:E}})}if(S.toolCalls.length)for(let k of S.toolCalls){let E={};try{E=JSON.parse(k.function.arguments||"{}")}catch(x){(n?.error??console.error)("Failed to parse tool_call arguments for tool '%s': %s",k.function.name,x)}C.push({type:"tool_use",id:ur(k.id)??k.id,name:k.function.name,input:E,...k.cache_control?{cache_control:k.cache_control}:{}})}C.length>0&&i.push({role:"assistant",content:C});continue}if(w.role==="user"){let C=[];if(typeof w.content=="string")C.push({type:"text",text:w.content});else if(Array.isArray(w.content)){for(let S of w.content)if(S.type==="text"&&S.text)C.push({type:"text",text:S.text,...S.cache_control?{cache_control:S.cache_control}:{}});else if(S.type==="image_url"&&S.image_url?.url){let k=S.image_url.url;if(k.startsWith("data:")){let[E,x]=k.split(","),O=E.split(":")[1]?.split(";")[0]??"image/jpeg";C.push({type:"image",source:{type:"base64",media_type:O,data:x},...S.cache_control?{cache_control:S.cache_control}:{}})}else C.push({type:"image",source:{type:"url",url:k},...S.cache_control?{cache_control:S.cache_control}:{}})}}C.length>0&&i.push({role:"user",content:C});continue}}let a;if(e.tools?.length){let w=e.tools.find(C=>C?.type!=="function"||!C?.function);if(w)throw J(`Tool type '${w?.type||"unknown"}' cannot be represented by Anthropic Messages`,400,"unsupported_hosted_tool","invalid_request_error");a=e.tools.map(C=>({name:C.function.name,description:C.function.description||"",input_schema:C.function.parameters,...C.cache_control?{cache_control:C.cache_control}:{}}))}let u;if(e.tool_choice){let w=e.tool_choice;w==="auto"?u={type:"auto"}:w==="required"?u={type:"any"}:typeof w=="string"?u={type:"tool",name:w}:w.type==="function"&&(u={type:"tool",name:w.function?.name})}e.parallel_tool_calls===!1&&e.tool_choice!=="none"&&(!u&&a?.length&&(u={type:"auto"}),u&&typeof u=="object"&&(u.disable_parallel_tool_use=!0));let d=o.length===1&&!o[0].cache_control?o[0].text:o.length>0?o:void 0,f={model:e.model,max_tokens:e.max_tokens??8192,messages:i,stream:e.stream??!0};d!==void 0&&(f.system=d),e.temperature!==void 0&&(f.temperature=e.temperature),e.top_p!==void 0&&(f.top_p=e.top_p),e.stop!==void 0&&(f.stop_sequences=Array.isArray(e.stop)?e.stop:[e.stop]),e.tool_choice!=="none"&&a?.length&&(f.tools=a),e.tool_choice!=="none"&&u&&(f.tool_choice=u);let p=r?.protocolContext?.anthropicSource,h=Ot(e.reasoning,e.thinking);h?f.thinking={type:"disabled"}:p?.thinking?f.thinking=p.thinking:e.anthropic_thinking?f.thinking=e.anthropic_thinking:(e.reasoning?.enabled||e.reasoning?.effort)&&(f.thinking={type:"adaptive"});let g=p?.outputConfig?p.outputConfig:e.anthropic_output_config?e.anthropic_output_config:e.reasoning?.effort?{effort:e.reasoning.effort}:void 0,b=yI(g,h)||{},m=e.response_format;return m?.type==="json_schema"&&m.json_schema?.schema&&typeof m.json_schema.schema=="object"&&(b.format={type:"json_schema",schema:m.json_schema.schema}),Object.keys(b).length&&(f.output_config=b),p?.metadata?f.metadata=p.metadata:e.anthropic_metadata&&(f.metadata=e.anthropic_metadata),p?.stopSequences?f.stop_sequences=p.stopSequences:e.anthropic_stop_sequences&&(f.stop_sequences=e.anthropic_stop_sequences),e.cache_control&&(f.cache_control=e.cache_control),f}convertAnthropicToolsToUnified(e){return e.map(n=>({type:"function",function:{name:n.name,description:n.description||"",parameters:n.input_schema},...n.cache_control?{cache_control:n.cache_control}:{}}))}async convertOpenAIStreamToAnthropic(e,n){let r=null,o=null;return new ReadableStream({start:async i=>{let a=new TextEncoder,u=`msg_${Date.now()}`,d=null,f="unknown",p=!1,h=!1,g=!1,b=new Map,m=new Map,w=0,C=0,S=!1;o=()=>{S=!0};let k=!1,E=0,x=-1,O=0,q=()=>{let te=E;return E++,te},V=te=>{if(!S)try{i.enqueue(te);let Q=new TextDecoder().decode(te);this.logger.debug({reqId:n.req.id,data:Q,type:"send data"})}catch(Q){if(Q instanceof TypeError&&Q.message.includes("Controller is already closed"))S=!0;else throw this.logger.debug({reqId:n.req.id,error:Q instanceof Error?Q.message:String(Q),type:"send data error"}),Q}},U=()=>{if(!S)try{if(x>=0){let Q={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
181
181
  data: ${JSON.stringify(Q)}
182
182
 
183
183
  `)),x=-1}if(d)O>0&&(d.usage.server_tool_use={web_search_requests:O}),V(a.encode(`event: message_delta
@@ -189,20 +189,20 @@ data: ${JSON.stringify({type:"message_delta",delta:{stop_reason:"end_turn",stop_
189
189
  `))}let te={type:"message_stop"};V(a.encode(`event: message_stop
190
190
  data: ${JSON.stringify(te)}
191
191
 
192
- `)),i.close(),A=!0}catch(te){if(te instanceof TypeError&&te.message.includes("Controller is already closed"))A=!0;else throw te}},ee=te=>{if(!A)try{x>=0&&(V(a.encode(`event: content_block_stop
192
+ `)),i.close(),S=!0}catch(te){if(te instanceof TypeError&&te.message.includes("Controller is already closed"))S=!0;else throw te}},ee=te=>{if(!S)try{x>=0&&(V(a.encode(`event: content_block_stop
193
193
  data: ${JSON.stringify({type:"content_block_stop",index:x})}
194
194
 
195
195
  `)),x=-1);let Q=te&&typeof te=="object"?te:{},_e=typeof Q.type=="string"?Q.type:"api_error",Oe=te instanceof Error?te.message:typeof Q.message=="string"?Q.message:String(te||"Upstream stream failed");V(a.encode(`event: error
196
196
  data: ${JSON.stringify({type:"error",error:{type:_e,message:Oe}})}
197
197
 
198
- `)),i.close(),A=!0}catch(Q){try{i.error(Q)}catch(_e){this.logger?.error(_e)}}},z=null;try{z=e.getReader(),r=z;let te=new TextDecoder,Q="";for(;!A;){let{done:_e,value:Oe}=await z.read();if(_e)break;Q+=te.decode(Oe,{stream:!0});let Te=Q.split(`
199
- `);Q=Te.pop()||"";for(let Ke of Te){if(A||g)break;if(!Ke.startsWith("data:"))continue;let ne=Ke.slice(5).trim();if(ne!=="[DONE]")try{let Z=JSON.parse(ne);if(Z.error){let we={type:"error",message:{type:"api_error",message:JSON.stringify(Z.error)}};V(a.encode(`event: error
198
+ `)),i.close(),S=!0}catch(Q){try{i.error(Q)}catch(_e){this.logger?.error(_e)}}},z=null;try{z=e.getReader(),r=z;let te=new TextDecoder,Q="";for(;!S;){let{done:_e,value:Oe}=await z.read();if(_e)break;Q+=te.decode(Oe,{stream:!0});let Te=Q.split(`
199
+ `);Q=Te.pop()||"";for(let Ke of Te){if(S||g)break;if(!Ke.startsWith("data:"))continue;let ne=Ke.slice(5).trim();if(ne!=="[DONE]")try{let Z=JSON.parse(ne);if(Z.error){let we={type:"error",message:{type:"api_error",message:JSON.stringify(Z.error)}};V(a.encode(`event: error
200
200
  data: ${JSON.stringify(we)}
201
201
 
202
- `));continue}if(f=Z.model||f,!p&&!A&&!g){p=!0;let we={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:f,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}};V(a.encode(`event: message_start
202
+ `));continue}if(f=Z.model||f,!p&&!S&&!g){p=!0;let we={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:f,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}};V(a.encode(`event: message_start
203
203
  data: ${JSON.stringify(we)}
204
204
 
205
- `))}let ae=Z.choices?.[0];if(Z.usage&&(d?d.usage=Tu(Z.usage):d={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Tu(Z.usage)}),!ae)continue;let Ie=Rn(ae?.delta);if(Ie&&!A&&!g){let we=typeof Ie.content=="string"?Ie.content:"",H=ss(Ie);if(we||H){if(x>=0&&!k){let Ee={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
205
+ `))}let ae=Z.choices?.[0];if(Z.usage&&(d?d.usage=Tu(Z.usage):d={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Tu(Z.usage)}),!ae)continue;let Ie=Rn(ae?.delta);if(Ie&&!S&&!g){let we=typeof Ie.content=="string"?Ie.content:"",H=ss(Ie);if(we||H){if(x>=0&&!k){let Ee={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
206
206
  data: ${JSON.stringify(Ee)}
207
207
 
208
208
  `)),x=-1,h=!1}if(!k){let Ee=q(),Ze={type:"content_block_start",index:Ee,content_block:{type:"thinking",thinking:""}};V(a.encode(`event: content_block_start
@@ -217,16 +217,16 @@ data: ${JSON.stringify(Ze)}
217
217
  `)),x=-1,k=!1}else if(we){let Ee={type:"content_block_delta",index:x,delta:{type:"thinking_delta",thinking:we}};V(a.encode(`event: content_block_delta
218
218
  data: ${JSON.stringify(Ee)}
219
219
 
220
- `))}}}if(ae?.delta?.content&&!A&&!g){if(w++,x>=0&&!h){let H={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
220
+ `))}}}if(ae?.delta?.content&&!S&&!g){if(w++,x>=0&&!h){let H={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
221
221
  data: ${JSON.stringify(H)}
222
222
 
223
223
  `)),x=-1,k=!1}if(!h&&!g){h=!0;let we=q(),H={type:"content_block_start",index:we,content_block:{type:"text",text:""}};V(a.encode(`event: content_block_start
224
224
  data: ${JSON.stringify(H)}
225
225
 
226
- `)),x=we}if(!A&&!g){let we={type:"content_block_delta",index:x,delta:{type:"text_delta",text:ae.delta.content}};V(a.encode(`event: content_block_delta
226
+ `)),x=we}if(!S&&!g){let we={type:"content_block_delta",index:x,delta:{type:"text_delta",text:ae.delta.content}};V(a.encode(`event: content_block_delta
227
227
  data: ${JSON.stringify(we)}
228
228
 
229
- `))}}if(ae?.delta?.annotations?.length&&!A&&!g){if(O+=ae.delta.annotations.length,x>=0&&h){let we={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
229
+ `))}}if(ae?.delta?.annotations?.length&&!S&&!g){if(O+=ae.delta.annotations.length,x>=0&&h){let we={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
230
230
  data: ${JSON.stringify(we)}
231
231
 
232
232
  `)),x=-1,h=!1}ae?.delta?.annotations.forEach(we=>{let H=q(),Ee={type:"content_block_start",index:H,content_block:{type:"web_search_tool_result",tool_use_id:`srvtoolu_${On()}`,content:[{type:"web_search_result",title:we.url_citation.title,url:we.url_citation.url}]}};V(a.encode(`event: content_block_start
@@ -235,32 +235,32 @@ data: ${JSON.stringify(Ee)}
235
235
  `));let Ze={type:"content_block_stop",index:H};V(a.encode(`event: content_block_stop
236
236
  data: ${JSON.stringify(Ze)}
237
237
 
238
- `))})}if(ae?.delta?.tool_calls&&!A&&!g){C++;let we=new Set;for(let H of ae.delta.tool_calls){if(A)break;let Ee=H.index??0;if(we.has(Ee))continue;if(we.add(Ee),!m.has(Ee)){if(x>=0){let R={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
238
+ `))})}if(ae?.delta?.tool_calls&&!S&&!g){C++;let we=new Set;for(let H of ae.delta.tool_calls){if(S)break;let Ee=H.index??0;if(we.has(Ee))continue;if(we.add(Ee),!m.has(Ee)){if(x>=0){let R={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
239
239
  data: ${JSON.stringify(R)}
240
240
 
241
- `)),x=-1}h=!1,k=!1;let X=q();m.set(Ee,X);let de=ur(H.id)||`call_${Date.now()}_${Ee}`,ce=H.function?.name||`tool_${Ee}`,S={type:"content_block_start",index:X,content_block:{type:"tool_use",id:de,name:ce,input:{}}};V(a.encode(`event: content_block_start
242
- data: ${JSON.stringify(S)}
241
+ `)),x=-1}h=!1,k=!1;let X=q();m.set(Ee,X);let de=ur(H.id)||`call_${Date.now()}_${Ee}`,ce=H.function?.name||`tool_${Ee}`,A={type:"content_block_start",index:X,content_block:{type:"tool_use",id:de,name:ce,input:{}}};V(a.encode(`event: content_block_start
242
+ data: ${JSON.stringify(A)}
243
243
 
244
- `)),x=X;let T={id:de,name:ce,arguments:"",contentBlockIndex:X};b.set(Ee,T)}else if(H.id&&H.function?.name){let X=b.get(Ee);X.id.startsWith("call_")&&X.name.startsWith("tool_")&&(X.id=H.id,X.name=H.function.name)}if(H.function?.arguments&&!A&&!g){let X=m.get(Ee);if(X===void 0)continue;let de=b.get(Ee);de&&(de.arguments+=H.function.arguments);try{let ce={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:H.function.arguments}};V(a.encode(`event: content_block_delta
244
+ `)),x=X;let T={id:de,name:ce,arguments:"",contentBlockIndex:X};b.set(Ee,T)}else if(H.id&&H.function?.name){let X=b.get(Ee);X.id.startsWith("call_")&&X.name.startsWith("tool_")&&(X.id=H.id,X.name=H.function.name)}if(H.function?.arguments&&!S&&!g){let X=m.get(Ee);if(X===void 0)continue;let de=b.get(Ee);de&&(de.arguments+=H.function.arguments);try{let ce={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:H.function.arguments}};V(a.encode(`event: content_block_delta
245
245
  data: ${JSON.stringify(ce)}
246
246
 
247
- `))}catch{try{let ce=H.function.arguments.replace(new RegExp("\\p{Cc}","gu"),"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:ce}};V(a.encode(`event: content_block_delta
248
- data: ${JSON.stringify(S)}
247
+ `))}catch{try{let ce=H.function.arguments.replace(new RegExp("\\p{Cc}","gu"),"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),A={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:ce}};V(a.encode(`event: content_block_delta
248
+ data: ${JSON.stringify(A)}
249
249
 
250
- `))}catch(ce){this.logger?.error(ce)}}}}}if(ae?.finish_reason&&!A&&!g){if(w===0&&C===0&&this.logger?.warn("No content in the stream response!"),x>=0){let we={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
250
+ `))}catch(ce){this.logger?.error(ce)}}}}}if(ae?.finish_reason&&!S&&!g){if(w===0&&C===0&&this.logger?.warn("No content in the stream response!"),x>=0){let we={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
251
251
  data: ${JSON.stringify(we)}
252
252
 
253
- `)),x=-1}if(!A){let H={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[ae.finish_reason]||"end_turn";m.size>0&&H==="end_turn"&&(H="tool_use"),d={type:"message_delta",delta:{stop_reason:H,stop_sequence:null},usage:Tu(Z.usage)}}break}}catch(Z){this.logger?.error(`parseError: ${Z.name} message: ${Z.message} stack: ${Z.stack} data: ${ne}`)}}}j()}catch(te){ee(te)}finally{if(r===z&&(r=null),z)try{z.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:async i=>{o?.();let a=r;r=null,a&&await a.cancel(i).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${i}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[],s=Rn(r.message);if(s?.content){let u=ss(s);o.push({type:"thinking",thinking:s.content,...u?{signature:u}:{}})}if(r.message.content&&o.push({type:"text",text:r.message.content}),r.message.annotations){let u=`srvtoolu_${On()}`;o.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:u,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(u=>{if(!("function"in u)||!u.function)return;let d={};try{let f=u.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:u.function.arguments||""}}o.push({type:"tool_use",id:ur(u.id)??u.id,name:u.function.name,input:d})});let i=String(r.finish_reason||""),a={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":i==="length"?"max_tokens":i==="tool_calls"?"tool_use":i==="content_filter"?"stop_sequence":i==="model_context_window_exceeded"?"model_context_window_exceeded":"end_turn",stop_sequence:null,usage:{...Tu(e.usage),...r.message.annotations?.length?{server_tool_use:{web_search_requests:r.message.annotations.length}}:{}}};return this.logger.debug({reqId:n.req.id,result:a},"Conversion complete, final Anthropic response"),a}catch{throw J(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var yI=new Set(["type","format","title","description","nullable","enum","maxItems","minItems","properties","required","minProperties","maxProperties","minLength","maxLength","pattern","example","anyOf","propertyOrdering","default","items","minimum","maximum","additionalProperties","allOf","oneOf"]);function Hr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Hr(r,e));let n={};for(let r in t){if(e!=="properties"&&!yI.has(r))continue;let o=t[r];if(!(r==="enum"&&t.type&&t.type!=="string")&&!(r==="format"&&t.type==="string"&&o&&!["enum","date-time"].includes(o))&&!(r==="format"&&o==="uri")&&r!=="$schema")if(r==="properties"&&typeof o=="object"&&!Array.isArray(o)){let s={};for(let i in o)s[i]=Hr(o[i]);n[r]=s}else r==="items"?n[r]=Hr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>Hr(s,r)):n[r]=o}if(Array.isArray(n.required)&&n.properties){let r=new Set(Object.keys(n.properties));n.required=n.required.filter(o=>r.has(o)),n.required.length===0&&delete n.required}return n}function _s(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(_s);let e={};for(let h in t){let g=t[h];if(h==="properties"&&g&&typeof g=="object"){let b={};for(let m in g)b[m]=_s(g[m]);e[h]=b}else h==="items"?e[h]=_s(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(_s):e[h]=g}let n=e.anyOf||e.oneOf;if(!Array.isArray(n)||e.type)return e;let r=n.filter(h=>h&&typeof h=="object"),o=r.find(h=>h.type)||r[0];if(!o)return e;let{anyOf:s,oneOf:i,description:a,...u}=e,d=[...new Set(r.filter(h=>h!==o).map(h=>String(h.description||h.type||"").split(" (alternatives:")[0]).filter(Boolean))],f={...o,...u},p=[a,o.description,...d].filter(Boolean);return p.length&&(f.description=d.length?`${p[0]} (alternatives: ${d.join("; ")})`:p[0]),f}function Ru(t){return!t||typeof t!="object"?t:Hr(t)}var ea=["minimal","low","medium","high"];function _I(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function bI(t){let e=_I(t);return e?e.includes("-image")||e.includes("imagen")?{kind:"none"}:e.startsWith("claude")?{kind:"budget",min:1024,max:64e3,requireMin:!0}:/^gemini-3(\.\d+)?\b/.test(e)||e.startsWith("gemini-pro-agent")?/^gemini-3-pro\b/.test(e)?{kind:"level",levels:["low","high"]}:e.includes("flash")?{kind:"level",levels:ea}:{kind:"level",levels:["low","medium","high"]}:/^gemini-2\.5/.test(e)?e.includes("pro")?{kind:"budget",min:128,max:32768}:{kind:"budget",min:0,max:24576}:{kind:"includeOnly"}:{kind:"includeOnly"}}function CI(t,e){let n=t.toLowerCase(),r=ea.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=ea.indexOf(n);return o<0?r[r.length-1]:r.find(s=>ea.indexOf(s)>=o)??r[r.length-1]}function wI(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function kI(t,e,n){return Math.min(Math.max(t,e),n)}function Xk(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=bI(t.model);if(r.kind==="none")return;let o=e.effort?.toLowerCase(),s=o==="none"||e.enabled===!1;if(r.kind==="includeOnly")return s?void 0:{includeThoughts:!0};if(r.kind==="level"){let d=ea.filter(f=>r.levels.includes(f));return s?{includeThoughts:!1,thinkingLevel:d[0]}:o?{includeThoughts:!0,thinkingLevel:CI(o,r.levels)}:{includeThoughts:!0}}if(s)return r.min===0?{includeThoughts:!1,thinkingBudget:0}:void 0;let i=e.max_tokens,a=typeof i=="number"?i:o?wI(o,r.max):void 0;if(typeof a!="number")return{includeThoughts:!0};let u=kI(a,r.min,r.max);if(t.max_tokens&&u>=t.max_tokens&&(u=t.max_tokens-1),u<r.min){if(r.requireMin)return;u=r.min}return{includeThoughts:!0,thinkingBudget:u}}var So=new Map,Qk=(t,e)=>`${t||"default"}${e}`;function Zk(t,e,n){if(!e||!n)return;let r=Qk(t,e);for(So.delete(r),So.set(r,{signature:n,expiresAt:Date.now()+216e5});So.size>4096;){let o=So.keys().next();if(o.done)break;So.delete(o.value)}}function eS(t,e){if(!e)return;let n=Qk(t,e),r=So.get(n);if(r){if(r.expiresAt<=Date.now()){So.delete(n);return}return r.signature}}function SI(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var bs={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function AI(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(bs).includes(r)?r:bs.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(bs).includes(o)?o:bs.TYPE_UNSPECIFIED})}}}function ta(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&AI(t.type,e);for(let[i,a]of Object.entries(t))if(a!=null)if(i=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(a))continue;let u=String(a).toUpperCase();e.type=Object.values(bs).includes(u)?u:bs.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=ta(a);else if(r.includes(i)){let u=[];for(let d of Array.isArray(a)?a:[]){if(d.type=="null"){e.nullable=!0;continue}u.push(ta(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=ta(f);e[i]=u}else{if(i==="additionalProperties")continue;e[i]=a}if(e.type==="ARRAY"&&!e.items&&(e.items={type:"STRING"}),Array.isArray(e.required)&&e.properties){let i=new Set(Object.keys(e.properties));e.required=e.required.filter(a=>i.has(a)),e.required.length===0&&delete e.required}return e}function EI(t,e){let n=r=>e?.collapseUnions?_s(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=Hr(r.parameters);r.parameters=n(ta(o))}if(r.response){let o=Hr(r.response);r.response=n(ta(o))}}return t}var nS="skip_thought_signature_validator";function Du(t,e){let n=[],r=t.tools||[],o=r.filter(C=>ys(C).name!=="web_search").map(C=>{let{name:A,description:k,parameters:E}=ys(C);return{name:Mk(A),description:k,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(EI({functionDeclarations:o},{collapseUnions:SI(t.model)})),r.find(C=>ys(C).name==="web_search")&&n.push({googleSearch:{}});let i=[],a=t.messages||[],u=[],d=C=>{if(typeof C=="string")C&&u.push(C);else if(Array.isArray(C))for(let A of C)A?.type==="text"&&A.text?u.push(A.text):typeof A=="string"&&A&&u.push(A)};t.system&&d(t.system);for(let C of a)C.role==="system"&&d(C.content);let f=a.filter(C=>C.role==="tool"),p=a.filter(C=>C.role!=="tool"&&C.role!=="system"),h=e?.thoughtSignatureFallback!=="none";p.forEach(C=>{let A=_u(C.role,{assistant:"model"}),k=[],E=Rn(C),x=ss(E),O=x?.startsWith("ccr_")?void 0:x,q=j=>A==="model"&&(j==="(no content)"||j.startsWith(Hh));if(O&&A==="model"&&k.push({thought:!0,text:E?.content||"",thoughtSignature:O}),typeof C.content=="string")C.content&&!q(C.content)&&k.push({text:C.content});else if(Array.isArray(C.content))C.content.forEach(ee=>{if(ee.type==="text"){let z=ee.text||"";z&&!q(z)&&k.push({text:z})}}),bu(C.content).forEach(ee=>{k.push(wu(ee,"gemini"))});else if(C.content&&typeof C.content=="object")if(C.content.text){let j=C.content.text;q(j)||k.push({text:j})}else k.push({text:JSON.stringify(C.content)});let V=Array.isArray(C.tool_calls)?C.tool_calls.map((j,ee)=>{let z=j.id||`tool_${Math.random().toString(36).substring(2,15)}`,te=j.thought_signature||eS(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?nS:void 0)),{toolCall:j,id:z,signature:te}}):[];if(V.length>0&&k.push(...V.map(({toolCall:j,id:ee,signature:z})=>({functionCall:{id:ee,name:j.function.name,args:JSON.parse(j.function.arguments||"{}")},...z&&{thoughtSignature:z}}))),k.length===0&&k.push({text:""}),i.push({role:A,parts:k}),A==="model"&&V.length>0){let j=V.map(({toolCall:ee,id:z})=>{let Q=f.find(_e=>_e.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(_e=>_e.type==="text").map(_e=>_e.text).join(`
254
- `):typeof Q=="object"&&Q!==null&&(Q=JSON.stringify(Q)),{functionResponse:{id:z,name:ee?.function?.name,response:{result:Q}}}});i.push({role:"user",parts:j})}});let g=Cu(i,"parts"),b={},m=Xk(t);m&&(b.thinkingConfig=m),t.max_tokens&&(b.maxOutputTokens=t.max_tokens),t.temperature!==void 0&&(b.temperature=t.temperature);let w={contents:g.length?g:[{role:"user",parts:[{text:""}]}],tools:n.length?n:void 0,generationConfig:b};if(u.length&&(w.systemInstruction={parts:[{text:u.join(`
253
+ `)),x=-1}if(!S){let H={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[ae.finish_reason]||"end_turn";m.size>0&&H==="end_turn"&&(H="tool_use"),d={type:"message_delta",delta:{stop_reason:H,stop_sequence:null},usage:Tu(Z.usage)}}break}}catch(Z){this.logger?.error(`parseError: ${Z.name} message: ${Z.message} stack: ${Z.stack} data: ${ne}`)}}}U()}catch(te){ee(te)}finally{if(r===z&&(r=null),z)try{z.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:async i=>{o?.();let a=r;r=null,a&&await a.cancel(i).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${i}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[],s=Rn(r.message);if(s?.content){let u=ss(s);o.push({type:"thinking",thinking:s.content,...u?{signature:u}:{}})}if(r.message.content&&o.push({type:"text",text:r.message.content}),r.message.annotations){let u=`srvtoolu_${On()}`;o.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:u,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(u=>{if(!("function"in u)||!u.function)return;let d={};try{let f=u.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:u.function.arguments||""}}o.push({type:"tool_use",id:ur(u.id)??u.id,name:u.function.name,input:d})});let i=String(r.finish_reason||""),a={id:e.id,type:"message",role:"assistant",model:e.model,content:o,stop_reason:r.finish_reason==="stop"?"end_turn":i==="length"?"max_tokens":i==="tool_calls"?"tool_use":i==="content_filter"?"stop_sequence":i==="model_context_window_exceeded"?"model_context_window_exceeded":"end_turn",stop_sequence:null,usage:{...Tu(e.usage),...r.message.annotations?.length?{server_tool_use:{web_search_requests:r.message.annotations.length}}:{}}};return this.logger.debug({reqId:n.req.id,result:a},"Conversion complete, final Anthropic response"),a}catch{throw J(`Provider error: ${JSON.stringify(e)}`,500,"provider_error")}}};var _I=new Set(["type","format","title","description","nullable","enum","maxItems","minItems","properties","required","minProperties","maxProperties","minLength","maxLength","pattern","example","anyOf","propertyOrdering","default","items","minimum","maximum","additionalProperties","allOf","oneOf"]);function Hr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Hr(r,e));let n={};for(let r in t){if(e!=="properties"&&!_I.has(r))continue;let o=t[r];if(!(r==="enum"&&t.type&&t.type!=="string")&&!(r==="format"&&t.type==="string"&&o&&!["enum","date-time"].includes(o))&&!(r==="format"&&o==="uri")&&r!=="$schema")if(r==="properties"&&typeof o=="object"&&!Array.isArray(o)){let s={};for(let i in o)s[i]=Hr(o[i]);n[r]=s}else r==="items"?n[r]=Hr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>Hr(s,r)):n[r]=o}if(Array.isArray(n.required)&&n.properties){let r=new Set(Object.keys(n.properties));n.required=n.required.filter(o=>r.has(o)),n.required.length===0&&delete n.required}return n}function _s(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(_s);let e={};for(let h in t){let g=t[h];if(h==="properties"&&g&&typeof g=="object"){let b={};for(let m in g)b[m]=_s(g[m]);e[h]=b}else h==="items"?e[h]=_s(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(_s):e[h]=g}let n=e.anyOf||e.oneOf;if(!Array.isArray(n)||e.type)return e;let r=n.filter(h=>h&&typeof h=="object"),o=r.find(h=>h.type)||r[0];if(!o)return e;let{anyOf:s,oneOf:i,description:a,...u}=e,d=[...new Set(r.filter(h=>h!==o).map(h=>String(h.description||h.type||"").split(" (alternatives:")[0]).filter(Boolean))],f={...o,...u},p=[a,o.description,...d].filter(Boolean);return p.length&&(f.description=d.length?`${p[0]} (alternatives: ${d.join("; ")})`:p[0]),f}function Ru(t){return!t||typeof t!="object"?t:Hr(t)}var ea=["minimal","low","medium","high"];function bI(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function CI(t){let e=bI(t);return e?e.includes("-image")||e.includes("imagen")?{kind:"none"}:e.startsWith("claude")?{kind:"budget",min:1024,max:64e3,requireMin:!0}:/^gemini-3(\.\d+)?\b/.test(e)||e.startsWith("gemini-pro-agent")?/^gemini-3-pro\b/.test(e)?{kind:"level",levels:["low","high"]}:e.includes("flash")?{kind:"level",levels:ea}:{kind:"level",levels:["low","medium","high"]}:/^gemini-2\.5/.test(e)?e.includes("pro")?{kind:"budget",min:128,max:32768}:{kind:"budget",min:0,max:24576}:{kind:"includeOnly"}:{kind:"includeOnly"}}function wI(t,e){let n=t.toLowerCase(),r=ea.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=ea.indexOf(n);return o<0?r[r.length-1]:r.find(s=>ea.indexOf(s)>=o)??r[r.length-1]}function kI(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function SI(t,e,n){return Math.min(Math.max(t,e),n)}function Xk(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=CI(t.model);if(r.kind==="none")return;let o=e.effort?.toLowerCase(),s=o==="none"||e.enabled===!1;if(r.kind==="includeOnly")return s?void 0:{includeThoughts:!0};if(r.kind==="level"){let d=ea.filter(f=>r.levels.includes(f));return s?{includeThoughts:!1,thinkingLevel:d[0]}:o?{includeThoughts:!0,thinkingLevel:wI(o,r.levels)}:{includeThoughts:!0}}if(s)return r.min===0?{includeThoughts:!1,thinkingBudget:0}:void 0;let i=e.max_tokens,a=typeof i=="number"?i:o?kI(o,r.max):void 0;if(typeof a!="number")return{includeThoughts:!0};let u=SI(a,r.min,r.max);if(t.max_tokens&&u>=t.max_tokens&&(u=t.max_tokens-1),u<r.min){if(r.requireMin)return;u=r.min}return{includeThoughts:!0,thinkingBudget:u}}var So=new Map,Qk=(t,e)=>`${t||"default"}${e}`;function Zk(t,e,n){if(!e||!n)return;let r=Qk(t,e);for(So.delete(r),So.set(r,{signature:n,expiresAt:Date.now()+216e5});So.size>4096;){let o=So.keys().next();if(o.done)break;So.delete(o.value)}}function eS(t,e){if(!e)return;let n=Qk(t,e),r=So.get(n);if(r){if(r.expiresAt<=Date.now()){So.delete(n);return}return r.signature}}function AI(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var bs={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function EI(t,e){t.includes("null")&&(e.nullable=!0);let n=t.filter(r=>r!=="null");if(n.length===1){let r=n[0].toUpperCase();e.type=Object.values(bs).includes(r)?r:bs.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(bs).includes(o)?o:bs.TYPE_UNSPECIFIED})}}}function ta(t){let e={},n=["items"],r=["anyOf"],o=["properties"];if(t.type&&t.anyOf)throw new Error("type and anyOf cannot be both populated.");let s=t.anyOf;s!=null&&Array.isArray(s)&&s.length==2&&(s[0]&&s[0].type==="null"?(e.nullable=!0,t=s[1]):s[1]&&s[1].type==="null"&&(e.nullable=!0,t=s[0])),t.type&&Array.isArray(t.type)&&EI(t.type,e);for(let[i,a]of Object.entries(t))if(a!=null)if(i=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(Array.isArray(a))continue;let u=String(a).toUpperCase();e.type=Object.values(bs).includes(u)?u:bs.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=ta(a);else if(r.includes(i)){let u=[];for(let d of Array.isArray(a)?a:[]){if(d.type=="null"){e.nullable=!0;continue}u.push(ta(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=ta(f);e[i]=u}else{if(i==="additionalProperties")continue;e[i]=a}if(e.type==="ARRAY"&&!e.items&&(e.items={type:"STRING"}),Array.isArray(e.required)&&e.properties){let i=new Set(Object.keys(e.properties));e.required=e.required.filter(a=>i.has(a)),e.required.length===0&&delete e.required}return e}function vI(t,e){let n=r=>e?.collapseUnions?_s(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=Hr(r.parameters);r.parameters=n(ta(o))}if(r.response){let o=Hr(r.response);r.response=n(ta(o))}}return t}var nS="skip_thought_signature_validator";function Du(t,e){let n=[],r=t.tools||[],o=r.filter(C=>ys(C).name!=="web_search").map(C=>{let{name:S,description:k,parameters:E}=ys(C);return{name:Mk(S),description:k,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(vI({functionDeclarations:o},{collapseUnions:AI(t.model)})),r.find(C=>ys(C).name==="web_search")&&n.push({googleSearch:{}});let i=[],a=t.messages||[],u=[],d=C=>{if(typeof C=="string")C&&u.push(C);else if(Array.isArray(C))for(let S of C)S?.type==="text"&&S.text?u.push(S.text):typeof S=="string"&&S&&u.push(S)};t.system&&d(t.system);for(let C of a)C.role==="system"&&d(C.content);let f=a.filter(C=>C.role==="tool"),p=a.filter(C=>C.role!=="tool"&&C.role!=="system"),h=e?.thoughtSignatureFallback!=="none";p.forEach(C=>{let S=_u(C.role,{assistant:"model"}),k=[],E=Rn(C),x=ss(E),O=x?.startsWith("ccr_")?void 0:x,q=U=>S==="model"&&(U==="(no content)"||U.startsWith(qh));if(O&&S==="model"&&k.push({thought:!0,text:E?.content||"",thoughtSignature:O}),typeof C.content=="string")C.content&&!q(C.content)&&k.push({text:C.content});else if(Array.isArray(C.content))C.content.forEach(ee=>{if(ee.type==="text"){let z=ee.text||"";z&&!q(z)&&k.push({text:z})}}),bu(C.content).forEach(ee=>{k.push(wu(ee,"gemini"))});else if(C.content&&typeof C.content=="object")if(C.content.text){let U=C.content.text;q(U)||k.push({text:U})}else k.push({text:JSON.stringify(C.content)});let V=Array.isArray(C.tool_calls)?C.tool_calls.map((U,ee)=>{let z=U.id||`tool_${Math.random().toString(36).substring(2,15)}`,te=U.thought_signature||eS(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?nS:void 0)),{toolCall:U,id:z,signature:te}}):[];if(V.length>0&&k.push(...V.map(({toolCall:U,id:ee,signature:z})=>({functionCall:{id:ee,name:U.function.name,args:JSON.parse(U.function.arguments||"{}")},...z&&{thoughtSignature:z}}))),k.length===0&&k.push({text:""}),i.push({role:S,parts:k}),S==="model"&&V.length>0){let U=V.map(({toolCall:ee,id:z})=>{let Q=f.find(_e=>_e.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(_e=>_e.type==="text").map(_e=>_e.text).join(`
254
+ `):typeof Q=="object"&&Q!==null&&(Q=JSON.stringify(Q)),{functionResponse:{id:z,name:ee?.function?.name,response:{result:Q}}}});i.push({role:"user",parts:U})}});let g=Cu(i,"parts"),b={},m=Xk(t);m&&(b.thinkingConfig=m),t.max_tokens&&(b.maxOutputTokens=t.max_tokens),t.temperature!==void 0&&(b.temperature=t.temperature);let w={contents:g.length?g:[{role:"user",parts:[{text:""}]}],tools:n.length?n:void 0,generationConfig:b};if(u.length&&(w.systemInstruction={parts:[{text:u.join(`
255
255
 
256
- `)}]}),t.tool_choice){let C={functionCallingConfig:{}};t.tool_choice==="auto"?C.functionCallingConfig.mode="auto":t.tool_choice==="none"?C.functionCallingConfig.mode="none":t.tool_choice==="required"?C.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(C.functionCallingConfig.mode="any",C.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),w.toolConfig=C}return w}function Ou(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,i=t.stream,a=t.tool_choice,u={messages:[],model:r,max_tokens:o,temperature:s,stream:i,tool_choice:a};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?u.messages.push({role:"user",content:d}):typeof d.text=="string"?u.messages.push({role:"user",content:d.text||null}):d.role==="user"?u.messages.push({role:"user",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):d.role==="model"&&u.messages.push({role:"assistant",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(n)&&(u.tools=[],n.forEach(d=>{let f=d.functionDeclarations;Array.isArray(f)&&f.forEach(p=>{u.tools.push({type:"function",function:{name:p.name,description:p.description,parameters:p.parameters}})})})),u}function tS(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===nS||r.startsWith("ccr_")||Zk(t,n.id,r)})}async function Pu(t,e,n,r){let o=r||e;if(t.headers.get("Content-Type")?.includes("application/json")){let s=await t.json();if(n?.debug({response:s},`${e} response:`),t.status>=400){let A=(s.error?.message||"").toLowerCase();if(["user input too long","input too long","prompt is too long","exceeds the token limit","request payload size exceeds","context_length_exceeded"].some(E=>A.includes(E))){let E={id:`ctxexceeded_${Date.now()}`,choices:[{finish_reason:"model_context_window_exceeded",index:0,message:{content:"",role:"assistant"}}],created:Math.floor(Date.now()/1e3),model:"",object:"chat.completion",usage:{completion_tokens:0,prompt_tokens:0,total_tokens:0}};return new Response(JSON.stringify(E),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}if(!s.candidates||s.candidates.length===0)return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers});let i="",a,u=s.candidates[0]?.content?.parts||[],d=[];for(let C of u)C.text&&C.thought===!0?i+=Qi(C.text):d.push(C);a=u.find(C=>C.thoughtSignature)?.thoughtSignature,i&&!a&&(a=`ccr_${+new Date}`);let f=d?.filter(C=>C.functionCall)?.map(C=>({id:C.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})},thought_signature:C.thoughtSignature||C.thought_signature||void 0}))||[];a&&f.length>0&&!f[0].thought_signature&&(f[0].thought_signature=a),tS(o,f);let p=d?.filter(C=>C.text)?.map(C=>Qi(C.text||""))?.join(`
257
- `)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",b=!g&&f.length===0?zh(h):null,m=Xi(h?.finishReason),w={id:s.responseId,choices:[{finish_reason:f.length>0?"tool_calls":m,index:0,message:{content:b||g,role:"assistant",tool_calls:f.length>0?f:void 0,...a&&i&&{thinking:{content:i,signature:a}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:s.modelVersion,object:"chat.completion",usage:{completion_tokens:s.usageMetadata?.candidatesTokenCount||0,prompt_tokens:s.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:s.usageMetadata?.cachedContentTokenCount||0},total_tokens:s.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:s.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(w),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let s=0,i=-1,a=null,u=null,d=null,f=(w,C)=>{w.controller.enqueue(w.encoder.encode(`data: ${JSON.stringify(C)}
256
+ `)}]}),t.tool_choice){let C={functionCallingConfig:{}};t.tool_choice==="auto"?C.functionCallingConfig.mode="auto":t.tool_choice==="none"?C.functionCallingConfig.mode="none":t.tool_choice==="required"?C.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(C.functionCallingConfig.mode="any",C.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),w.toolConfig=C}return w}function Ou(t){let e=t.contents,n=t.tools,r=t.model,o=t.max_tokens,s=t.temperature,i=t.stream,a=t.tool_choice,u={messages:[],model:r,max_tokens:o,temperature:s,stream:i,tool_choice:a};return Array.isArray(e)&&e.forEach(d=>{typeof d=="string"?u.messages.push({role:"user",content:d}):typeof d.text=="string"?u.messages.push({role:"user",content:d.text||null}):d.role==="user"?u.messages.push({role:"user",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]}):d.role==="model"&&u.messages.push({role:"assistant",content:d?.parts?.map(f=>({type:"text",text:f.text||""}))||[]})}),Array.isArray(n)&&(u.tools=[],n.forEach(d=>{let f=d.functionDeclarations;Array.isArray(f)&&f.forEach(p=>{u.tools.push({type:"function",function:{name:p.name,description:p.description,parameters:p.parameters}})})})),u}function tS(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===nS||r.startsWith("ccr_")||Zk(t,n.id,r)})}async function Pu(t,e,n,r){let o=r||e;if(t.headers.get("Content-Type")?.includes("application/json")){let s=await t.json();if(n?.debug({response:s},`${e} response:`),t.status>=400){let S=(s.error?.message||"").toLowerCase();if(["user input too long","input too long","prompt is too long","exceeds the token limit","request payload size exceeds","context_length_exceeded"].some(E=>S.includes(E))){let E={id:`ctxexceeded_${Date.now()}`,choices:[{finish_reason:"model_context_window_exceeded",index:0,message:{content:"",role:"assistant"}}],created:Math.floor(Date.now()/1e3),model:"",object:"chat.completion",usage:{completion_tokens:0,prompt_tokens:0,total_tokens:0}};return new Response(JSON.stringify(E),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers})}if(!s.candidates||s.candidates.length===0)return new Response(JSON.stringify(s),{status:t.status,statusText:t.statusText,headers:t.headers});let i="",a,u=s.candidates[0]?.content?.parts||[],d=[];for(let C of u)C.text&&C.thought===!0?i+=Qi(C.text):d.push(C);a=u.find(C=>C.thoughtSignature)?.thoughtSignature,i&&!a&&(a=`ccr_${+new Date}`);let f=d?.filter(C=>C.functionCall)?.map(C=>({id:C.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:C.functionCall?.name,arguments:JSON.stringify(C.functionCall?.args||{})},thought_signature:C.thoughtSignature||C.thought_signature||void 0}))||[];a&&f.length>0&&!f[0].thought_signature&&(f[0].thought_signature=a),tS(o,f);let p=d?.filter(C=>C.text)?.map(C=>Qi(C.text||""))?.join(`
257
+ `)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",b=!g&&f.length===0?Hh(h):null,m=Xi(h?.finishReason),w={id:s.responseId,choices:[{finish_reason:f.length>0?"tool_calls":m,index:0,message:{content:b||g,role:"assistant",tool_calls:f.length>0?f:void 0,...a&&i&&{thinking:{content:i,signature:a}}}}],created:parseInt(new Date().getTime()/1e3+"",10),model:s.modelVersion,object:"chat.completion",usage:{completion_tokens:s.usageMetadata?.candidatesTokenCount||0,prompt_tokens:s.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:s.usageMetadata?.cachedContentTokenCount||0},total_tokens:s.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:s.usageMetadata?.thoughtsTokenCount||0}}};return new Response(JSON.stringify(w),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let s=0,i=-1,a=null,u=null,d=null,f=(w,C)=>{w.controller.enqueue(w.encoder.encode(`data: ${JSON.stringify(C)}
258
258
 
259
- `))},p=w=>({completion_tokens:w?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w?.usageMetadata?.cachedContentTokenCount||0},total_tokens:w?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w?.usageMetadata?.thoughtsTokenCount||0}}),h=w=>w?.groundingMetadata?.groundingChunks?.map((C,A)=>{let k=w?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:C?.web?.uri||"",title:C?.web?.title||"",content:k?.[0]?.segment?.text||"",start_index:k?.[0]?.segment?.startIndex||0,end_index:k?.[0]?.segment?.endIndex||0}}})||[],g=(w,C,A)=>{let k=A?.mode||"direct";k==="direct"&&s++;let E={choices:[{delta:{role:"assistant",content:C},finish_reason:A?.finishReason??(k==="direct"||k==="finish"?Xi(A?.candidate?.finishReason):null),index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:A?.chunk?.responseId||"",model:A?.chunk?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(k==="direct"||k==="finish"){E.usage=p(A?.chunk);let x=h(A?.candidate);x.length>0&&(E.choices[0].delta.annotations=x)}f(w,E)},b=new yu({thinking:(w,C)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{content:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},signature:(w,C)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{signature:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},content:(w,C)=>{a&&g(a,w,C)}});return Ne(t,(w,C)=>{if(a=C,w.startsWith("data: ")){let A=w.slice(6).trim();if(A){n?.debug({chunkStr:A},`${e} chunk:`);try{let k=JSON.parse(A);if(!k.candidates||!k.candidates[0]){n?.debug({chunkStr:A},"Invalid chunk structure");return}let E=k.candidates[0];u=k,d=E;let x=E.content?.parts||[];x.filter(z=>z.text&&z.thought===!0).forEach(z=>{b.processThinking(Qi(z.text),k)});let O=x.filter(z=>z.functionCall).map(z=>({id:z.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:z.functionCall?.name,arguments:JSON.stringify(z.functionCall?.args||{})},thought_signature:z.thoughtSignature||z.thought_signature||void 0})),q=x.filter(z=>z.text&&z.thought!==!0).map(z=>Qi(z.text||"")).join(`
260
- `),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),tS(o,O);let j=!!(q&&q!=="(no content)")||O.length>0||!!E.finishReason;if(q&&q!=="(no content)"&&k.modelVersion?.includes("3")&&b.shouldDeferContent(!!E.finishReason,O.length>0))b.bufferContent(q);else if(q&&q!=="(no content)"){if(b.hasThinkingContent&&!b.signatureSent&&j&&!V){let z=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:k,candidate:E,mode:"buffered",finishReason:null}:void 0})}b.processContent(q,k,E)}V&&(O.length>0&&!b.hasThinkingContent&&!q&&!b.contentSent?b.acknowledgeSignature():b.processSignatureWithMeta(V,k,{beforeFlush:()=>{s++},flushMeta:{chunk:k,candidate:E,mode:"buffered"}}));let ee=i<0&&O.length===0&&!q?zh(E):null;if(!q&&O.length===0&&i<0&&E.finishReason&&!ee&&b.needsContentPlaceholder&&b.emitContentPlaceholder("(no content)",{chunk:k,candidate:E}),!V&&!q&&b.hasThinkingContent&&!b.signatureSent&&j){let z=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:k,candidate:E,mode:"buffered",finishReason:null}:void 0})}if(q&&k.modelVersion?.includes("3")&&b.hasBufferedContent&&!V&&O.length===0&&!E.finishReason)return;O.length>0&&O.forEach((z,te)=>{s++,i++;let Q=E.finishReason!=null&&te===O.length-1?"tool_calls":null,_e={choices:[{delta:{role:"assistant",tool_calls:[{...z,index:i}]},finish_reason:Q,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:k.responseId||"",model:k.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:p(k)},Oe=h(E);Oe.length>0&&(_e.choices[0].delta.annotations=Oe),f(C,_e)}),E.finishReason&&(b.hasBufferedContent?b.finalize(k,E,{beforeFlush:()=>{b.signatureSent||s++}}):!q&&O.length===0&&(s++,g(C,ee||"",{chunk:k,candidate:E,mode:"finish",...i>=0?{finishReason:"tool_calls"}:{}})))}catch(k){n?.error(`Error parsing ${e} stream chunk`,A,k.message)}}}},{onComplete:w=>{a=w,(b.hasBufferedContent||b.hasThinkingContent&&!b.signatureSent)&&b.finalize(u||void 0,d||void 0,{beforeFlush:()=>{b.signatureSent||s++}})}})}return t}import{createHash as vI}from"crypto";var TI=15e3,xI=256,fr=new Map,rg=new Map;function rS(t){return vI("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function RI(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function DI(t){return Math.floor(JSON.stringify(t).length/4)}function OI(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function oS(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function Iu(t,e){let n=Date.now();for(let[r,o]of fr)o.expiresAt<=n&&fr.delete(r);for(fr.delete(t),fr.set(t,e);fr.size>xI;){let r=fr.keys().next().value;if(r===void 0)break;fr.delete(r)}}async function Fu(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=OI(e);if(Object.keys(s).length===0||DI(s)<RI(n))return e;let i=rS(o),a=[String(r),i,n,rS(s)].join(":"),u=Date.now(),d=fr.get(a);if(d&&d.expiresAt>u)return d.name?oS(e,d.name):e;d&&fr.delete(a);let f=3600,p={model:n,...s,ttl:`${f}s`},h=rg.get(a);h||(h=(async()=>{try{let b=await fetch(r,{method:"POST",headers:Object.fromEntries(Object.entries({"Content-Type":"application/json",...o}).filter(([,w])=>w!==void 0)),body:JSON.stringify(p),signal:AbortSignal.timeout(TI)});if(!b.ok){t.logger?.debug?.({status:b.status},"Gemini cached-content create failed; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}let m=await b.json();if(!m?.name){t.logger?.debug?.("Gemini cached-content response had no resource name; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}return Iu(a,{name:m.name,expiresAt:Date.now()+(f-30)*1e3}),m.name}catch(b){t.logger?.debug?.({error:b?.message||String(b)},"Gemini cached-content create errored; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}finally{rg.delete(a)}})(),rg.set(a,h));let g=await h;return g?oS(e,g):e}var Nu=class{constructor(e){this.options=e;this.cachedContent=e?.cachedContent!==!1,this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}options;static TransformerName="gemini";logger;name="gemini";endPoint="/v1beta/models/:modelAndAction";cachedContent;thoughtSignatureFallback;async transformRequestIn(e,n,r){let o=e.model||(typeof r?.req?.model=="string"?r.req.model:Array.isArray(r?.req?.model)?r.req.model.join(","):"")||n.models?.[0]||"",s=Du(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await Fu({body:s,modelResource:o.startsWith("models/")?o:`models/${o}`,createUrl:new URL("../cachedContents",n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0},logger:this.logger}):s,config:{url:new URL(`./${o}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}async transformRequestOut(e){return Ou(e)}async transformResponseOut(e,n){return Pu(e,this.name,this.logger,n?.provider?.name||this.name)}};async function jj(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(gd(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
259
+ `))},p=w=>({completion_tokens:w?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:w?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:w?.usageMetadata?.cachedContentTokenCount||0},total_tokens:w?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:w?.usageMetadata?.thoughtsTokenCount||0}}),h=w=>w?.groundingMetadata?.groundingChunks?.map((C,S)=>{let k=w?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(S));return{type:"url_citation",url_citation:{url:C?.web?.uri||"",title:C?.web?.title||"",content:k?.[0]?.segment?.text||"",start_index:k?.[0]?.segment?.startIndex||0,end_index:k?.[0]?.segment?.endIndex||0}}})||[],g=(w,C,S)=>{let k=S?.mode||"direct";k==="direct"&&s++;let E={choices:[{delta:{role:"assistant",content:C},finish_reason:S?.finishReason??(k==="direct"||k==="finish"?Xi(S?.candidate?.finishReason):null),index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:S?.chunk?.responseId||"",model:S?.chunk?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"};if(k==="direct"||k==="finish"){E.usage=p(S?.chunk);let x=h(S?.candidate);x.length>0&&(E.choices[0].delta.annotations=x)}f(w,E)},b=new yu({thinking:(w,C)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{content:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},signature:(w,C)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{signature:w}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:C?.responseId||"",model:C?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},content:(w,C)=>{a&&g(a,w,C)}});return Ne(t,(w,C)=>{if(a=C,w.startsWith("data: ")){let S=w.slice(6).trim();if(S){n?.debug({chunkStr:S},`${e} chunk:`);try{let k=JSON.parse(S);if(!k.candidates||!k.candidates[0]){n?.debug({chunkStr:S},"Invalid chunk structure");return}let E=k.candidates[0];u=k,d=E;let x=E.content?.parts||[];x.filter(z=>z.text&&z.thought===!0).forEach(z=>{b.processThinking(Qi(z.text),k)});let O=x.filter(z=>z.functionCall).map(z=>({id:z.functionCall?.id||`ccr_tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:z.functionCall?.name,arguments:JSON.stringify(z.functionCall?.args||{})},thought_signature:z.thoughtSignature||z.thought_signature||void 0})),q=x.filter(z=>z.text&&z.thought!==!0).map(z=>Qi(z.text||"")).join(`
260
+ `),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),tS(o,O);let U=!!(q&&q!=="(no content)")||O.length>0||!!E.finishReason;if(q&&q!=="(no content)"&&k.modelVersion?.includes("3")&&b.shouldDeferContent(!!E.finishReason,O.length>0))b.bufferContent(q);else if(q&&q!=="(no content)"){if(b.hasThinkingContent&&!b.signatureSent&&U&&!V){let z=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:k,candidate:E,mode:"buffered",finishReason:null}:void 0})}b.processContent(q,k,E)}V&&(O.length>0&&!b.hasThinkingContent&&!q&&!b.contentSent?b.acknowledgeSignature():b.processSignatureWithMeta(V,k,{beforeFlush:()=>{s++},flushMeta:{chunk:k,candidate:E,mode:"buffered"}}));let ee=i<0&&O.length===0&&!q?Hh(E):null;if(!q&&O.length===0&&i<0&&E.finishReason&&!ee&&b.needsContentPlaceholder&&b.emitContentPlaceholder("(no content)",{chunk:k,candidate:E}),!V&&!q&&b.hasThinkingContent&&!b.signatureSent&&U){let z=b.hasBufferedContent;b.processSignatureWithMeta(`ccr_${+new Date}`,k,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:k,candidate:E,mode:"buffered",finishReason:null}:void 0})}if(q&&k.modelVersion?.includes("3")&&b.hasBufferedContent&&!V&&O.length===0&&!E.finishReason)return;O.length>0&&O.forEach((z,te)=>{s++,i++;let Q=E.finishReason!=null&&te===O.length-1?"tool_calls":null,_e={choices:[{delta:{role:"assistant",tool_calls:[{...z,index:i}]},finish_reason:Q,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:k.responseId||"",model:k.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:p(k)},Oe=h(E);Oe.length>0&&(_e.choices[0].delta.annotations=Oe),f(C,_e)}),E.finishReason&&(b.hasBufferedContent?b.finalize(k,E,{beforeFlush:()=>{b.signatureSent||s++}}):!q&&O.length===0&&(s++,g(C,ee||"",{chunk:k,candidate:E,mode:"finish",...i>=0?{finishReason:"tool_calls"}:{}})))}catch(k){n?.error(`Error parsing ${e} stream chunk`,S,k.message)}}}},{onComplete:w=>{a=w,(b.hasBufferedContent||b.hasThinkingContent&&!b.signatureSent)&&b.finalize(u||void 0,d||void 0,{beforeFlush:()=>{b.signatureSent||s++}})}})}return t}import{createHash as TI}from"crypto";var xI=15e3,RI=256,fr=new Map,ng=new Map;function rS(t){return TI("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function DI(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function OI(t){return Math.floor(JSON.stringify(t).length/4)}function PI(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function oS(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function Iu(t,e){let n=Date.now();for(let[r,o]of fr)o.expiresAt<=n&&fr.delete(r);for(fr.delete(t),fr.set(t,e);fr.size>RI;){let r=fr.keys().next().value;if(r===void 0)break;fr.delete(r)}}async function Fu(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=PI(e);if(Object.keys(s).length===0||OI(s)<DI(n))return e;let i=rS(o),a=[String(r),i,n,rS(s)].join(":"),u=Date.now(),d=fr.get(a);if(d&&d.expiresAt>u)return d.name?oS(e,d.name):e;d&&fr.delete(a);let f=3600,p={model:n,...s,ttl:`${f}s`},h=ng.get(a);h||(h=(async()=>{try{let b=await fetch(r,{method:"POST",headers:Object.fromEntries(Object.entries({"Content-Type":"application/json",...o}).filter(([,w])=>w!==void 0)),body:JSON.stringify(p),signal:AbortSignal.timeout(xI)});if(!b.ok){t.logger?.debug?.({status:b.status},"Gemini cached-content create failed; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}let m=await b.json();if(!m?.name){t.logger?.debug?.("Gemini cached-content response had no resource name; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}return Iu(a,{name:m.name,expiresAt:Date.now()+(f-30)*1e3}),m.name}catch(b){t.logger?.debug?.({error:b?.message||String(b)},"Gemini cached-content create errored; using implicit cache"),Iu(a,{expiresAt:Date.now()+300*1e3});return}finally{ng.delete(a)}})(),ng.set(a,h));let g=await h;return g?oS(e,g):e}var Nu=class{constructor(e){this.options=e;this.cachedContent=e?.cachedContent!==!1,this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}options;static TransformerName="gemini";logger;name="gemini";endPoint="/v1beta/models/:modelAndAction";cachedContent;thoughtSignatureFallback;async transformRequestIn(e,n,r){let o=e.model||(typeof r?.req?.model=="string"?r.req.model:Array.isArray(r?.req?.model)?r.req.model.join(","):"")||n.models?.[0]||"",s=Du(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await Fu({body:s,modelResource:o.startsWith("models/")?o:`models/${o}`,createUrl:new URL("../cachedContents",n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0},logger:this.logger}):s,config:{url:new URL(`./${o}:${e.stream?"streamGenerateContent?alt=sse":"generateContent"}`,n.baseUrl),headers:{"x-goog-api-key":n.apiKey,Authorization:void 0}}}}async transformRequestOut(e){return Ou(e)}async transformResponseOut(e,n){return Pu(e,this.name,this.logger,n?.provider?.name||this.name)}};async function LU(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(gd(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
261
261
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
262
262
  2. Run "gcloud auth application-default login"
263
- 3. Use Google Cloud environment with default service account`,{cause:e})}}var md=class{static TransformerName="vertex-gemini";logger;name="vertex-gemini";thoughtSignatureFallback;constructor(e){this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}async transformRequestIn(e,n,r){let o=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let h=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),g=JSON.parse(h);g&&g.project_id&&(o=g.project_id)}catch(p){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",p)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await jj(this.logger),a=e.model||n.models?.[0]||"",u=n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`,d=`projects/${o}/locations/${s}/publishers/google/models/${a}`;return{body:await Fu({body:Du(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name}),modelResource:d,createUrl:new URL(`./v1beta1/projects/${o}/locations/${s}/cachedContents`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0},logger:this.logger}),config:{url:new URL(`./v1beta1/${d}:${e.stream?"streamGenerateContent":"generateContent"}`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Ou(e)}async transformResponseOut(e,n){return Pu(e,this.name,this.logger,n?.provider?.name||this.name)}};function yd(){return{content:"",isComplete:!1,hasContent:!1}}function _d(t,e){t.content+=e,t.hasContent=!0}function bd(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Zr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function Ys(t){if(t.reasoning_content){let e=t.reasoning_content;return typeof e=="string"?e:typeof e?.text=="string"?e.text:null}if(t.reasoning){let e=t.reasoning;return typeof e=="string"?e:null}return null}function eo(t){delete t.reasoning_content,delete t.reasoning}import{createHash as Lj}from"node:crypto";var vT=360*60*1e3,$j=4096,Uy="__ccrDeepseekReasoning",jy=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>vT){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,n),n.reasoning}}put(e,n){n&&(this.cache.delete(e),this.cache.set(e,{reasoning:n,createdAt:Date.now()}),this.prune())}prune(){for(let[e,n]of this.cache)Date.now()-n.createdAt>vT&&this.cache.delete(e);for(;this.cache.size>$j;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},Cd=new jy;function Ly(t){return Array.isArray(t)?t.map(Ly):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=Ly(t[n]),e),{}):t}function Mo(t){return JSON.stringify(Ly(t))}function wd(t){return Lj("sha256").update(t).digest("hex")}function xT(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):Mo(e)).join(""):Mo(t)}function $y(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Mo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function RT(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function DT(t){let e=$y(t);return wd(Mo({...e,id:void 0}))}function OT(t){return wd(Mo({content:xT(t.content),tool_calls:(t.tool_calls||[]).map(e=>$y(e))}))}function qj(t){let e={role:t.role,content:xT(t.content)};return t.name&&(e.name=t.name),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.tool_calls?.length&&(e.tool_calls=t.tool_calls.map(n=>$y(n))),e}function TT(t,e){let n=t.filter(r=>r.role!=="system").map(r=>qj(r));return wd(Mo({namespace:e,messages:n}))}function Hj(t){if(typeof t.reasoning_content=="string"&&t.reasoning_content.length>0)return t.reasoning_content;if(typeof t.thinking?.content=="string"&&t.thinking.content.length>0)return t.thinking.content}function PT(t,e){if(t.role!=="assistant")return 0;let n=Hj(t);if(!n)return 0;let r=[`scope:${e}:signature:${OT(t)}`];return r.push(...RT(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${DT(o)}`)),r.forEach(o=>Cd.put(o,n)),r.length}function zj(t,e){let n=Cd.get(`scope:${e}:signature:${OT(t)}`);if(n)return n;for(let r of RT(t)){let o=Cd.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=Cd.get(`scope:${e}:tool_call_signature:${DT(r)}`);if(o)return o}}function Wj(t,e){if(t.tool_calls?.length)return!0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool")return!0;if(r.role==="user"||r.role==="system")return!1}return!1}function Gj(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek");if(t.enable_thinking===!1||Ot(t.reasoning,t.thinking))return!1;let i=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&i}function Jj(t,e){return wd(Mo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function kd(t,e,n){if(!Gj(t,e))return n?.req&&delete n.req[Uy],{restoredFromCache:0,restoredFromThinking:0};let r=Jj(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=TT(o,r);if(Wj(a,o)&&!(typeof a.reasoning_content=="string"&&a.reasoning_content.length>0?a.reasoning_content:void 0)){let p=typeof a.thinking?.content=="string"&&a.thinking.content.length>0?a.thinking.content:void 0;if(p)a.reasoning_content=p,i++;else{let h=zj(a,u);h&&(a.reasoning_content=h,s++)}}PT(a,u)}o.push(a)}return n?.req&&(n.req[Uy]={enabled:!0,namespace:r,requestScope:TT(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function IT(t){return t?.req?.[Uy]}function Sd(t){return IT(t)?.enabled===!0}function Xs(t,e){if(!t)return 0;let n=IT(e);return n?PT(t,n.requestScope):0}function Ad(){return{content:"",reasoning:"",toolCalls:new Map}}function Qs(t,e){e&&(typeof e.reasoning_content=="string"&&(t.reasoning+=e.reasoning_content),typeof e.content=="string"&&(t.content+=e.content),Array.isArray(e.tool_calls)&&e.tool_calls.forEach((n,r)=>{let o=typeof n.index=="number"?n.index:r,s=t.toolCalls.get(o)||{id:"",type:"function",function:{name:"",arguments:""}};typeof n.id=="string"&&n.id.length>0&&(s.id=n.id),typeof n.type=="string"&&n.type.length>0&&(s.type=n.type);let i=n.function||{};typeof i.name=="string"&&i.name.length>0&&(s.function.name+=i.name),typeof i.arguments=="string"&&i.arguments.length>0&&(s.function.arguments+=i.arguments),t.toolCalls.set(o,s)}))}function Ed(t){if(!t.reasoning)return null;let e=Array.from(t.toolCalls.entries()).sort(([n],[r])=>n-r).map(([,n])=>n).filter(n=>typeof n.id=="string"&&n.id.length>0&&typeof n.function?.name=="string"&&n.function.name.length>0);return!t.content&&e.length===0?null:{role:"assistant",content:t.content||null,tool_calls:e.length>0?e:void 0,reasoning_content:t.reasoning}}function FT(t){let e=t?.usage;!e||e.prompt_cache_hit_tokens===void 0||(e.prompt_tokens_details={...e.prompt_tokens_details||{},cached_tokens:e.prompt_cache_hit_tokens||0})}var vd=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Ve(e.messages),e.tools=Ye(e.tools),kd(e,n,r),e}async transformResponseOut(e,n){let r=Sd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return FT(o),r&&Xs({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=yd(),s=r?Ad():null;return Ne(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Pe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Pe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);FT(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(ve(JSON.stringify(d),a.encoder));return}let p=Ys(f);if(p){s&&Qs(s,f),_d(o,p);let h=Zr(d,{content:p});eo(h.choices[0].delta),a.controller.enqueue(ve(JSON.stringify(h),a.encoder));return}if(s&&Qs(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=bd(o),b=Zr(d,{content:h,signature:g});eo(b.choices[0].delta),b.choices[0].delta.content=null,a.controller.enqueue(ve(JSON.stringify(b),a.encoder))}f.reasoning_content&&delete f.reasoning_content,d.choices?.[0]?.delta&&Object.keys(d.choices[0].delta).length>0&&(o.isComplete&&d.choices[0].index++,a.controller.enqueue(ve(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Pe(i,a.encoder))}},{onComplete:()=>{s&&Xs(Ed(s),n)}})}return e}};var Td=class{name="tooluse";async transformRequestIn(e,n,r){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice=e.tool_choice||"required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
263
+ 3. Use Google Cloud environment with default service account`,{cause:e})}}var md=class{static TransformerName="vertex-gemini";logger;name="vertex-gemini";thoughtSignatureFallback;constructor(e){this.thoughtSignatureFallback=e?.thoughtSignatureFallback==="none"?"none":"skip"}async transformRequestIn(e,n,r){let o=process.env.GOOGLE_CLOUD_PROJECT,s=process.env.GOOGLE_CLOUD_LOCATION||"us-central1";if(!o&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let h=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),g=JSON.parse(h);g&&g.project_id&&(o=g.project_id)}catch(p){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",p)}if(!o)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let i=await LU(this.logger),a=e.model||n.models?.[0]||"",u=n.baseUrl.endsWith("/")?n.baseUrl:n.baseUrl+"/"||`https://${s}-aiplatform.googleapis.com`,d=`projects/${o}/locations/${s}/publishers/google/models/${a}`;return{body:await Fu({body:Du(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name}),modelResource:d,createUrl:new URL(`./v1beta1/projects/${o}/locations/${s}/cachedContents`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0},logger:this.logger}),config:{url:new URL(`./v1beta1/${d}:${e.stream?"streamGenerateContent":"generateContent"}`,u),headers:{Authorization:`Bearer ${i}`,"x-goog-api-key":void 0}}}}async transformRequestOut(e){return Ou(e)}async transformResponseOut(e,n){return Pu(e,this.name,this.logger,n?.provider?.name||this.name)}};function yd(){return{content:"",isComplete:!1,hasContent:!1}}function _d(t,e){t.content+=e,t.hasContent=!0}function bd(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Zr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function Ys(t){if(t.reasoning_content){let e=t.reasoning_content;return typeof e=="string"?e:typeof e?.text=="string"?e.text:null}if(t.reasoning){let e=t.reasoning;return typeof e=="string"?e:null}return null}function eo(t){delete t.reasoning_content,delete t.reasoning}import{createHash as $U}from"node:crypto";var vT=360*60*1e3,qU=4096,By="__ccrDeepseekReasoning",jy=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>vT){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,n),n.reasoning}}put(e,n){n&&(this.cache.delete(e),this.cache.set(e,{reasoning:n,createdAt:Date.now()}),this.prune())}prune(){for(let[e,n]of this.cache)Date.now()-n.createdAt>vT&&this.cache.delete(e);for(;this.cache.size>qU;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},Cd=new jy;function Uy(t){return Array.isArray(t)?t.map(Uy):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=Uy(t[n]),e),{}):t}function Mo(t){return JSON.stringify(Uy(t))}function wd(t){return $U("sha256").update(t).digest("hex")}function xT(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):Mo(e)).join(""):Mo(t)}function Ly(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Mo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function RT(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function DT(t){let e=Ly(t);return wd(Mo({...e,id:void 0}))}function OT(t){return wd(Mo({content:xT(t.content),tool_calls:(t.tool_calls||[]).map(e=>Ly(e))}))}function HU(t){let e={role:t.role,content:xT(t.content)};return t.name&&(e.name=t.name),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.tool_calls?.length&&(e.tool_calls=t.tool_calls.map(n=>Ly(n))),e}function TT(t,e){let n=t.filter(r=>r.role!=="system").map(r=>HU(r));return wd(Mo({namespace:e,messages:n}))}function zU(t){if(typeof t.reasoning_content=="string"&&t.reasoning_content.length>0)return t.reasoning_content;if(typeof t.thinking?.content=="string"&&t.thinking.content.length>0)return t.thinking.content}function PT(t,e){if(t.role!=="assistant")return 0;let n=zU(t);if(!n)return 0;let r=[`scope:${e}:signature:${OT(t)}`];return r.push(...RT(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${DT(o)}`)),r.forEach(o=>Cd.put(o,n)),r.length}function WU(t,e){let n=Cd.get(`scope:${e}:signature:${OT(t)}`);if(n)return n;for(let r of RT(t)){let o=Cd.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=Cd.get(`scope:${e}:tool_call_signature:${DT(r)}`);if(o)return o}}function GU(t,e){if(t.tool_calls?.length)return!0;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="tool")return!0;if(r.role==="user"||r.role==="system")return!1}return!1}function JU(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek");if(t.enable_thinking===!1||Ot(t.reasoning,t.thinking))return!1;let i=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&i}function KU(t,e){return wd(Mo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function kd(t,e,n){if(!JU(t,e))return n?.req&&delete n.req[By],{restoredFromCache:0,restoredFromThinking:0};let r=KU(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=TT(o,r);if(GU(a,o)&&!(typeof a.reasoning_content=="string"&&a.reasoning_content.length>0?a.reasoning_content:void 0)){let p=typeof a.thinking?.content=="string"&&a.thinking.content.length>0?a.thinking.content:void 0;if(p)a.reasoning_content=p,i++;else{let h=WU(a,u);h&&(a.reasoning_content=h,s++)}}PT(a,u)}o.push(a)}return n?.req&&(n.req[By]={enabled:!0,namespace:r,requestScope:TT(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function IT(t){return t?.req?.[By]}function Sd(t){return IT(t)?.enabled===!0}function Xs(t,e){if(!t)return 0;let n=IT(e);return n?PT(t,n.requestScope):0}function Ad(){return{content:"",reasoning:"",toolCalls:new Map}}function Qs(t,e){e&&(typeof e.reasoning_content=="string"&&(t.reasoning+=e.reasoning_content),typeof e.content=="string"&&(t.content+=e.content),Array.isArray(e.tool_calls)&&e.tool_calls.forEach((n,r)=>{let o=typeof n.index=="number"?n.index:r,s=t.toolCalls.get(o)||{id:"",type:"function",function:{name:"",arguments:""}};typeof n.id=="string"&&n.id.length>0&&(s.id=n.id),typeof n.type=="string"&&n.type.length>0&&(s.type=n.type);let i=n.function||{};typeof i.name=="string"&&i.name.length>0&&(s.function.name+=i.name),typeof i.arguments=="string"&&i.arguments.length>0&&(s.function.arguments+=i.arguments),t.toolCalls.set(o,s)}))}function Ed(t){if(!t.reasoning)return null;let e=Array.from(t.toolCalls.entries()).sort(([n],[r])=>n-r).map(([,n])=>n).filter(n=>typeof n.id=="string"&&n.id.length>0&&typeof n.function?.name=="string"&&n.function.name.length>0);return!t.content&&e.length===0?null:{role:"assistant",content:t.content||null,tool_calls:e.length>0?e:void 0,reasoning_content:t.reasoning}}function FT(t){let e=t?.usage;!e||e.prompt_cache_hit_tokens===void 0||(e.prompt_tokens_details={...e.prompt_tokens_details||{},cached_tokens:e.prompt_cache_hit_tokens||0})}var vd=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Ve(e.messages),e.tools=Ye(e.tools),kd(e,n,r),e}async transformResponseOut(e,n){let r=Sd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return FT(o),r&&Xs({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=yd(),s=r?Ad():null;return Ne(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Pe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Pe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);FT(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(ve(JSON.stringify(d),a.encoder));return}let p=Ys(f);if(p){s&&Qs(s,f),_d(o,p);let h=Zr(d,{content:p});eo(h.choices[0].delta),a.controller.enqueue(ve(JSON.stringify(h),a.encoder));return}if(s&&Qs(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=bd(o),b=Zr(d,{content:h,signature:g});eo(b.choices[0].delta),b.choices[0].delta.content=null,a.controller.enqueue(ve(JSON.stringify(b),a.encoder))}f.reasoning_content&&delete f.reasoning_content,d.choices?.[0]?.delta&&Object.keys(d.choices[0].delta).length>0&&(o.isComplete&&d.choices[0].index++,a.controller.enqueue(ve(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Pe(i,a.encoder))}},{onComplete:()=>{s&&Xs(Ed(s),n)}})}return e}};var Td=class{name="tooluse";async transformRequestIn(e,n,r){return e.messages.push({role:"system",content:"<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>"}),e.tools?.length&&(e.tool_choice=e.tool_choice||"required",e.tools.push({type:"function",function:{name:"ExitTool",description:`Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
264
264
  IMPORTANT: Before using this tool, ensure that none of the available tools are applicable to the current task. You must evaluate all available options \u2014 only if no suitable tool can help you complete the task should you use ExitTool to terminate tool mode.
265
265
  Examples:
266
266
  1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
@@ -270,28 +270,28 @@ Examples:
270
270
 
271
271
  `;a.enqueue(u.encode(f))}}catch{a.enqueue(u.encode(s+`
272
272
  `))}else a.enqueue(u.encode(s+`
273
- `))})}return e}};var xd=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=en(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=$c(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=zi(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=yo(e):s.includes("gemini")?e=yo(e):e={...e,messages:Ve(e.messages),tools:Ye(e.tools)},e.model.includes("claude")?e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)})}):e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`${a.image_url.url}`),delete a.media_type)})}),Object.assign(e,this.options||{}),o&&(e.session_id=o,e.prompt_cache_key=o),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=yd(),r=!1,o=!1;return Ne(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Pe(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Pe(s,i.encoder));return}try{let a=s.slice(6),u=JSON.parse(a);u.usage&&(this.logger?.debug({usage:u.usage,hasToolCall:o},"usage"),u.choices[0].finish_reason=o?"tool_calls":"stop"),u.choices?.[0]?.finish_reason==="error"&&i.controller.enqueue(ve(JSON.stringify({error:u.choices?.[0]?.error}),i.encoder)),u.choices?.[0]?.delta?.content&&!r&&(r=!0);let d=u.choices?.[0]?.delta,f=d?Ys(d):null;if(f){_d(n,f);let p=Zr(u,{content:f});eo(p.choices[0].delta),i.controller.enqueue(ve(JSON.stringify(p),i.encoder));return}if(d?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=bd(n),g=Zr(u,{content:p,signature:h});eo(g.choices[0].delta),g.choices[0].delta.content=null,i.controller.enqueue(ve(JSON.stringify(g),i.encoder))}d?.reasoning&&delete d.reasoning,d?.tool_calls?.length&&!Number.isNaN(parseInt(d.tool_calls[0].id,10))&&d.tool_calls.forEach(p=>{p.id=`call_${On()}`}),d?.tool_calls?.length&&!o&&(o=!0),d?.tool_calls?.length&&r&&(typeof u.choices[0].index=="number"?u.choices[0].index+=1:u.choices[0].index=1),i.controller.enqueue(ve(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Pe(s,i.encoder))}})}return e}};var Rd=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}options;static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Dd=class{name="groq";async transformRequestIn(e){return e.messages=Ve(e.messages),e.tools=Ye(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=Ru(n.function.parameters))}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=!1;return Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}try{let s=r.slice(5).trim(),i=JSON.parse(s);if(i.error)throw new Error(JSON.stringify(i));i.choices?.[0]?.delta?.content&&!n&&(n=!0),i.choices?.[0]?.delta?.tool_calls?.length&&i.choices[0].delta.tool_calls.forEach(a=>{a.id=`call_${On()}`}),i.choices?.[0]?.delta?.tool_calls?.length&&n&&(typeof i.choices[0].index=="number"?i.choices[0].index+=1:i.choices[0].index=1),o.controller.enqueue(ve(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}})}return e}};var Od=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{n.cache_control&&delete n.cache_control}),e}};var WT=nr(sh());var br=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function NT(t){return/^[0-9A-Fa-f]$/.test(t)}function wr(t){return t>="0"&&t<="9"}function MT(t){return t>=" "}function ei(t){return`,:[]/{}()
274
- +`.includes(t)}function qy(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Pd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var Hy=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,zy=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function Wy(t){return`,[]/{}
275
- +`.includes(t)}function Gy(t){return ti(t)||Kj.test(t)}var Kj=/^[[{\w-]$/;function Jy(t){return t===`
276
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Cr(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function BT(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function UT(t,e){let n=t.charCodeAt(e);return n===160||n===6158||n>=8192&&n<=8203||n===8239||n===8287||n===12288||n===65279}function ti(t){return Ky(t)||Id(t)}function Ky(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Vy(t){return t==='"'}function Id(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Yy(t){return t==="'"}function ni(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Yt(t,e){let n=t.length;if(!Cr(t,n-1))return t+e;for(;Cr(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function jT(t,e,n){return t.substring(0,e)+t.substring(e+n)}function LT(t){return/[,\n][ \t\r]*$/.test(t)}var Vj={"&quot;":'"',"&amp;":"&","&lt;":"<","&gt;":">","&apos;":"'"},Xy=12;function Qy(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=Vj[n];if(r!==void 0)return{char:r,length:n.length};if(t.charAt(1)==="#"){let o=t.substring(2,e),s=o.charAt(0)==="x"||o.charAt(0)==="X",i=s?o.substring(1):o;if(i.length>0){let a=Number.parseInt(i,s?16:10);if(!Number.isNaN(a)&&a>=0&&a<=1114111)return{char:String.fromCodePoint(a),length:n.length}}}return null}function $T(t){return t!==null&&t.char==='"'}function qT(t){return t!==null&&t.char==="'"}function Zs(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function HT(t,e){switch(e){case")":return Zs(t,"(")>Zs(t,")");case"]":return Zs(t,"[")>Zs(t,"]");case"}":return Zs(t,"{")>Zs(t,"}");default:return!1}}var zT={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Yj={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
277
- `,r:"\r",t:" "};function Zy(t){let e=0,n="";d(["```","[```","{```"]),s()||_e(),d(["```","```]","```}"]);let o=p(",");for(o&&i(),Gy(t[e])&&LT(n)?(o||(n=Yt(n,",")),C()):o&&(n=ni(n,","));t[e]==="}"||t[e]==="]";)e++,i();if(e>=t.length)return n;Q();function s(){i();let ne=m()||w()||A()||E()||x()||q(!1)||V();return i(),ne}function i(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ae=a(ne);do ae=u(),ae&&(ae=a(ne));while(ae);return e>Z}function a(ne){let Z=ne?Cr:BT,ae="";for(;;)if(Z(t,e))ae+=t[e],e++;else if(UT(t,e))ae+=" ",e++;else break;return ae.length>0?(n+=ae,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Xj(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
278
- `;)e++;return!0}return!1}function d(ne){if(f(ne)){if(qy(t[e]))for(;e<t.length&&Pd(t[e]);)e++;return i(),!0}return!1}function f(ne){a(!0);for(let Z of ne){let ae=e+Z.length;if(t.slice(e,ae)===Z)return e=ae,!0}return!1}function p(ne){return t[e]===ne?(n+=t[e],e++,!0):!1}function h(ne){return t[e]===ne?(e++,!0):!1}function g(){return h("\\")}function b(){return i(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,i(),h(","),!0):!1}function m(){if(t[e]==="{"){n+="{",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(ne?Z=!0:(Z=p(","),Z||(n=Yt(n,",")),i()),b(),!(A()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ne||(n=ni(n,",")):Oe();break}i();let Ie=p(":"),we=e>=t.length;Ie||(Gy(t[e])||we?n=Yt(n,":"):Te()),s()||(Ie||we?n+="null":Te()),ne=!1}return t[e]==="}"?(n+="}",e++):n=Yt(n,"}"),!0}return!1}function w(){if(t[e]==="["){n+="[",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="]";){if(ne||p(",")||(n=Yt(n,",")),b(),!s()){ne||(n=ni(n,","));break}ne=!1}return t[e]==="]"?(n+="]",e++):n=Yt(n,"]"),!0}return!1}function C(){let ne=!0,Z=!0;for(;Z;)ne?ne=!1:p(",")||(n=Yt(n,",")),Z=s();Z||(n=ni(n,",")),n=`[
273
+ `))})}return e}};var xd=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=en(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=$c(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=zi(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=yo(e):s.includes("gemini")?e=yo(e):e={...e,messages:Ve(e.messages),tools:Ye(e.tools)},e.model.includes("claude")?e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`data:${a.media_type};base64,${a.image_url.url}`),delete a.media_type)})}):e.messages.forEach(i=>{Array.isArray(i.content)&&i.content.forEach(a=>{a.type==="image_url"&&(a.image_url.url.startsWith("http")||(a.image_url.url=`${a.image_url.url}`),delete a.media_type)})}),Object.assign(e,this.options||{}),o&&(e.session_id=o,e.prompt_cache_key=o),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=yd(),r=!1,o=!1;return Ne(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Pe(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Pe(s,i.encoder));return}try{let a=s.slice(6),u=JSON.parse(a);u.usage&&(this.logger?.debug({usage:u.usage,hasToolCall:o},"usage"),u.choices[0].finish_reason=o?"tool_calls":"stop"),u.choices?.[0]?.finish_reason==="error"&&i.controller.enqueue(ve(JSON.stringify({error:u.choices?.[0]?.error}),i.encoder)),u.choices?.[0]?.delta?.content&&!r&&(r=!0);let d=u.choices?.[0]?.delta,f=d?Ys(d):null;if(f){_d(n,f);let p=Zr(u,{content:f});eo(p.choices[0].delta),i.controller.enqueue(ve(JSON.stringify(p),i.encoder));return}if(d?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=bd(n),g=Zr(u,{content:p,signature:h});eo(g.choices[0].delta),g.choices[0].delta.content=null,i.controller.enqueue(ve(JSON.stringify(g),i.encoder))}d?.reasoning&&delete d.reasoning,d?.tool_calls?.length&&!Number.isNaN(parseInt(d.tool_calls[0].id,10))&&d.tool_calls.forEach(p=>{p.id=`call_${On()}`}),d?.tool_calls?.length&&!o&&(o=!0),d?.tool_calls?.length&&r&&(typeof u.choices[0].index=="number"?u.choices[0].index+=1:u.choices[0].index=1),i.controller.enqueue(ve(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Pe(s,i.encoder))}})}return e}};var Rd=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens}options;static TransformerName="maxtoken";max_tokens;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),e}};var Dd=class{name="groq";async transformRequestIn(e){return e.messages=Ve(e.messages),e.tools=Ye(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=Ru(n.function.parameters))}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=!1;return Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}try{let s=r.slice(5).trim(),i=JSON.parse(s);if(i.error)throw new Error(JSON.stringify(i));i.choices?.[0]?.delta?.content&&!n&&(n=!0),i.choices?.[0]?.delta?.tool_calls?.length&&i.choices[0].delta.tool_calls.forEach(a=>{a.id=`call_${On()}`}),i.choices?.[0]?.delta?.tool_calls?.length&&n&&(typeof i.choices[0].index=="number"?i.choices[0].index+=1:i.choices[0].index=1),o.controller.enqueue(ve(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}})}return e}};var Od=class{name="cleancache";async transformRequestIn(e){return Array.isArray(e.messages)&&e.messages.forEach(n=>{Array.isArray(n.content)?n.content.forEach(r=>{r.cache_control&&delete r.cache_control}):n.cache_control&&delete n.cache_control}),Array.isArray(e.tools)&&e.tools.forEach(n=>{n.cache_control&&delete n.cache_control}),e}};var WT=nr(oh());var br=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function NT(t){return/^[0-9A-Fa-f]$/.test(t)}function wr(t){return t>="0"&&t<="9"}function MT(t){return t>=" "}function ei(t){return`,:[]/{}()
274
+ +`.includes(t)}function $y(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Pd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var qy=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Hy=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function zy(t){return`,[]/{}
275
+ +`.includes(t)}function Wy(t){return ti(t)||VU.test(t)}var VU=/^[[{\w-]$/;function Gy(t){return t===`
276
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function Cr(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function BT(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function jT(t,e){let n=t.charCodeAt(e);return n===160||n===6158||n>=8192&&n<=8203||n===8239||n===8287||n===12288||n===65279}function ti(t){return Jy(t)||Id(t)}function Jy(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Ky(t){return t==='"'}function Id(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Vy(t){return t==="'"}function ni(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Yt(t,e){let n=t.length;if(!Cr(t,n-1))return t+e;for(;Cr(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function UT(t,e,n){return t.substring(0,e)+t.substring(e+n)}function LT(t){return/[,\n][ \t\r]*$/.test(t)}var YU={"&quot;":'"',"&amp;":"&","&lt;":"<","&gt;":">","&apos;":"'"},Yy=12;function Xy(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=YU[n];if(r!==void 0)return{char:r,length:n.length};if(t.charAt(1)==="#"){let o=t.substring(2,e),s=o.charAt(0)==="x"||o.charAt(0)==="X",i=s?o.substring(1):o;if(i.length>0){let a=Number.parseInt(i,s?16:10);if(!Number.isNaN(a)&&a>=0&&a<=1114111)return{char:String.fromCodePoint(a),length:n.length}}}return null}function $T(t){return t!==null&&t.char==='"'}function qT(t){return t!==null&&t.char==="'"}function Zs(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function HT(t,e){switch(e){case")":return Zs(t,"(")>Zs(t,")");case"]":return Zs(t,"[")>Zs(t,"]");case"}":return Zs(t,"{")>Zs(t,"}");default:return!1}}var zT={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},XU={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
277
+ `,r:"\r",t:" "};function Qy(t){let e=0,n="";d(["```","[```","{```"]),s()||_e(),d(["```","```]","```}"]);let o=p(",");for(o&&i(),Wy(t[e])&&LT(n)?(o||(n=Yt(n,",")),C()):o&&(n=ni(n,","));t[e]==="}"||t[e]==="]";)e++,i();if(e>=t.length)return n;Q();function s(){i();let ne=m()||w()||S()||E()||x()||q(!1)||V();return i(),ne}function i(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ae=a(ne);do ae=u(),ae&&(ae=a(ne));while(ae);return e>Z}function a(ne){let Z=ne?Cr:BT,ae="";for(;;)if(Z(t,e))ae+=t[e],e++;else if(jT(t,e))ae+=" ",e++;else break;return ae.length>0?(n+=ae,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!QU(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
278
+ `;)e++;return!0}return!1}function d(ne){if(f(ne)){if($y(t[e]))for(;e<t.length&&Pd(t[e]);)e++;return i(),!0}return!1}function f(ne){a(!0);for(let Z of ne){let ae=e+Z.length;if(t.slice(e,ae)===Z)return e=ae,!0}return!1}function p(ne){return t[e]===ne?(n+=t[e],e++,!0):!1}function h(ne){return t[e]===ne?(e++,!0):!1}function g(){return h("\\")}function b(){return i(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,i(),h(","),!0):!1}function m(){if(t[e]==="{"){n+="{",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(ne?Z=!0:(Z=p(","),Z||(n=Yt(n,",")),i()),b(),!(S()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ne||(n=ni(n,",")):Oe();break}i();let Ie=p(":"),we=e>=t.length;Ie||(Wy(t[e])||we?n=Yt(n,":"):Te()),s()||(Ie||we?n+="null":Te()),ne=!1}return t[e]==="}"?(n+="}",e++):n=Yt(n,"}"),!0}return!1}function w(){if(t[e]==="["){n+="[",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="]";){if(ne||p(",")||(n=Yt(n,",")),b(),!s()){ne||(n=ni(n,","));break}ne=!1}return t[e]==="]"?(n+="]",e++):n=Yt(n,"]"),!0}return!1}function C(){let ne=!0,Z=!0;for(;Z;)ne?ne=!1:p(",")||(n=Yt(n,",")),Z=s();Z||(n=ni(n,",")),n=`[
279
279
  ${n}
280
- ]`}function A(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";ae&&(e++,ti(t[e])||Q());let Ie=t[e]==="&"?Qy(t.slice(e,e+Xy)):null,we=$T(Ie)||qT(Ie);if(ti(t[e])||we){let H=Vy(t[e])?Vy:Yy(t[e])?Yy:Id(t[e])?Id:Ky,Ee=e,Ze=n.length,X='"';for(e+=we&&Ie?Ie.length:1;;){if(e>=t.length){let S=j(e-1);return!ne&&ei(t.charAt(S))?(e=Ee,n=n.substring(0,Ze),A(!0)):(X=Yt(X,'"'),n+=X,!0)}if(e===Z)return X=Yt(X,'"'),n+=X,!0;let de=we&&t[e]==="&"?Qy(t.slice(e,e+Xy)):null;if(de&&Ie?de.char===Ie.char:H(t[e])){let S=e,T=X.length;if(X+='"',e+=de?de.length:1,n+=X,i(!1),ne||e>=t.length||ei(t[e])&&!HT(X,t[e])||ti(t[e])&&!ee(e)||wr(t[e]))return k(),!0;t[e]==="\\"&&Q();let R=j(S-1),M=t.charAt(R);if(M===",")return e=Ee,n=n.substring(0,Ze),A(!1,R);if(ei(M))return e=Ee,n=n.substring(0,Ze),A(!0);n=n.substring(0,Ze),e=S+(de?de.length:1),X=`${X.substring(0,T)}\\${X.substring(T)}`}else if(ne&&Wy(t[e])){if(t[e-1]===":"&&Hy.test(t.substring(Ee+1,e+2)))for(;e<t.length&&zy.test(t[e]);)X+=t[e],e++;return X=Yt(X,'"'),n+=X,k(),!0}else if(de){let S=de.char;S==='"'?X+='\\"':Jy(S)?X+=zT[S]:X+=S,e+=de.length}else if(t[e]==="\\"){let S=t.charAt(e+1);if(Yj[S]!==void 0)X+=t.slice(e,e+2),e+=2;else if(S==="u"){let R=2;for(;R<6&&NT(t[e+R]);)R++;R===6?(X+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Ke()}else S===`
281
- `?(X+="\\n",e+=2):(X+=S,e+=2)}else{let S=t.charAt(e);S==='"'&&t[e-1]!=="\\"?(X+=`\\${S}`,e++):Jy(S)?(X+=zT[S],e++):(MT(S)||te(S),X+=S,e++)}ae&&g()}}return!1}function k(){let ne=!1;for(i();t[e]==="+";){ne=!0,e++,i(),n=ni(n,'"',!0);let Z=n.length;A()?n=jT(n,Z,1):n=Yt(n,'"')}return ne}function E(){let ne=e,Z="",ae=!1;for(t[e]==="-"&&(Z+=t[e],e++,!wr(t[e])&&z()&&(Z+="0")),t[e]==="0"&&wr(t[e+1])&&(ae=!0);wr(t[e]);)Z+=t[e],e++;if(t[e]===".")for((Z===""||Z==="-")&&(Z+="0"),Z+=t[e],e++,wr(t[e])||(Z+="0");wr(t[e]);)Z+=t[e],e++;if(e>ne){if(t[e]==="e"||t[e]==="E")for(Z==="-"&&(ae=!0),Z+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Z+=t[e],e++),wr(t[e])||(Z+="0");wr(t[e]);)Z+=t[e],e++;return z()?(n+=ae?`"${t.substring(ne,e)}"`:Z,!0):(e=ne,!1)}return!1}function x(){return O("true","true")||O("false","false")||O("null","null")||O("True","true")||O("False","false")||O("None","null")}function O(ne,Z){return t.slice(e,e+ne.length)===ne&&!Pd(t[e+ne.length])?(n+=Z,e+=ne.length,!0):!1}function q(ne){let Z=e;if(qy(t[e])){for(;e<t.length&&Pd(t[e]);)e++;let ae=e;for(;Cr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!Wy(t[e])&&!ti(t[e])&&(!ne||t[e]!==":");)e++;if(t[e-1]===":"&&Hy.test(t.substring(Z,e+2)))for(;e<t.length&&zy.test(t[e]);)e++;if(e>Z){for(;Cr(t,e-1)&&e>0;)e--;let ae=t.slice(Z,e);return n+=ae==="undefined"?"null":JSON.stringify(ae),t[e]==='"'&&e++,!0}}function V(){if(t[e]==="/"){let ne=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=JSON.stringify(t.substring(ne,e)),!0}}function j(ne){let Z=ne;for(;Z>0&&Cr(t,Z);)Z--;return Z}function ee(ne){let Z=ne+1;for(;Z<t.length&&Cr(t,Z);)Z++;return Z>=t.length||ei(t[Z])}function z(){return e>=t.length||ei(t[e])||Cr(t,e)}function te(ne){throw new br(`Invalid character ${JSON.stringify(ne)}`,e)}function Q(){throw new br(`Unexpected character ${JSON.stringify(t[e])}`,e)}function _e(){throw new br("Unexpected end of json string",t.length)}function Oe(){throw new br("Object key expected",e)}function Te(){throw new br("Colon expected",e)}function Ke(){let ne=t.slice(e,e+6);throw new br(`Invalid unicode character "${ne}"`,e)}}function Xj(t,e){return t[e]==="*"&&t[e+1]==="/"}function e_(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=WT.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Zy(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Fd=class{logger;name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=e_(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,i="",a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(m,w,C)=>{let A=m.split(`
282
- `);for(let k of A)k.trim()&&w.enqueue(C.encode(k+`
283
- `))},g=(m,w,C)=>{let A;try{A=e_(o.arguments||"",this.logger)}catch(O){this.logger?.error(`${O.message} ${O.stack} Tool call argument parsing failed: ${JSON.stringify(o)}`),A=o.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:o.name,arguments:A},id:o.id,index:o.index,type:"function"}]},E={...m,choices:[{...m.choices[0],delta:k}]};E.choices[0].delta.content!==void 0&&delete E.choices[0].delta.content;let x=`data: ${JSON.stringify(E)}
280
+ ]`}function S(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";ae&&(e++,ti(t[e])||Q());let Ie=t[e]==="&"?Xy(t.slice(e,e+Yy)):null,we=$T(Ie)||qT(Ie);if(ti(t[e])||we){let H=Ky(t[e])?Ky:Vy(t[e])?Vy:Id(t[e])?Id:Jy,Ee=e,Ze=n.length,X='"';for(e+=we&&Ie?Ie.length:1;;){if(e>=t.length){let A=U(e-1);return!ne&&ei(t.charAt(A))?(e=Ee,n=n.substring(0,Ze),S(!0)):(X=Yt(X,'"'),n+=X,!0)}if(e===Z)return X=Yt(X,'"'),n+=X,!0;let de=we&&t[e]==="&"?Xy(t.slice(e,e+Yy)):null;if(de&&Ie?de.char===Ie.char:H(t[e])){let A=e,T=X.length;if(X+='"',e+=de?de.length:1,n+=X,i(!1),ne||e>=t.length||ei(t[e])&&!HT(X,t[e])||ti(t[e])&&!ee(e)||wr(t[e]))return k(),!0;t[e]==="\\"&&Q();let R=U(A-1),M=t.charAt(R);if(M===",")return e=Ee,n=n.substring(0,Ze),S(!1,R);if(ei(M))return e=Ee,n=n.substring(0,Ze),S(!0);n=n.substring(0,Ze),e=A+(de?de.length:1),X=`${X.substring(0,T)}\\${X.substring(T)}`}else if(ne&&zy(t[e])){if(t[e-1]===":"&&qy.test(t.substring(Ee+1,e+2)))for(;e<t.length&&Hy.test(t[e]);)X+=t[e],e++;return X=Yt(X,'"'),n+=X,k(),!0}else if(de){let A=de.char;A==='"'?X+='\\"':Gy(A)?X+=zT[A]:X+=A,e+=de.length}else if(t[e]==="\\"){let A=t.charAt(e+1);if(XU[A]!==void 0)X+=t.slice(e,e+2),e+=2;else if(A==="u"){let R=2;for(;R<6&&NT(t[e+R]);)R++;R===6?(X+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Ke()}else A===`
281
+ `?(X+="\\n",e+=2):(X+=A,e+=2)}else{let A=t.charAt(e);A==='"'&&t[e-1]!=="\\"?(X+=`\\${A}`,e++):Gy(A)?(X+=zT[A],e++):(MT(A)||te(A),X+=A,e++)}ae&&g()}}return!1}function k(){let ne=!1;for(i();t[e]==="+";){ne=!0,e++,i(),n=ni(n,'"',!0);let Z=n.length;S()?n=UT(n,Z,1):n=Yt(n,'"')}return ne}function E(){let ne=e,Z="",ae=!1;for(t[e]==="-"&&(Z+=t[e],e++,!wr(t[e])&&z()&&(Z+="0")),t[e]==="0"&&wr(t[e+1])&&(ae=!0);wr(t[e]);)Z+=t[e],e++;if(t[e]===".")for((Z===""||Z==="-")&&(Z+="0"),Z+=t[e],e++,wr(t[e])||(Z+="0");wr(t[e]);)Z+=t[e],e++;if(e>ne){if(t[e]==="e"||t[e]==="E")for(Z==="-"&&(ae=!0),Z+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Z+=t[e],e++),wr(t[e])||(Z+="0");wr(t[e]);)Z+=t[e],e++;return z()?(n+=ae?`"${t.substring(ne,e)}"`:Z,!0):(e=ne,!1)}return!1}function x(){return O("true","true")||O("false","false")||O("null","null")||O("True","true")||O("False","false")||O("None","null")}function O(ne,Z){return t.slice(e,e+ne.length)===ne&&!Pd(t[e+ne.length])?(n+=Z,e+=ne.length,!0):!1}function q(ne){let Z=e;if($y(t[e])){for(;e<t.length&&Pd(t[e]);)e++;let ae=e;for(;Cr(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!zy(t[e])&&!ti(t[e])&&(!ne||t[e]!==":");)e++;if(t[e-1]===":"&&qy.test(t.substring(Z,e+2)))for(;e<t.length&&Hy.test(t[e]);)e++;if(e>Z){for(;Cr(t,e-1)&&e>0;)e--;let ae=t.slice(Z,e);return n+=ae==="undefined"?"null":JSON.stringify(ae),t[e]==='"'&&e++,!0}}function V(){if(t[e]==="/"){let ne=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=JSON.stringify(t.substring(ne,e)),!0}}function U(ne){let Z=ne;for(;Z>0&&Cr(t,Z);)Z--;return Z}function ee(ne){let Z=ne+1;for(;Z<t.length&&Cr(t,Z);)Z++;return Z>=t.length||ei(t[Z])}function z(){return e>=t.length||ei(t[e])||Cr(t,e)}function te(ne){throw new br(`Invalid character ${JSON.stringify(ne)}`,e)}function Q(){throw new br(`Unexpected character ${JSON.stringify(t[e])}`,e)}function _e(){throw new br("Unexpected end of json string",t.length)}function Oe(){throw new br("Object key expected",e)}function Te(){throw new br("Colon expected",e)}function Ke(){let ne=t.slice(e,e+6);throw new br(`Invalid unicode character "${ne}"`,e)}}function QU(t,e){return t[e]==="*"&&t[e+1]==="/"}function Zy(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=WT.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Qy(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Fd=class{logger;name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Zy(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,i="",a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(m,w,C)=>{let S=m.split(`
282
+ `);for(let k of S)k.trim()&&w.enqueue(C.encode(k+`
283
+ `))},g=(m,w,C)=>{let S;try{S=Zy(o.arguments||"",this.logger)}catch(O){this.logger?.error(`${O.message} ${O.stack} Tool call argument parsing failed: ${JSON.stringify(o)}`),S=o.arguments||""}let k={role:"assistant",tool_calls:[{function:{name:o.name,arguments:S},id:o.id,index:o.index,type:"function"}]},E={...m,choices:[{...m.choices[0],delta:k}]};E.choices[0].delta.content!==void 0&&delete E.choices[0].delta.content;let x=`data: ${JSON.stringify(E)}
284
284
 
285
- `;w.enqueue(C.encode(x))},b=(m,w)=>{let{controller:C,encoder:A}=w;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let E=JSON.parse(k);if(E.choices?.[0]?.delta?.tool_calls?.length){let O=E.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""},O.function?.arguments&&(O.function.arguments="");let q=`data: ${JSON.stringify(E)}
285
+ `;w.enqueue(C.encode(x))},b=(m,w)=>{let{controller:C,encoder:S}=w;if(m.startsWith("data: ")&&m.trim()!=="data: [DONE]"){let k=m.slice(6);try{let E=JSON.parse(k);if(E.choices?.[0]?.delta?.tool_calls?.length){let O=E.choices[0].delta.tool_calls[0];if(typeof o.index>"u"){o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""},O.function?.arguments&&(O.function.arguments="");let q=`data: ${JSON.stringify(E)}
286
286
 
287
- `;C.enqueue(A.encode(q));return}else if(o.index===O.index){O.function?.arguments&&(o.arguments+=O.function.arguments);return}else{g(E,C,A),o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""};return}}if(E.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){g(E,C,A),o={};return}E.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof E.choices[0].index=="number"?E.choices[0].index+=1:E.choices[0].index=1);let x=`data: ${JSON.stringify(E)}
287
+ `;C.enqueue(S.encode(q));return}else if(o.index===O.index){O.function?.arguments&&(o.arguments+=O.function.arguments);return}else{g(E,C,S),o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""};return}}if(E.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){g(E,C,S),o={};return}E.choices?.[0]?.delta?.tool_calls?.length&&w.hasTextContent()&&(typeof E.choices[0].index=="number"?E.choices[0].index+=1:E.choices[0].index=1);let x=`data: ${JSON.stringify(E)}
288
288
 
289
- `;C.enqueue(A.encode(x))}catch{C.enqueue(A.encode(m+`
290
- `))}}else C.enqueue(A.encode(m+`
289
+ `;C.enqueue(S.encode(x))}catch{C.enqueue(S.encode(m+`
290
+ `))}}else C.enqueue(S.encode(m+`
291
291
  `))};try{for(;;){let{done:m,value:w}=await p.read();if(m){u.trim()&&h(u,f,r);break}if(!w||w.length===0)continue;let C;try{C=n.decode(w,{stream:!0})}catch(k){this.logger?.warn("Failed to decode chunk",k);continue}if(C.length===0)continue;if(u+=C,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let k=u.split(`
292
292
  `);u=k.pop()||"";for(let E of k)if(E.trim())try{b(E,{controller:f,encoder:r,hasTextContent:()=>s,setHasTextContent:x=>s=x,reasoningContent:()=>i,appendReasoningContent:x=>i+=x,isReasoningComplete:()=>a,setReasoningComplete:x=>a=x})}catch(x){this.logger?.error("Error processing line:",E,x),f.enqueue(r.encode(E+`
293
- `))}continue}let A=u.split(`
294
- `);u=A.pop()||"";for(let k of A)if(k.trim())try{b(k,{controller:f,encoder:r,hasTextContent:()=>s,setHasTextContent:E=>s=E,reasoningContent:()=>i,appendReasoningContent:E=>i+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){this.logger?.error("Error processing line:",k,E),f.enqueue(r.encode(k+`
293
+ `))}continue}let S=u.split(`
294
+ `);u=S.pop()||"";for(let k of S)if(k.trim())try{b(k,{controller:f,encoder:r,hasTextContent:()=>s,setHasTextContent:E=>s=E,reasoningContent:()=>i,appendReasoningContent:E=>i+=E,isReasoningComplete:()=>a,setReasoningComplete:E=>a=E})}catch(E){this.logger?.error("Error processing line:",k,E),f.enqueue(r.encode(k+`
295
295
  `))}}}catch(m){this.logger?.error("Stream error:",m),f.error(m)}finally{try{p.releaseLock()}catch(m){this.logger?.error("Error releasing reader lock:",m)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Nd=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}options;static TransformerName="reasoning";enable;async transformRequestIn(e,n,r){return this.enable?Ot(e.reasoning,e.thinking)?(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e):(e.reasoning?(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0):e.model&&String(e.model).startsWith("deepseek")&&(e.enable_thinking=!0),kd(e,n,r),e):(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e)}async transformResponseOut(e,n){if(!this.enable)return e;let r=Sd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return o.choices[0]?.message.reasoning_content&&(o.thinking={content:o.choices[0]?.message.reasoning_content}),r&&Xs({role:"assistant",content:o.choices?.[0]?.message?.content??null,tool_calls:o.choices?.[0]?.message?.tool_calls,reasoning_content:o.choices?.[0]?.message?.reasoning_content},n),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o="",s=!1,i=r?Ad():null;return Ne(e,(u,d)=>{let{controller:f,encoder:p}=d;if(u.startsWith("data: ")&&u.trim()!=="data: [DONE]")try{let h=JSON.parse(u.slice(6)),g=h.choices?.[0]?.delta;if(!g){f.enqueue(p.encode(u+`
296
296
  `));return}if(g.reasoning_content){o+=typeof g.reasoning_content=="string"?g.reasoning_content:JSON.stringify(g.reasoning_content),i&&Qs(i,g);let b={...h,choices:[{...h.choices[0],delta:{...g,thinking:{content:g.reasoning_content}}}]};delete b.choices[0].delta.reasoning_content;let m=`data: ${JSON.stringify(b)}
297
297
 
@@ -301,11 +301,11 @@ ${n}
301
301
 
302
302
  `;f.enqueue(p.encode(b))}}catch{f.enqueue(p.encode(u+`
303
303
  `))}else f.enqueue(p.encode(u+`
304
- `))},{onComplete:()=>{i&&Xs(Ed(i),n)}})}return e}};var Md=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}options;static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Bd=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};async function Qj(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(gd(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
304
+ `))},{onComplete:()=>{i&&Xs(Ed(i),n)}})}return e}};var Md=class{constructor(e){this.options=e;this.max_tokens=this.options?.max_tokens,this.temperature=this.options?.temperature,this.top_p=this.options?.top_p,this.top_k=this.options?.top_k,this.repetition_penalty=this.options?.repetition_penalty}options;static TransformerName="sampling";max_tokens;temperature;top_p;top_k;repetition_penalty;async transformRequestIn(e){return e.max_tokens&&e.max_tokens>this.max_tokens&&(e.max_tokens=this.max_tokens),typeof this.temperature<"u"&&(e.temperature=this.temperature),typeof this.top_p<"u"&&(e.top_p=this.top_p),typeof this.top_k<"u"&&(e.top_k=this.top_k),typeof this.repetition_penalty<"u"&&(e.repetition_penalty=this.repetition_penalty),e}};var Bd=class{static TransformerName="maxcompletiontokens";async transformRequestIn(e){return e.max_tokens&&(e.max_completion_tokens=e.max_tokens,delete e.max_tokens),e}};async function ZU(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(gd(),1));return(await(await new e({scopes:["https://www.googleapis.com/auth/cloud-platform"]}).getClient()).getAccessToken()).token||""}catch(e){throw(t?.error??console.error)("Error getting access token:",e),new Error(`Failed to get access token for Vertex AI. Please ensure you have set up authentication using one of these methods:
305
305
  1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
306
306
  2. Run "gcloud auth application-default login"
307
- 3. Use Google Cloud environment with default service account`,{cause:e})}}var Ud=class{logger;name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let a=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),u=JSON.parse(a);u&&u.project_id&&(r=u.project_id)}catch(i){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await Qj(this.logger);return{body:Bk(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return Uk(e)}async transformResponseOut(e){return ku(e,this.name,this.logger)}};var GT=nr(gd(),1);var jd=class{static TransformerName="vertex-openai";client;client_email;private_key;constructor(e={}){this.client_email=e.client_email,this.private_key=e.private_key?.replace(/\\n/g,`
308
- `)}async getClient(){if(this.client)return this.client;if(!this.client_email||!this.private_key)throw new Error("vertex-openai requires client_email and private_key in transformer options");let e=new GT.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],credentials:{client_email:this.client_email,private_key:this.private_key}});return this.client=await e.getClient(),this.client}async transformRequestIn(e){let n=await this.getClient(),{token:r}=await n.getAccessToken();if(!r)throw new Error("Failed to get access token");return{body:{...e,messages:Ve(e.messages),tools:Ye(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var Ld=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Ve(o.messages),o.tools=Ye(o.tools);let s=en(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var $d=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var qd=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return Zj(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),Wc(e),e.messages=tL(e.messages),zc(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return rL(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json();return new Response(JSON.stringify(JT(o)),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function Zj(t){if(!t||typeof t!="object")throw J("Invalid Chat Completions body",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model.trim())throw J("Chat Completions requires model",400,"invalid_body","invalid_request_error");if(!Array.isArray(t.messages))throw J("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(t.stream!==void 0&&typeof t.stream!="boolean")throw J("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.n!==void 0&&t.n!==1)throw J("n values other than 1 are not supported",400,"unsupported_n","invalid_request_error");if(t.logprobs===!0||t.top_logprobs!==void 0)throw J("logprobs/top_logprobs are not supported",400,"unsupported_logprobs","invalid_request_error");if(Array.isArray(t.modalities)&&t.modalities.filter(a=>a!=="text"&&a!==void 0).length>0)throw J("Non-text output modalities are not supported",400,"unsupported_modalities","invalid_request_error");if(t.audio!==void 0)throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.store===!0||t.metadata!==void 0)throw J("Stored Chat Completions and metadata are not supported",400,"unsupported_state","invalid_request_error");for(let i of["prediction","web_search_options","moderation","service_tier","frequency_penalty","presence_penalty","seed","user","verbosity","safety_identifier","functions","function_call"])if(t[i]!==void 0&&t[i]!==null)throw J(`Chat Completions field '${i}' is not supported`,400,"unsupported_field","invalid_request_error");if(t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;if(a&&a!=="text"&&a!=="json_schema"&&a!=="json_object")throw J("response_format structured output is not supported without a verified provider mapping",400,"unsupported_response_format","invalid_request_error")}if(t.stream_options!=null&&t.stream!==!0)throw J("stream_options requires stream: true",400,"invalid_stream_options","invalid_request_error");if(t.stream_options!=null){if(typeof t.stream_options!="object"||Array.isArray(t.stream_options))throw J("stream_options must be an object",400,"invalid_stream_options","invalid_request_error");let i=Object.keys(t.stream_options).find(a=>a!=="include_usage");if(i)throw J(`Unsupported stream option '${i}'`,400,"invalid_stream_options","invalid_request_error");if(t.stream_options.include_usage!==void 0&&typeof t.stream_options.include_usage!="boolean")throw J("stream_options.include_usage must be a boolean",400,"invalid_stream_options","invalid_request_error")}let e=t.max_tokens!=null,n=t.max_completion_tokens!=null;if(e&&n&&Number(t.max_tokens)!==Number(t.max_completion_tokens))throw J("max_tokens and max_completion_tokens both present and differ",400,"conflicting_token_limits","invalid_request_error");for(let[i,a]of[["max_tokens",e],["max_completion_tokens",n]]){if(!a)continue;let u=Number(t[i]);if(!Number.isInteger(u)||u<=0)throw J(`${i} must be a positive integer`,400,"invalid_token_limit","invalid_request_error")}if(nL(t.tools,t.tool_choice),t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw J("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");let r=t.messages.map(i=>eL(i)),o={model:t.model,messages:r,stream:t.stream===!0};if(t.stream_options&&(o.stream_options=t.stream_options),e&&(o.max_tokens=Number(t.max_tokens)),n&&(o.max_completion_tokens=Number(t.max_completion_tokens),e||(o.max_tokens=Number(t.max_completion_tokens))),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.stop!==void 0&&(o.stop=t.stop),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),t.parallel_tool_calls!==void 0&&(o.parallel_tool_calls=t.parallel_tool_calls),t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;(a==="json_schema"||a==="json_object")&&(o.response_format=i)}let s=Dt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...ns(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function eL(t){if(!t||typeof t!="object")throw J("Invalid message in messages[]",400,"invalid_body","invalid_request_error");let e=t.role;if(!["developer","system","user","assistant","tool"].includes(e))throw J(`Unsupported message role '${e}'`,400,"unsupported_role","invalid_request_error");if(t.audio!==void 0)throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.name!==void 0)throw J("Named messages are not supported by the cross-protocol compatibility tier",400,"unsupported_message_name","invalid_request_error");if(Array.isArray(t.content)){let r={developer:new Set(["text"]),system:new Set(["text"]),user:new Set(["text","image_url"]),assistant:new Set(["text","refusal"]),tool:new Set(["text"])};for(let o of t.content){if(!o||typeof o!="object")throw J(`Invalid content part for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if(o?.type==="input_audio"||o?.type==="audio")throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(o?.type==="file")throw J("Provider-hosted file inputs are not supported",400,"unsupported_file","invalid_request_error");if(!r[e]?.has(o?.type))throw J(`Unsupported content part '${o?.type||"unknown"}' for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if((o.type==="text"||o.type==="refusal")&&typeof o.text!="string"&&typeof o.refusal!="string")throw J(`Content part '${o.type}' requires text`,400,"invalid_content_part","invalid_request_error");if(o.type==="image_url"&&(typeof o.image_url!="object"||typeof o.image_url?.url!="string"||!o.image_url.url))throw J("image_url content requires image_url.url",400,"invalid_image","invalid_request_error")}}else if(typeof t.content!="string"&&!(e==="assistant"&&t.content==null))throw J(`Message role '${e}' requires string or array content`,400,"invalid_message_content","invalid_request_error");if(e==="tool"){if(typeof t.tool_call_id!="string"||!t.tool_call_id)throw J("Tool messages require tool_call_id",400,"invalid_tool_call_id","invalid_request_error")}else if(t.tool_call_id!==void 0)throw J("tool_call_id is only valid on tool messages",400,"invalid_tool_call_id","invalid_request_error");if(t.tool_calls!==void 0){if(e!=="assistant"||!Array.isArray(t.tool_calls))throw J("tool_calls must be an array on assistant messages",400,"invalid_tool_calls","invalid_request_error");for(let r of t.tool_calls)if(r?.type!=="function"||typeof r?.id!="string"||!r.id||typeof r?.function?.name!="string"||!r.function.name||typeof r?.function?.arguments!="string")throw J("Invalid function call in assistant tool_calls",400,"invalid_tool_calls","invalid_request_error")}let n=e==="developer"?{...t,role:"system"}:t;return n.role==="assistant"&&Hd(n),n}function Hd(t){if(!t||typeof t!="object")return;let e=typeof t.thinking?.content=="string"?t.thinking.content:"",n=typeof t.reasoning_content=="string"?t.reasoning_content:"",r=e||n;!r&&!t.thinking?.signature&&!t.thinking?.encrypted_content&&!t.thinking?.id||(r&&(t.reasoning_content=r),t.thinking?!e&&r&&(t.thinking.content=r):t.thinking={content:r})}function tL(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),Hd(n),delete n.thinking,n})}function JT(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0]?.message;e&&Hd(e);let n=t.choices?.[0]?.delta;return n&&Hd(n),t}function nL(t,e){if(t!==void 0&&!Array.isArray(t))throw J("tools must be an array",400,"invalid_tools","invalid_request_error");for(let n of t||[])if(n?.type!=="function"||typeof n?.function?.name!="string"||!n.function.name)throw J("Only function tools are supported by Chat Completions inbound routes",400,"unsupported_tool","invalid_request_error");if(e!=null&&!["auto","none","required"].includes(e)&&!(e?.type==="function"&&typeof e?.function?.name=="string"&&e.function.name))throw J("Unsupported tool_choice",400,"unsupported_tool_choice","invalid_request_error")}function rL(t,e){if(!t.body)return t;let n=t.body.getReader(),r=new TextDecoder,o=new TextEncoder,s="",i=!1,a=e?.aliasThinking===!0,u=p=>{if(!a||!p.startsWith("data:"))return p;let h=p.slice(5).trim();if(!h||h==="[DONE]")return p;try{return`data: ${JSON.stringify(JT(JSON.parse(h)))}`}catch{return p}},d=(p,h=!1)=>{s+=p;let g=s.split(/\r?\n/);s=h?"":g.pop()||"";let b=[],m=w=>{if(!i)for(let C of Yc(w)){if(i)return;if(Xc(C)){i=!0,Qc(b);return}b.push(u(C))}};for(let w of g)m(w);return h&&s&&(m(s),s=""),b.length?`${b.join(`
307
+ 3. Use Google Cloud environment with default service account`,{cause:e})}}var jd=class{logger;name="vertex-claude";async transformRequestIn(e,n){let r=process.env.GOOGLE_CLOUD_PROJECT,o=process.env.GOOGLE_CLOUD_LOCATION||"us-east5";if(!r&&process.env.GOOGLE_APPLICATION_CREDENTIALS)try{let a=(await import("fs")).readFileSync(process.env.GOOGLE_APPLICATION_CREDENTIALS,"utf8"),u=JSON.parse(a);u&&u.project_id&&(r=u.project_id)}catch(i){this.logger?.error("Error extracting project_id from GOOGLE_APPLICATION_CREDENTIALS:",i)}if(!r)throw new Error("Project ID is required for Vertex AI. Set GOOGLE_CLOUD_PROJECT environment variable or ensure project_id is in GOOGLE_APPLICATION_CREDENTIALS file.");let s=await ZU(this.logger);return{body:Bk(e),config:{url:new URL(`/v1/projects/${r}/locations/${o}/publishers/anthropic/models/${e.model}:${e.stream?"streamRawPredict":"rawPredict"}`,`https://${o}-aiplatform.googleapis.com`).toString(),headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}}}}async transformRequestOut(e){return jk(e)}async transformResponseOut(e){return ku(e,this.name,this.logger)}};var GT=nr(gd(),1);var Ud=class{static TransformerName="vertex-openai";client;client_email;private_key;constructor(e={}){this.client_email=e.client_email,this.private_key=e.private_key?.replace(/\\n/g,`
308
+ `)}async getClient(){if(this.client)return this.client;if(!this.client_email||!this.private_key)throw new Error("vertex-openai requires client_email and private_key in transformer options");let e=new GT.GoogleAuth({scopes:["https://www.googleapis.com/auth/cloud-platform"],credentials:{client_email:this.client_email,private_key:this.private_key}});return this.client=await e.getClient(),this.client}async transformRequestIn(e){let n=await this.getClient(),{token:r}=await n.getAccessToken();if(!r)throw new Error("Failed to get access token");return{body:{...e,messages:Ve(e.messages),tools:Ye(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var Ld=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Ve(o.messages),o.tools=Ye(o.tools);let s=en(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var $d=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var qd=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return eL(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),Wc(e),e.messages=oL(e.messages),zc(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return iL(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json(),s=KT(structuredClone(o));return new Response(JSON.stringify(s??o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function eL(t){if(!t||typeof t!="object")throw J("Invalid Chat Completions body",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model.trim())throw J("Chat Completions requires model",400,"invalid_body","invalid_request_error");if(!Array.isArray(t.messages))throw J("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(t.stream!==void 0&&typeof t.stream!="boolean")throw J("stream must be a boolean",400,"invalid_stream","invalid_request_error");if(t.n!==void 0&&t.n!==1)throw J("n values other than 1 are not supported",400,"unsupported_n","invalid_request_error");if(t.logprobs===!0||t.top_logprobs!==void 0)throw J("logprobs/top_logprobs are not supported",400,"unsupported_logprobs","invalid_request_error");if(Array.isArray(t.modalities)&&t.modalities.filter(a=>a!=="text"&&a!==void 0).length>0)throw J("Non-text output modalities are not supported",400,"unsupported_modalities","invalid_request_error");if(t.audio!==void 0)throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.store===!0||t.metadata!==void 0)throw J("Stored Chat Completions and metadata are not supported",400,"unsupported_state","invalid_request_error");for(let i of["prediction","web_search_options","moderation","service_tier","frequency_penalty","presence_penalty","seed","user","verbosity","safety_identifier","functions","function_call"])if(t[i]!==void 0&&t[i]!==null)throw J(`Chat Completions field '${i}' is not supported`,400,"unsupported_field","invalid_request_error");if(t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;if(a&&a!=="text"&&a!=="json_schema"&&a!=="json_object")throw J("response_format structured output is not supported without a verified provider mapping",400,"unsupported_response_format","invalid_request_error")}if(t.stream_options!=null&&t.stream!==!0)throw J("stream_options requires stream: true",400,"invalid_stream_options","invalid_request_error");if(t.stream_options!=null){if(typeof t.stream_options!="object"||Array.isArray(t.stream_options))throw J("stream_options must be an object",400,"invalid_stream_options","invalid_request_error");let i=Object.keys(t.stream_options).find(a=>a!=="include_usage");if(i)throw J(`Unsupported stream option '${i}'`,400,"invalid_stream_options","invalid_request_error");if(t.stream_options.include_usage!==void 0&&typeof t.stream_options.include_usage!="boolean")throw J("stream_options.include_usage must be a boolean",400,"invalid_stream_options","invalid_request_error")}let e=t.max_tokens!=null,n=t.max_completion_tokens!=null;if(e&&n&&Number(t.max_tokens)!==Number(t.max_completion_tokens))throw J("max_tokens and max_completion_tokens both present and differ",400,"conflicting_token_limits","invalid_request_error");for(let[i,a]of[["max_tokens",e],["max_completion_tokens",n]]){if(!a)continue;let u=Number(t[i]);if(!Number.isInteger(u)||u<=0)throw J(`${i} must be a positive integer`,400,"invalid_token_limit","invalid_request_error")}if(sL(t.tools,t.tool_choice),t.parallel_tool_calls!==void 0&&typeof t.parallel_tool_calls!="boolean")throw J("parallel_tool_calls must be a boolean",400,"invalid_parallel_tool_calls","invalid_request_error");let r=t.messages.map(i=>tL(i)),o={model:t.model,messages:r,stream:t.stream===!0};if(t.stream_options&&(o.stream_options=t.stream_options),e&&(o.max_tokens=Number(t.max_tokens)),n&&(o.max_completion_tokens=Number(t.max_completion_tokens),e||(o.max_tokens=Number(t.max_completion_tokens))),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.stop!==void 0&&(o.stop=t.stop),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),t.parallel_tool_calls!==void 0&&(o.parallel_tool_calls=t.parallel_tool_calls),t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;(a==="json_schema"||a==="json_object")&&(o.response_format=i)}let s=Dt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...ns(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function tL(t){if(!t||typeof t!="object")throw J("Invalid message in messages[]",400,"invalid_body","invalid_request_error");let e=t.role;if(!["developer","system","user","assistant","tool"].includes(e))throw J(`Unsupported message role '${e}'`,400,"unsupported_role","invalid_request_error");if(t.audio!==void 0)throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(t.name!==void 0)throw J("Named messages are not supported by the cross-protocol compatibility tier",400,"unsupported_message_name","invalid_request_error");if(Array.isArray(t.content)){let r={developer:new Set(["text"]),system:new Set(["text"]),user:new Set(["text","image_url"]),assistant:new Set(["text","refusal"]),tool:new Set(["text"])};for(let o of t.content){if(!o||typeof o!="object")throw J(`Invalid content part for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if(o?.type==="input_audio"||o?.type==="audio")throw J("Audio input/output is not supported",400,"unsupported_audio","invalid_request_error");if(o?.type==="file")throw J("Provider-hosted file inputs are not supported",400,"unsupported_file","invalid_request_error");if(!r[e]?.has(o?.type))throw J(`Unsupported content part '${o?.type||"unknown"}' for role '${e}'`,400,"unsupported_content_part","invalid_request_error");if((o.type==="text"||o.type==="refusal")&&typeof o.text!="string"&&typeof o.refusal!="string")throw J(`Content part '${o.type}' requires text`,400,"invalid_content_part","invalid_request_error");if(o.type==="image_url"&&(typeof o.image_url!="object"||typeof o.image_url?.url!="string"||!o.image_url.url))throw J("image_url content requires image_url.url",400,"invalid_image","invalid_request_error")}}else if(typeof t.content!="string"&&!(e==="assistant"&&t.content==null))throw J(`Message role '${e}' requires string or array content`,400,"invalid_message_content","invalid_request_error");if(e==="tool"){if(typeof t.tool_call_id!="string"||!t.tool_call_id)throw J("Tool messages require tool_call_id",400,"invalid_tool_call_id","invalid_request_error")}else if(t.tool_call_id!==void 0)throw J("tool_call_id is only valid on tool messages",400,"invalid_tool_call_id","invalid_request_error");if(t.tool_calls!==void 0){if(e!=="assistant"||!Array.isArray(t.tool_calls))throw J("tool_calls must be an array on assistant messages",400,"invalid_tool_calls","invalid_request_error");for(let r of t.tool_calls)if(r?.type!=="function"||typeof r?.id!="string"||!r.id||typeof r?.function?.name!="string"||!r.function.name||typeof r?.function?.arguments!="string")throw J("Invalid function call in assistant tool_calls",400,"invalid_tool_calls","invalid_request_error")}let n=e==="developer"?{...t,role:"system"}:t;return n.role==="assistant"&&e_(n),n}function e_(t){if(!t||typeof t!="object")return;let e=typeof t.thinking?.content=="string"?t.thinking.content:"",n=typeof t.reasoning_content=="string"?t.reasoning_content:"",r=typeof t.reasoning=="string"?t.reasoning:"",o=e||n||r;!o&&!t.thinking?.signature&&!t.thinking?.encrypted_content&&!t.thinking?.id||(o&&(t.reasoning_content=o,t.reasoning=o),t.thinking?!e&&o&&(t.thinking.content=o):t.thinking={content:o})}function JT(t){!t||typeof t!="object"||(e_(t),delete t.thinking)}function nL(t){!t||typeof t!="object"||(e_(t),delete t.thinking,delete t.reasoning)}function rL(t){return!t||typeof t!="object"?!0:Object.keys(t).length===0}function oL(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),nL(n),n})}function KT(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0];return e?(e.message&&JT(e.message),e.delta&&(JT(e.delta),rL(e.delta)&&e.finish_reason==null&&t.usage==null)?null:t):t}function sL(t,e){if(t!==void 0&&!Array.isArray(t))throw J("tools must be an array",400,"invalid_tools","invalid_request_error");for(let n of t||[])if(n?.type!=="function"||typeof n?.function?.name!="string"||!n.function.name)throw J("Only function tools are supported by Chat Completions inbound routes",400,"unsupported_tool","invalid_request_error");if(e!=null&&!["auto","none","required"].includes(e)&&!(e?.type==="function"&&typeof e?.function?.name=="string"&&e.function.name))throw J("Unsupported tool_choice",400,"unsupported_tool_choice","invalid_request_error")}function iL(t,e){if(!t.body)return t;let n=t.body.getReader(),r=new TextDecoder,o=new TextEncoder,s="",i=!1,a=e?.aliasThinking===!0,u=p=>{if(!a||!p.startsWith("data:"))return p;let h=p.slice(5).trim();if(!h||h==="[DONE]")return p;try{let g=KT(JSON.parse(h));return g==null?null:`data: ${JSON.stringify(g)}`}catch{return p}},d=(p,h=!1)=>{s+=p;let g=s.split(/\r?\n/);s=h?"":g.pop()||"";let b=[],m=w=>{if(!i)for(let C of Yc(w)){if(i)return;if(Xc(C)){i=!0,Qc(b);return}let S=u(C);S!=null&&b.push(S)}};for(let w of g)m(w);return h&&s&&(m(s),s=""),b.length?`${b.join(`
309
309
  `)}
310
310
  `:""},f=new ReadableStream({async pull(p){try{let{done:h,value:g}=await n.read();if(h){let m=d(r.decode(),!0);m&&p.enqueue(o.encode(m)),i||p.enqueue(o.encode(`
311
311
  data: [DONE]
@@ -315,9 +315,9 @@ data: [DONE]
315
315
  `)),p.enqueue(o.encode(`
316
316
  data: [DONE]
317
317
 
318
- `))),p.close()}},cancel(p){return n.cancel(p)}});return new Response(f,{status:t.status,statusText:t.statusText,headers:t.headers})}var zd=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var Wd=class{constructor(e){this.options=e}options;static TransformerName="vercel";logger;endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){e={...e,messages:Ve(e.messages),tools:Ye(e.tools)},e.messages.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="image_url"&&(i.image_url.url.startsWith("http")||(i.image_url.url=`data:${i.media_type};base64,${i.image_url.url}`),delete i.media_type)})}),Object.assign(e,this.options||{});let o=e.providerOptions||{};return e.providerOptions={...o,gateway:{...o.gateway||{},caching:"auto"}},e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",i=!1,a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(b,m,w)=>{let C=b.split(`
319
- `);for(let A of C)A.trim()&&m.enqueue(w.encode(A+`
320
- `))},g=(b,m)=>{let{controller:w,encoder:C}=m;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let A=b.slice(6);try{let k=JSON.parse(A);if(k.usage&&(this.logger?.debug({usage:k.usage,hasToolCall:a},"usage"),k.choices[0].finish_reason=a?"tool_calls":"stop"),k.choices?.[0]?.finish_reason==="error"&&w.enqueue(C.encode(`data: ${JSON.stringify({error:k.choices?.[0].error})}
318
+ `))),p.close()}},cancel(p){return n.cancel(p)}});return new Response(f,{status:t.status,statusText:t.statusText,headers:t.headers})}var Hd=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var zd=class{constructor(e){this.options=e}options;static TransformerName="vercel";logger;endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){e={...e,messages:Ve(e.messages),tools:Ye(e.tools)},e.messages.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="image_url"&&(i.image_url.url.startsWith("http")||(i.image_url.url=`data:${i.media_type};base64,${i.image_url.url}`),delete i.media_type)})}),Object.assign(e,this.options||{});let o=e.providerOptions||{};return e.providerOptions={...o,gateway:{...o.gateway||{},caching:"auto"}},e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",i=!1,a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(b,m,w)=>{let C=b.split(`
319
+ `);for(let S of C)S.trim()&&m.enqueue(w.encode(S+`
320
+ `))},g=(b,m)=>{let{controller:w,encoder:C}=m;if(b.startsWith("data: ")&&b.trim()!=="data: [DONE]"){let S=b.slice(6);try{let k=JSON.parse(S);if(k.usage&&(this.logger?.debug({usage:k.usage,hasToolCall:a},"usage"),k.choices[0].finish_reason=a?"tool_calls":"stop"),k.choices?.[0]?.finish_reason==="error"&&w.enqueue(C.encode(`data: ${JSON.stringify({error:k.choices?.[0].error})}
321
321
 
322
322
  `)),k.choices?.[0]?.delta?.content&&!m.hasTextContent()&&m.setHasTextContent(!0),k.choices?.[0]?.delta?.reasoning){m.appendReasoningContent(k.choices[0].delta.reasoning);let x={...k,choices:[{...k.choices?.[0],delta:{...k.choices[0].delta,thinking:{content:k.choices[0].delta.reasoning}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let O=`data: ${JSON.stringify(x)}
323
323
 
@@ -327,73 +327,73 @@ data: [DONE]
327
327
 
328
328
  `;w.enqueue(C.encode(E))}catch{w.enqueue(C.encode(b+`
329
329
  `))}}else w.enqueue(C.encode(b+`
330
- `))};try{for(;;){let{done:b,value:m}=await p.read();if(b){u.trim()&&h(u,f,r);break}if(!m||m.length===0)continue;let w;try{w=n.decode(m,{stream:!0})}catch(A){this.logger?.warn("Failed to decode chunk",A);continue}if(w.length===0)continue;if(u+=w,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let A=u.split(`
331
- `);u=A.pop()||"";for(let k of A)if(k.trim())try{g(k,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>i,setReasoningComplete:E=>i=E})}catch(E){this.logger?.error("Error processing line:",k,E),f.enqueue(r.encode(k+`
330
+ `))};try{for(;;){let{done:b,value:m}=await p.read();if(b){u.trim()&&h(u,f,r);break}if(!m||m.length===0)continue;let w;try{w=n.decode(m,{stream:!0})}catch(S){this.logger?.warn("Failed to decode chunk",S);continue}if(w.length===0)continue;if(u+=w,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let S=u.split(`
331
+ `);u=S.pop()||"";for(let k of S)if(k.trim())try{g(k,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:E=>o=E,reasoningContent:()=>s,appendReasoningContent:E=>s+=E,isReasoningComplete:()=>i,setReasoningComplete:E=>i=E})}catch(E){this.logger?.error("Error processing line:",k,E),f.enqueue(r.encode(k+`
332
332
  `))}continue}let C=u.split(`
333
- `);u=C.pop()||"";for(let A of C)if(A.trim())try{g(A,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){this.logger?.error("Error processing line:",A,k),f.enqueue(r.encode(A+`
334
- `))}}}catch(b){this.logger?.error("Stream error:",b),f.error(b)}finally{try{p.releaseLock()}catch(b){this.logger?.error("Error releasing reader lock:",b)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Gd=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=rs(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),Zc(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||rs(),o=n?.protocolContext?.originalModel||n?.req?.protocolContext?.originalModel,s=n?.responsesCustomToolNames||n?.protocolContext?.responsesCustomToolNames||n?.req?.protocolContext?.responsesCustomToolNames||new Set,i=e.headers.get("Content-Type")||"";if(i.includes("application/json")){let a=await e.json();if(a?.object==="response")return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:e.headers});let u=Uw(a,{originalModel:o,callIdMap:r,customToolNames:s,codexIsolateConventions:!0});return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}return i.includes("text/event-stream")?this.convertUnifiedStreamToResponses(e,{callIdMap:r,originalModel:o,customToolNames:s,codexIsolateConventions:!0}):e}convertUnifiedStreamToResponses(e,n){if(!e.body)return e;let r=jw({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Ne(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=Ki("Malformed upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return}let i=o.slice(5).trim();if(i==="[DONE]"){if(!r.finished)for(let a of Oh(r))s.controller.enqueue(ve(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=Ki(Ge(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=Hw(a,r);for(let d of u)s.controller.enqueue(ve(JSON.stringify(d),s.encoder))}catch{let a=Ki("Malformed JSON in upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of Oh(r))o.controller.enqueue(ve(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=Ki(Ge(i)||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return!0},logger:this.logger})}async transformRequestIn(e,n,r){e=structuredClone(e);let o=e.max_tokens??e.max_completion_tokens;if(o!=null&&(e.max_output_tokens=Math.max(16,Number(o))),delete e.max_tokens,delete e.max_completion_tokens,e.reasoning){let h=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning.effort);e.reasoning={...h?{effort:h}:{},...h!=="none"&&e.reasoning.summary?{summary:e.reasoning.summary}:{}}}delete e.stop,delete e.stream_options;let s=tu(e.response_format);s&&(e.text={...e.text,format:s}),delete e.response_format;let i=e.model||"";e=zi(e,n,r);let a=qc(e.messages);e.messages=a;let u=[],d=!1;e.messages.filter(h=>h.role==="system").forEach((h,g)=>{Array.isArray(h.content)?h.content.forEach(b=>{let m="";typeof b=="string"?m=b:b&&typeof b=="object"&&"text"in b&&(m=b.text),u.push({role:"system",content:[{type:"input_text",text:m,...Hc(b,i)}]})}):g===0?e.instructions=h.content:u.push({role:"system",content:[{type:"input_text",text:String(h.content||"")}]})});let p=h=>{let g=us(Rn(h));g&&u.push(g)};if(e.messages.forEach(h=>{if(h.role!=="system"){if(Array.isArray(h.content)){let g=h.content.map(b=>this.normalizeRequestContent(b,h.role,i)).filter(b=>b!==null);g.length>0?h.content=g:delete h.content}if(h.role==="tool"){let g={...h};g.type="function_call_output",g.call_id=_t(h.tool_call_id)??h.tool_call_id,g.output=h.content,delete g.cache_control,delete g.role,delete g.tool_call_id,delete g.content,u.push(g),d=!0;return}if(h.role==="assistant"){let g=cs(h);if(g.thinking||g.toolCalls.length||Ji(g)||g.images.length){if(d=!1,g.thinking&&p(h),Ji(g)||g.images.length){let b={...h};delete b.tool_calls,delete b.thinking,delete b.reasoning_content,g.texts.length===1&&g.images.length===0&&(b.content=g.texts[0].text),u.push(b)}for(let b of g.toolCalls)u.push({type:"function_call",arguments:b.function.arguments,name:b.function.name,call_id:_t(b.id)??b.id});return}}d&&h.role==="user"&&u.push({role:"assistant",content:""}),d=!1,u.push(h)}}),e.input=u,delete e.messages,Array.isArray(e.tools)){let h=b=>b?.type==="web_search"||b?.function?.name==="web_search",g=e.tools.find(h);e.tools=e.tools.filter(b=>!h(b)).map(b=>(b.function.name==="WebSearch"&&b.function.parameters?.properties&&delete b.function.parameters.properties.allowed_domains,b.function.name==="Edit"?{type:b.type,name:b.function.name,description:b.function.description,parameters:{...b.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:b.type,name:b.function.name,description:b.function.description,parameters:b.function.parameters})),g&&e.tools.push({type:"web_search"})}return e.tool_choice&&typeof e.tool_choice=="object"&&e.tool_choice.type==="function"?e.tool_choice={type:"function",name:e.tool_choice.function?.name}:e.tool_choice==="required"?e.tool_choice="required":e.tool_choice==="none"?e.tool_choice="none":e.tool_choice==="auto"&&(e.tool_choice="auto"),e.parallel_tool_calls!==void 0&&(e.parallel_tool_calls=e.parallel_tool_calls),e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new Map,o=new Map,s=new Map,i=0,a=!1,u=f=>{let p=f.item_id||f.item?.id||(typeof f.output_index=="number"?`output:${f.output_index}`:void 0);if(p!==void 0){let h=r.get(p);if(h!==void 0)return h;let g=i++;return r.set(p,g),g}return i++},d=()=>{a=!0,r.clear()};return Ne(e,(f,p)=>{if(!a&&f.trim()&&!f.startsWith("event: "))if(f.startsWith("data: ")){let h=f.slice(5).trim();if(h==="[DONE]"){p.controller.enqueue(ve("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let m=g.response?.error??{},w=Ge(String(m.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(ve(JSON.stringify({error:{message:w,type:typeof m.type=="string"?m.type:"api_error",code:typeof m.code=="string"?m.code:null}}),p.encoder)),p.controller.enqueue(ve("[DONE]",p.encoder));return}let b=this.convertStreamEvent(g,u,o,s);for(let m of b)p.controller.enqueue(ve(JSON.stringify(m),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(ve("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Pe(f,p.encoder))}}else p.controller.enqueue(Pe(f,p.encoder))})}return e}convertStreamEvent(e,n,r,o){let s=d=>(d?.content||[]).filter(f=>f?.type==="output_text").map(f=>f.text||"").join(""),i=d=>d?[d]:[],a=d=>d?.id||e.item?.id||e.item_id||"text",u=d=>{let f=a();r.set(f,(r.get(f)||"")+(typeof d=="string"?d:""))};if(e.type==="response.output_text.delta"&&typeof e.delta=="string"?u(e.delta):e.type==="response.output_item.added"&&e.item?.type==="message"&&u(s(e.item)),e.type==="response.reasoning_summary_text.delta"&&typeof e.delta=="string"&&eu(o,e.item_id,e.delta),e.type==="response.output_text.done"&&typeof e.text=="string"){let d=a(),f=r.get(d)||"",p=e.text.startsWith(f)?e.text.slice(f.length):e.text;return r.set(d,e.text),p?i({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:p},finish_reason:null}]}):[]}if(e.type==="response.output_item.done"&&e.item?.type==="message"){let d=a(e.item),f=s(e.item),p=r.get(d)||"",h=f.startsWith(p)?f.slice(p.length):f;return r.set(d,f),h?i({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:h},finish_reason:null}]}):[]}if(e.type==="response.output_item.done"&&e.item?.type==="reasoning"){let d=as(e.item,o);return d?i({id:e.item.id||e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:d},finish_reason:null}]}):[]}if(e.type==="response.completed"){let d=[],f=e.response?.output||[];for(let h of f){if(h.type!=="message")continue;let g=h.id||"text";s(h)&&!r.has(g)&&r.set(g,"")}for(let h of e.response?.output||[]){if(h.type!=="message")continue;let g=h.id||"text",b=s(h),m=r.get(g)||"",w=b.startsWith(m)?b.slice(m.length):b;r.set(g,b),w&&d.push({id:g,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:w},finish_reason:null}]})}for(let h of e.response?.output||[]){if(h.type!=="reasoning")continue;let g=as(h,o);g&&d.push({id:h.id||e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:g},finish_reason:null}]})}let p=this.convertStreamEventCore(e,n);return p&&d.push(p),d}return i(this.convertStreamEventCore(e,n))}convertStreamEventCore(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:n(e),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:0,delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{tool_calls:[{index:n(e),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call"||s.type==="custom_tool_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{id:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...Hc(e,r)};if(e.type==="image_url"){this.logger?.debug(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),{...o,...Hc(e,r)}}return null}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="reasoning"),o=(e.output??[]).filter(d=>d.type==="function_call"||d.type==="custom_tool_call"),s;n?.content?.length&&n?.content[0].annotations&&(s=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger?.debug?.({data:s,type:"url_citation"});let i=null,a=null,u=is(r)||null;if(!u&&n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let h=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});h&&f.push(h)}else if(p.type==="output_image_base64"){let h=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});h&&f.push(h)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),i=p}else i=d.join("")}return o.length>0&&(a=o.map(d=>({id:_t(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[xn]:d.input||""}):d.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:a,thinking:u,annotations:s},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{randomUUID as TL}from"crypto";import{execFileSync as xL}from"child_process";import{arch as ZT,platform as d_,release as RL}from"os";import{resolveCodexPat as ex}from"@caeliq/ccr-shared";import{closeSync as oL,existsSync as KT,fstatSync as sL,mkdirSync as iL,openSync as aL,readFileSync as cL,renameSync as uL,statSync as VT,unlinkSync as o_,writeFileSync as lL}from"fs";import{dirname as dL,join as fL}from"path";import{homedir as pL}from"os";var hL=fL(pL(),".claude-code-router","codex_auth.json"),gL=300,mL=11520*60,yL=2*6e4,_L=35e3,YT={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Jd=null;function s_(){return process.env.CCR_CODEX_AUTH_FILE||hL}function n_(){return`${s_()}.refresh.lock`}function bL(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||YT.token_endpoint}function i_(t){if(!t)return null;let e=t.split(".");if(e.length!==3||!e[1])return null;try{return JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"))}catch{return null}}function Kd(t){let e=t.account_id?.trim();return e||i_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function CL(t){return i_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function XT(t){let e=i_(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Vd(t){let e=Kd(t),n=XT(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function r_(){try{let t=s_();if(!KT(t))return null;let e=JSON.parse(cL(t,"utf8"));return e.access_token?Vd(e):null}catch{return null}}function wL(t){let e=s_();iL(dL(e),{recursive:!0});let n=Vd(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{lL(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),uL(r,e)}finally{try{KT(r)&&o_(r)}catch{}}}function QT(t,e=gL){let n=XT(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+mL)}function t_(t,e){let n=Kd(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function kL(t){try{let e=JSON.parse(t),n=e?.error?.code||e?.error,r=e?.error?.message||e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function SL(t){if(!t.refresh_token)throw new Error("Codex OAuth token cannot be refreshed because no refresh token is available. Run `ccr codex-auth` again.");let e=await fetch(bL(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:YT.client_id,grant_type:"refresh_token",refresh_token:t.refresh_token}),signal:AbortSignal.timeout(3e4)}),n=await e.text();if(!e.ok)throw new Error(`Codex OAuth token refresh failed (${e.status}): ${kL(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("Codex OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return Vd({...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:r.expires_at||o+(typeof r.expires_in=="number"?r.expires_in:3600),account_id:r.account_id||t.account_id,last_refresh:o})}function AL(){let t=n_();try{return aL(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-VT(t).mtimeMs>yL&&o_(t)}catch{}return null}}async function EL(t){let e=Date.now()+_L,n=null;for(;n===null&&(n=AL(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh Codex OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=sL(n).ino;oL(n);try{VT(n_()).ino===r&&o_(n_())}catch{}}}async function vL(t,e){return EL(async()=>{let n=r_();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");t_(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!QT(n))return n;let o=await SL(n);t_(e.expectedAccountId,o);let s=r_();return s&&s.access_token!==n.access_token?(t_(e.expectedAccountId,s),s):(wL(o),o)})}async function Yd(t={}){let e=r_();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!QT(e)?e:(Jd||(Jd=vL(e,{...t,expectedAccountId:t.expectedAccountId||Kd(e)}).finally(()=>{Jd=null})),Jd)}function a_(t){let e=Vd(t);return{mode:"oauth",token:e.access_token,accountId:Kd(e),isFedramp:CL(e)}}var DL=300*1e3,Xd=new Map,c_=new Map,nx="0.145.0",rx="codex_cli_rs",ox="x-codex-turn-metadata",OL="x-codex-window-id",PL="x-codex-parent-thread-id",IL="session_id",FL="thread_id",NL="turn_id",ML="window_id";function u_(){let t=new Map,e=0;return n=>{let r=n.item_id||n.item?.id||(typeof n.output_index=="number"?`output:${n.output_index}`:void 0);if(r!==void 0){let o=t.get(r);if(o!==void 0)return o;let s=e++;return t.set(r,s),s}return e++}}function l_(t){return t.item_id||t.item?.id||t.item?.call_id||""}function BL(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function UL(){switch(d_()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return d_()||"unknown"}}function jL(){switch(ZT()){case"x64":return"x86_64";case"arm64":return"arm64";default:return ZT()||"unknown"}}function LL(){if(d_()==="darwin")try{return xL("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return RL()||"unknown"}function $L(){return`${rx}/${nx} (${UL()} ${LL()}; ${jL()})`}function tx(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",nx),e.toString()}function qL(t){return{session_id:t,thread_id:t,turn_id:TL(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function HL(t){return{[IL]:t.session_id,[FL]:t.thread_id,[NL]:t.turn_id,[ML]:t.window_id,[ox]:JSON.stringify(t)}}function zL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function WL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[OL]:t.window_id,[ox]:JSON.stringify(t),[PL]:t.thread_id}}function GL(t){let e=t?.metadata?.user_id;if(typeof e!="string"||!e)return;let n=e.split("_session_");if(n.length>1&&n[1])return n[1];try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}}function JL(t,e){return t?.req?.sessionId||GL(e)}function KL(t,e,n){if(!n)return;let r=qL(n);t.client_metadata=zL(t.client_metadata,HL(r)),Object.assign(e,WL(r))}var Qd=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let a=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning?.effort)||Dt(n?.reasoningEffort);if(a){let A={effort:a},k=["auto","detailed","none"],E=n?.reasoningSummary;a!=="none"&&(E&&k.includes(E)?E!=="none"&&(A.summary=E):A.summary="detailed"),e.reasoning=A}else delete e.reasoning;let u=["low","medium","high"];n?.verbosity&&u.includes(n.verbosity)&&(e.verbosity=n.verbosity);let d=tu(e.response_format);d&&(e.text={...e.text,format:d}),delete e.response_format,e=gh(e,r);let f=qc(e.messages);e.messages=f;let p=[],h=!1,g=BL(r),b=new Set,m=e.messages.filter(A=>A.role==="system");if(m.length>0){let A=m[0],k;Array.isArray(A.content)?k=A.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
335
- `):k=A.content,k&&(e.instructions=k)}for(let A of m.slice(1)){let k=Array.isArray(A.content)?A.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
336
- `):String(A.content||"");k&&p.push({type:"message",role:"system",content:[{type:"input_text",text:k}]})}if(e.instructions||(e.instructions=""),e.messages.forEach(A=>{if(A.role!=="system"){if(Array.isArray(A.content)){let k=A.content.map(E=>this.normalizeRequestContent(E,A.role)).filter(E=>E!==null);k.length>0?A.content=k:delete A.content}if(A.role==="tool"){let k=_t(A.tool_call_id)??A.tool_call_id;if(k&&b.has(k)){p.push({type:"custom_tool_call_output",call_id:k,output:A.content}),h=!0;return}let E={...A};E.type="function_call_output",E.call_id=k,E.output=A.content,delete E.cache_control,delete E.role,delete E.tool_call_id,delete E.content,p.push(E),h=!0;return}if(A.role==="assistant"){let k=cs(A);if(k.thinking||k.toolCalls.length){h=!1;let E=us(k.thinking);E&&p.push(E),(Ji(k)||k.images.length)&&p.push({type:"message",role:"assistant",content:k.images.length>0?A.content:[{type:"output_text",text:k.texts.map(x=>x.text).join(`
337
- `)}]});for(let x of k.toolCalls){let O=_t(x.id)??x.id;if(g.has(x.function.name)){b.add(O),p.push({type:"custom_tool_call",name:x.function.name,call_id:O,input:Rh(x.function.arguments)});continue}p.push({type:"function_call",arguments:x.function.arguments,name:x.function.name,call_id:O})}if(k.toolCalls.length||k.thinking)return}}h&&A.role==="user"&&p.push({type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),h=!1,typeof A.content=="string"?p.push({type:"message",role:A.role,content:[{type:A.role==="assistant"?"output_text":"input_text",text:A.content}]}):p.push({type:"message",role:A.role,content:A.content})}}),e.input=p,delete e.messages,e.store=!1,Array.isArray(e.tools)){let A=e.tools.find(k=>k.function.name==="web_search");e.tools=e.tools.filter(k=>k.function.name!=="web_search").map(k=>g.has(k.function.name)?{type:"custom",name:k.function.name,description:k.function.description}:(k.function.name==="WebSearch"&&delete k.function.parameters.properties.allowed_domains,k.function.name==="Edit"?{type:k.type,name:k.function.name,description:k.function.description,parameters:{...k.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:k.type,name:k.function.name,description:k.function.description,parameters:k.function.parameters})),A&&e.tools.push({type:"web_search"})}e.parallel_tool_calls=n?.parallelToolCalls===!0,e.stream=!0;let w=this.buildAuthHeaders(s);KL(e,w,e.prompt_cache_key||JL(r,e));let C=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:tx(`${C}/responses`),headers:w,__authRecovery:()=>this.recoverUnauthorizedAuth(n,s)}}}async auth(e,n){let r=await this.resolveAuth(n),o=this.buildAuthHeaders(r),s=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:tx(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=ex(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):a_(await Yd())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:rx,"User-Agent":$L()};return e.accountId&&(n["ChatGPT-Account-ID"]=e.accountId),e.isFedramp&&(n["X-OpenAI-Fedramp"]="true"),n}async recoverUnauthorizedAuth(e,n){if(n.mode==="pat")return Xd.delete(n.token),null;if(ex(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Yd({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),o=a_(r);if(n.accountId&&o.accountId&&n.accountId!==o.accountId)throw new Error("Codex OAuth account changed during unauthorized recovery.");return this.buildAuthHeaders(o)}async resolvePatAuth(e){let n=Xd.get(e);if(n&&n.expiresAt>Date.now())return n.value;Xd.delete(e);let r=c_.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{c_.delete(e)});return c_.set(e,o),o}async requestPatAuth(e){let n=(process.env.CODEX_AUTHAPI_BASE_URL||"https://auth.openai.com/api/accounts").replace(/\/+$/,""),r=await fetch(`${n}/v1/user-auth-credential/whoami`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new Error(`Codex PAT metadata request failed (${r.status}). Verify that the configured at- token is valid and has Codex access.`);let o=await r.json();if(!o.chatgpt_account_id||!o.chatgpt_user_id||!o.chatgpt_plan_type)throw new Error("Codex PAT metadata response is missing required account, user, or plan information.");let s={mode:"pat",token:e,accountId:o.chatgpt_account_id,isFedramp:o.chatgpt_account_is_fedramp===!0};return Xd.set(e,{value:s,expiresAt:Date.now()+DL}),s}async transformResponseOut(e,n){let r=e.headers.get("Content-Type")||"",o=n?.req?.id,s=o?this.streamIntent.get(o):void 0;try{return await this.transformResponseOutInner(e,r,this,o,s)}finally{o&&this.streamIntent.delete(o)}}async transformResponseOutInner(e,n,r,o,s){let i=o?s!==!1:!0,a,u=d=>d?(a=d,d):a;if(!n||n.includes("text/event-stream")){if(!e.body)return e;let d=await this.readBodyAndPeek(e.clone().body);if(d&&(d.firstChar==="{"||d.firstChar==="[")){let x;try{x=JSON.parse(d.text)}catch{return i?new Response(this.jsonToSseStream(d.text),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(d.text,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let O=x?.object==="response"&&x.output?this.convertResponseToChat(x):x,q=JSON.stringify(O);return i?new Response(this.jsonToSseStream(q),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(q,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}if(!i){let x=await this.collectSseIntoChatCompletion(e,u);return new Response(JSON.stringify(x),{status:e.status,statusText:e.statusText,headers:{"Content-Type":"application/json"}})}let f=-1,p="",h=new Map,g=new Map,b=u_(),m=x=>(x!==p&&(f++,p=x),f),C=Ne(e,(x,O)=>{if(x.trim()&&!x.startsWith("event: "))if(x.startsWith("data: ")){let q=x.slice(5).trim();if(q==="[DONE]"){O.controller.enqueue(ve("[DONE]",O.encoder));return}try{let V=JSON.parse(q);V.response?.model&&(a=V.response.model);let j=r.convertStreamEvent(V,m,u,h,b,g);j&&O.controller.enqueue(ve(JSON.stringify(j),O.encoder))}catch{O.controller.enqueue(Pe(x,O.encoder))}}else O.controller.enqueue(Pe(x,O.encoder))}).body,A=!1,k=null,E=new ReadableStream({start(x){k=C.getReader();let O=ee=>{if(!A)try{x.enqueue(ee)}catch{A=!0}},q=()=>{if(!A)try{x.close()}catch{}},V=ee=>{if(!A)try{x.error(ee)}catch{}},j=()=>{A||!k||k.read().then(({done:ee,value:z})=>{if(ee){q();return}z&&O(z),j()}).catch(ee=>{A||V(ee)})};j()},cancel(){if(A=!0,k)try{k.cancel().catch(()=>{})}catch{}}});return new Response(E,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else if(n.includes("application/json")){let d=await e.json();if(Array.isArray(d)){let p=new TextEncoder,h=-1,g="",b=new Map,m=new Map,w=u_(),C=k=>(k!==g&&(h++,g=k),h),A=new ReadableStream({start(k){for(let E of d){E?.response?.model&&(a=E.response.model);let x=r.convertStreamEvent(E,C,u,b,w,m);x&&k.enqueue(p.encode(`data: ${JSON.stringify(x)}
333
+ `);u=C.pop()||"";for(let S of C)if(S.trim())try{g(S,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:k=>o=k,reasoningContent:()=>s,appendReasoningContent:k=>s+=k,isReasoningComplete:()=>i,setReasoningComplete:k=>i=k})}catch(k){this.logger?.error("Error processing line:",S,k),f.enqueue(r.encode(S+`
334
+ `))}}}catch(b){this.logger?.error("Stream error:",b),f.error(b)}finally{try{p.releaseLock()}catch(b){this.logger?.error("Error releasing reader lock:",b)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wd=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=rs(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),Zc(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||rs(),o=n?.protocolContext?.originalModel||n?.req?.protocolContext?.originalModel,s=n?.responsesCustomToolNames||n?.protocolContext?.responsesCustomToolNames||n?.req?.protocolContext?.responsesCustomToolNames||new Set,i=e.headers.get("Content-Type")||"";if(i.includes("application/json")){let a=await e.json();if(a?.object==="response")return new Response(JSON.stringify(a),{status:e.status,statusText:e.statusText,headers:e.headers});let u=jw(a,{originalModel:o,callIdMap:r,customToolNames:s,codexIsolateConventions:!0});return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}return i.includes("text/event-stream")?this.convertUnifiedStreamToResponses(e,{callIdMap:r,originalModel:o,customToolNames:s,codexIsolateConventions:!0}):e}convertUnifiedStreamToResponses(e,n){if(!e.body)return e;let r=Uw({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Ne(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=Ki("Malformed upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return}let i=o.slice(5).trim();if(i==="[DONE]"){if(!r.finished)for(let a of Dh(r))s.controller.enqueue(ve(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=Ki(Ge(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=Hw(a,r);for(let d of u)s.controller.enqueue(ve(JSON.stringify(d),s.encoder))}catch{let a=Ki("Malformed JSON in upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of Dh(r))o.controller.enqueue(ve(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=Ki(Ge(i)||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return!0},logger:this.logger})}async transformRequestIn(e,n,r){e=structuredClone(e);let o=e.max_tokens??e.max_completion_tokens;if(o!=null&&(e.max_output_tokens=Math.max(16,Number(o))),delete e.max_tokens,delete e.max_completion_tokens,e.reasoning){let h=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning.effort);e.reasoning={...h?{effort:h}:{},...h!=="none"&&e.reasoning.summary?{summary:e.reasoning.summary}:{}}}delete e.stop,delete e.stream_options;let s=tu(e.response_format);s&&(e.text={...e.text,format:s}),delete e.response_format;let i=e.model||"";e=zi(e,n,r);let a=qc(e.messages);e.messages=a;let u=[],d=!1;e.messages.filter(h=>h.role==="system").forEach((h,g)=>{Array.isArray(h.content)?h.content.forEach(b=>{let m="";typeof b=="string"?m=b:b&&typeof b=="object"&&"text"in b&&(m=b.text),u.push({role:"system",content:[{type:"input_text",text:m,...Hc(b,i)}]})}):g===0?e.instructions=h.content:u.push({role:"system",content:[{type:"input_text",text:String(h.content||"")}]})});let p=h=>{let g=us(Rn(h));g&&u.push(g)};if(e.messages.forEach(h=>{if(h.role!=="system"){if(Array.isArray(h.content)){let g=h.content.map(b=>this.normalizeRequestContent(b,h.role,i)).filter(b=>b!==null);g.length>0?h.content=g:delete h.content}if(h.role==="tool"){let g={...h};g.type="function_call_output",g.call_id=_t(h.tool_call_id)??h.tool_call_id,g.output=h.content,delete g.cache_control,delete g.role,delete g.tool_call_id,delete g.content,u.push(g),d=!0;return}if(h.role==="assistant"){let g=cs(h);if(g.thinking||g.toolCalls.length||Ji(g)||g.images.length){if(d=!1,g.thinking&&p(h),Ji(g)||g.images.length){let b={...h};delete b.tool_calls,delete b.thinking,delete b.reasoning_content,g.texts.length===1&&g.images.length===0&&(b.content=g.texts[0].text),u.push(b)}for(let b of g.toolCalls)u.push({type:"function_call",arguments:b.function.arguments,name:b.function.name,call_id:_t(b.id)??b.id});return}}d&&h.role==="user"&&u.push({role:"assistant",content:""}),d=!1,u.push(h)}}),e.input=u,delete e.messages,Array.isArray(e.tools)){let h=b=>b?.type==="web_search"||b?.function?.name==="web_search",g=e.tools.find(h);e.tools=e.tools.filter(b=>!h(b)).map(b=>(b.function.name==="WebSearch"&&b.function.parameters?.properties&&delete b.function.parameters.properties.allowed_domains,b.function.name==="Edit"?{type:b.type,name:b.function.name,description:b.function.description,parameters:{...b.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:b.type,name:b.function.name,description:b.function.description,parameters:b.function.parameters})),g&&e.tools.push({type:"web_search"})}return e.tool_choice&&typeof e.tool_choice=="object"&&e.tool_choice.type==="function"?e.tool_choice={type:"function",name:e.tool_choice.function?.name}:e.tool_choice==="required"?e.tool_choice="required":e.tool_choice==="none"?e.tool_choice="none":e.tool_choice==="auto"&&(e.tool_choice="auto"),e.parallel_tool_calls!==void 0&&(e.parallel_tool_calls=e.parallel_tool_calls),e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new Map,o=new Map,s=new Map,i=0,a=!1,u=f=>{let p=f.item_id||f.item?.id||(typeof f.output_index=="number"?`output:${f.output_index}`:void 0);if(p!==void 0){let h=r.get(p);if(h!==void 0)return h;let g=i++;return r.set(p,g),g}return i++},d=()=>{a=!0,r.clear()};return Ne(e,(f,p)=>{if(!a&&f.trim()&&!f.startsWith("event: "))if(f.startsWith("data: ")){let h=f.slice(5).trim();if(h==="[DONE]"){p.controller.enqueue(ve("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let m=g.response?.error??{},w=Ge(String(m.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(ve(JSON.stringify({error:{message:w,type:typeof m.type=="string"?m.type:"api_error",code:typeof m.code=="string"?m.code:null}}),p.encoder)),p.controller.enqueue(ve("[DONE]",p.encoder));return}let b=this.convertStreamEvent(g,u,o,s);for(let m of b)p.controller.enqueue(ve(JSON.stringify(m),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(ve("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Pe(f,p.encoder))}}else p.controller.enqueue(Pe(f,p.encoder))})}return e}convertStreamEvent(e,n,r,o){let s=d=>(d?.content||[]).filter(f=>f?.type==="output_text").map(f=>f.text||"").join(""),i=d=>d?[d]:[],a=d=>d?.id||e.item?.id||e.item_id||"text",u=d=>{let f=a();r.set(f,(r.get(f)||"")+(typeof d=="string"?d:""))};if(e.type==="response.output_text.delta"&&typeof e.delta=="string"?u(e.delta):e.type==="response.output_item.added"&&e.item?.type==="message"&&u(s(e.item)),e.type==="response.reasoning_summary_text.delta"&&typeof e.delta=="string"&&eu(o,e.item_id,e.delta),e.type==="response.output_text.done"&&typeof e.text=="string"){let d=a(),f=r.get(d)||"",p=e.text.startsWith(f)?e.text.slice(f.length):e.text;return r.set(d,e.text),p?i({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:p},finish_reason:null}]}):[]}if(e.type==="response.output_item.done"&&e.item?.type==="message"){let d=a(e.item),f=s(e.item),p=r.get(d)||"",h=f.startsWith(p)?f.slice(p.length):f;return r.set(d,f),h?i({id:d,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:h},finish_reason:null}]}):[]}if(e.type==="response.output_item.done"&&e.item?.type==="reasoning"){let d=as(e.item,o);return d?i({id:e.item.id||e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:d},finish_reason:null}]}):[]}if(e.type==="response.completed"){let d=[],f=e.response?.output||[];for(let h of f){if(h.type!=="message")continue;let g=h.id||"text";s(h)&&!r.has(g)&&r.set(g,"")}for(let h of e.response?.output||[]){if(h.type!=="message")continue;let g=h.id||"text",b=s(h),m=r.get(g)||"",w=b.startsWith(m)?b.slice(m.length):b;r.set(g,b),w&&d.push({id:g,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:w},finish_reason:null}]})}for(let h of e.response?.output||[]){if(h.type!=="reasoning")continue;let g=as(h,o);g&&d.push({id:h.id||e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:g},finish_reason:null}]})}let p=this.convertStreamEventCore(e,n);return p&&d.push(p),d}return i(this.convertStreamEventCore(e,n))}convertStreamEventCore(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:n(e),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:0,delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{tool_calls:[{index:n(e),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call"||s.type==="custom_tool_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{id:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...Hc(e,r)};if(e.type==="image_url"){this.logger?.debug(e);let o={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(o.image_url=e.image_url.url),{...o,...Hc(e,r)}}return null}convertResponseToChat(e){let n=e.output?.find(d=>d.type==="message"),r=e.output?.find(d=>d.type==="reasoning"),o=(e.output??[]).filter(d=>d.type==="function_call"||d.type==="custom_tool_call"),s;n?.content?.length&&n?.content[0].annotations&&(s=n.content[0].annotations.map(d=>({type:"url_citation",url_citation:{url:d.url||"",title:d.title||"",content:"",start_index:d.start_index||0,end_index:d.end_index||0}}))),this.logger?.debug?.({data:s,type:"url_citation"});let i=null,a=null,u=is(r)||null;if(!u&&n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let h=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});h&&f.push(h)}else if(p.type==="output_image_base64"){let h=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});h&&f.push(h)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),i=p}else i=d.join("")}return o.length>0&&(a=o.map(d=>({id:_t(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[xn]:d.input||""}):d.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:a,thinking:u,annotations:s},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{randomUUID as DL}from"crypto";import{execFileSync as OL}from"child_process";import{arch as ex,platform as d_,release as PL}from"os";import{resolveCodexPat as tx}from"@caeliq/ccr-shared";import{closeSync as aL,existsSync as VT,fstatSync as cL,mkdirSync as uL,openSync as lL,readFileSync as dL,renameSync as fL,statSync as YT,unlinkSync as o_,writeFileSync as pL}from"fs";import{dirname as hL,join as gL}from"path";import{homedir as mL}from"os";var yL=gL(mL(),".claude-code-router","codex_auth.json"),_L=300,bL=11520*60,CL=2*6e4,wL=35e3,XT={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Gd=null;function s_(){return process.env.CCR_CODEX_AUTH_FILE||yL}function n_(){return`${s_()}.refresh.lock`}function kL(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||XT.token_endpoint}function i_(t){if(!t)return null;let e=t.split(".");if(e.length!==3||!e[1])return null;try{return JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"))}catch{return null}}function Jd(t){let e=t.account_id?.trim();return e||i_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function SL(t){return i_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function QT(t){let e=i_(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Kd(t){let e=Jd(t),n=QT(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function r_(){try{let t=s_();if(!VT(t))return null;let e=JSON.parse(dL(t,"utf8"));return e.access_token?Kd(e):null}catch{return null}}function AL(t){let e=s_();uL(hL(e),{recursive:!0});let n=Kd(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{pL(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),fL(r,e)}finally{try{VT(r)&&o_(r)}catch{}}}function ZT(t,e=_L){let n=QT(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+bL)}function t_(t,e){let n=Jd(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function EL(t){try{let e=JSON.parse(t),n=e?.error?.code||e?.error,r=e?.error?.message||e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function vL(t){if(!t.refresh_token)throw new Error("Codex OAuth token cannot be refreshed because no refresh token is available. Run `ccr codex-auth` again.");let e=await fetch(kL(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:XT.client_id,grant_type:"refresh_token",refresh_token:t.refresh_token}),signal:AbortSignal.timeout(3e4)}),n=await e.text();if(!e.ok)throw new Error(`Codex OAuth token refresh failed (${e.status}): ${EL(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("Codex OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return Kd({...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:r.expires_at||o+(typeof r.expires_in=="number"?r.expires_in:3600),account_id:r.account_id||t.account_id,last_refresh:o})}function TL(){let t=n_();try{return lL(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-YT(t).mtimeMs>CL&&o_(t)}catch{}return null}}async function xL(t){let e=Date.now()+wL,n=null;for(;n===null&&(n=TL(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh Codex OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=cL(n).ino;aL(n);try{YT(n_()).ino===r&&o_(n_())}catch{}}}async function RL(t,e){return xL(async()=>{let n=r_();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");t_(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!ZT(n))return n;let o=await vL(n);t_(e.expectedAccountId,o);let s=r_();return s&&s.access_token!==n.access_token?(t_(e.expectedAccountId,s),s):(AL(o),o)})}async function Vd(t={}){let e=r_();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!ZT(e)?e:(Gd||(Gd=RL(e,{...t,expectedAccountId:t.expectedAccountId||Jd(e)}).finally(()=>{Gd=null})),Gd)}function a_(t){let e=Kd(t);return{mode:"oauth",token:e.access_token,accountId:Jd(e),isFedramp:SL(e)}}var IL=300*1e3,Yd=new Map,c_=new Map,rx="0.145.0",ox="codex_cli_rs",sx="x-codex-turn-metadata",FL="x-codex-window-id",NL="x-codex-parent-thread-id",ML="session_id",BL="thread_id",jL="turn_id",UL="window_id";function u_(){let t=new Map,e=0;return n=>{let r=n.item_id||n.item?.id||(typeof n.output_index=="number"?`output:${n.output_index}`:void 0);if(r!==void 0){let o=t.get(r);if(o!==void 0)return o;let s=e++;return t.set(r,s),s}return e++}}function l_(t){return t.item_id||t.item?.id||t.item?.call_id||""}function LL(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function $L(){switch(d_()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return d_()||"unknown"}}function qL(){switch(ex()){case"x64":return"x86_64";case"arm64":return"arm64";default:return ex()||"unknown"}}function HL(){if(d_()==="darwin")try{return OL("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return PL()||"unknown"}function zL(){return`${ox}/${rx} (${$L()} ${HL()}; ${qL()})`}function nx(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",rx),e.toString()}function WL(t){return{session_id:t,thread_id:t,turn_id:DL(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function GL(t){return{[ML]:t.session_id,[BL]:t.thread_id,[jL]:t.turn_id,[UL]:t.window_id,[sx]:JSON.stringify(t)}}function JL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function KL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[FL]:t.window_id,[sx]:JSON.stringify(t),[NL]:t.thread_id}}function VL(t){let e=t?.metadata?.user_id;if(typeof e!="string"||!e)return;let n=e.split("_session_");if(n.length>1&&n[1])return n[1];try{let r=JSON.parse(e);if(r&&typeof r.session_id=="string"&&r.session_id)return r.session_id}catch{}}function YL(t,e){return t?.req?.sessionId||VL(e)}function XL(t,e,n){if(!n)return;let r=WL(n);t.client_metadata=JL(t.client_metadata,GL(r)),Object.assign(e,KL(r))}var Xd=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let a=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning?.effort)||Dt(n?.reasoningEffort);if(a){let S={effort:a},k=["auto","detailed","none"],E=n?.reasoningSummary;a!=="none"&&(E&&k.includes(E)?E!=="none"&&(S.summary=E):S.summary="detailed"),e.reasoning=S}else delete e.reasoning;let u=["low","medium","high"];n?.verbosity&&u.includes(n.verbosity)&&(e.verbosity=n.verbosity);let d=tu(e.response_format);d&&(e.text={...e.text,format:d}),delete e.response_format,e=hh(e,r);let f=qc(e.messages);e.messages=f;let p=[],h=!1,g=LL(r),b=new Set,m=e.messages.filter(S=>S.role==="system");if(m.length>0){let S=m[0],k;Array.isArray(S.content)?k=S.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
335
+ `):k=S.content,k&&(e.instructions=k)}for(let S of m.slice(1)){let k=Array.isArray(S.content)?S.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
336
+ `):String(S.content||"");k&&p.push({type:"message",role:"system",content:[{type:"input_text",text:k}]})}if(e.instructions||(e.instructions=""),e.messages.forEach(S=>{if(S.role!=="system"){if(Array.isArray(S.content)){let k=S.content.map(E=>this.normalizeRequestContent(E,S.role)).filter(E=>E!==null);k.length>0?S.content=k:delete S.content}if(S.role==="tool"){let k=_t(S.tool_call_id)??S.tool_call_id;if(k&&b.has(k)){p.push({type:"custom_tool_call_output",call_id:k,output:S.content}),h=!0;return}let E={...S};E.type="function_call_output",E.call_id=k,E.output=S.content,delete E.cache_control,delete E.role,delete E.tool_call_id,delete E.content,p.push(E),h=!0;return}if(S.role==="assistant"){let k=cs(S);if(k.thinking||k.toolCalls.length){h=!1;let E=us(k.thinking);E&&p.push(E),(Ji(k)||k.images.length)&&p.push({type:"message",role:"assistant",content:k.images.length>0?S.content:[{type:"output_text",text:k.texts.map(x=>x.text).join(`
337
+ `)}]});for(let x of k.toolCalls){let O=_t(x.id)??x.id;if(g.has(x.function.name)){b.add(O),p.push({type:"custom_tool_call",name:x.function.name,call_id:O,input:xh(x.function.arguments)});continue}p.push({type:"function_call",arguments:x.function.arguments,name:x.function.name,call_id:O})}if(k.toolCalls.length||k.thinking)return}}h&&S.role==="user"&&p.push({type:"message",role:"assistant",content:[{type:"output_text",text:""}]}),h=!1,typeof S.content=="string"?p.push({type:"message",role:S.role,content:[{type:S.role==="assistant"?"output_text":"input_text",text:S.content}]}):p.push({type:"message",role:S.role,content:S.content})}}),e.input=p,delete e.messages,e.store=!1,Array.isArray(e.tools)){let S=e.tools.find(k=>k.function.name==="web_search");e.tools=e.tools.filter(k=>k.function.name!=="web_search").map(k=>g.has(k.function.name)?{type:"custom",name:k.function.name,description:k.function.description}:(k.function.name==="WebSearch"&&delete k.function.parameters.properties.allowed_domains,k.function.name==="Edit"?{type:k.type,name:k.function.name,description:k.function.description,parameters:{...k.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:k.type,name:k.function.name,description:k.function.description,parameters:k.function.parameters})),S&&e.tools.push({type:"web_search"})}e.parallel_tool_calls=n?.parallelToolCalls===!0,e.stream=!0;let w=this.buildAuthHeaders(s);XL(e,w,e.prompt_cache_key||YL(r,e));let C=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:nx(`${C}/responses`),headers:w,__authRecovery:()=>this.recoverUnauthorizedAuth(n,s)}}}async auth(e,n){let r=await this.resolveAuth(n),o=this.buildAuthHeaders(r),s=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:nx(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=tx(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):a_(await Vd())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:ox,"User-Agent":zL()};return e.accountId&&(n["ChatGPT-Account-ID"]=e.accountId),e.isFedramp&&(n["X-OpenAI-Fedramp"]="true"),n}async recoverUnauthorizedAuth(e,n){if(n.mode==="pat")return Yd.delete(n.token),null;if(tx(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Vd({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),o=a_(r);if(n.accountId&&o.accountId&&n.accountId!==o.accountId)throw new Error("Codex OAuth account changed during unauthorized recovery.");return this.buildAuthHeaders(o)}async resolvePatAuth(e){let n=Yd.get(e);if(n&&n.expiresAt>Date.now())return n.value;Yd.delete(e);let r=c_.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{c_.delete(e)});return c_.set(e,o),o}async requestPatAuth(e){let n=(process.env.CODEX_AUTHAPI_BASE_URL||"https://auth.openai.com/api/accounts").replace(/\/+$/,""),r=await fetch(`${n}/v1/user-auth-credential/whoami`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new Error(`Codex PAT metadata request failed (${r.status}). Verify that the configured at- token is valid and has Codex access.`);let o=await r.json();if(!o.chatgpt_account_id||!o.chatgpt_user_id||!o.chatgpt_plan_type)throw new Error("Codex PAT metadata response is missing required account, user, or plan information.");let s={mode:"pat",token:e,accountId:o.chatgpt_account_id,isFedramp:o.chatgpt_account_is_fedramp===!0};return Yd.set(e,{value:s,expiresAt:Date.now()+IL}),s}async transformResponseOut(e,n){let r=e.headers.get("Content-Type")||"",o=n?.req?.id,s=o?this.streamIntent.get(o):void 0;try{return await this.transformResponseOutInner(e,r,this,o,s)}finally{o&&this.streamIntent.delete(o)}}async transformResponseOutInner(e,n,r,o,s){let i=o?s!==!1:!0,a,u=d=>d?(a=d,d):a;if(!n||n.includes("text/event-stream")){if(!e.body)return e;let d=await this.readBodyAndPeek(e.clone().body);if(d&&(d.firstChar==="{"||d.firstChar==="[")){let x;try{x=JSON.parse(d.text)}catch{return i?new Response(this.jsonToSseStream(d.text),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(d.text,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let O=x?.object==="response"&&x.output?this.convertResponseToChat(x):x,q=JSON.stringify(O);return i?new Response(this.jsonToSseStream(q),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(q,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}if(!i){let x=await this.collectSseIntoChatCompletion(e,u);return new Response(JSON.stringify(x),{status:e.status,statusText:e.statusText,headers:{"Content-Type":"application/json"}})}let f=-1,p="",h=new Map,g=new Map,b=u_(),m=x=>(x!==p&&(f++,p=x),f),C=Ne(e,(x,O)=>{if(x.trim()&&!x.startsWith("event: "))if(x.startsWith("data: ")){let q=x.slice(5).trim();if(q==="[DONE]"){O.controller.enqueue(ve("[DONE]",O.encoder));return}try{let V=JSON.parse(q);V.response?.model&&(a=V.response.model);let U=r.convertStreamEvent(V,m,u,h,b,g);U&&O.controller.enqueue(ve(JSON.stringify(U),O.encoder))}catch{O.controller.enqueue(Pe(x,O.encoder))}}else O.controller.enqueue(Pe(x,O.encoder))}).body,S=!1,k=null,E=new ReadableStream({start(x){k=C.getReader();let O=ee=>{if(!S)try{x.enqueue(ee)}catch{S=!0}},q=()=>{if(!S)try{x.close()}catch{}},V=ee=>{if(!S)try{x.error(ee)}catch{}},U=()=>{S||!k||k.read().then(({done:ee,value:z})=>{if(ee){q();return}z&&O(z),U()}).catch(ee=>{S||V(ee)})};U()},cancel(){if(S=!0,k)try{k.cancel().catch(()=>{})}catch{}}});return new Response(E,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}else if(n.includes("application/json")){let d=await e.json();if(Array.isArray(d)){let p=new TextEncoder,h=-1,g="",b=new Map,m=new Map,w=u_(),C=k=>(k!==g&&(h++,g=k),h),S=new ReadableStream({start(k){for(let E of d){E?.response?.model&&(a=E.response.model);let x=r.convertStreamEvent(E,C,u,b,w,m);x&&k.enqueue(p.encode(`data: ${JSON.stringify(x)}
338
338
 
339
339
  `))}k.enqueue(p.encode(`data: [DONE]
340
340
 
341
- `)),k.close()}});return new Response(A,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(d.object==="response"&&d.output){let p=this.convertResponseToChat(d),h=JSON.stringify(p);return o&&i?new Response(this.jsonToSseStream(h),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(h,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let f=JSON.stringify(d);return o&&i?new Response(this.jsonToSseStream(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r,o,s,i){let a=()=>s?s(e):0,u=i??new Map,d=p=>r?r(p):p,f=p=>p||d(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="custom_tool_call"){let p=l_(e);return p&&o?.set(p,""),{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]}}if(e.type==="response.custom_tool_call_input.delta"){let p=l_(e);if(o&&p){let h=o.get(p)??"",g=typeof e.delta=="string"?e.delta:"";o.set(p,h+g)}return null}if(e.type==="response.custom_tool_call_input.done"){let p=l_(e),h=(typeof e.input=="string"?e.input:void 0)??(p?o?.get(p):void 0)??"";return p&&o?.delete(p),{id:e.item_id||e.item?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n("response.function_call_arguments.delta"),delta:{tool_calls:[{index:a(),function:{arguments:JSON.stringify({[xn]:h})}}]},finish_reason:null}]}}if(e.type==="response.output_item.added"&&e.item?.type==="message"){let p=[];(e.item.content||[]).forEach(g=>{g.type==="output_text"&&p.push({type:"text",text:g.text||""})});let h={role:"assistant"};return p.length===1&&p[0].type==="text"?h.content=p[0].text:p.length>0&&(h.content=p),h.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:h,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{tool_calls:[{index:a(),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let p=e.response?.output?.some(b=>b.type==="function_call"||b.type==="custom_tool_call")?"tool_calls":"stop",h=as(e.response?.output?.find(b=>b.type==="reasoning"),u),g={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:0,delta:h?{thinking:h}:{},finish_reason:p}]};return e.response?.usage&&(g.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),g}if(e.type==="response.reasoning_summary_text.delta")return eu(u,e.item_id,e.delta),{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{content:e.delta||""}},finish_reason:null}]};if(e.type==="response.reasoning_summary_text.done")return typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{id:e.item_id}},finish_reason:null}]};if(e.type==="response.output_text.done")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]};if(e.type==="response.output_item.done"){if(e.item?.type==="reasoning"){let p=as(e.item,u);return p?{id:e.item.id||e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:p},finish_reason:null}]}:null}return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}}return null}jsonToSseStream(e){let n=new TextEncoder,r;try{r=JSON.parse(e)}catch{r=null}let o=s=>n.encode(`data: ${JSON.stringify(s)}
341
+ `)),k.close()}});return new Response(S,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(d.object==="response"&&d.output){let p=this.convertResponseToChat(d),h=JSON.stringify(p);return o&&i?new Response(this.jsonToSseStream(h),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(h,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let f=JSON.stringify(d);return o&&i?new Response(this.jsonToSseStream(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r,o,s,i){let a=()=>s?s(e):0,u=i??new Map,d=p=>r?r(p):p,f=p=>p||d(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="custom_tool_call"){let p=l_(e);return p&&o?.set(p,""),{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]}}if(e.type==="response.custom_tool_call_input.delta"){let p=l_(e);if(o&&p){let h=o.get(p)??"",g=typeof e.delta=="string"?e.delta:"";o.set(p,h+g)}return null}if(e.type==="response.custom_tool_call_input.done"){let p=l_(e),h=(typeof e.input=="string"?e.input:void 0)??(p?o?.get(p):void 0)??"";return p&&o?.delete(p),{id:e.item_id||e.item?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n("response.function_call_arguments.delta"),delta:{tool_calls:[{index:a(),function:{arguments:JSON.stringify({[xn]:h})}}]},finish_reason:null}]}}if(e.type==="response.output_item.added"&&e.item?.type==="message"){let p=[];(e.item.content||[]).forEach(g=>{g.type==="output_text"&&p.push({type:"text",text:g.text||""})});let h={role:"assistant"};return p.length===1&&p[0].type==="text"?h.content=p[0].text:p.length>0&&(h.content=p),h.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:h,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{tool_calls:[{index:a(),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let p=e.response?.output?.some(b=>b.type==="function_call"||b.type==="custom_tool_call")?"tool_calls":"stop",h=as(e.response?.output?.find(b=>b.type==="reasoning"),u),g={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:0,delta:h?{thinking:h}:{},finish_reason:p}]};return e.response?.usage&&(g.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),g}if(e.type==="response.reasoning_summary_text.delta")return eu(u,e.item_id,e.delta),{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{content:e.delta||""}},finish_reason:null}]};if(e.type==="response.reasoning_summary_text.done")return typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:{id:e.item_id}},finish_reason:null}]};if(e.type==="response.output_text.done")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]};if(e.type==="response.output_item.done"){if(e.item?.type==="reasoning"){let p=as(e.item,u);return p?{id:e.item.id||e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{thinking:p},finish_reason:null}]}:null}return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{},finish_reason:null}]}}return null}jsonToSseStream(e){let n=new TextEncoder,r;try{r=JSON.parse(e)}catch{r=null}let o=s=>n.encode(`data: ${JSON.stringify(s)}
342
342
 
343
343
  `);return new ReadableStream({start(s){if(!r){s.close();return}let i={id:r.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:r.created||Math.floor(Date.now()/1e3),model:r.model||"unknown"},a=r.choices?.[0];if(a){let u=a.message||{};if(typeof u.content=="string"&&u.content&&s.enqueue(o({...i,choices:[{index:0,delta:{role:"assistant",content:u.content},finish_reason:null}]})),(u.thinking?.content||u.thinking?.encrypted_content||u.thinking?.id)&&s.enqueue(o({...i,choices:[{index:0,delta:{thinking:{...u.thinking?.content?{content:u.thinking.content}:{},...u.thinking?.encrypted_content?{encrypted_content:u.thinking.encrypted_content}:{},...u.thinking?.id?{id:u.thinking.id}:{}}},finish_reason:null}]})),Array.isArray(u.tool_calls))for(let f of u.tool_calls)s.enqueue(o({...i,choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:0,id:f.id,type:"function",function:{name:f.function?.name||"",arguments:f.function?.arguments||""}}]},finish_reason:null}]}));let d={...i,choices:[{index:0,delta:{},finish_reason:a.finish_reason||"stop"}]};r.usage&&(d.usage={prompt_tokens:r.usage.prompt_tokens||0,completion_tokens:r.usage.completion_tokens||0,total_tokens:r.usage.total_tokens||0,...r.usage.prompt_tokens_details?{prompt_tokens_details:{...r.usage.prompt_tokens_details}}:{}}),s.enqueue(o(d))}s.enqueue(n.encode(`data: [DONE]
344
344
 
345
- `)),s.close()}})}async readBodyAndPeek(e){let n=e.getReader(),r=new TextDecoder,o=()=>{try{n.releaseLock()}catch{}},s;try{s=await n.read()}catch(f){throw o(),f}if(s.done)return o(),null;let i=r.decode(s.value,{stream:!0}),u=i.trimStart().charAt(0)||"";if(u!=="{"&&u!=="[")return o(),null;let d=i;try{for(;;){let f=await n.read();if(f.done)break;d+=r.decode(f.value,{stream:!0})}}finally{d+=r.decode(),o()}return{firstChar:u,text:d}}async collectSseIntoChatCompletion(e,n){let r=e.body.getReader(),o=new TextDecoder,s="",i="unknown",a="chatcmpl-"+Date.now(),u=Math.floor(Date.now()/1e3),d="",f="",p,h,g=[],b=new Map,m=null,w,C=-1,A="",k=new Map,E=new Map,x=u_(),O=j=>(j!==A&&(C++,A=j),C),q=()=>{let j={role:"assistant"};(f||p||h)&&(j.thinking={content:f,...p?{encrypted_content:p}:{},...h?{id:h}:{}});let ee=Array.from(b.values());ee.length&&(j.tool_calls=ee),g.length&&(j.annotations=g),d?j.content=d:ee.length===0&&!f?j.content=null:j.content=d||null;let z={index:0,message:j,logprobs:null,finish_reason:ee.length?"tool_calls":m||"stop"};return{id:a,object:"chat.completion",created:u,model:i||"unknown",choices:[z],usage:w||null}},V=j=>{if(!j)return;j.id&&(a=j.id),j.model&&(i=j.model),j.created&&(u=j.created),j.usage&&(w=j.usage);let ee=j.choices?.[0];if(!ee)return;ee.finish_reason&&(m=ee.finish_reason);let z=ee.delta||{};z.role,typeof z.content=="string"&&z.content&&(d+=z.content),z.thinking?.content&&(f+=z.thinking.content);let te=os(z.thinking?.encrypted_content);if(te&&(p=te),typeof z.thinking?.id=="string"&&z.thinking.id?h=z.thinking.id:lr(z.thinking?.signature)&&(h=z.thinking.signature),Array.isArray(z.annotations))for(let Q of z.annotations)g.push(Q);if(Array.isArray(z.tool_calls))for(let Q of z.tool_calls){let _e=Q.index??0,Oe=b.get(_e)||{index:_e,id:Q.id,type:"function",function:{name:Q.function?.name||"",arguments:""}};Q.id&&(Oe.id=Q.id),Q.function?.name&&(Oe.function.name=Q.function.name),typeof Q.function?.arguments=="string"&&(Oe.function.arguments=(Oe.function.arguments||"")+Q.function.arguments),b.set(_e,Oe)}};for(;;){let{done:j,value:ee}=await r.read();if(j)break;s+=o.decode(ee,{stream:!0});let z=s.split(`
346
- `);s=z.pop()||"";for(let te of z){if(!te.startsWith("data: "))continue;let Q=te.slice(5).trim();if(!(!Q||Q==="[DONE]"))try{let _e=JSON.parse(Q);if(_e.response?.model){let Te=n(_e.response.model);Te&&(i=Te)}let Oe=this.convertStreamEvent(_e,O,n,k,x,E);V(Oe)}catch{}}}return q()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=(e.output??[]).filter(u=>u.type==="function_call"||u.type==="custom_tool_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,i=null,a=is(e.output?.find(u=>u.type==="reasoning"))||null;if(!a&&n&&n.reasoning&&(a={content:n.reasoning}),n&&n.content){let u=[],d=[];if(n.content.forEach(f=>{if(f.type==="output_text")u.push(f.text||"");else if(f.type==="output_image"){let p=this.buildImageContent({url:f.image_url,mime_type:f.mime_type});p&&d.push(p)}else if(f.type==="output_image_base64"){let p=this.buildImageContent({b64_json:f.image_base64,mime_type:f.mime_type});p&&d.push(p)}}),d.length>0){let f=[];u.length>0&&f.push({type:"text",text:u.join("")}),f.push(...d),s=f}else s=u.join("")}return r.length>0&&(i=r.map(u=>({id:_t(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[xn]:u.input||""}):u.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:a,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{existsSync as sx,readFileSync as VL,writeFileSync as YL,mkdirSync as XL}from"fs";import{dirname as QL,join as ZL}from"path";import{homedir as e2}from"os";var t2=ZL(e2(),".claude-code-router","qwen_auth.json"),n2="https://qwen.aikit.club",r2=1e4,o2=120,Zd=null;function ix(){return process.env.CCR_QWEN_AUTH_FILE||t2}function s2(){try{let t=ix();if(!sx(t))return null;let e=JSON.parse(VL(t,"utf-8"));return e.token?e:null}catch{return null}}function i2(t){let e=ix(),n=QL(e);sx(n)||XL(n,{recursive:!0}),YL(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function a2(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1],"base64url").toString());if(e.exp)return e.exp*1e3}catch{}return null}async function c2(t){try{let e=await fetch(`${n2}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(r2)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function f_(t){let e=s2();if(!e)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");return(t?.force||e.expiresAt!=null&&Date.now()+o2*1e3>=e.expiresAt)&&(Zd||(Zd=(async()=>{let r=await c2(e.token);if(!r)throw new Error("Qwen token expired and refresh failed. Run `ccr qwen-auth` to re-authenticate.");let o={token:r,expiresAt:a2(r),updatedAt:Date.now()};return i2(o),o})().finally(()=>{Zd=null})),e=await Zd),e}var u2="https://qwen.aikit.club",ax=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,ef=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await f_();return{url:e?.api_base_url||e?.baseUrl||u2,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:yo(e),config:await this.buildAuthConfig(n)}}async auth(e,n){return{config:await this.buildAuthConfig(n)}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}let i=s.replace(ax,"");o.controller.enqueue(Pe(`data: ${i}`,o.encoder));return}o.controller.enqueue(Pe(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(ax,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var p_=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
345
+ `)),s.close()}})}async readBodyAndPeek(e){let n=e.getReader(),r=new TextDecoder,o=()=>{try{n.releaseLock()}catch{}},s;try{s=await n.read()}catch(f){throw o(),f}if(s.done)return o(),null;let i=r.decode(s.value,{stream:!0}),u=i.trimStart().charAt(0)||"";if(u!=="{"&&u!=="[")return o(),null;let d=i;try{for(;;){let f=await n.read();if(f.done)break;d+=r.decode(f.value,{stream:!0})}}finally{d+=r.decode(),o()}return{firstChar:u,text:d}}async collectSseIntoChatCompletion(e,n){let r=e.body.getReader(),o=new TextDecoder,s="",i="unknown",a="chatcmpl-"+Date.now(),u=Math.floor(Date.now()/1e3),d="",f="",p,h,g=[],b=new Map,m=null,w,C=-1,S="",k=new Map,E=new Map,x=u_(),O=U=>(U!==S&&(C++,S=U),C),q=()=>{let U={role:"assistant"};(f||p||h)&&(U.thinking={content:f,...p?{encrypted_content:p}:{},...h?{id:h}:{}});let ee=Array.from(b.values());ee.length&&(U.tool_calls=ee),g.length&&(U.annotations=g),d?U.content=d:ee.length===0&&!f?U.content=null:U.content=d||null;let z={index:0,message:U,logprobs:null,finish_reason:ee.length?"tool_calls":m||"stop"};return{id:a,object:"chat.completion",created:u,model:i||"unknown",choices:[z],usage:w||null}},V=U=>{if(!U)return;U.id&&(a=U.id),U.model&&(i=U.model),U.created&&(u=U.created),U.usage&&(w=U.usage);let ee=U.choices?.[0];if(!ee)return;ee.finish_reason&&(m=ee.finish_reason);let z=ee.delta||{};z.role,typeof z.content=="string"&&z.content&&(d+=z.content),z.thinking?.content&&(f+=z.thinking.content);let te=os(z.thinking?.encrypted_content);if(te&&(p=te),typeof z.thinking?.id=="string"&&z.thinking.id?h=z.thinking.id:lr(z.thinking?.signature)&&(h=z.thinking.signature),Array.isArray(z.annotations))for(let Q of z.annotations)g.push(Q);if(Array.isArray(z.tool_calls))for(let Q of z.tool_calls){let _e=Q.index??0,Oe=b.get(_e)||{index:_e,id:Q.id,type:"function",function:{name:Q.function?.name||"",arguments:""}};Q.id&&(Oe.id=Q.id),Q.function?.name&&(Oe.function.name=Q.function.name),typeof Q.function?.arguments=="string"&&(Oe.function.arguments=(Oe.function.arguments||"")+Q.function.arguments),b.set(_e,Oe)}};for(;;){let{done:U,value:ee}=await r.read();if(U)break;s+=o.decode(ee,{stream:!0});let z=s.split(`
346
+ `);s=z.pop()||"";for(let te of z){if(!te.startsWith("data: "))continue;let Q=te.slice(5).trim();if(!(!Q||Q==="[DONE]"))try{let _e=JSON.parse(Q);if(_e.response?.model){let Te=n(_e.response.model);Te&&(i=Te)}let Oe=this.convertStreamEvent(_e,O,n,k,x,E);V(Oe)}catch{}}}return q()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=(e.output??[]).filter(u=>u.type==="function_call"||u.type==="custom_tool_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,i=null,a=is(e.output?.find(u=>u.type==="reasoning"))||null;if(!a&&n&&n.reasoning&&(a={content:n.reasoning}),n&&n.content){let u=[],d=[];if(n.content.forEach(f=>{if(f.type==="output_text")u.push(f.text||"");else if(f.type==="output_image"){let p=this.buildImageContent({url:f.image_url,mime_type:f.mime_type});p&&d.push(p)}else if(f.type==="output_image_base64"){let p=this.buildImageContent({b64_json:f.image_base64,mime_type:f.mime_type});p&&d.push(p)}}),d.length>0){let f=[];u.length>0&&f.push({type:"text",text:u.join("")}),f.push(...d),s=f}else s=u.join("")}return r.length>0&&(i=r.map(u=>({id:_t(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[xn]:u.input||""}):u.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:a,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{existsSync as ix,readFileSync as QL,writeFileSync as ZL,mkdirSync as e2}from"fs";import{dirname as t2,join as n2}from"path";import{homedir as r2}from"os";var o2=n2(r2(),".claude-code-router","qwen_auth.json"),s2="https://qwen.aikit.club",i2=1e4,a2=120,Qd=null;function ax(){return process.env.CCR_QWEN_AUTH_FILE||o2}function c2(){try{let t=ax();if(!ix(t))return null;let e=JSON.parse(QL(t,"utf-8"));return e.token?e:null}catch{return null}}function u2(t){let e=ax(),n=t2(e);ix(n)||e2(n,{recursive:!0}),ZL(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function l2(t){try{let e=JSON.parse(Buffer.from(t.split(".")[1],"base64url").toString());if(e.exp)return e.exp*1e3}catch{}return null}async function d2(t){try{let e=await fetch(`${s2}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(i2)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function f_(t){let e=c2();if(!e)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");return(t?.force||e.expiresAt!=null&&Date.now()+a2*1e3>=e.expiresAt)&&(Qd||(Qd=(async()=>{let r=await d2(e.token);if(!r)throw new Error("Qwen token expired and refresh failed. Run `ccr qwen-auth` to re-authenticate.");let o={token:r,expiresAt:l2(r),updatedAt:Date.now()};return u2(o),o})().finally(()=>{Qd=null})),e=await Qd),e}var f2="https://qwen.aikit.club",cx=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Zd=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await f_();return{url:e?.api_base_url||e?.baseUrl||f2,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:yo(e),config:await this.buildAuthConfig(n)}}async auth(e,n){return{config:await this.buildAuthConfig(n)}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}let i=s.replace(cx,"");o.controller.enqueue(Pe(`data: ${i}`,o.encoder));return}o.controller.enqueue(Pe(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(cx,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var p_=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
347
347
 
348
348
  Output format:
349
349
  <reasoning_content>
350
350
  Your detailed thinking process goes here
351
351
  </reasoning_content>
352
- Your final answer must follow after the closing tag above.`,l2=10,tf=class{logger;name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<l2)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
352
+ Your final answer must follow after the closing tag above.`,p2=10,ef=class{logger;name="forcereasoning";async transformRequestIn(e){let n=0;e.messages.filter(o=>o.role==="assistant").reverse().forEach(o=>{o.thinking&&(o.thinking.content&&(!o.content||n<p2)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
353
353
  ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return r.role==="user"&&(Array.isArray(r.content)?r.content.push({type:"text",text:p_}):r.content=[{type:"text",text:p_},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:p_}]}),e}async transformResponseOut(e){let n="<reasoning_content>",r="</reasoning_content>";if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();if(o.choices[0]?.message.content){let s=/<reasoning_content>(.*?)<\/reasoning_content>/s,i=o.choices[0]?.message.content.match(s);i&&i[1]&&(o.thinking={content:i[1]})}return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let o=0,s=new TextDecoder,i=new TextEncoder,a=new ReadableStream({start:async u=>{let d=e.body.getReader(),f="",p="SEARCHING",h="",g="",b=(m,w)=>{if(typeof w!="string"){m.choices?.[0]?.delta&&Object.keys(m.choices[0].delta).length>0&&!m.choices[0].delta.content&&(m.choices[0].index=o,u.enqueue(i.encode(`data: ${JSON.stringify(m)}
354
354
 
355
- `)));return}let C=h+w;for(h="";C.length>0;)if(p==="SEARCHING"){let A=C.indexOf(n);if(A!==-1)C=C.substring(A+n.length),p="REASONING";else{for(let k=n.length-1;k>0;k--)if(C.endsWith(n.substring(0,k))){h=C.substring(C.length-k);break}C=""}}else if(p==="REASONING"){let A=C.indexOf(r);if(A!==-1){let k=C.substring(0,A);if(k.length>0){let O={...m.choices[0].delta,thinking:{content:k}};delete O.content;let q={...m,choices:[{...m.choices[0],delta:O,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(q)}
355
+ `)));return}let C=h+w;for(h="";C.length>0;)if(p==="SEARCHING"){let S=C.indexOf(n);if(S!==-1)C=C.substring(S+n.length),p="REASONING";else{for(let k=n.length-1;k>0;k--)if(C.endsWith(n.substring(0,k))){h=C.substring(C.length-k);break}C=""}}else if(p==="REASONING"){let S=C.indexOf(r);if(S!==-1){let k=C.substring(0,S);if(k.length>0){let O={...m.choices[0].delta,thinking:{content:k}};delete O.content;let q={...m,choices:[{...m.choices[0],delta:O,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(q)}
356
356
 
357
357
  `))}let E={...m.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete E.content;let x={...m,choices:[{...m.choices[0],delta:E,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
358
358
 
359
- `)),o++,C=C.substring(A+r.length),p="FINAL"}else{let k=C;for(let E=r.length-1;E>0;E--)if(C.endsWith(r.substring(0,E))){h=C.substring(C.length-E),k=C.substring(0,C.length-E);break}if(k.length>0){let E={...m.choices[0].delta,thinking:{content:k}};delete E.content;let x={...m,choices:[{...m.choices[0],delta:E,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
359
+ `)),o++,C=C.substring(S+r.length),p="FINAL"}else{let k=C;for(let E=r.length-1;E>0;E--)if(C.endsWith(r.substring(0,E))){h=C.substring(C.length-E),k=C.substring(0,C.length-E);break}if(k.length>0){let E={...m.choices[0].delta,thinking:{content:k}};delete E.content;let x={...m,choices:[{...m.choices[0],delta:E,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
360
360
 
361
361
  `))}C=""}}else if(p==="FINAL"){if(C.length>0)if(/^\s*$/.test(C))g+=C;else{let k=g+C,E={...m.choices[0].delta,content:k};E.thinking&&delete E.thinking;let x={...m,choices:[{...m.choices[0],delta:E}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
362
362
 
363
- `)),g=""}o++,C=""}};try{for(;;){let{done:m,value:w}=await d.read();if(m)break;let C=s.decode(w,{stream:!0});f+=C;let A=f.split(`
364
- `);f=A.pop()||"";for(let k of A)if(k.trim()){if(k.trim()==="data: [DONE]"){u.enqueue(i.encode(k+`
363
+ `)),g=""}o++,C=""}};try{for(;;){let{done:m,value:w}=await d.read();if(m)break;let C=s.decode(w,{stream:!0});f+=C;let S=f.split(`
364
+ `);f=S.pop()||"";for(let k of S)if(k.trim()){if(k.trim()==="data: [DONE]"){u.enqueue(i.encode(k+`
365
365
 
366
366
  `));break}if(k.startsWith("data:"))try{let E=JSON.parse(k.slice(5));b(E,E.choices?.[0]?.delta?.content)}catch{u.enqueue(i.encode(k+`
367
367
  `))}else u.enqueue(i.encode(k+`
368
368
  `))}}}catch(m){this.logger?.error("Stream error:",m),u.error(m)}finally{try{d.releaseLock()}catch(m){this.logger?.error("Error releasing reader lock:",m)}if(p==="REASONING"){let w={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};u.enqueue(i.encode(`data: ${JSON.stringify(w)}
369
369
 
370
- `))}u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var nf=class{name="extrathinktag";async transformRequestIn(e){return e}async transformResponseOut(e){let n="<think>",r="</think>";if(e.headers.get("Content-Type")?.includes("application/json"))try{let u=await e.json(),d=u?.choices?.[0]?.message?.content;if(typeof d=="string"){let f=d.match(/<think>([\s\S]*?)<\/think>/);f?.[1]&&(u.thinking={content:f[1]})}return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return e}if(!e.headers.get("Content-Type")?.includes("stream")||!e.body)return e;let o=new TextDecoder,s=new TextEncoder,i=0,a=new ReadableStream({async start(u){let d=e.body.getReader(),f="",p="SEARCHING",h="",g="",b=w=>{u.enqueue(s.encode(`data: ${JSON.stringify(w)}
370
+ `))}u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var tf=class{name="extrathinktag";async transformRequestIn(e){return e}async transformResponseOut(e){let n="<think>",r="</think>";if(e.headers.get("Content-Type")?.includes("application/json"))try{let u=await e.json(),d=u?.choices?.[0]?.message?.content;if(typeof d=="string"){let f=d.match(/<think>([\s\S]*?)<\/think>/);f?.[1]&&(u.thinking={content:f[1]})}return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return e}if(!e.headers.get("Content-Type")?.includes("stream")||!e.body)return e;let o=new TextDecoder,s=new TextEncoder,i=0,a=new ReadableStream({async start(u){let d=e.body.getReader(),f="",p="SEARCHING",h="",g="",b=w=>{u.enqueue(s.encode(`data: ${JSON.stringify(w)}
371
371
 
372
- `))},m=(w,C)=>{if(typeof C!="string"&&w?.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0&&!w.choices[0].delta.content){w.choices[0].index=i,b(w);return}if(typeof C!="string")return;let A=h+C;for(h="";A.length>0;){if(p==="SEARCHING"){let k=A.indexOf(n);if(k!==-1){A=A.substring(k+n.length),p="THINKING";continue}for(let E=n.length-1;E>0;E--)if(A.endsWith(n.substring(0,E))){h=A.substring(A.length-E);break}A="";continue}if(p==="THINKING"){let k=A.indexOf(r);if(k!==-1){let x=A.substring(0,k);if(x.length>0){let q={...w.choices[0].delta,thinking:{content:x}};delete q.content,b({...w,choices:[{...w.choices[0],delta:q,index:i}]})}let O={...w.choices[0].delta,thinking:{signature:Date.now().toString()}};delete O.content,b({...w,choices:[{...w.choices[0],delta:O,index:i}]}),i++,A=A.substring(k+r.length),p="FINAL";continue}let E=A;for(let x=r.length-1;x>0;x--)if(A.endsWith(r.substring(0,x))){h=A.substring(A.length-x),E=A.substring(0,A.length-x);break}if(E.length>0){let x={...w.choices[0].delta,thinking:{content:E}};delete x.content,b({...w,choices:[{...w.choices[0],delta:x,index:i}]})}A="";continue}if(A.length>0)if(/^\s*$/.test(A))g+=A;else{let k=g+A,E={...w.choices[0].delta,content:k};E.thinking&&delete E.thinking,b({...w,choices:[{...w.choices[0],delta:E}]}),g=""}i++,A=""}};try{for(;;){let{done:w,value:C}=await d.read();if(w)break;f+=o.decode(C,{stream:!0});let A=f.split(`
373
- `);f=A.pop()||"";for(let k of A)if(k.trim()){if(k.trim()==="data: [DONE]"){u.enqueue(s.encode(k+`
372
+ `))},m=(w,C)=>{if(typeof C!="string"&&w?.choices?.[0]?.delta&&Object.keys(w.choices[0].delta).length>0&&!w.choices[0].delta.content){w.choices[0].index=i,b(w);return}if(typeof C!="string")return;let S=h+C;for(h="";S.length>0;){if(p==="SEARCHING"){let k=S.indexOf(n);if(k!==-1){S=S.substring(k+n.length),p="THINKING";continue}for(let E=n.length-1;E>0;E--)if(S.endsWith(n.substring(0,E))){h=S.substring(S.length-E);break}S="";continue}if(p==="THINKING"){let k=S.indexOf(r);if(k!==-1){let x=S.substring(0,k);if(x.length>0){let q={...w.choices[0].delta,thinking:{content:x}};delete q.content,b({...w,choices:[{...w.choices[0],delta:q,index:i}]})}let O={...w.choices[0].delta,thinking:{signature:Date.now().toString()}};delete O.content,b({...w,choices:[{...w.choices[0],delta:O,index:i}]}),i++,S=S.substring(k+r.length),p="FINAL";continue}let E=S;for(let x=r.length-1;x>0;x--)if(S.endsWith(r.substring(0,x))){h=S.substring(S.length-x),E=S.substring(0,S.length-x);break}if(E.length>0){let x={...w.choices[0].delta,thinking:{content:E}};delete x.content,b({...w,choices:[{...w.choices[0],delta:x,index:i}]})}S="";continue}if(S.length>0)if(/^\s*$/.test(S))g+=S;else{let k=g+S,E={...w.choices[0].delta,content:k};E.thinking&&delete E.thinking,b({...w,choices:[{...w.choices[0],delta:E}]}),g=""}i++,S=""}};try{for(;;){let{done:w,value:C}=await d.read();if(w)break;f+=o.decode(C,{stream:!0});let S=f.split(`
373
+ `);f=S.pop()||"";for(let k of S)if(k.trim()){if(k.trim()==="data: [DONE]"){u.enqueue(s.encode(k+`
374
374
 
375
375
  `));continue}if(k.startsWith("data:"))try{let E=JSON.parse(k.slice(5));m(E,E?.choices?.[0]?.delta?.content)}catch{u.enqueue(s.encode(k+`
376
376
  `))}else u.enqueue(s.encode(k+`
377
- `))}}}catch(w){console.error("Stream error:",w),u.error(w)}finally{try{d.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}p==="THINKING"&&b({choices:[{delta:{thinking:{signature:Date.now().toString()}}}]}),u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}};function d2(t){return!t||t.type!=="thinking"?"":(Array.isArray(t.thinking)?t.thinking:[t.thinking]).map(n=>typeof n=="string"?n:n&&typeof n.text=="string"?n.text:n==null?"":JSON.stringify(n)).join("")}function f2(t){let e=typeof t?.thinking?.content=="string"?t.thinking.content:"",n=typeof t?.reasoning_content=="string"?t.reasoning_content:"",r="";if(Array.isArray(t?.content))for(let o of t.content)r+=d2(o);return e||n||r}function p2(t){return{type:"thinking",thinking:[{type:"text",text:t}]}}function cx(t){if(!t||typeof t!="object"||!("cache_control"in t))return t;let{cache_control:e,...n}=t;return n}function h2(t){let e={...t},n=f2(e),r=Array.isArray(e.content)?e.content:void 0,o=(r||[]).filter(i=>i?.type==="image_url").map(cx),s=r?r.filter(i=>i?.type==="text").map(i=>i.text).filter(i=>i&&i.length>0).join(`
378
- `):typeof e.content=="string"?e.content:"";if(e.role==="assistant"&&n){let i=[];i.push(p2(n)),s&&i.push({type:"text",text:s}),i.push(...o),e.content=i}else r&&(o.length>0?e.content=r.filter(i=>i?.type==="text"||i?.type==="image_url").map(cx):e.content=s);return delete e.thinking,delete e.reasoning_content,delete e.cache_control,e}function g2(t){return t==="auto"||t==="none"?t:t==="required"?"any":typeof t=="object"&&t.function?.name?{type:"function",function:{name:t.function.name}}:t}function m2(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="minimal"?"low":e==="low"||e==="medium"||e==="high"?e:"high"}var ux=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function lx(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>h2(s))),r.stream===void 0&&(r.stream=!0);let o=en(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=g2(r.tool_choice)),Array.isArray(r.tools)&&(r.tools=r.tools.map(s=>{let{cache_control:i,...a}=s;return a?.function?.parameters?{...a,function:{...a.function,parameters:Ru(a.function.parameters)}}:a})),r.reasoning&&r.model){let s=r.model;(s.startsWith("magistral-")||s.startsWith("labs-leanstral-")||s==="mistral-vibe-cli-fast"||s.startsWith("mistral-small-")&&!ux.has(s)||s.startsWith("mistral-medium-")&&!ux.has(s))&&(r.reasoning_effort=m2(r.reasoning)),delete r.reasoning}return delete r.thinking,delete r.enable_thinking,delete r.anthropic_thinking,delete r.anthropic_output_config,delete r.anthropic_metadata,delete r.anthropic_stop_sequences,r}async function dx(t,e,n){let r=t.headers.get("Content-Type")??"";if(r.includes("application/json")){let o=await t.json();n?.debug({response:o},`${e} response:`);let s=o.choices?.[0];if(s?.message){let i=s.message,a="";if(i.reasoning_content){let u=i.reasoning_content;a+=typeof u=="string"?u:typeof u?.text=="string"?u.text:JSON.stringify(u),delete i.reasoning_content}if(Array.isArray(i.content)){let u="";for(let d of i.content)if(d.type==="thinking"){let f=Array.isArray(d.thinking)?d.thinking:[d.thinking];a+=f.map(p=>typeof p=="string"?p:p&&typeof p.text=="string"?p.text:JSON.stringify(p)).join("")}else d.type==="text"&&(u+=typeof d.text=="string"?d.text:JSON.stringify(d.text??""));i.content=u}a&&(o.thinking={content:a},i.thinking={content:a})}return new Response(JSON.stringify(o),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(r.includes("stream"))return t.body?Ne(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Pe(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Pe(o,s.encoder));return}try{let i=o.slice(5).trim(),a=JSON.parse(i),u=a.choices?.[0]?.delta;if(!u){s.controller.enqueue(Pe(o,s.encoder));return}let d=Ys(u);if(d){let f=Zr(a,{content:d});eo(f.choices[0].delta);let p=u.content;if(Array.isArray(p)){let h="",g=p.filter(b=>b.type==="text").map(b=>typeof b.text=="string"?b.text:JSON.stringify(b.text??"")).join("");for(let b of p)if(b.type==="thinking"){let m=Array.isArray(b.thinking)?b.thinking:[b.thinking];h+=m.map(w=>typeof w=="string"?w:w&&typeof w.text=="string"?w.text:JSON.stringify(w)).join("")}delete f.choices[0].delta.content,(h||d)&&(f.choices[0].delta.thinking={content:h||d}),g&&(f.choices[0].delta.content=g)}s.controller.enqueue(ve(JSON.stringify(f),s.encoder));return}if(Array.isArray(u.content)){let f="",p=u.content.filter(h=>h.type==="text").map(h=>typeof h.text=="string"?h.text:JSON.stringify(h.text??"")).join("");for(let h of u.content)if(h.type==="thinking"){let g=Array.isArray(h.thinking)?h.thinking:[h.thinking];f+=g.map(b=>typeof b=="string"?b:b&&typeof b.text=="string"?b.text:JSON.stringify(b)).join("")}delete u.content,f&&(u.thinking={content:f}),p&&(u.content=p)}s.controller.enqueue(ve(JSON.stringify(a),s.encoder))}catch{s.controller.enqueue(Pe(o,s.encoder))}}):t;return t}var rf=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:lx(e,r,n),config:{url:new URL("/v1/chat/completions",n.baseUrl),headers:{Authorization:`Bearer ${n.apiKey}`}}}}transformRequestOut;async transformResponseOut(e,n){try{return await dx(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var y2="http://127.0.0.1:3457",of=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||y2;r?.req?.body&&(r.req.body.stream=!0);let s=en(r,e);return{body:{...e,messages:Ve(e.messages),tools:Ye(e.tools),stream:!0},config:{url:`${o}/v1/chat/completions`,headers:{"Content-Type":"application/json",...s?{"x-ccr-session-id":s}:{}}}}}async transformResponseOut(e){return(e.headers.get("Content-Type")||"").includes("text/event-stream")||!e.body,e}};import{randomBytes as _2,createHash as b2}from"crypto";var C2="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",w2="1.18.21",k2=`opencode/${w2}`,h_=3,S2=500,A2=2e3,g_=3e4,E2=.25,sf=class t{name="opencode-headers";sessionCache=new Map;MAX_SESSIONS=100;lastTimestamp=0;counter=0;async transformRequestIn(e,n,r){let o=r?.req?.sessionId||this.fingerprintConversation(e,r),s=e.body||e,i=e.config||{},a=this.generateId("msg"),u=await this.sendWithSessionRetry(s,i,n,r,o,a);return{body:s,config:{...i,url:n?.baseUrl||n?.api_base_url,__providerResponse:u}}}async transformResponseOut(e){let n=e.headers.get("content-type")||"";return!e.body||!n.includes("text/event-stream")?e:this.preserveZenStreamErrors(e)}async sendWithSessionRetry(e,n,r,o,s,i){let a=r?.baseUrl||r?.api_base_url,u=o?.req?.server?.configService?.getHttpsProxy?.(),d=o?.req?.log??o?.req?.server?.log,f=e?.model,p=o?.signal??n?.signal;for(let h=0;h<h_;h++){let g=this.buildHeaders(n,r,s,i),b;try{b=await ts(a,e,{httpsProxy:u,...n,headers:g,signal:p},o,d)}catch(E){if(h===h_-1||Je(E)||!ar(E))throw E;let O=this.exponentialRetryDelayMs(h);d?.warn?.({provider:r?.name,model:f,attempt:h+1,waitMs:O},"opencode: Zen network failure \u2014 preserving session and retrying"),await es(O,p);continue}if(b.ok)return b;let m=await b.text(),w=h===h_-1,C=this.isZenRoutingFailure(b.status,m),A=this.isZenTransientStatus(b.status);if(!w&&(C||A)){C&&this.invalidateSession(s);let E=A?this.retryDelayMs(b,h):0;d?.warn?.({provider:r?.name,model:f,status:b.status,attempt:h+1,waitMs:E,sessionRerolled:C},C?"opencode: Zen provider-routing failure \u2014 re-rolling session and retrying":"opencode: transient Zen failure \u2014 preserving session and retrying"),E>0&&await es(E,p);continue}let k=Ge(m)||m.slice(0,240);throw J(`Error from provider(${r?.name},${f}: ${b.status}): ${k}`,b.status,"provider_response_error","api_error",this.retryAfterHeaders(b))}throw J(`Error from provider(${r?.name},${f}): Zen retries exhausted`,503,"provider_response_error")}preserveZenStreamErrors(e){let n=e.body.getReader(),r=new TextDecoder,o=new TextEncoder,s="",i=!1,a=new ReadableStream({async pull(u){try{for(;!i;){let{done:d,value:f}=await n.read();if(d){let b=s+r.decode();s="";let m=b?t.zenStreamFailure(b):void 0;if(m){let w=Object.assign(new Error(m),{code:"provider_network_error"});i=!0,u.error(w);return}b&&u.enqueue(o.encode(b)),u.close();return}s+=r.decode(f,{stream:!0});let p=s.split(/\r?\n\r?\n/);if(s=p.pop()||"",!p.length)continue;let h=[],g;for(let b of p){if(g=t.zenStreamFailure(b),g){i=!0;break}h.push(b)}if(h.length&&u.enqueue(o.encode(`${h.join(`
377
+ `))}}}catch(w){console.error("Stream error:",w),u.error(w)}finally{try{d.releaseLock()}catch(w){console.error("Error releasing reader lock:",w)}p==="THINKING"&&b({choices:[{delta:{thinking:{signature:Date.now().toString()}}}]}),u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}};function h2(t){return!t||t.type!=="thinking"?"":(Array.isArray(t.thinking)?t.thinking:[t.thinking]).map(n=>typeof n=="string"?n:n&&typeof n.text=="string"?n.text:n==null?"":JSON.stringify(n)).join("")}function g2(t){let e=typeof t?.thinking?.content=="string"?t.thinking.content:"",n=typeof t?.reasoning_content=="string"?t.reasoning_content:"",r="";if(Array.isArray(t?.content))for(let o of t.content)r+=h2(o);return e||n||r}function m2(t){return{type:"thinking",thinking:[{type:"text",text:t}]}}function ux(t){if(!t||typeof t!="object"||!("cache_control"in t))return t;let{cache_control:e,...n}=t;return n}function y2(t){let e={...t},n=g2(e),r=Array.isArray(e.content)?e.content:void 0,o=(r||[]).filter(i=>i?.type==="image_url").map(ux),s=r?r.filter(i=>i?.type==="text").map(i=>i.text).filter(i=>i&&i.length>0).join(`
378
+ `):typeof e.content=="string"?e.content:"";if(e.role==="assistant"&&n){let i=[];i.push(m2(n)),s&&i.push({type:"text",text:s}),i.push(...o),e.content=i}else r&&(o.length>0?e.content=r.filter(i=>i?.type==="text"||i?.type==="image_url").map(ux):e.content=s);return delete e.thinking,delete e.reasoning_content,delete e.cache_control,e}function _2(t){return t==="auto"||t==="none"?t:t==="required"?"any":typeof t=="object"&&t.function?.name?{type:"function",function:{name:t.function.name}}:t}function b2(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="minimal"?"low":e==="low"||e==="medium"||e==="high"?e:"high"}var lx=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function dx(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>y2(s))),r.stream===void 0&&(r.stream=!0);let o=en(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=_2(r.tool_choice)),Array.isArray(r.tools)&&(r.tools=r.tools.map(s=>{let{cache_control:i,...a}=s;return a?.function?.parameters?{...a,function:{...a.function,parameters:Ru(a.function.parameters)}}:a})),r.reasoning&&r.model){let s=r.model;(s.startsWith("magistral-")||s.startsWith("labs-leanstral-")||s==="mistral-vibe-cli-fast"||s.startsWith("mistral-small-")&&!lx.has(s)||s.startsWith("mistral-medium-")&&!lx.has(s))&&(r.reasoning_effort=b2(r.reasoning)),delete r.reasoning}return delete r.thinking,delete r.enable_thinking,delete r.anthropic_thinking,delete r.anthropic_output_config,delete r.anthropic_metadata,delete r.anthropic_stop_sequences,r}async function fx(t,e,n){let r=t.headers.get("Content-Type")??"";if(r.includes("application/json")){let o=await t.json();n?.debug({response:o},`${e} response:`);let s=o.choices?.[0];if(s?.message){let i=s.message,a="";if(i.reasoning_content){let u=i.reasoning_content;a+=typeof u=="string"?u:typeof u?.text=="string"?u.text:JSON.stringify(u),delete i.reasoning_content}if(Array.isArray(i.content)){let u="";for(let d of i.content)if(d.type==="thinking"){let f=Array.isArray(d.thinking)?d.thinking:[d.thinking];a+=f.map(p=>typeof p=="string"?p:p&&typeof p.text=="string"?p.text:JSON.stringify(p)).join("")}else d.type==="text"&&(u+=typeof d.text=="string"?d.text:JSON.stringify(d.text??""));i.content=u}a&&(o.thinking={content:a},i.thinking={content:a})}return new Response(JSON.stringify(o),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(r.includes("stream"))return t.body?Ne(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Pe(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Pe(o,s.encoder));return}try{let i=o.slice(5).trim(),a=JSON.parse(i),u=a.choices?.[0]?.delta;if(!u){s.controller.enqueue(Pe(o,s.encoder));return}let d=Ys(u);if(d){let f=Zr(a,{content:d});eo(f.choices[0].delta);let p=u.content;if(Array.isArray(p)){let h="",g=p.filter(b=>b.type==="text").map(b=>typeof b.text=="string"?b.text:JSON.stringify(b.text??"")).join("");for(let b of p)if(b.type==="thinking"){let m=Array.isArray(b.thinking)?b.thinking:[b.thinking];h+=m.map(w=>typeof w=="string"?w:w&&typeof w.text=="string"?w.text:JSON.stringify(w)).join("")}delete f.choices[0].delta.content,(h||d)&&(f.choices[0].delta.thinking={content:h||d}),g&&(f.choices[0].delta.content=g)}s.controller.enqueue(ve(JSON.stringify(f),s.encoder));return}if(Array.isArray(u.content)){let f="",p=u.content.filter(h=>h.type==="text").map(h=>typeof h.text=="string"?h.text:JSON.stringify(h.text??"")).join("");for(let h of u.content)if(h.type==="thinking"){let g=Array.isArray(h.thinking)?h.thinking:[h.thinking];f+=g.map(b=>typeof b=="string"?b:b&&typeof b.text=="string"?b.text:JSON.stringify(b)).join("")}delete u.content,f&&(u.thinking={content:f}),p&&(u.content=p)}s.controller.enqueue(ve(JSON.stringify(a),s.encoder))}catch{s.controller.enqueue(Pe(o,s.encoder))}}):t;return t}var nf=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:dx(e,r,n),config:{url:new URL("/v1/chat/completions",n.baseUrl),headers:{Authorization:`Bearer ${n.apiKey}`}}}}transformRequestOut;async transformResponseOut(e,n){try{return await fx(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var C2="http://127.0.0.1:3457",rf=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||C2;r?.req?.body&&(r.req.body.stream=!0);let s=en(r,e);return{body:{...e,messages:Ve(e.messages),tools:Ye(e.tools),stream:!0},config:{url:`${o}/v1/chat/completions`,headers:{"Content-Type":"application/json",...s?{"x-ccr-session-id":s}:{}}}}}async transformResponseOut(e){return(e.headers.get("Content-Type")||"").includes("text/event-stream")||!e.body,e}};import{randomBytes as w2,createHash as k2}from"crypto";var S2="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",A2="1.18.21",E2=`opencode/${A2}`,h_=3,v2=500,T2=2e3,g_=3e4,x2=.25,of=class t{name="opencode-headers";sessionCache=new Map;MAX_SESSIONS=100;lastTimestamp=0;counter=0;async transformRequestIn(e,n,r){let o=r?.req?.sessionId||this.fingerprintConversation(e,r),s=e.body||e,i=e.config||{},a=this.generateId("msg"),u=await this.sendWithSessionRetry(s,i,n,r,o,a);return{body:s,config:{...i,url:n?.baseUrl||n?.api_base_url,__providerResponse:u}}}async transformResponseOut(e){let n=e.headers.get("content-type")||"";return!e.body||!n.includes("text/event-stream")?e:this.preserveZenStreamErrors(e)}async sendWithSessionRetry(e,n,r,o,s,i){let a=r?.baseUrl||r?.api_base_url,u=o?.req?.server?.configService?.getHttpsProxy?.(),d=o?.req?.log??o?.req?.server?.log,f=e?.model,p=o?.signal??n?.signal;for(let h=0;h<h_;h++){let g=this.buildHeaders(n,r,s,i),b;try{b=await ts(a,e,{httpsProxy:u,...n,headers:g,signal:p},o,d)}catch(E){if(h===h_-1||Je(E)||!ar(E))throw E;let O=this.exponentialRetryDelayMs(h);d?.warn?.({provider:r?.name,model:f,attempt:h+1,waitMs:O},"opencode: Zen network failure \u2014 preserving session and retrying"),await es(O,p);continue}if(b.ok)return b;let m=await b.text(),w=h===h_-1,C=this.isZenRoutingFailure(b.status,m),S=this.isZenTransientStatus(b.status);if(!w&&(C||S)){C&&this.invalidateSession(s);let E=S?this.retryDelayMs(b,h):0;d?.warn?.({provider:r?.name,model:f,status:b.status,attempt:h+1,waitMs:E,sessionRerolled:C},C?"opencode: Zen provider-routing failure \u2014 re-rolling session and retrying":"opencode: transient Zen failure \u2014 preserving session and retrying"),E>0&&await es(E,p);continue}let k=Ge(m)||m.slice(0,240);throw J(`Error from provider(${r?.name},${f}: ${b.status}): ${k}`,b.status,"provider_response_error","api_error",this.retryAfterHeaders(b))}throw J(`Error from provider(${r?.name},${f}): Zen retries exhausted`,503,"provider_response_error")}preserveZenStreamErrors(e){let n=e.body.getReader(),r=new TextDecoder,o=new TextEncoder,s="",i=!1,a=new ReadableStream({async pull(u){try{for(;!i;){let{done:d,value:f}=await n.read();if(d){let b=s+r.decode();s="";let m=b?t.zenStreamFailure(b):void 0;if(m){let w=Object.assign(new Error(m),{code:"provider_network_error"});i=!0,u.error(w);return}b&&u.enqueue(o.encode(b)),u.close();return}s+=r.decode(f,{stream:!0});let p=s.split(/\r?\n\r?\n/);if(s=p.pop()||"",!p.length)continue;let h=[],g;for(let b of p){if(g=t.zenStreamFailure(b),g){i=!0;break}h.push(b)}if(h.length&&u.enqueue(o.encode(`${h.join(`
379
379
 
380
380
  `)}
381
381
 
382
- `)),g){let b=Object.assign(new Error(g),{code:"provider_network_error"});await n.cancel(b).catch(()=>{}),u.error(b)}return}}catch(d){u.error(d)}},cancel(u){return i=!0,n.cancel(u)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}static zenStreamFailure(e){for(let n of e.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!r||r==="[DONE]")continue;let o;try{o=JSON.parse(r)}catch{continue}let s=String(o?.choices?.[0]?.finish_reason||"");if(/^network[-_\s]error$/i.test(s))return`Provider finish_reason: ${s}`;if(o?.error){let i=typeof o.error?.message=="string"?o.error.message:typeof o.error=="string"?o.error:"OpenCode provider stream error";return Ge(i)||"OpenCode provider stream error"}}}buildHeaders(e,n,r,o){let s=this.getOrCreateSessionId(r);return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":s,"x-opencode-request":o,"x-opencode-client":"cli","user-agent":k2,authorization:void 0}}isZenRoutingFailure(e,n){if(e!==401&&e!==400)return!1;let r;try{r=JSON.parse(n)}catch{return!1}let o=String(r?.error?.message||"");return!!(e===401&&r?.error?.type==="ModelError"&&/no provider available/i.test(o)||e===400&&/upstream request failed/i.test(o)&&!/validation error/i.test(o))}isZenTransientStatus(e){return dh(e)}retryDelayMs(e,n){let r=e.headers.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(Number.isFinite(s)&&s>=0)return Math.min(s,g_)}let o=e.headers.get("retry-after");if(o){let s=Number.parseFloat(o);if(Number.isFinite(s)&&s>=0)return Math.min(s*1e3,g_);let i=Date.parse(o);if(Number.isFinite(i))return Math.min(Math.max(0,i-Date.now()),g_)}return this.exponentialRetryDelayMs(n)}exponentialRetryDelayMs(e){let n=S2*2**e*(1+Math.random()*E2);return Math.min(n,A2)}retryAfterHeaders(e){let n=e.headers.get("retry-after"),r=e.headers.get("retry-after-ms");if(!(!n&&!r))return{...n?{"Retry-After":n}:{},...r?{"Retry-After-Ms":r}:{}}}fingerprintConversation(e,n){let r=e.body||e,o=r.model||"",s=r.messages||[],i=JSON.stringify(s.slice(0,3)),a=n?.req?.headers?.["x-forwarded-for"]||n?.req?.ip||"",u=n?.req?.headers?.["user-agent"]||"";return b2("sha256").update(`${o}|${a}|${u}|${i}`).digest("hex").slice(0,32)}getOrCreateSessionId(e){let n=this.sessionCache.get(e);if(n)return n;if(this.sessionCache.size>=this.MAX_SESSIONS){let o=this.sessionCache.keys().next().value;o!==void 0&&this.sessionCache.delete(o)}let r=this.generateId("ses");return this.sessionCache.set(e,r),r}invalidateSession(e){this.sessionCache.delete(e)}generateId(e){let n=Date.now();n!==this.lastTimestamp&&(this.lastTimestamp=n,this.counter=0),this.counter++;let r=BigInt(n)*BigInt(4096)+BigInt(this.counter),o=Buffer.alloc(6);for(let i=0;i<6;i++)o[i]=Number(r>>BigInt(40-8*i)&BigInt(255));let s="";for(;s.length<14;){let i=_2(1)[0];i>=248||(s+=C2[i%62])}return`${e}_${o.toString("hex")}${s}`}};import{Cursor as A$}from"@cursor/sdk";var v2=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function fx(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!v2.test(e)&&!e.includes("$CURSOR_API_KEY")&&!e.includes("${"))return e;let n=process.env.CURSOR_API_KEY?.trim();if(n)return n;throw Object.assign(new Error("Cursor API key not found. Set Providers[].api_key to a crsr_ key, or export CURSOR_API_KEY."),{statusCode:401,code:"provider_response_error",type:"api_error"})}import{createHash as T2}from"crypto";import{homedir as x2}from"os";import{basename as R2,dirname as D2,join as px}from"path";var m_="cursor-sdk",af="bridge",O2=px(x2(),".claude-code-router"),zn=px(O2,"cursor-sdk-workspaces"),hx=900*1e3,y_=32,gx=1440*60*1e3,mx=3600*1e3,P2=/^[0-9a-f]{32}$/;function __(t,e=zn){let n=t.replace(/[\\/]+$/,"");return D2(n)!==e.replace(/[\\/]+$/,"")?!1:P2.test(R2(n))}var yx=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],xa="custom-user-tools";function dn(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):"").filter(Boolean).join(`
383
- `):String(t)}function ri(t){return T2("sha256").update(t.filter(Boolean).join(`
384
- `)).digest("hex").slice(0,32)}function oi(t){if(typeof t=="string")return t;if(t==null)return"";if(typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function b_(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function _x(t,e){let n=Math.floor(Date.now()/1e3),r=`chatcmpl-cursor-${Date.now()}`,o=()=>({id:r,object:"chat.completion.chunk",created:n,model:t});return{setId(s){s&&(r=s)},content(s){return{...o(),choices:[{index:0,delta:{role:"assistant",content:s},finish_reason:null}]}},thinking(s){return{...o(),choices:[{index:0,delta:{thinking:{content:oi(s)}},finish_reason:null}]}},thinkingSignature(s=`ccr_cursor_${Date.now()}`){return{...o(),choices:[{index:0,delta:{thinking:{signature:s}},finish_reason:null}]}},toolCall(s,i=0){return{...o(),choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:i,id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}]},finish_reason:null}]}},finish(s,i){let a=Number(i?.prompt_tokens)||0,u=Number(i?.completion_tokens)||0,d=Number(i?.total_tokens)||a+u;return{...o(),choices:[{index:0,delta:{},finish_reason:s}],usage:{prompt_tokens:a,completion_tokens:u,total_tokens:d,prompt_tokens_details:{cached_tokens:Number(i?.prompt_tokens_details?.cached_tokens)||0}}}},encode(s){return ve(JSON.stringify(s),e)},encodeDone(){return ve("[DONE]",e)}}}function C_(t,e){let n="",r="",o="",s=[],i="stop",a=null,u=`chatcmpl-cursor-${Date.now()}`,d=Math.floor(Date.now()/1e3);for(let p of e){typeof p.id=="string"&&(u=p.id);let h=p.choices?.[0];if(!h)continue;h.finish_reason&&(i=h.finish_reason);let g=h.delta||{};if(typeof g.content=="string"&&(n+=g.content),g.thinking?.content&&(r+=oi(g.thinking.content)),typeof g.thinking?.signature=="string"&&g.thinking.signature&&(o=g.thinking.signature),Array.isArray(g.tool_calls))for(let b of g.tool_calls){let m=b.index??s.length;s[m]||(s[m]={id:b.id,type:"function",function:{name:b.function?.name||"",arguments:""}}),b.id&&(s[m].id=b.id),b.function?.name&&(s[m].function.name=b.function.name),typeof b.function?.arguments=="string"&&(s[m].function.arguments+=b.function.arguments)}p.usage&&(a=p.usage)}let f={role:"assistant",content:n||null};return r&&(f.thinking={content:r,signature:o||`ccr_cursor_${d}`}),s.length&&(f.tool_calls=s.filter(Boolean),i="tool_calls"),{id:u,object:"chat.completion",created:d,model:t,choices:[{index:0,message:f,finish_reason:i}],usage:a}}var to={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},bx=/<(env|environment|system-info|system_info)>([\s\S]*?)<\/\1>/gi,I2=/^\s*[-*]?\s*([A-Za-z][A-Za-z0-9 _/'-]{2,48}?)\s*:\s*(\S.*?)\s*$/,F2=/working director|workspace root|project root|platform|os version|operating system|git repo/i,Cx=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],wx=[/^additional working director/i,/^additional director/i,/^extra working director/i],kx=[/^platform$/i,/^operating system$/i,/^os$/i],Sx=[/^os version$/i,/^system version$/i],N2=[...Cx,...wx,...kx,...Sx],M2=2e5,B2=16,U2=400;function j2(t){let e=[],n=M2,r=!1;for(let o of t.messages||[]){if(o.role!=="system"&&o.role!=="user")continue;if(o.role==="user"&&r)break;o.role==="user"&&(r=!0);let s=dn(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
385
- `)}function L2(t){let e=[],n=new Set,r=i=>{if(e.length>=B2)return;let a=i.match(I2);if(!a)return;let u=a[1].trim(),d=a[2].trim().slice(0,U2);if(!u||!d)return;let f=u.toLowerCase();n.has(f)||(n.add(f),e.push({key:u,value:d}))},o=!1;bx.lastIndex=0;let s;for(;s=bx.exec(t);){o=!0;for(let i of s[2].split(/\r?\n/))r(i)}if(!o)for(let i of t.split(/\r?\n/))F2.test(i)&&r(i);return e}function cf(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function Ax(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function $2(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>Ax(e)):[]}function Ra(t){let e=L2(j2(t)),n=cf(e,Cx),r=n&&Ax(n)?n:void 0,o=$2(cf(e,wx)).filter(u=>u!==r),s=cf(e,kx),i=cf(e,Sx),a=!!(r||s||i||e.length);return a?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:a,fingerprint:ri([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:to}function Ex(t){let e=[];t.projectRoot&&e.push(`- Project root: ${t.projectRoot}`);for(let n of t.additionalRoots)e.push(`- Additional in-scope root: ${n}`);t.platform&&e.push(`- Platform: ${t.platform}`),t.osVersion&&e.push(`- OS version: ${t.osVersion}`);for(let n of t.facts)N2.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function Bo(t){return t.projectRoot?`Every path you pass to a host tool must be an absolute path on the host, normally under ${t.projectRoot}.`:"Every path you pass to a host tool must be an absolute host path taken from this conversation \u2014 never invent one and never derive one from your local filesystem."}function q2(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(!n||typeof n!="object")&&n.type==="image_url"&&n.image_url?.url){let r=String(n.image_url.url),o=r.match(/^data:([^;]+);base64,(.+)$/);o?e.push({data:o[2],mimeType:o[1]}):e.push({url:r})}return e}function H2(t){return!Array.isArray(t.tools)||t.tools.length===0?"(no host tools advertised on this request)":t.tools.map(e=>{let n=e.function?.name||"unknown",r=e.function?.description||"";return`- ${n}: ${r}`}).join(`
386
- `)}function Tx(t,e){let n=["You are a remote reasoning agent driving Claude Code (the host).","Tools do not run where you are running: every tool call is executed by the host on the user's machine, and only the result is sent back to you.",`Your local environment is disposable scratch space: ${t}`,"It is empty and contains none of the user's files. Never read, list, search, or verify paths against it, and never prefix a host tool path with it.","Your own cwd, OS, and workspace root describe that scratch container only \u2014 they say nothing about the user's project, so never reason from them or report them to the user."],r=Ex(e);return r.length&&(n.push("The user's project lives on the host machine, which is where every tool call lands:"),n.push(...r)),n.push(Bo(e)),n.push(`Host tools are exposed via MCP server "${xa}" using bare tool names.`,"Cursor built-in tools are denied here. That denial only routes tool use through the host \u2014 it is not a restriction on the user's project, which stays fully reachable through the host tools."),n}function z2(t,e,n=Ra(t)){return[...Tx(e,n),"A progress update such as 'Checking...', 'Inspecting...', or 'Let me look...' is not a final answer.","After progress narration, call a host tool in the same turn; if no tool is needed, provide the complete user-facing answer before finishing.","Never end a turn with progress narration alone.","Available host tools:",H2(t)].join(`
387
- `)}function W2(t,e){return["[bridge reminder]",`Tools run on the host machine, not here. ${t} is empty scratch space \u2014 never treat it as the project, and never build a tool path from it.`,Bo(e)].join(`
388
- `)}function xx(t,e){return["# Agent rules","",...Tx(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
389
- `)}function Rx(t){return["Your local filesystem is empty scratch space on a different machine from the user's project.","The project is reachable only through the host tools, and it is not restricted.",Bo(t)].join(" ")}var G2=[/^(?:checking|inspecting|reviewing|examining|investigating|verifying|reading|searching)\s+(?:the|this|that|these|those|your|our|which|whether|for|how|why|what|where)\b/i,/^looking\s+(?:at|into|for|through|up)\b/i,/^(?:i(?:'ll| will)|let me)\s+(?:check|inspect|review|examine|investigate|verify|read|search|look)\b/i];function J2(t){let e=String(t||"").trim();if(!e||e.length>240||/\n\s*\n/.test(e))return!1;let n=e.replace(/\s+/g," ");return(n.match(/[.!?](?:\s|$)/g)?.length||0)>1?!1:G2.some(o=>o.test(n))}function Dx(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&J2(t.assistantText)}function Ox(t){let e=["Continue the same turn now.","Your previous assistant message was only progress narration and ended without a host tool call or a complete answer.","Do not repeat the progress update.","If evidence is still needed, call an available host tool immediately; otherwise provide the complete user-facing answer now.","Do not finish until the requested work or answer is complete."];return t?.known&&e.push(Bo(t)),{text:e.join(" ")}}function vx(t){let e=t.trim();return qh.some(n=>e===n)}function K2(t){if(!Array.isArray(t)){let e=dn(t);return e.trim().length>0&&!vx(e)}return t.some(e=>{if(!e||typeof e!="object")return!1;if("text"in e){let n=String(e.text||"");return n.trim().length>0&&!vx(n)}return!0})}function Px(t,e){let n=t.messages||[],r=[],o=e.hostEnv||Ra(t);e.mode==="bridge"?(r.push(z2(t,e.workspaceDir,o)),r.push("")):e.mode==="plan"&&(r.push("You are a planning/chat assistant. Respond with text and reasoning only. Do not execute tools."),r.push(""));let s=n.filter(f=>f.role==="system");for(let f of s){let p=dn(f.content);p&&r.push(`[system]
390
- ${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,V2(i,e.turnIntent)+1)):i,u=[];for(let f of a){if(f.role==="assistant"){let p=dn(f.content);if(p&&r.push(`[assistant]
382
+ `)),g){let b=Object.assign(new Error(g),{code:"provider_network_error"});await n.cancel(b).catch(()=>{}),u.error(b)}return}}catch(d){u.error(d)}},cancel(u){return i=!0,n.cancel(u)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}static zenStreamFailure(e){for(let n of e.split(/\r?\n/)){if(!n.startsWith("data:"))continue;let r=n.slice(5).trim();if(!r||r==="[DONE]")continue;let o;try{o=JSON.parse(r)}catch{continue}let s=String(o?.choices?.[0]?.finish_reason||"");if(/^network[-_\s]error$/i.test(s))return`Provider finish_reason: ${s}`;if(o?.error){let i=typeof o.error?.message=="string"?o.error.message:typeof o.error=="string"?o.error:"OpenCode provider stream error";return Ge(i)||"OpenCode provider stream error"}}}buildHeaders(e,n,r,o){let s=this.getOrCreateSessionId(r);return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":s,"x-opencode-request":o,"x-opencode-client":"cli","user-agent":E2,authorization:void 0}}isZenRoutingFailure(e,n){if(e!==401&&e!==400)return!1;let r;try{r=JSON.parse(n)}catch{return!1}let o=String(r?.error?.message||"");return!!(e===401&&r?.error?.type==="ModelError"&&/no provider available/i.test(o)||e===400&&/upstream request failed/i.test(o)&&!/validation error/i.test(o))}isZenTransientStatus(e){return lh(e)}retryDelayMs(e,n){let r=e.headers.get("retry-after-ms");if(r){let s=Number.parseFloat(r);if(Number.isFinite(s)&&s>=0)return Math.min(s,g_)}let o=e.headers.get("retry-after");if(o){let s=Number.parseFloat(o);if(Number.isFinite(s)&&s>=0)return Math.min(s*1e3,g_);let i=Date.parse(o);if(Number.isFinite(i))return Math.min(Math.max(0,i-Date.now()),g_)}return this.exponentialRetryDelayMs(n)}exponentialRetryDelayMs(e){let n=v2*2**e*(1+Math.random()*x2);return Math.min(n,T2)}retryAfterHeaders(e){let n=e.headers.get("retry-after"),r=e.headers.get("retry-after-ms");if(!(!n&&!r))return{...n?{"Retry-After":n}:{},...r?{"Retry-After-Ms":r}:{}}}fingerprintConversation(e,n){let r=e.body||e,o=r.model||"",s=r.messages||[],i=JSON.stringify(s.slice(0,3)),a=n?.req?.headers?.["x-forwarded-for"]||n?.req?.ip||"",u=n?.req?.headers?.["user-agent"]||"";return k2("sha256").update(`${o}|${a}|${u}|${i}`).digest("hex").slice(0,32)}getOrCreateSessionId(e){let n=this.sessionCache.get(e);if(n)return n;if(this.sessionCache.size>=this.MAX_SESSIONS){let o=this.sessionCache.keys().next().value;o!==void 0&&this.sessionCache.delete(o)}let r=this.generateId("ses");return this.sessionCache.set(e,r),r}invalidateSession(e){this.sessionCache.delete(e)}generateId(e){let n=Date.now();n!==this.lastTimestamp&&(this.lastTimestamp=n,this.counter=0),this.counter++;let r=BigInt(n)*BigInt(4096)+BigInt(this.counter),o=Buffer.alloc(6);for(let i=0;i<6;i++)o[i]=Number(r>>BigInt(40-8*i)&BigInt(255));let s="";for(;s.length<14;){let i=w2(1)[0];i>=248||(s+=S2[i%62])}return`${e}_${o.toString("hex")}${s}`}};import{Cursor as T$}from"@cursor/sdk";var R2=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function px(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!R2.test(e)&&!e.includes("$CURSOR_API_KEY")&&!e.includes("${"))return e;let n=process.env.CURSOR_API_KEY?.trim();if(n)return n;throw Object.assign(new Error("Cursor API key not found. Set Providers[].api_key to a crsr_ key, or export CURSOR_API_KEY."),{statusCode:401,code:"provider_response_error",type:"api_error"})}import{createHash as D2}from"crypto";import{homedir as O2}from"os";import{basename as P2,dirname as I2,join as hx}from"path";var m_="cursor-sdk",sf="bridge",F2=hx(O2(),".claude-code-router"),zn=hx(F2,"cursor-sdk-workspaces"),gx=900*1e3,y_=32,mx=1440*60*1e3,yx=3600*1e3,N2=/^[0-9a-f]{32}$/;function __(t,e=zn){let n=t.replace(/[\\/]+$/,"");return I2(n)!==e.replace(/[\\/]+$/,"")?!1:N2.test(P2(n))}var _x=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],xa="custom-user-tools";function dn(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):"").filter(Boolean).join(`
383
+ `):String(t)}function ri(t){return D2("sha256").update(t.filter(Boolean).join(`
384
+ `)).digest("hex").slice(0,32)}function oi(t){if(typeof t=="string")return t;if(t==null)return"";if(typeof t=="object"){let e=t;if(typeof e.text=="string")return e.text;if(typeof e.content=="string")return e.content;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function b_(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function bx(t,e){let n=Math.floor(Date.now()/1e3),r=`chatcmpl-cursor-${Date.now()}`,o=()=>({id:r,object:"chat.completion.chunk",created:n,model:t});return{setId(s){s&&(r=s)},content(s){return{...o(),choices:[{index:0,delta:{role:"assistant",content:s},finish_reason:null}]}},thinking(s){return{...o(),choices:[{index:0,delta:{thinking:{content:oi(s)}},finish_reason:null}]}},thinkingSignature(s=`ccr_cursor_${Date.now()}`){return{...o(),choices:[{index:0,delta:{thinking:{signature:s}},finish_reason:null}]}},toolCall(s,i=0){return{...o(),choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:i,id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}]},finish_reason:null}]}},finish(s,i){let a=Number(i?.prompt_tokens)||0,u=Number(i?.completion_tokens)||0,d=Number(i?.total_tokens)||a+u;return{...o(),choices:[{index:0,delta:{},finish_reason:s}],usage:{prompt_tokens:a,completion_tokens:u,total_tokens:d,prompt_tokens_details:{cached_tokens:Number(i?.prompt_tokens_details?.cached_tokens)||0}}}},encode(s){return ve(JSON.stringify(s),e)},encodeDone(){return ve("[DONE]",e)}}}function C_(t,e){let n="",r="",o="",s=[],i="stop",a=null,u=`chatcmpl-cursor-${Date.now()}`,d=Math.floor(Date.now()/1e3);for(let p of e){typeof p.id=="string"&&(u=p.id);let h=p.choices?.[0];if(!h)continue;h.finish_reason&&(i=h.finish_reason);let g=h.delta||{};if(typeof g.content=="string"&&(n+=g.content),g.thinking?.content&&(r+=oi(g.thinking.content)),typeof g.thinking?.signature=="string"&&g.thinking.signature&&(o=g.thinking.signature),Array.isArray(g.tool_calls))for(let b of g.tool_calls){let m=b.index??s.length;s[m]||(s[m]={id:b.id,type:"function",function:{name:b.function?.name||"",arguments:""}}),b.id&&(s[m].id=b.id),b.function?.name&&(s[m].function.name=b.function.name),typeof b.function?.arguments=="string"&&(s[m].function.arguments+=b.function.arguments)}p.usage&&(a=p.usage)}let f={role:"assistant",content:n||null};return r&&(f.thinking={content:r,signature:o||`ccr_cursor_${d}`}),s.length&&(f.tool_calls=s.filter(Boolean),i="tool_calls"),{id:u,object:"chat.completion",created:d,model:t,choices:[{index:0,message:f,finish_reason:i}],usage:a}}var to={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},Cx=/<(env|environment|system-info|system_info)>([\s\S]*?)<\/\1>/gi,M2=/^\s*[-*]?\s*([A-Za-z][A-Za-z0-9 _/'-]{2,48}?)\s*:\s*(\S.*?)\s*$/,B2=/working director|workspace root|project root|platform|os version|operating system|git repo/i,wx=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],kx=[/^additional working director/i,/^additional director/i,/^extra working director/i],Sx=[/^platform$/i,/^operating system$/i,/^os$/i],Ax=[/^os version$/i,/^system version$/i],j2=[...wx,...kx,...Sx,...Ax],U2=2e5,L2=16,$2=400;function q2(t){let e=[],n=U2,r=!1;for(let o of t.messages||[]){if(o.role!=="system"&&o.role!=="user")continue;if(o.role==="user"&&r)break;o.role==="user"&&(r=!0);let s=dn(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
385
+ `)}function H2(t){let e=[],n=new Set,r=i=>{if(e.length>=L2)return;let a=i.match(M2);if(!a)return;let u=a[1].trim(),d=a[2].trim().slice(0,$2);if(!u||!d)return;let f=u.toLowerCase();n.has(f)||(n.add(f),e.push({key:u,value:d}))},o=!1;Cx.lastIndex=0;let s;for(;s=Cx.exec(t);){o=!0;for(let i of s[2].split(/\r?\n/))r(i)}if(!o)for(let i of t.split(/\r?\n/))B2.test(i)&&r(i);return e}function af(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function Ex(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function z2(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>Ex(e)):[]}function Ra(t){let e=H2(q2(t)),n=af(e,wx),r=n&&Ex(n)?n:void 0,o=z2(af(e,kx)).filter(u=>u!==r),s=af(e,Sx),i=af(e,Ax),a=!!(r||s||i||e.length);return a?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:a,fingerprint:ri([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:to}function vx(t){let e=[];t.projectRoot&&e.push(`- Project root: ${t.projectRoot}`);for(let n of t.additionalRoots)e.push(`- Additional in-scope root: ${n}`);t.platform&&e.push(`- Platform: ${t.platform}`),t.osVersion&&e.push(`- OS version: ${t.osVersion}`);for(let n of t.facts)j2.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function Bo(t){return t.projectRoot?`Every path you pass to a host tool must be an absolute path on the host, normally under ${t.projectRoot}.`:"Every path you pass to a host tool must be an absolute host path taken from this conversation \u2014 never invent one and never derive one from your local filesystem."}function W2(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)if(!(!n||typeof n!="object")&&n.type==="image_url"&&n.image_url?.url){let r=String(n.image_url.url),o=r.match(/^data:([^;]+);base64,(.+)$/);o?e.push({data:o[2],mimeType:o[1]}):e.push({url:r})}return e}function G2(t){return!Array.isArray(t.tools)||t.tools.length===0?"(no host tools advertised on this request)":t.tools.map(e=>{let n=e.function?.name||"unknown",r=e.function?.description||"";return`- ${n}: ${r}`}).join(`
386
+ `)}function xx(t,e){let n=["You are a remote reasoning agent driving Claude Code (the host).","Tools do not run where you are running: every tool call is executed by the host on the user's machine, and only the result is sent back to you.",`Your local environment is disposable scratch space: ${t}`,"It is empty and contains none of the user's files. Never read, list, search, or verify paths against it, and never prefix a host tool path with it.","Your own cwd, OS, and workspace root describe that scratch container only \u2014 they say nothing about the user's project, so never reason from them or report them to the user."],r=vx(e);return r.length&&(n.push("The user's project lives on the host machine, which is where every tool call lands:"),n.push(...r)),n.push(Bo(e)),n.push(`Host tools are exposed via MCP server "${xa}" using bare tool names.`,"Cursor built-in tools are denied here. That denial only routes tool use through the host \u2014 it is not a restriction on the user's project, which stays fully reachable through the host tools."),n}function J2(t,e,n=Ra(t)){return[...xx(e,n),"A progress update such as 'Checking...', 'Inspecting...', or 'Let me look...' is not a final answer.","After progress narration, call a host tool in the same turn; if no tool is needed, provide the complete user-facing answer before finishing.","Never end a turn with progress narration alone.","Available host tools:",G2(t)].join(`
387
+ `)}function K2(t,e){return["[bridge reminder]",`Tools run on the host machine, not here. ${t} is empty scratch space \u2014 never treat it as the project, and never build a tool path from it.`,Bo(e)].join(`
388
+ `)}function Rx(t,e){return["# Agent rules","",...xx(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
389
+ `)}function Dx(t){return["Your local filesystem is empty scratch space on a different machine from the user's project.","The project is reachable only through the host tools, and it is not restricted.",Bo(t)].join(" ")}var V2=[/^(?:checking|inspecting|reviewing|examining|investigating|verifying|reading|searching)\s+(?:the|this|that|these|those|your|our|which|whether|for|how|why|what|where)\b/i,/^looking\s+(?:at|into|for|through|up)\b/i,/^(?:i(?:'ll| will)|let me)\s+(?:check|inspect|review|examine|investigate|verify|read|search|look)\b/i];function Y2(t){let e=String(t||"").trim();if(!e||e.length>240||/\n\s*\n/.test(e))return!1;let n=e.replace(/\s+/g," ");return(n.match(/[.!?](?:\s|$)/g)?.length||0)>1?!1:V2.some(o=>o.test(n))}function Ox(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&Y2(t.assistantText)}function Px(t){let e=["Continue the same turn now.","Your previous assistant message was only progress narration and ended without a host tool call or a complete answer.","Do not repeat the progress update.","If evidence is still needed, call an available host tool immediately; otherwise provide the complete user-facing answer now.","Do not finish until the requested work or answer is complete."];return t?.known&&e.push(Bo(t)),{text:e.join(" ")}}function Tx(t){let e=t.trim();return $h.some(n=>e===n)}function X2(t){if(!Array.isArray(t)){let e=dn(t);return e.trim().length>0&&!Tx(e)}return t.some(e=>{if(!e||typeof e!="object")return!1;if("text"in e){let n=String(e.text||"");return n.trim().length>0&&!Tx(n)}return!0})}function Ix(t,e){let n=t.messages||[],r=[],o=e.hostEnv||Ra(t);e.mode==="bridge"?(r.push(J2(t,e.workspaceDir,o)),r.push("")):e.mode==="plan"&&(r.push("You are a planning/chat assistant. Respond with text and reasoning only. Do not execute tools."),r.push(""));let s=n.filter(f=>f.role==="system");for(let f of s){let p=dn(f.content);p&&r.push(`[system]
390
+ ${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,Q2(i,e.turnIntent)+1)):i,u=[];for(let f of a){if(f.role==="assistant"){let p=dn(f.content);if(p&&r.push(`[assistant]
391
391
  ${p}`),Array.isArray(f.tool_calls)&&f.tool_calls.length)for(let h of f.tool_calls)r.push(`[assistant tool_call id=${h.id} name=${h.function.name}]
392
392
  ${h.function.arguments||"{}"}`);continue}if(f.role==="tool"){r.push(`[tool_result id=${f.tool_call_id||"unknown"}]
393
- ${dn(f.content)}`);continue}if(f.role==="user"){let p=dn(f.content);u=[...u,...q2(f.content)],p&&r.push(`[user]
394
- ${p}`)}}e.mode==="bridge"&&r.push(W2(e.workspaceDir,o));let d=r.join(`
393
+ ${dn(f.content)}`);continue}if(f.role==="user"){let p=dn(f.content);u=[...u,...W2(f.content)],p&&r.push(`[user]
394
+ ${p}`)}}e.mode==="bridge"&&r.push(K2(e.workspaceDir,o));let d=r.join(`
395
395
 
396
- `).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function V2(t,e){let n=t.length-1,r=0;e?.interruption==="synthetic_client_interrupt"&&e.steering==="none"&&t[n]?.role==="user"&&(r=1,n-=1);let o=0;for(;n>=0;n--){if(t[n].role==="tool"){o+=1;continue}break}return o>0?r+o:0}function Ix(t,e){if(e)return{toolResults:e.trailingToolResults.map(i=>({toolCallId:i.toolCallId,content:i.content,isError:i.isError})),hasTrailingUserInput:e.steering==="meaningful"};let n=[],r=t.messages||[],o=r.length-1,s=!1;for(;o>=0&&r[o].role==="user";)s=s||K2(r[o].content),o-=1;for(;o>=0;o--){let i=r[o];if(i.role!=="tool")break;n.unshift({toolCallId:String(i.tool_call_id||""),content:dn(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}import{createHash as k_}from"crypto";import{existsSync as Ux,mkdirSync as Fx,readdirSync as n$,rmSync as r$,statSync as o$}from"fs";import{join as jx}from"path";import{Agent as Nx}from"@cursor/sdk";import{chmodSync as Y2,mkdirSync as X2,readFileSync as Q2,writeFileSync as Z2}from"fs";import{join as Da}from"path";function e$(t){return`#!/usr/bin/env node
396
+ `).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function Q2(t,e){let n=t.length-1,r=0;e?.interruption==="synthetic_client_interrupt"&&e.steering==="none"&&t[n]?.role==="user"&&(r=1,n-=1);let o=0;for(;n>=0;n--){if(t[n].role==="tool"){o+=1;continue}break}return o>0?r+o:0}function Fx(t,e){if(e)return{toolResults:e.trailingToolResults.map(i=>({toolCallId:i.toolCallId,content:i.content,isError:i.isError})),hasTrailingUserInput:e.steering==="meaningful"};let n=[],r=t.messages||[],o=r.length-1,s=!1;for(;o>=0&&r[o].role==="user";)s=s||X2(r[o].content),o-=1;for(;o>=0;o--){let i=r[o];if(i.role!=="tool")break;n.unshift({toolCallId:String(i.tool_call_id||""),content:dn(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}import{createHash as k_}from"crypto";import{existsSync as Ux,mkdirSync as Nx,readdirSync as s$,rmSync as i$,statSync as a$}from"fs";import{join as Lx}from"path";import{Agent as Mx}from"@cursor/sdk";import{chmodSync as Z2,mkdirSync as e$,readFileSync as t$,writeFileSync as n$}from"fs";import{join as Da}from"path";function r$(t){return`#!/usr/bin/env node
397
397
  const chunks = [];
398
398
  process.stdin.on("data", (c) => chunks.push(c));
399
399
  process.stdin.on("end", () => {
@@ -432,17 +432,17 @@ process.stdin.on("end", () => {
432
432
  })
433
433
  );
434
434
  });
435
- `}function t$(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${xa}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,Rx(t)].join(" ")}function w_(t,e,n){try{if(Q2(t,"utf-8")===e)return}catch{}Z2(t,e,{encoding:"utf-8",mode:n})}function Oa(t,e=to){let n=Da(t,".cursor"),r=Da(n,"hooks");X2(r,{recursive:!0});let o=Da(r,"deny-builtin.cjs");w_(o,e$(t$(e)),448);try{Y2(o,448)}catch{}let s=yx.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};w_(Da(n,"hooks.json"),JSON.stringify(a,null,2),384),w_(Da(t,"AGENTS.md"),xx(t,e),384)}var s$=2e3;function i$(t){let e=t;return e?.name==="AbortError"||String(e?.message||t).toLowerCase()==="this operation was aborted"}function si(t,e){t.poisoned=!0,t.poisonReason=e}async function A_(t,e={}){let n={skipped:!1,hadRun:!!t.run,hadIterator:!!t.streamIterator,runCancelFailed:!1,iteratorReturnFailed:!1,failed:!1,timedOut:!1};if(e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken)return{...n,skipped:!0};let r=t.run,o=t.streamIterator,s=t.streamNext;if(t.run=void 0,t.streamIterator=void 0,t.streamNext=void 0,t.streamNextRunToken=void 0,t.activeRunToken=void 0,t.pendingEmit=[],t.pendingSdkMessages=[],t.notifyEmit(),t.notifySdkMessage?.(),s?.catch(()=>{}),e.rejectParked&&t.parked.length){let u=e.reason||"cursor-sdk run cancelled";for(let d of t.parked.splice(0,t.parked.length))try{d.reject(new Error(u))}catch{}}let i=async(u,d,f)=>{try{await lf(Promise.resolve().then(u),e.timeoutMs??2e3,d)}catch(p){n.failed=!0,f==="run"&&(n.runCancelFailed=!0),f==="iterator"&&(n.iteratorReturnFailed=!0),n.timedOut=n.timedOut||String(p?.message||p).toLowerCase().includes("timed out")}},a=[];return r?.status==="running"&&a.push(i(()=>r.cancel(),"cursor-sdk run cancel timed out","run")),o&&typeof o.return=="function"&&a.push(i(()=>o.return(void 0),"cursor-sdk stream iterator return timed out","iterator")),await Promise.all(a),n.failed&&e.poisonOnFailure&&si(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function lf(t,e,n){let r;try{return await Promise.race([t,new Promise((o,s)=>{r=setTimeout(()=>s(new Error(n)),e)})])}finally{r&&clearTimeout(r)}}async function df(t,e){let n=t.sendChain,r,o=new Promise(s=>{r=s});t.sendChain=n.then(()=>o).catch(()=>o),await n.catch(()=>{});try{return await e()}finally{r()}}function Pa(t){if(t===!1)return!1;let e=process.env.CCR_CURSOR_SANDBOX?.trim().toLowerCase();return!(e==="0"||e==="false"||e==="off"||!(t===!0||e==="1"||e==="true"||e==="on")||Ux("/.dockerenv")||process.env.container==="docker")}function a$(t,e){Ux(zn)||Fx(zn,{recursive:!0});let n=jx(zn,t);return Fx(n,{recursive:!0}),Oa(n,e),n}function E_(t,e){if(!e.known&&t.hostEnv?.known)return!1;let n=t.guidanceFingerprint!==e.fingerprint;if(t.hostEnv=e,t.mode!=="bridge"||!n)return!1;try{return Oa(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function Mx(t,e,n=zn){if(!__(t,n))return!1;try{return r$(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function Lx(t){if(t.headerSession)return k_("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?k_("sha256").update(e[1]).digest("hex").slice(0,32):k_("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return ri([t.model||"",t.systemAndFirstUser||""])}function Bx(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function uf(t){t.lastActiveAt=Date.now()}var S_=class{constructor(e){this.logger=e;this.cleanupTimer=setInterval(()=>this.evictIdle(),6e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}logger;sessions=new Map;retirements=new Map;creations=new Map;cleanupTimer;lastSweepAt=0;setLogger(e){this.logger=e}get(e){let n=this.sessions.get(e);if(n?.poisoned){let r=n.poisonReason||"cursor-sdk session poisoned";this.retireSession(n,r,async()=>(await this.invalidate(n,r),!0)).catch(o=>{this.logger?.warn?.({err:o,sessionKey:n.key,agentId:n.agentId,reason:r},"cursor-sdk poisoned session retirement failed")});return}return n&&uf(n),n}async retireSession(e,n,r){si(e,n),this.sessions.get(e.key)===e&&this.sessions.delete(e.key);let o=this.retirements.get(e.key);o||(o={tail:Promise.resolve(),pending:new Map},this.retirements.set(e.key,o));let s=o.pending.get(e);if(s)return await s.catch(()=>{}),!1;let i=o.pending.size>0,a=o.tail,u=async()=>(this.logger?.debug?.({sessionKey:e.key,agentId:e.agentId,reason:n},"cursor-sdk session retirement started"),r()),d=i?a.then(u):u();o.pending.set(e,d);let f=d.then(()=>{},()=>{});o.tail=f;try{return await d}finally{o.pending.get(e)===d&&o.pending.delete(e),this.retirements.get(e.key)===o&&o.tail===f&&o.pending.size===0&&this.retirements.delete(e.key)}}async getOrCreate(e){for(;;){let o=this.retirements.get(e.key);if(o){await o.tail;continue}let s=this.get(e.key);if(s)return s;let i=this.retirements.get(e.key);if(i){await i.tail;continue}let a=this.creations.get(e.key);if(!a)break;await a}let n,r=new Promise(o=>{n=o});this.creations.set(e.key,r);try{this.evictIfNeeded();let o=e.hostEnv||to,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:a$(e.key,o);e.mode==="bridge"&&Oa(s,o);let i=e.mode==="plan"?"plan":"agent",a=Pa(e.sandboxEnabled),u=await Nx.create({apiKey:e.apiKey,model:e.model,name:`ccr-${e.key.slice(0,8)}`,mode:i,local:{cwd:s,settingSources:[],sandboxOptions:{enabled:a},enableAgentRetries:!0}}),d=this.createSessionRecord({key:e.key,agent:u,mode:e.mode,workspaceDir:s,hostEnv:o,guidanceFingerprint:o.fingerprint});return this.sessions.set(e.key,d),this.logger?.info?.({sessionKey:e.key,agentId:u.agentId,mode:e.mode,sandboxEnabled:a},"cursor-sdk session created"),d}finally{this.creations.get(e.key)===r&&this.creations.delete(e.key),n()}}async resume(e){let n=Pa(e.sandboxEnabled),r=e.hostEnv||to;e.mode==="bridge"&&Oa(e.workspaceDir,r);let o=await Nx.resume(e.agentId,{apiKey:e.apiKey,model:e.model,local:{cwd:e.workspaceDir,settingSources:[],sandboxOptions:{enabled:n}}}),s=this.createSessionRecord({key:e.key,agent:o,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:r,guidanceFingerprint:r.fingerprint});return this.sessions.set(e.key,s),s}resolveParkedTools(e,n){let r=0,o=[],s=e.parked.map(i=>i.id).filter((i,a,u)=>i&&u.indexOf(i)!==a);s.length&&this.logger?.warn?.({sessionKey:e.key,duplicates:[...new Set(s)]},"cursor-sdk parked tools share an id; results may mispair");for(let i of n){let a=-1;if(i.toolCallId?a=e.parked.findIndex(d=>d.id===i.toolCallId):n.length===1&&e.parked.length===1&&(a=0),a===-1){o.push(i.toolCallId||"(empty)");continue}let[u]=e.parked.splice(a,1);u.resolve(i.content),r++}return o.length&&this.logger?.warn?.({unmatched:o,parkedRemaining:e.parked.map(i=>i.id),resolved:r},"cursor-sdk tool results did not match parked tools"),uf(e),r}async dispose(e){let n=this.sessions.get(e);if(!n)return;let r="cursor-sdk session disposed";await this.retireSession(n,r,async()=>(await A_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),Mx(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(si(r,n),r.run=void 0,r.streamIterator=void 0,r.streamNext?.catch(()=>{}),r.streamNext=void 0,r.streamNextRunToken=void 0,r.activeRunToken=void 0,r.pendingEmit=[],r.pendingSdkMessages=[],r.parked.length)for(let o of r.parked.splice(0,r.parked.length))try{o.reject(new Error(n))}catch{}return r.notifyEmit(),r.notifySdkMessage(),this.sessions.get(r.key)===r&&this.sessions.delete(r.key),this.logger?.warn?.({sessionKey:r.key,agentId:r.agentId,reason:n},"cursor-sdk session invalidated"),this.disposeAgent(r,n)}async disposeAgent(e,n){try{let r=e.agent[Symbol.asyncDispose]();r.catch(()=>{}),await lf(r,s$,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};i$(r)?this.logger?.debug?.(o,"cursor-sdk agent disposal observed expected cancellation"):this.logger?.warn?.(o,"cursor-sdk agent disposal failed")}}createSessionRecord(e){let n={key:e.key,agent:e.agent,agentId:e.agent.agentId,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:e.hostEnv,parked:[],pendingEmit:[],emitWaiters:[],pendingSdkMessages:[],sdkMessageWaiters:[],sendChain:Promise.resolve(),hasSentPrompt:!1,guidanceFingerprint:e.guidanceFingerprint,lastActiveAt:Date.now(),metrics:{customToolCalls:0,builtinToolCallsSeen:0,scratchPathViolations:0,scratchPathCorrections:0},parkHostTool:({id:r,name:o,args:s})=>{let i,a,u=new Promise((f,p)=>{i=f,a=p}),d=n.activeRunToken;return n.parked.push({id:r,name:o,args:s,runToken:d,resolve:i,reject:a,promise:u}),n.pendingEmit.push({id:r,name:o,args:s,runToken:d}),n.notifyEmit(),u},notifyEmit:()=>{let r=n.emitWaiters.splice(0,n.emitWaiters.length);for(let o of r)o()},waitForEmit:()=>new Promise(r=>{if(n.pendingEmit.length){r();return}n.emitWaiters.push(r)}),enqueueSdkMessage:(r,o=n.activeRunToken)=>{n.pendingSdkMessages.push({message:r,runToken:o,source:"delta"}),n.notifySdkMessage()},notifySdkMessage:()=>{let r=n.sdkMessageWaiters.splice(0,n.sdkMessageWaiters.length);for(let o of r)o()},waitForSdkMessage:()=>new Promise(r=>{if(n.pendingSdkMessages.length){r();return}n.sdkMessageWaiters.push(r)})};return n}evictIfNeeded(){for(;this.sessions.size>=y_;){let e,n=1/0;for(let[r,o]of this.sessions)Bx(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:y_},"cursor-sdk session capacity reached with all sessions in-flight; deferring eviction");break}this.dispose(e)}}evictIdle(){let e=Date.now();for(let[n,r]of this.sessions)Bx(r)||e-r.lastActiveAt>hx&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=zn){if(e-this.lastSweepAt<mx)return 0;this.lastSweepAt=e;let r;try{r=n$(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=jx(n,i);if(!(o.has(a)||!__(a,n))){try{let u=o$(a);if(!u.isDirectory()||e-u.mtimeMs<=gx)continue}catch{continue}Mx(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},no=new S_;var c$="Cursor SDK agent.send timed out";function v_(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentBusyError"||e.status===409||r.includes("already has active run")||r.includes("agent busy")}function T_(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentNotFoundError"||n==="NetworkError"||e.status===503||e.status===504||r.includes("agent not found")||r.includes("request aborted before send")||r.includes("request aborted during send")||r.includes("agent.send timed out")||r.includes("network error")||r.includes("network request failed")||r.includes("network timeout")||r.includes("network connection")}function u$(t){if(!t)return;let e;return{promise:new Promise((r,o)=>{if(t.aborted){o(new Error("cursor-sdk request aborted before send"));return}e=()=>o(new Error("cursor-sdk request aborted during send")),t.addEventListener("abort",e,{once:!0})}),cleanup:()=>{e&&t.removeEventListener("abort",e)}}}async function l$(t,e,n,r){let o,s;try{if(r?.aborted)throw new Error("cursor-sdk request aborted before send");return o=t.agent.send(e,n),s=u$(r),await lf(s?Promise.race([o,s.promise]):o,15e3,c$)}catch(i){throw o&&o.then(a=>a.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function x_(t,e,n,r={}){return l$(t,e,n,r.abortSignal)}import{randomUUID as m$}from"crypto";var d$=6,f$=512,p$=4;function h$(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function g$(t,e){return t.length<8?!1:t.includes(e)||t.includes(zn)}function $x(t,e){let n=[],r=0,o=(s,i,a)=>{if(!(n.length>=p$||r>=f$||a>d$)){if(r++,typeof s=="string"){g$(s,e)&&n.push({argPath:i||"(argument)",value:h$(s)});return}if(Array.isArray(s)){s.forEach((u,d)=>o(u,`${i}.${d}`,a+1));return}if(s&&typeof s=="object")for(let[u,d]of Object.entries(s))o(d,i?`${i}.${u}`:u,a+1)}};return o(t,"",0),n}function qx(t){return t.projectRoot?!t.projectRoot.startsWith(zn):!0}function Hx(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
435
+ `}function o$(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${xa}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,Dx(t)].join(" ")}function w_(t,e,n){try{if(t$(t,"utf-8")===e)return}catch{}n$(t,e,{encoding:"utf-8",mode:n})}function Oa(t,e=to){let n=Da(t,".cursor"),r=Da(n,"hooks");e$(r,{recursive:!0});let o=Da(r,"deny-builtin.cjs");w_(o,r$(o$(e)),448);try{Z2(o,448)}catch{}let s=_x.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};w_(Da(n,"hooks.json"),JSON.stringify(a,null,2),384),w_(Da(t,"AGENTS.md"),Rx(t,e),384)}var c$=2e3;function u$(t){let e=t;return e?.name==="AbortError"||String(e?.message||t).toLowerCase()==="this operation was aborted"}function si(t,e){t.poisoned=!0,t.poisonReason=e}async function A_(t,e={}){let n={skipped:!1,hadRun:!!t.run,hadIterator:!!t.streamIterator,runCancelFailed:!1,iteratorReturnFailed:!1,failed:!1,timedOut:!1};if(e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken)return{...n,skipped:!0};let r=t.run,o=t.streamIterator,s=t.streamNext;if(t.run=void 0,t.streamIterator=void 0,t.streamNext=void 0,t.streamNextRunToken=void 0,t.activeRunToken=void 0,t.pendingEmit=[],t.pendingSdkMessages=[],t.notifyEmit(),t.notifySdkMessage?.(),s?.catch(()=>{}),e.rejectParked&&t.parked.length){let u=e.reason||"cursor-sdk run cancelled";for(let d of t.parked.splice(0,t.parked.length))try{d.reject(new Error(u))}catch{}}let i=async(u,d,f)=>{try{await uf(Promise.resolve().then(u),e.timeoutMs??2e3,d)}catch(p){n.failed=!0,f==="run"&&(n.runCancelFailed=!0),f==="iterator"&&(n.iteratorReturnFailed=!0),n.timedOut=n.timedOut||String(p?.message||p).toLowerCase().includes("timed out")}},a=[];return r?.status==="running"&&a.push(i(()=>r.cancel(),"cursor-sdk run cancel timed out","run")),o&&typeof o.return=="function"&&a.push(i(()=>o.return(void 0),"cursor-sdk stream iterator return timed out","iterator")),await Promise.all(a),n.failed&&e.poisonOnFailure&&si(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function uf(t,e,n){let r;try{return await Promise.race([t,new Promise((o,s)=>{r=setTimeout(()=>s(new Error(n)),e)})])}finally{r&&clearTimeout(r)}}async function lf(t,e){let n=t.sendChain,r,o=new Promise(s=>{r=s});t.sendChain=n.then(()=>o).catch(()=>o),await n.catch(()=>{});try{return await e()}finally{r()}}function Pa(t){if(t===!1)return!1;let e=process.env.CCR_CURSOR_SANDBOX?.trim().toLowerCase();return!(e==="0"||e==="false"||e==="off"||!(t===!0||e==="1"||e==="true"||e==="on")||Ux("/.dockerenv")||process.env.container==="docker")}function l$(t,e){Ux(zn)||Nx(zn,{recursive:!0});let n=Lx(zn,t);return Nx(n,{recursive:!0}),Oa(n,e),n}function E_(t,e){if(!e.known&&t.hostEnv?.known)return!1;let n=t.guidanceFingerprint!==e.fingerprint;if(t.hostEnv=e,t.mode!=="bridge"||!n)return!1;try{return Oa(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function Bx(t,e,n=zn){if(!__(t,n))return!1;try{return i$(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function $x(t){if(t.headerSession)return k_("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?k_("sha256").update(e[1]).digest("hex").slice(0,32):k_("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return ri([t.model||"",t.systemAndFirstUser||""])}function jx(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function cf(t){t.lastActiveAt=Date.now()}var S_=class{constructor(e){this.logger=e;this.cleanupTimer=setInterval(()=>this.evictIdle(),6e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}logger;sessions=new Map;retirements=new Map;creations=new Map;cleanupTimer;lastSweepAt=0;setLogger(e){this.logger=e}get(e){let n=this.sessions.get(e);if(n?.poisoned){let r=n.poisonReason||"cursor-sdk session poisoned";this.retireSession(n,r,async()=>(await this.invalidate(n,r),!0)).catch(o=>{this.logger?.warn?.({err:o,sessionKey:n.key,agentId:n.agentId,reason:r},"cursor-sdk poisoned session retirement failed")});return}return n&&cf(n),n}async retireSession(e,n,r){si(e,n),this.sessions.get(e.key)===e&&this.sessions.delete(e.key);let o=this.retirements.get(e.key);o||(o={tail:Promise.resolve(),pending:new Map},this.retirements.set(e.key,o));let s=o.pending.get(e);if(s)return await s.catch(()=>{}),!1;let i=o.pending.size>0,a=o.tail,u=async()=>(this.logger?.debug?.({sessionKey:e.key,agentId:e.agentId,reason:n},"cursor-sdk session retirement started"),r()),d=i?a.then(u):u();o.pending.set(e,d);let f=d.then(()=>{},()=>{});o.tail=f;try{return await d}finally{o.pending.get(e)===d&&o.pending.delete(e),this.retirements.get(e.key)===o&&o.tail===f&&o.pending.size===0&&this.retirements.delete(e.key)}}async getOrCreate(e){for(;;){let o=this.retirements.get(e.key);if(o){await o.tail;continue}let s=this.get(e.key);if(s)return s;let i=this.retirements.get(e.key);if(i){await i.tail;continue}let a=this.creations.get(e.key);if(!a)break;await a}let n,r=new Promise(o=>{n=o});this.creations.set(e.key,r);try{this.evictIfNeeded();let o=e.hostEnv||to,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:l$(e.key,o);e.mode==="bridge"&&Oa(s,o);let i=e.mode==="plan"?"plan":"agent",a=Pa(e.sandboxEnabled),u=await Mx.create({apiKey:e.apiKey,model:e.model,name:`ccr-${e.key.slice(0,8)}`,mode:i,local:{cwd:s,settingSources:[],sandboxOptions:{enabled:a},enableAgentRetries:!0}}),d=this.createSessionRecord({key:e.key,agent:u,mode:e.mode,workspaceDir:s,hostEnv:o,guidanceFingerprint:o.fingerprint});return this.sessions.set(e.key,d),this.logger?.info?.({sessionKey:e.key,agentId:u.agentId,mode:e.mode,sandboxEnabled:a},"cursor-sdk session created"),d}finally{this.creations.get(e.key)===r&&this.creations.delete(e.key),n()}}async resume(e){let n=Pa(e.sandboxEnabled),r=e.hostEnv||to;e.mode==="bridge"&&Oa(e.workspaceDir,r);let o=await Mx.resume(e.agentId,{apiKey:e.apiKey,model:e.model,local:{cwd:e.workspaceDir,settingSources:[],sandboxOptions:{enabled:n}}}),s=this.createSessionRecord({key:e.key,agent:o,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:r,guidanceFingerprint:r.fingerprint});return this.sessions.set(e.key,s),s}resolveParkedTools(e,n){let r=0,o=[],s=e.parked.map(i=>i.id).filter((i,a,u)=>i&&u.indexOf(i)!==a);s.length&&this.logger?.warn?.({sessionKey:e.key,duplicates:[...new Set(s)]},"cursor-sdk parked tools share an id; results may mispair");for(let i of n){let a=-1;if(i.toolCallId?a=e.parked.findIndex(d=>d.id===i.toolCallId):n.length===1&&e.parked.length===1&&(a=0),a===-1){o.push(i.toolCallId||"(empty)");continue}let[u]=e.parked.splice(a,1);u.resolve(i.content),r++}return o.length&&this.logger?.warn?.({unmatched:o,parkedRemaining:e.parked.map(i=>i.id),resolved:r},"cursor-sdk tool results did not match parked tools"),cf(e),r}async dispose(e){let n=this.sessions.get(e);if(!n)return;let r="cursor-sdk session disposed";await this.retireSession(n,r,async()=>(await A_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),Bx(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(si(r,n),r.run=void 0,r.streamIterator=void 0,r.streamNext?.catch(()=>{}),r.streamNext=void 0,r.streamNextRunToken=void 0,r.activeRunToken=void 0,r.pendingEmit=[],r.pendingSdkMessages=[],r.parked.length)for(let o of r.parked.splice(0,r.parked.length))try{o.reject(new Error(n))}catch{}return r.notifyEmit(),r.notifySdkMessage(),this.sessions.get(r.key)===r&&this.sessions.delete(r.key),this.logger?.warn?.({sessionKey:r.key,agentId:r.agentId,reason:n},"cursor-sdk session invalidated"),this.disposeAgent(r,n)}async disposeAgent(e,n){try{let r=e.agent[Symbol.asyncDispose]();r.catch(()=>{}),await uf(r,c$,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};u$(r)?this.logger?.debug?.(o,"cursor-sdk agent disposal observed expected cancellation"):this.logger?.warn?.(o,"cursor-sdk agent disposal failed")}}createSessionRecord(e){let n={key:e.key,agent:e.agent,agentId:e.agent.agentId,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:e.hostEnv,parked:[],pendingEmit:[],emitWaiters:[],pendingSdkMessages:[],sdkMessageWaiters:[],sendChain:Promise.resolve(),hasSentPrompt:!1,guidanceFingerprint:e.guidanceFingerprint,lastActiveAt:Date.now(),metrics:{customToolCalls:0,builtinToolCallsSeen:0,scratchPathViolations:0,scratchPathCorrections:0},parkHostTool:({id:r,name:o,args:s})=>{let i,a,u=new Promise((f,p)=>{i=f,a=p}),d=n.activeRunToken;return n.parked.push({id:r,name:o,args:s,runToken:d,resolve:i,reject:a,promise:u}),n.pendingEmit.push({id:r,name:o,args:s,runToken:d}),n.notifyEmit(),u},notifyEmit:()=>{let r=n.emitWaiters.splice(0,n.emitWaiters.length);for(let o of r)o()},waitForEmit:()=>new Promise(r=>{if(n.pendingEmit.length){r();return}n.emitWaiters.push(r)}),enqueueSdkMessage:(r,o=n.activeRunToken)=>{n.pendingSdkMessages.push({message:r,runToken:o,source:"delta"}),n.notifySdkMessage()},notifySdkMessage:()=>{let r=n.sdkMessageWaiters.splice(0,n.sdkMessageWaiters.length);for(let o of r)o()},waitForSdkMessage:()=>new Promise(r=>{if(n.pendingSdkMessages.length){r();return}n.sdkMessageWaiters.push(r)})};return n}evictIfNeeded(){for(;this.sessions.size>=y_;){let e,n=1/0;for(let[r,o]of this.sessions)jx(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:y_},"cursor-sdk session capacity reached with all sessions in-flight; deferring eviction");break}this.dispose(e)}}evictIdle(){let e=Date.now();for(let[n,r]of this.sessions)jx(r)||e-r.lastActiveAt>gx&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=zn){if(e-this.lastSweepAt<yx)return 0;this.lastSweepAt=e;let r;try{r=s$(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=Lx(n,i);if(!(o.has(a)||!__(a,n))){try{let u=a$(a);if(!u.isDirectory()||e-u.mtimeMs<=mx)continue}catch{continue}Bx(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},no=new S_;var d$="Cursor SDK agent.send timed out";function v_(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentBusyError"||e.status===409||r.includes("already has active run")||r.includes("agent busy")}function T_(t){let e=t||{},n=typeof e.name=="string"?e.name:"",r=(typeof e.message=="string"?e.message:String(t)).toLowerCase();return n==="AgentNotFoundError"||n==="NetworkError"||e.status===503||e.status===504||r.includes("agent not found")||r.includes("request aborted before send")||r.includes("request aborted during send")||r.includes("agent.send timed out")||r.includes("network error")||r.includes("network request failed")||r.includes("network timeout")||r.includes("network connection")}function f$(t){if(!t)return;let e;return{promise:new Promise((r,o)=>{if(t.aborted){o(new Error("cursor-sdk request aborted before send"));return}e=()=>o(new Error("cursor-sdk request aborted during send")),t.addEventListener("abort",e,{once:!0})}),cleanup:()=>{e&&t.removeEventListener("abort",e)}}}async function p$(t,e,n,r){let o,s;try{if(r?.aborted)throw new Error("cursor-sdk request aborted before send");return o=t.agent.send(e,n),s=f$(r),await uf(s?Promise.race([o,s.promise]):o,15e3,d$)}catch(i){throw o&&o.then(a=>a.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function x_(t,e,n,r={}){return p$(t,e,n,r.abortSignal)}import{randomUUID as b$}from"crypto";var h$=6,g$=512,m$=4;function y$(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function _$(t,e){return t.length<8?!1:t.includes(e)||t.includes(zn)}function qx(t,e){let n=[],r=0,o=(s,i,a)=>{if(!(n.length>=m$||r>=g$||a>h$)){if(r++,typeof s=="string"){_$(s,e)&&n.push({argPath:i||"(argument)",value:y$(s)});return}if(Array.isArray(s)){s.forEach((u,d)=>o(u,`${i}.${d}`,a+1));return}if(s&&typeof s=="object")for(let[u,d]of Object.entries(s))o(d,i?`${i}.${u}`:u,a+1)}};return o(t,"",0),n}function Hx(t){return t.projectRoot?!t.projectRoot.startsWith(zn):!0}function zx(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
436
436
  `);return[`Error: this ${e} call was not executed because it points at your local scratch container, not at the user's machine.`,"Offending arguments:",o,`${n} is disposable scratch space on the machine running the model bridge. It is empty and contains none of the user's files.`,"Host tools execute on the user's machine, where that path does not exist.",Bo(r),"Retry the call with a host path."].join(`
437
- `)}var y$=3;function _$(t){if(!t)return{type:"object",properties:{}};if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object")return e}catch{return{type:"object",properties:{}}}return typeof t=="object"?t:{type:"object",properties:{}}}function R_(){return{scratchViolations:0,scratchCorrections:0}}function zx(t,e,n,r=R_()){let o={};if(!Array.isArray(t.tools))return o;for(let s of t.tools){let i=s.function?.name;!i||typeof i!="string"||(o[i]={description:s.function.description||`Claude Code host tool: ${i}`,inputSchema:_$(s.function.parameters),async execute(a,u){let d=ur(u.toolCallId)||m$(),f=a||{},p=e.hostEnv||to,h=qx(p)?$x(f,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let g=e.metrics.scratchPathCorrections<y$;if(n?.warn?.({sessionKey:e.key,tool:i,hits:h,corrected:g,violations:e.metrics.scratchPathViolations},"cursor-sdk host tool call referenced the scratch workspace"),g)return e.metrics.scratchPathCorrections+=1,r.scratchCorrections+=1,Hx(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:d,name:i,args:f})}})}return o}function Gx(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function Wx(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function Jx(t){let e=[];t.system&&e.push(Wx(t.system));for(let n of t.messages||[])e.push(Wx(n.content)),n.thinking?.content&&e.push(String(n.thinking.content)),n.reasoning_content&&e.push(String(n.reasoning_content)),n.tool_calls?.length&&e.push(JSON.stringify(n.tool_calls));return t.tools?.length&&e.push(JSON.stringify(t.tools)),Gx(e.join(`
438
- `).length)}function Kx(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=Gx(e),s=Math.min(r,Math.max(0,Math.trunc(n)||0));return{prompt_tokens:r,completion_tokens:o,total_tokens:r+o,prompt_tokens_details:{cached_tokens:s}}}function ff(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Vx(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=ff(t.prompt_tokens),s=ff(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=ff(e?.prompt_tokens),a=ff(e?.prompt_tokens_details?.cached_tokens),u=o-i,d=s-a,f=u>0&&d>0?d/u:s/o,p=Math.min(1,Math.max(0,f));return Math.min(r,Math.floor(r*p))}function Yx(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,i=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:i}}}import{createHash as b$}from"crypto";var C$=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Wn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="bigint")return String(t);if(Array.isArray(t))return t.map(n=>Wn(n)).filter(n=>n!==void 0);if(typeof t!="object")return;let e={};for(let n of Object.keys(t).sort()){if(n==="cache_control")continue;let r=Wn(t[n]);r!==void 0&&(e[n]=r)}return e}function O_(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Wn(t);return e===void 0?[]:[e]}return t.map(e=>{if(typeof e=="string")return{text:e,type:"text"};if(!e||typeof e!="object")return Wn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Wn(n)}).filter(e=>e!==void 0)}function w$(t){if(typeof t!="string")return Wn(t)??null;try{return Wn(JSON.parse(t))??null}catch{return t}}function P_(t){let e=t,n={content:O_(e.content),role:e.role};return e.reasoning_content&&(n.reasoning_content=e.reasoning_content),e.thinking?.content&&(n.thinking={content:e.thinking.content}),e.tool_call_id&&(n.tool_call_id=e.tool_call_id),e.is_error!==void 0&&(n.is_error=e.is_error),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(n.tool_calls=e.tool_calls.map(r=>({function:{arguments:w$(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function Xx(t){return Array.isArray(t)?t.map(e=>Wn(e)).filter(e=>e!==void 0).sort((e,n)=>D_(e).localeCompare(D_(n))):[]}function D_(t){return JSON.stringify(t)}function I_(t){return b$("sha256").update(D_(t)).digest("hex")}function Qx(t){return{system:O_(t.system),messages:(t.messages||[]).map(P_)}}function k$(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(C$.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(P_):r==="system"?o=O_(t.system):r==="tools"?o=Xx(t.tools):o=Wn(e[r]),o!==void 0&&(n[r]=o)}return n}function Zx(t,e={}){return I_({compatibilityStamp:e.compatibilityStamp||"",request:k$(t),turnIntent:e.turnIntent?{interruption:e.turnIntent.interruption,source:e.turnIntent.source,steering:e.turnIntent.steering,trailingToolResults:e.turnIntent.trailingToolResults.map(n=>({content:n.content,isError:n.isError,toolCallId:n.toolCallId}))}:null})}function F_(t){return I_({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Wn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:Xx(t.tools),workspaceDir:t.workspaceDir})}function eR(t,e){return I_({messages:e,system:t})}function tR(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=Qx(t);return e&&n.messages.push(P_(e)),Object.freeze({transcriptHash:eR(n.system,n.messages),messageCount:n.messages.length})}function nR(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=Qx(e);if(!(n.messages.length<=t.messageCount)&&eR(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function S$(t,e){if(t.length===0||t.length!==e.length)return;let n=new Map;for(let s of e){let i=s.toolCallId;if(!i||n.has(i))return;n.set(i,s)}let r=new Set,o=[];for(let s of t){if(!s.id||r.has(s.id))return;r.add(s.id);let i=n.get(s.id);if(!i)return;o.push({parked:s,result:i})}return o}var kr=t=>({action:"retire-and-replay-full",reason:t});function rR(t){let{session:e,turn:n}=t;if(e.poisoned)return kr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:kr("inconsistent-unused-session");if(e.alignment==="unknown")return kr("unknown-context-alignment");if(e.alignment==="divergent")return kr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return kr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return kr("dead-parked-run");if(n.hasMeaningfulSteering)return kr("parked-turn-has-steering");let r=S$(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:kr("parked-tool-results-mismatch")}return n.toolResults.length>0?kr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function fn(t){let e=t instanceof Error?t.message:typeof t=="string"&&t?t:"Cursor turn subscriber aborted";return Object.assign(new Error(e),{name:"AbortError"})}async function N_(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var M_=class{constructor(e,n,r,o){this.sessionKey=e;this.fingerprint=n;this.responseKind=r;this.onTerminal=o;this.ready.catch(()=>{})}sessionKey;fingerprint;responseKind;onTerminal;abortController=new AbortController;phase="awaiting_response";responseMetadata;sourceReader;chunks=[];bufferedBytes=0;replayable=!0;readySettled=!1;completedAt;nextInterestId=1;nextSubscriberId=1;interests=new Set;subscribers=new Map;failure;readyResolve;readyReject;settledResolve;ready=new Promise((e,n)=>{this.readyResolve=e,this.readyReject=n});settled=new Promise(e=>{this.settledResolve=e});get canReplay(){return this.phase==="completed"&&this.replayable}get replayAgeMs(){return this.completedAt===void 0?Number.POSITIVE_INFINITY:Date.now()-this.completedAt}get isJoinable(){return this.replayable&&(this.phase==="awaiting_response"||this.phase==="streaming")}get isProducing(){return this.phase==="awaiting_response"||this.phase==="streaming"}reserve(e,n){let r=this.nextInterestId++;return this.interests.add(r),new B_(this,r,e,n)}releaseInterest(e){if(this.interests.delete(e))return this.abortIfUnobserved("Cursor turn has no remaining subscribers")}async attach(e,n,r){if(this.phase==="aborting"||this.phase==="failed"||this.abortController.signal.aborted){try{await e.body?.cancel(this.abortController.signal.reason)}catch{}this.finishFailed(fn(this.abortController.signal.reason??"Cursor turn superseded"));return}let o=[];e.headers.forEach((i,a)=>{o.push([a,i])}),this.responseMetadata={status:e.status,statusText:e.statusText,headers:o},this.phase="streaming";let s=this.interests.has(n)?this.responseForReadyInterest(n,r):void 0;return this.readySettled=!0,this.readyResolve(),e.body?(this.sourceReader=e.body.getReader(),s&&this.ensurePumpStarted(),s):(this.finishCompleted(),s)}fail(e){this.finishFailed(e instanceof Error?e:new Error(String(e)))}async supersede(e){if(this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"){await N_(this.settled,3e3);return}this.phase="aborting";let n=fn(e);this.readySettled||(this.readySettled=!0,this.readyReject(n)),this.abortController.abort(n),this.errorSubscribers(n);let r=this.sourceReader;if(r){let o=Promise.resolve(r.cancel(n)).catch(()=>{}).then(()=>{});await N_(o,3e3),this.finishFailed(n)}await N_(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw fn(n?.reason);if(!this.responseMetadata)throw this.failure||new Error("Cursor turn response metadata is missing");if(!this.replayable&&this.phase!=="streaming")throw this.releaseInterest(e),Object.assign(new Error("Cursor turn result exceeded the bounded replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});let r=this.responseForReadyInterest(e,n);return this.ensurePumpStarted(),r}responseForReadyInterest(e,n){let r=this.openStream(e,n);return new Response(r,{status:this.responseMetadata.status,statusText:this.responseMetadata.statusText,headers:this.responseMetadata.headers})}openStream(e,n){let r;return new ReadableStream({start:o=>{if(!this.interests.has(e)){o.error(fn(n?.reason));return}r=this.nextSubscriberId++;let s={controller:o};if(this.subscribers.set(r,s),this.interests.delete(e),n){let i=()=>{r!==void 0&&this.removeSubscriber(r,fn(n.reason))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0}),s.removeAbortListener=()=>n.removeEventListener("abort",i)}if(!this.replayable){this.removeSubscriber(r,Object.assign(new Error("Cursor turn cannot replay an oversized active result"),{statusCode:409,code:"cursor_turn_not_replayable"}));return}for(let i of this.chunks)o.enqueue(i);this.phase==="completed"?this.closeSubscriber(r):(this.phase==="failed"||this.phase==="aborting")&&this.removeSubscriber(r,this.failure||fn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,fn(o),!1):this.releaseInterest(e)})}pumpStarted=!1;ensurePumpStarted(){this.pumpStarted||!this.sourceReader||this.phase!=="streaming"||(this.pumpStarted=!0,this.pump())}async pump(){let e=this.sourceReader;if(e)try{for(;this.phase==="streaming";){let{done:n,value:r}=await e.read();if(n){this.finishCompleted();return}if(r){if(this.replayable)if(this.bufferedBytes+r.byteLength<=8388608){let o=r.slice();this.chunks.push(o),this.bufferedBytes+=o.byteLength}else this.replayable=!1,this.chunks=[];for(let o of this.subscribers.values())o.controller.enqueue(r)}}}catch(n){this.finishFailed(n instanceof Error?n:new Error(String(n)))}}abortIfUnobserved(e){if(!(this.interests.size>0||this.subscribers.size>0||this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"))return this.supersede(e)}removeSubscriber(e,n,r=!0){let o=this.subscribers.get(e);if(o){if(this.subscribers.delete(e),o.removeAbortListener?.(),r)try{o.controller.error(n)}catch{}return this.abortIfUnobserved(n.message)}}closeSubscriber(e){let n=this.subscribers.get(e);if(n){this.subscribers.delete(e),n.removeAbortListener?.();try{n.controller.close()}catch{}}}errorSubscribers(e){for(let n of[...this.subscribers.keys()])this.removeSubscriber(n,e)}releaseSourceReader(){let e=this.sourceReader;if(this.sourceReader=void 0,!!e)try{e.releaseLock()}catch{}}finishCompleted(){if(!(this.phase==="completed"||this.phase==="failed")){if(this.phase==="aborting"){this.finishFailed(fn(this.abortController.signal.reason));return}this.phase="completed",this.completedAt=Date.now(),this.releaseSourceReader();for(let e of[...this.subscribers.keys()])this.closeSubscriber(e);this.settledResolve(),this.onTerminal(this,"completed")}}finishFailed(e){this.phase==="completed"||this.phase==="failed"||(this.phase="failed",this.failure=e,this.releaseSourceReader(),this.readySettled||(this.readySettled=!0,this.readyReject(e)),this.errorSubscribers(e),this.interests.clear(),this.settledResolve(),this.onTerminal(this,"failed"))}},B_=class{constructor(e,n,r,o="join"){this.turn=e;this.interestId=n;this.signal=r;this.kind=o;if(r){let s=()=>{this.turn.releaseInterest(this.interestId)};r.aborted?s():(r.addEventListener("abort",s,{once:!0}),this.removeReservationAbortListener=()=>r.removeEventListener("abort",s))}}turn;interestId;signal;kind;attachedResponse;removeReservationAbortListener;get producerSignal(){return this.turn.abortController.signal}attach(e){if(this.kind!=="leader")throw new Error("Only the Cursor turn leader may attach a response");return this.turn.attach(e,this.interestId,this.signal).then(n=>{this.attachedResponse=n})}fail(e){this.kind==="leader"&&this.turn.fail(e),this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}async response(){try{if(this.attachedResponse){let e=this.attachedResponse;return this.attachedResponse=void 0,e}return await this.turn.responseFor(this.interestId,this.signal)}finally{this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}}},U_=class{sessions=new Map;admissionGates=new Map;forgetExpiredSuperseded(e,n,r=!0){let o=Date.now();for(let[s,i]of n.superseded)i<=o&&n.superseded.delete(s);r&&!n.active&&!n.completed&&n.superseded.size===0&&this.sessions.delete(e)}rememberSuperseded(e,n,r){for(n.superseded.delete(r),n.superseded.set(r,Date.now()+9e5);n.superseded.size>16;){let s=n.superseded.keys().next().value;if(typeof s!="string")break;n.superseded.delete(s)}let o=setTimeout(()=>{let s=this.sessions.get(e);s&&this.forgetExpiredSuperseded(e,s)},9e5);typeof o.unref=="function"&&o.unref()}async admit(e){if(e.signal?.aborted)throw fn(e.signal.reason);let n=this.admissionGates.get(e.sessionKey),r,o=new Promise(s=>{r=s});this.admissionGates.set(e.sessionKey,o),n&&await n;try{if(e.signal?.aborted)throw fn(e.signal.reason);for(;;){if(e.signal?.aborted)throw fn(e.signal.reason);let s=this.sessions.get(e.sessionKey)||{superseded:new Map};if(this.sessions.set(e.sessionKey,s),this.forgetExpiredSuperseded(e.sessionKey,s,!1),s.superseded.has(e.fingerprint))throw Object.assign(new Error("This Cursor turn was superseded by a newer request"),{statusCode:409,code:"cursor_turn_superseded"});let i=s.active;if(i){if(i.fingerprint===e.fingerprint){if(i.responseKind!==e.responseKind)throw Object.assign(new Error("An identical Cursor turn is already using a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});if(i.isJoinable)return i.reserve(e.signal,"join");if(i.isProducing)throw Object.assign(new Error("The active Cursor turn exceeded the bounded duplicate replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});await i.supersede("Waiting for the aborted Cursor turn to finish cleanup"),s.active===i&&(s.active=void 0);continue}this.rememberSuperseded(e.sessionKey,s,i.fingerprint),await i.supersede("Cursor turn superseded by a newer request"),s.active===i&&(s.active=void 0);continue}let a=s.completed;if(a&&a.replayAgeMs<=6e4&&a.fingerprint===e.fingerprint&&a.canReplay){if(a.responseKind!==e.responseKind)throw Object.assign(new Error("The cached Cursor turn uses a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});return a.reserve(e.signal,"replay")}a&&a.fingerprint!==e.fingerprint&&this.rememberSuperseded(e.sessionKey,s,a.fingerprint),s.completed=void 0;let u=new M_(e.sessionKey,e.fingerprint,e.responseKind,(d,f)=>{let p=this.sessions.get(e.sessionKey);if(p){if(p.active===d&&(p.active=void 0),f==="completed"&&d.canReplay){p.completed=d;let h=setTimeout(()=>{let g=this.sessions.get(e.sessionKey);g?.completed===d&&(g.completed=void 0,this.forgetExpiredSuperseded(e.sessionKey,g))},6e4);typeof h.unref=="function"&&h.unref()}!p.active&&!p.completed&&p.superseded.size===0&&this.sessions.delete(e.sessionKey)}});return s.active=u,s.completed=void 0,u.reserve(e.signal,"leader")}}finally{r(),this.admissionGates.get(e.sessionKey)===o&&this.admissionGates.delete(e.sessionKey)}}clear(){for(let e of this.sessions.values())e.active&&e.active.supersede("Cursor turn registry cleared");this.sessions.clear()}},oR=new U_;var E$=900*1e3,Ia=null;function j_(t){return ri([t])}async function v$(t){let e=j_(t);if(Ia&&Ia.apiKeyFingerprint===e&&Date.now()-Ia.fetchedAt<E$)return Ia.models;let n=await A$.models.list({apiKey:t})||[];return Ia={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function T$(t,e,n){let r;try{r=await v$(t)}catch{return{id:e}}let o=r.find(i=>i.id===e||i.displayName===e||Array.isArray(i.aliases)&&i.aliases.includes(e));if(!o)return{id:e};if(n&&Array.isArray(o.variants)&&o.variants.length){let i=o.variants.find(a=>a.params?.some(u=>/effort|reasoning/i.test(u.id)&&String(u.value).toLowerCase()===String(n).toLowerCase()))||o.variants.find(a=>(a.displayName||"").toLowerCase().includes(String(n).toLowerCase()));if(i)return{id:o.id,params:i.params}}let s=o.variants?.find(i=>i.isDefault)||o.variants?.[0];return s?.params?.length?{id:o.id,params:s.params}:{id:o.id}}function x$(t){let e=[];for(let n of t.messages||[])if((n.role==="system"||n.role==="user")&&(typeof n.content=="string"?e.push(n.content):Array.isArray(n.content)&&e.push(n.content.map(r=>typeof r=="string"?r:r?.text||"").join("")),n.role==="user"))break;return e.join(`
439
- `)}function R$(t){return t.length===1&&t[0]?.role==="user"}function D$(t,e,n){if(e.hasTrailingUserInput)return!1;let r=n?.interruption==="synthetic_client_interrupt"&&n.steering==="none",o=e.toolResults.length+(r?1:0);if(t.length!==o)return!1;for(let s=0;s<e.toolResults.length;s+=1){let i=t[s],a=e.toolResults[s];if(i?.role!=="tool"||i.tool_call_id!==a.toolCallId||dn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function pn(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*O$(t,e,n,r){let o=t.streamIterator;if(!o){yield{kind:"end"};return}let s=f=>(f.catch(()=>{}),t.streamNext=f,t.streamNextRunToken=n,f),i=s(t.streamNextRunToken===n&&t.streamNext?t.streamNext:o.next()),a=t.waitForEmit().then(()=>"emit"),u=t.waitForSdkMessage().then(()=>"sdk_message"),d=()=>{let f=t.pendingSdkMessages.findIndex(h=>h.runToken===n);if(f===-1)return;let[p]=t.pendingSdkMessages.splice(f,1);return p};for(;;){if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}let f=d();if(f){yield{kind:"sdk",message:f.message,source:f.source};continue}let p=await Promise.race([u.then(b=>({type:b})),i.then(b=>({type:"msg",r:b})),a.then(b=>({type:b}))]);if(p.type==="emit"){for(;t.pendingEmit.length&&t.pendingEmit[0]?.runToken===n;)yield{kind:"host_tool",tool:t.pendingEmit.shift()};a=t.waitForEmit().then(()=>"emit");continue}if(p.type==="sdk_message"){for(;;){let b=d();if(!b)break;yield{kind:"sdk",message:b.message,source:b.source}}u=t.waitForSdkMessage().then(()=>"sdk_message");continue}let{r:h}=p;if(t.streamNext===i&&(t.streamNext=void 0,t.streamNextRunToken=void 0),h.done){yield{kind:"end"};return}let g=h.value;if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}g?.type==="tool_call"&&e==="bridge"&&(t.metrics.builtinToolCallsSeen+=1),yield{kind:"sdk",message:g,source:"stream"},i=s(o.next())}}function P$(t,e){if(!e||e.type!=="thinking-delta")return;let n=oi(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function Fa(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:no.retireSession(t,e.reason,()=>df(t,async()=>(await A_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await no.invalidate(t,e.reason),!0)))}function I$(t,e,n,r){let o=r.cursorMode||af,s=t.model||"composer-2",i;try{i=fx(e)}catch(f){throw Object.assign(f instanceof Error?f:new Error(String(f)),{statusCode:f?.statusCode||401,code:"provider_response_error",type:"api_error"})}let a=n?.req?.headers?.["x-ccr-cursor-session"]||n?.req?.headers?.["X-Ccr-Cursor-Session"],u=r.sourceSessionIdentity||n?.unifiedRequest?.sourceSessionIdentity||t?.metadata?.user_id,d=Lx({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:x$(t)});return{apiKey:i,hostEnv:Ra(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function sR(t,e,n,r={}){let o=I$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=F_({credentialFingerprint:j_(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:b_(t)||""},sandboxEnabled:Pa(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=Zx(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await oR.admit({sessionKey:o.sessionKey,fingerprint:a,responseKind:t.stream===!0?"stream":"json",signal:r.abortSignal});if(u.kind!=="leader")return u.response();try{let d=await F$(t,e,n,{...r,abortSignal:u.producerSignal,turnIntent:o.turnIntent},o);await u.attach(d)}catch(d){throw u.fail(d),d}return u.response()}async function F$(t,e,n,r,o){pn(r.abortSignal);let s=r.logger||e?.logger;s&&no.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=b_(t),h=await T$(d,u,p);pn(r.abortSignal);let g=o.hostEnv,b={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};pn(r.abortSignal);let m=await no.getOrCreate(b);pn(r.abortSignal);let w=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,C=X=>F_({credentialFingerprint:j_(d),guidanceFingerprint:w(X).fingerprint,mode:i,model:h,sandboxEnabled:Pa(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),A=w(m),k=C(m),E=Ix(t,r.turnIntent),x=E.toolResults,O=m.parked.length>0?{kind:"parked",live:!!(m.run&&m.streamIterator&&m.activeRunToken&&!m.poisoned),tools:m.parked}:m.run||m.streamIterator||m.streamNext||m.activeRunToken?{kind:"active-different-turn"}:{kind:"idle"},q=m.transcriptCommit&&m.compatibilityStamp===k?nR(m.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?D$(q,E,r.turnIntent):O.kind==="idle"?R$(q):!0,j=!m.hasSentPrompt||!m.transcriptCommit?"unknown":V?"strict":"divergent",ee=rR({session:{alignment:j,hasSentPrompt:m.hasSentPrompt,poisoned:m.poisoned===!0,run:O},turn:{hasMeaningfulSteering:E.hasTrailingUserInput,toolResults:x}});if(ee.action==="retire-and-replay-full"&&(s?.info?.({sessionKey:m.key,agentId:m.agentId,alignment:j,lifecycleReason:ee.reason,toolResultCount:x.length},"cursor-sdk retiring session before full transcript replay"),await Fa(m,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:m.activeRunToken}),pn(r.abortSignal),m=await no.getOrCreate(b),pn(r.abortSignal),A=w(m),k=C(m),ee={action:"send-full",reason:"unused-session"}),pn(r.abortSignal),E_(m,A),ee.action==="resume-parked"&&(pn(r.abortSignal),no.resolveParkedTools(m,x)!==x.length||m.parked.length!==0))throw new Error("cursor-sdk lifecycle changed while resolving exact parked tools");let z=ee.action!=="resume-parked",te=ee.action==="send-incremental",Q=m.activeRunToken,_e=(X,de)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ce=>ce.runToken!==de),X.notifySdkMessage()},Oe=(X,de)=>{let ce=i==="bridge"?zx(t,X,s,Te):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ce?{customTools:ce}:void 0,onDelta:({update:S})=>{let T=P$(X,S);T&&X.enqueueSdkMessage(T,de)}}},Te=R_(),Ke=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,de)=>de.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||v_(X)||T_(X)),Z=async(X,de)=>{let ce;if(await df(X,async()=>{if(X.poisoned)throw Object.assign(new Error("cursor-sdk session is no longer safe for sends"),{retryFreshCursorSession:!0});if(X.run||X.streamIterator||X.streamNext||X.activeRunToken||X.parked.length>0)throw si(X,"cursor-sdk session became active after lifecycle admission"),Object.assign(new Error("cursor-sdk session became active before prompt send"),{retryFreshCursorSession:!0});if(X.poisoned)throw Object.assign(new Error("cursor-sdk session was retired during cancellation"),{retryFreshCursorSession:!0});let S=Px(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:de,hostEnv:A,turnIntent:r.turnIntent});ce=Symbol("cursor-sdk-run"),X.activeRunToken=ce;try{let T=await x_(X,S,Oe(X,ce),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ce,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,pn(r.abortSignal)}catch(T){throw ce&&X.activeRunToken===ce&&(X.activeRunToken=void 0,_e(X,ce)),(r.abortSignal?.aborted||T_(T)||v_(T))&&si(X,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),s?.error?.({err:T},"cursor-sdk agent.send failed"),T}}),!ce)throw new Error("cursor-sdk agent.send did not produce a run token");return ce};if(z)try{Q=await Z(m,te)}catch(X){let de=ne(X,m);if(await Fa(m,{reason:"cursor-sdk prompt send failed before streaming"}),!de)throw Ke(X);pn(r.abortSignal),s?.warn?.({err:X,sessionKey:m.key,agentId:m.agentId},"cursor-sdk retrying failed resumed send with fresh session"),m=await no.getOrCreate(b),pn(r.abortSignal),A=w(m),k=C(m),E_(m,A);try{Q=await Z(m,!1)}catch(ce){throw await Fa(m,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ke(ce)}}Q||(Q=Symbol("cursor-sdk-run"),m.activeRunToken=Q);let ae=_x(u,new TextEncoder),Ie=[],we=Jx(t),H=0,Ee,Ze=new ReadableStream({async start(X){let de=()=>{Te.scratchViolations<=0||s?.warn?.({sessionKey:m.key,model:u,scratchViolations:Te.scratchViolations,scratchCorrections:Te.scratchCorrections,metrics:m.metrics,hostProjectRoot:A.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ce=D=>{Ie.push(D),a&&X.enqueue(ae.encode(D))},S=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=Vx(Ee,m.lastSdkUsageRaw,we),F=Kx(we,H,D);return Ee&&(m.lastSdkUsageRaw=Ee),F},R=()=>{if(m.activeRunToken!==Q)return;let F=C_(u,Ie)?.choices?.[0]?.message;!F||F.role!=="assistant"||(m.transcriptCommit=tR(t,F),m.compatibilityStamp=k)},M=D=>{let F=T();s?.debug?.({reason:D,promptTokens:F.prompt_tokens,completionTokens:F.completion_tokens,outputChars:H,sdkUsageRaw:Ee,runUsage:m.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ce(ae.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,U,B="",K=0,ie=()=>{!P||N||(ce(ae.thinkingSignature()),N=!0,L=!1)};for(;;){let ue=!1;for await(let be of O$(m,i,Q,r.abortSignal)){if(uf(m),be.kind==="host_tool"){if(i!=="bridge")continue;for(ie(),L=!1,S(be.tool.name),S(JSON.stringify(be.tool.args??{})),ce(ae.toolCall(be.tool,D)),D+=1;m.pendingEmit.length;){let he=m.pendingEmit.shift();S(he.name),S(JSON.stringify(he.args??{})),ce(ae.toolCall(he,D)),D+=1}M("tool_calls"),a&&X.enqueue(ae.encodeDone()),X.close();return}if(be.kind==="end"){if(be.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(Dx({mode:i,assistantText:B,emittedHostTools:D,continuationAttempts:K})){m.activeRunToken===Q&&(m.streamIterator=void 0,m.streamNext=void 0,m.streamNextRunToken=void 0,m.run=void 0,m.activeRunToken=void 0),K+=1,s?.warn?.({assistantText:B,attempt:K},"cursor-sdk continuing progress-only terminal turn");let he=Symbol("cursor-sdk-run");Q=he,m.activeRunToken=he,await df(m,async()=>{if(m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let ye=await x_(m,Ox(A),Oe(m,he),{abortSignal:r.abortSignal,logger:s});if(m.run=ye,m.activeRunToken=he,m.streamIterator=ye.stream()[Symbol.asyncIterator](),m.streamNext=void 0,m.streamNextRunToken=void 0,m.hasSentPrompt=!0,m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation retired during send")}),B="",ue=!0;break}ie(),M("stop"),m.activeRunToken===Q&&(m.streamIterator=void 0,m.streamNext=void 0,m.streamNextRunToken=void 0,m.run=void 0,m.activeRunToken=void 0),a&&X.enqueue(ae.encodeDone()),X.close();return}let me=be.message;if(me){if(me.type==="assistant")for(let he of me.message?.content||[])he.type==="text"&&he.text&&(ie(),L=!1,F=!0,B+=he.text,S(he.text),ce(ae.content(he.text)));else if(me.type==="thinking"){if(!L)continue;let he=be.source||"stream";if(U&&U!==he)continue;U=he;let ye=oi(me.text);ye&&(P=!0,S(ye),ce(ae.thinking(ye)))}else if(me.type==="usage")Ee=Yx(me);else if(me.type==="status"){if(me.status==="ERROR"||me.status==="CANCELLED")throw Object.assign(new Error(me.message||`Cursor run ${me.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(me.type==="tool_call"&&i!=="bridge"&&i==="agent"&&me.name){ie(),L=!1;let he=`
437
+ `)}var C$=3;function w$(t){if(!t)return{type:"object",properties:{}};if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object")return e}catch{return{type:"object",properties:{}}}return typeof t=="object"?t:{type:"object",properties:{}}}function R_(){return{scratchViolations:0,scratchCorrections:0}}function Wx(t,e,n,r=R_()){let o={};if(!Array.isArray(t.tools))return o;for(let s of t.tools){let i=s.function?.name;!i||typeof i!="string"||(o[i]={description:s.function.description||`Claude Code host tool: ${i}`,inputSchema:w$(s.function.parameters),async execute(a,u){let d=ur(u.toolCallId)||b$(),f=a||{},p=e.hostEnv||to,h=Hx(p)?qx(f,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let g=e.metrics.scratchPathCorrections<C$;if(n?.warn?.({sessionKey:e.key,tool:i,hits:h,corrected:g,violations:e.metrics.scratchPathViolations},"cursor-sdk host tool call referenced the scratch workspace"),g)return e.metrics.scratchPathCorrections+=1,r.scratchCorrections+=1,zx(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:d,name:i,args:f})}})}return o}function Jx(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function Gx(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function Kx(t){let e=[];t.system&&e.push(Gx(t.system));for(let n of t.messages||[])e.push(Gx(n.content)),n.thinking?.content&&e.push(String(n.thinking.content)),n.reasoning_content&&e.push(String(n.reasoning_content)),n.tool_calls?.length&&e.push(JSON.stringify(n.tool_calls));return t.tools?.length&&e.push(JSON.stringify(t.tools)),Jx(e.join(`
438
+ `).length)}function Vx(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=Jx(e),s=Math.min(r,Math.max(0,Math.trunc(n)||0));return{prompt_tokens:r,completion_tokens:o,total_tokens:r+o,prompt_tokens_details:{cached_tokens:s}}}function df(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Yx(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=df(t.prompt_tokens),s=df(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=df(e?.prompt_tokens),a=df(e?.prompt_tokens_details?.cached_tokens),u=o-i,d=s-a,f=u>0&&d>0?d/u:s/o,p=Math.min(1,Math.max(0,f));return Math.min(r,Math.floor(r*p))}function Xx(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,i=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:i}}}import{createHash as k$}from"crypto";var S$=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Wn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="bigint")return String(t);if(Array.isArray(t))return t.map(n=>Wn(n)).filter(n=>n!==void 0);if(typeof t!="object")return;let e={};for(let n of Object.keys(t).sort()){if(n==="cache_control")continue;let r=Wn(t[n]);r!==void 0&&(e[n]=r)}return e}function O_(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Wn(t);return e===void 0?[]:[e]}return t.map(e=>{if(typeof e=="string")return{text:e,type:"text"};if(!e||typeof e!="object")return Wn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Wn(n)}).filter(e=>e!==void 0)}function A$(t){if(typeof t!="string")return Wn(t)??null;try{return Wn(JSON.parse(t))??null}catch{return t}}function P_(t){let e=t,n={content:O_(e.content),role:e.role};return e.reasoning_content&&(n.reasoning_content=e.reasoning_content),e.thinking?.content&&(n.thinking={content:e.thinking.content}),e.tool_call_id&&(n.tool_call_id=e.tool_call_id),e.is_error!==void 0&&(n.is_error=e.is_error),Array.isArray(e.tool_calls)&&e.tool_calls.length&&(n.tool_calls=e.tool_calls.map(r=>({function:{arguments:A$(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function Qx(t){return Array.isArray(t)?t.map(e=>Wn(e)).filter(e=>e!==void 0).sort((e,n)=>D_(e).localeCompare(D_(n))):[]}function D_(t){return JSON.stringify(t)}function I_(t){return k$("sha256").update(D_(t)).digest("hex")}function Zx(t){return{system:O_(t.system),messages:(t.messages||[]).map(P_)}}function E$(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(S$.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(P_):r==="system"?o=O_(t.system):r==="tools"?o=Qx(t.tools):o=Wn(e[r]),o!==void 0&&(n[r]=o)}return n}function eR(t,e={}){return I_({compatibilityStamp:e.compatibilityStamp||"",request:E$(t),turnIntent:e.turnIntent?{interruption:e.turnIntent.interruption,source:e.turnIntent.source,steering:e.turnIntent.steering,trailingToolResults:e.turnIntent.trailingToolResults.map(n=>({content:n.content,isError:n.isError,toolCallId:n.toolCallId}))}:null})}function F_(t){return I_({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Wn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:Qx(t.tools),workspaceDir:t.workspaceDir})}function tR(t,e){return I_({messages:e,system:t})}function nR(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=Zx(t);return e&&n.messages.push(P_(e)),Object.freeze({transcriptHash:tR(n.system,n.messages),messageCount:n.messages.length})}function rR(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=Zx(e);if(!(n.messages.length<=t.messageCount)&&tR(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function v$(t,e){if(t.length===0||t.length!==e.length)return;let n=new Map;for(let s of e){let i=s.toolCallId;if(!i||n.has(i))return;n.set(i,s)}let r=new Set,o=[];for(let s of t){if(!s.id||r.has(s.id))return;r.add(s.id);let i=n.get(s.id);if(!i)return;o.push({parked:s,result:i})}return o}var kr=t=>({action:"retire-and-replay-full",reason:t});function oR(t){let{session:e,turn:n}=t;if(e.poisoned)return kr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:kr("inconsistent-unused-session");if(e.alignment==="unknown")return kr("unknown-context-alignment");if(e.alignment==="divergent")return kr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return kr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return kr("dead-parked-run");if(n.hasMeaningfulSteering)return kr("parked-turn-has-steering");let r=v$(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:kr("parked-tool-results-mismatch")}return n.toolResults.length>0?kr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function fn(t){let e=t instanceof Error?t.message:typeof t=="string"&&t?t:"Cursor turn subscriber aborted";return Object.assign(new Error(e),{name:"AbortError"})}async function N_(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var M_=class{constructor(e,n,r,o){this.sessionKey=e;this.fingerprint=n;this.responseKind=r;this.onTerminal=o;this.ready.catch(()=>{})}sessionKey;fingerprint;responseKind;onTerminal;abortController=new AbortController;phase="awaiting_response";responseMetadata;sourceReader;chunks=[];bufferedBytes=0;replayable=!0;readySettled=!1;completedAt;nextInterestId=1;nextSubscriberId=1;interests=new Set;subscribers=new Map;failure;readyResolve;readyReject;settledResolve;ready=new Promise((e,n)=>{this.readyResolve=e,this.readyReject=n});settled=new Promise(e=>{this.settledResolve=e});get canReplay(){return this.phase==="completed"&&this.replayable}get replayAgeMs(){return this.completedAt===void 0?Number.POSITIVE_INFINITY:Date.now()-this.completedAt}get isJoinable(){return this.replayable&&(this.phase==="awaiting_response"||this.phase==="streaming")}get isProducing(){return this.phase==="awaiting_response"||this.phase==="streaming"}reserve(e,n){let r=this.nextInterestId++;return this.interests.add(r),new B_(this,r,e,n)}releaseInterest(e){if(this.interests.delete(e))return this.abortIfUnobserved("Cursor turn has no remaining subscribers")}async attach(e,n,r){if(this.phase==="aborting"||this.phase==="failed"||this.abortController.signal.aborted){try{await e.body?.cancel(this.abortController.signal.reason)}catch{}this.finishFailed(fn(this.abortController.signal.reason??"Cursor turn superseded"));return}let o=[];e.headers.forEach((i,a)=>{o.push([a,i])}),this.responseMetadata={status:e.status,statusText:e.statusText,headers:o},this.phase="streaming";let s=this.interests.has(n)?this.responseForReadyInterest(n,r):void 0;return this.readySettled=!0,this.readyResolve(),e.body?(this.sourceReader=e.body.getReader(),s&&this.ensurePumpStarted(),s):(this.finishCompleted(),s)}fail(e){this.finishFailed(e instanceof Error?e:new Error(String(e)))}async supersede(e){if(this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"){await N_(this.settled,3e3);return}this.phase="aborting";let n=fn(e);this.readySettled||(this.readySettled=!0,this.readyReject(n)),this.abortController.abort(n),this.errorSubscribers(n);let r=this.sourceReader;if(r){let o=Promise.resolve(r.cancel(n)).catch(()=>{}).then(()=>{});await N_(o,3e3),this.finishFailed(n)}await N_(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw fn(n?.reason);if(!this.responseMetadata)throw this.failure||new Error("Cursor turn response metadata is missing");if(!this.replayable&&this.phase!=="streaming")throw this.releaseInterest(e),Object.assign(new Error("Cursor turn result exceeded the bounded replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});let r=this.responseForReadyInterest(e,n);return this.ensurePumpStarted(),r}responseForReadyInterest(e,n){let r=this.openStream(e,n);return new Response(r,{status:this.responseMetadata.status,statusText:this.responseMetadata.statusText,headers:this.responseMetadata.headers})}openStream(e,n){let r;return new ReadableStream({start:o=>{if(!this.interests.has(e)){o.error(fn(n?.reason));return}r=this.nextSubscriberId++;let s={controller:o};if(this.subscribers.set(r,s),this.interests.delete(e),n){let i=()=>{r!==void 0&&this.removeSubscriber(r,fn(n.reason))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0}),s.removeAbortListener=()=>n.removeEventListener("abort",i)}if(!this.replayable){this.removeSubscriber(r,Object.assign(new Error("Cursor turn cannot replay an oversized active result"),{statusCode:409,code:"cursor_turn_not_replayable"}));return}for(let i of this.chunks)o.enqueue(i);this.phase==="completed"?this.closeSubscriber(r):(this.phase==="failed"||this.phase==="aborting")&&this.removeSubscriber(r,this.failure||fn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,fn(o),!1):this.releaseInterest(e)})}pumpStarted=!1;ensurePumpStarted(){this.pumpStarted||!this.sourceReader||this.phase!=="streaming"||(this.pumpStarted=!0,this.pump())}async pump(){let e=this.sourceReader;if(e)try{for(;this.phase==="streaming";){let{done:n,value:r}=await e.read();if(n){this.finishCompleted();return}if(r){if(this.replayable)if(this.bufferedBytes+r.byteLength<=8388608){let o=r.slice();this.chunks.push(o),this.bufferedBytes+=o.byteLength}else this.replayable=!1,this.chunks=[];for(let o of this.subscribers.values())o.controller.enqueue(r)}}}catch(n){this.finishFailed(n instanceof Error?n:new Error(String(n)))}}abortIfUnobserved(e){if(!(this.interests.size>0||this.subscribers.size>0||this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"))return this.supersede(e)}removeSubscriber(e,n,r=!0){let o=this.subscribers.get(e);if(o){if(this.subscribers.delete(e),o.removeAbortListener?.(),r)try{o.controller.error(n)}catch{}return this.abortIfUnobserved(n.message)}}closeSubscriber(e){let n=this.subscribers.get(e);if(n){this.subscribers.delete(e),n.removeAbortListener?.();try{n.controller.close()}catch{}}}errorSubscribers(e){for(let n of[...this.subscribers.keys()])this.removeSubscriber(n,e)}releaseSourceReader(){let e=this.sourceReader;if(this.sourceReader=void 0,!!e)try{e.releaseLock()}catch{}}finishCompleted(){if(!(this.phase==="completed"||this.phase==="failed")){if(this.phase==="aborting"){this.finishFailed(fn(this.abortController.signal.reason));return}this.phase="completed",this.completedAt=Date.now(),this.releaseSourceReader();for(let e of[...this.subscribers.keys()])this.closeSubscriber(e);this.settledResolve(),this.onTerminal(this,"completed")}}finishFailed(e){this.phase==="completed"||this.phase==="failed"||(this.phase="failed",this.failure=e,this.releaseSourceReader(),this.readySettled||(this.readySettled=!0,this.readyReject(e)),this.errorSubscribers(e),this.interests.clear(),this.settledResolve(),this.onTerminal(this,"failed"))}},B_=class{constructor(e,n,r,o="join"){this.turn=e;this.interestId=n;this.signal=r;this.kind=o;if(r){let s=()=>{this.turn.releaseInterest(this.interestId)};r.aborted?s():(r.addEventListener("abort",s,{once:!0}),this.removeReservationAbortListener=()=>r.removeEventListener("abort",s))}}turn;interestId;signal;kind;attachedResponse;removeReservationAbortListener;get producerSignal(){return this.turn.abortController.signal}attach(e){if(this.kind!=="leader")throw new Error("Only the Cursor turn leader may attach a response");return this.turn.attach(e,this.interestId,this.signal).then(n=>{this.attachedResponse=n})}fail(e){this.kind==="leader"&&this.turn.fail(e),this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}async response(){try{if(this.attachedResponse){let e=this.attachedResponse;return this.attachedResponse=void 0,e}return await this.turn.responseFor(this.interestId,this.signal)}finally{this.removeReservationAbortListener?.(),this.removeReservationAbortListener=void 0}}},j_=class{sessions=new Map;admissionGates=new Map;forgetExpiredSuperseded(e,n,r=!0){let o=Date.now();for(let[s,i]of n.superseded)i<=o&&n.superseded.delete(s);r&&!n.active&&!n.completed&&n.superseded.size===0&&this.sessions.delete(e)}rememberSuperseded(e,n,r){for(n.superseded.delete(r),n.superseded.set(r,Date.now()+9e5);n.superseded.size>16;){let s=n.superseded.keys().next().value;if(typeof s!="string")break;n.superseded.delete(s)}let o=setTimeout(()=>{let s=this.sessions.get(e);s&&this.forgetExpiredSuperseded(e,s)},9e5);typeof o.unref=="function"&&o.unref()}async admit(e){if(e.signal?.aborted)throw fn(e.signal.reason);let n=this.admissionGates.get(e.sessionKey),r,o=new Promise(s=>{r=s});this.admissionGates.set(e.sessionKey,o),n&&await n;try{if(e.signal?.aborted)throw fn(e.signal.reason);for(;;){if(e.signal?.aborted)throw fn(e.signal.reason);let s=this.sessions.get(e.sessionKey)||{superseded:new Map};if(this.sessions.set(e.sessionKey,s),this.forgetExpiredSuperseded(e.sessionKey,s,!1),s.superseded.has(e.fingerprint))throw Object.assign(new Error("This Cursor turn was superseded by a newer request"),{statusCode:409,code:"cursor_turn_superseded"});let i=s.active;if(i){if(i.fingerprint===e.fingerprint){if(i.responseKind!==e.responseKind)throw Object.assign(new Error("An identical Cursor turn is already using a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});if(i.isJoinable)return i.reserve(e.signal,"join");if(i.isProducing)throw Object.assign(new Error("The active Cursor turn exceeded the bounded duplicate replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});await i.supersede("Waiting for the aborted Cursor turn to finish cleanup"),s.active===i&&(s.active=void 0);continue}this.rememberSuperseded(e.sessionKey,s,i.fingerprint),await i.supersede("Cursor turn superseded by a newer request"),s.active===i&&(s.active=void 0);continue}let a=s.completed;if(a&&a.replayAgeMs<=6e4&&a.fingerprint===e.fingerprint&&a.canReplay){if(a.responseKind!==e.responseKind)throw Object.assign(new Error("The cached Cursor turn uses a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});return a.reserve(e.signal,"replay")}a&&a.fingerprint!==e.fingerprint&&this.rememberSuperseded(e.sessionKey,s,a.fingerprint),s.completed=void 0;let u=new M_(e.sessionKey,e.fingerprint,e.responseKind,(d,f)=>{let p=this.sessions.get(e.sessionKey);if(p){if(p.active===d&&(p.active=void 0),f==="completed"&&d.canReplay){p.completed=d;let h=setTimeout(()=>{let g=this.sessions.get(e.sessionKey);g?.completed===d&&(g.completed=void 0,this.forgetExpiredSuperseded(e.sessionKey,g))},6e4);typeof h.unref=="function"&&h.unref()}!p.active&&!p.completed&&p.superseded.size===0&&this.sessions.delete(e.sessionKey)}});return s.active=u,s.completed=void 0,u.reserve(e.signal,"leader")}}finally{r(),this.admissionGates.get(e.sessionKey)===o&&this.admissionGates.delete(e.sessionKey)}}clear(){for(let e of this.sessions.values())e.active&&e.active.supersede("Cursor turn registry cleared");this.sessions.clear()}},sR=new j_;var x$=900*1e3,Ia=null;function U_(t){return ri([t])}async function R$(t){let e=U_(t);if(Ia&&Ia.apiKeyFingerprint===e&&Date.now()-Ia.fetchedAt<x$)return Ia.models;let n=await T$.models.list({apiKey:t})||[];return Ia={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function D$(t,e,n){let r;try{r=await R$(t)}catch{return{id:e}}let o=r.find(i=>i.id===e||i.displayName===e||Array.isArray(i.aliases)&&i.aliases.includes(e));if(!o)return{id:e};if(n&&Array.isArray(o.variants)&&o.variants.length){let i=o.variants.find(a=>a.params?.some(u=>/effort|reasoning/i.test(u.id)&&String(u.value).toLowerCase()===String(n).toLowerCase()))||o.variants.find(a=>(a.displayName||"").toLowerCase().includes(String(n).toLowerCase()));if(i)return{id:o.id,params:i.params}}let s=o.variants?.find(i=>i.isDefault)||o.variants?.[0];return s?.params?.length?{id:o.id,params:s.params}:{id:o.id}}function O$(t){let e=[];for(let n of t.messages||[])if((n.role==="system"||n.role==="user")&&(typeof n.content=="string"?e.push(n.content):Array.isArray(n.content)&&e.push(n.content.map(r=>typeof r=="string"?r:r?.text||"").join("")),n.role==="user"))break;return e.join(`
439
+ `)}function P$(t){return t.length===1&&t[0]?.role==="user"}function I$(t,e,n){if(e.hasTrailingUserInput)return!1;let r=n?.interruption==="synthetic_client_interrupt"&&n.steering==="none",o=e.toolResults.length+(r?1:0);if(t.length!==o)return!1;for(let s=0;s<e.toolResults.length;s+=1){let i=t[s],a=e.toolResults[s];if(i?.role!=="tool"||i.tool_call_id!==a.toolCallId||dn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function pn(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*F$(t,e,n,r){let o=t.streamIterator;if(!o){yield{kind:"end"};return}let s=f=>(f.catch(()=>{}),t.streamNext=f,t.streamNextRunToken=n,f),i=s(t.streamNextRunToken===n&&t.streamNext?t.streamNext:o.next()),a=t.waitForEmit().then(()=>"emit"),u=t.waitForSdkMessage().then(()=>"sdk_message"),d=()=>{let f=t.pendingSdkMessages.findIndex(h=>h.runToken===n);if(f===-1)return;let[p]=t.pendingSdkMessages.splice(f,1);return p};for(;;){if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}let f=d();if(f){yield{kind:"sdk",message:f.message,source:f.source};continue}let p=await Promise.race([u.then(b=>({type:b})),i.then(b=>({type:"msg",r:b})),a.then(b=>({type:b}))]);if(p.type==="emit"){for(;t.pendingEmit.length&&t.pendingEmit[0]?.runToken===n;)yield{kind:"host_tool",tool:t.pendingEmit.shift()};a=t.waitForEmit().then(()=>"emit");continue}if(p.type==="sdk_message"){for(;;){let b=d();if(!b)break;yield{kind:"sdk",message:b.message,source:b.source}}u=t.waitForSdkMessage().then(()=>"sdk_message");continue}let{r:h}=p;if(t.streamNext===i&&(t.streamNext=void 0,t.streamNextRunToken=void 0),h.done){yield{kind:"end"};return}let g=h.value;if(r?.aborted||t.activeRunToken!==n){yield{kind:"end",aborted:r?.aborted===!0};return}g?.type==="tool_call"&&e==="bridge"&&(t.metrics.builtinToolCallsSeen+=1),yield{kind:"sdk",message:g,source:"stream"},i=s(o.next())}}function N$(t,e){if(!e||e.type!=="thinking-delta")return;let n=oi(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function Fa(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:no.retireSession(t,e.reason,()=>lf(t,async()=>(await A_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await no.invalidate(t,e.reason),!0)))}function M$(t,e,n,r){let o=r.cursorMode||sf,s=t.model||"composer-2",i;try{i=px(e)}catch(f){throw Object.assign(f instanceof Error?f:new Error(String(f)),{statusCode:f?.statusCode||401,code:"provider_response_error",type:"api_error"})}let a=n?.req?.headers?.["x-ccr-cursor-session"]||n?.req?.headers?.["X-Ccr-Cursor-Session"],u=r.sourceSessionIdentity||n?.unifiedRequest?.sourceSessionIdentity||t?.metadata?.user_id,d=$x({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:O$(t)});return{apiKey:i,hostEnv:Ra(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function iR(t,e,n,r={}){let o=M$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=F_({credentialFingerprint:U_(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:b_(t)||""},sandboxEnabled:Pa(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=eR(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await sR.admit({sessionKey:o.sessionKey,fingerprint:a,responseKind:t.stream===!0?"stream":"json",signal:r.abortSignal});if(u.kind!=="leader")return u.response();try{let d=await B$(t,e,n,{...r,abortSignal:u.producerSignal,turnIntent:o.turnIntent},o);await u.attach(d)}catch(d){throw u.fail(d),d}return u.response()}async function B$(t,e,n,r,o){pn(r.abortSignal);let s=r.logger||e?.logger;s&&no.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=b_(t),h=await D$(d,u,p);pn(r.abortSignal);let g=o.hostEnv,b={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};pn(r.abortSignal);let m=await no.getOrCreate(b);pn(r.abortSignal);let w=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,C=X=>F_({credentialFingerprint:U_(d),guidanceFingerprint:w(X).fingerprint,mode:i,model:h,sandboxEnabled:Pa(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),S=w(m),k=C(m),E=Fx(t,r.turnIntent),x=E.toolResults,O=m.parked.length>0?{kind:"parked",live:!!(m.run&&m.streamIterator&&m.activeRunToken&&!m.poisoned),tools:m.parked}:m.run||m.streamIterator||m.streamNext||m.activeRunToken?{kind:"active-different-turn"}:{kind:"idle"},q=m.transcriptCommit&&m.compatibilityStamp===k?rR(m.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?I$(q,E,r.turnIntent):O.kind==="idle"?P$(q):!0,U=!m.hasSentPrompt||!m.transcriptCommit?"unknown":V?"strict":"divergent",ee=oR({session:{alignment:U,hasSentPrompt:m.hasSentPrompt,poisoned:m.poisoned===!0,run:O},turn:{hasMeaningfulSteering:E.hasTrailingUserInput,toolResults:x}});if(ee.action==="retire-and-replay-full"&&(s?.info?.({sessionKey:m.key,agentId:m.agentId,alignment:U,lifecycleReason:ee.reason,toolResultCount:x.length},"cursor-sdk retiring session before full transcript replay"),await Fa(m,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:m.activeRunToken}),pn(r.abortSignal),m=await no.getOrCreate(b),pn(r.abortSignal),S=w(m),k=C(m),ee={action:"send-full",reason:"unused-session"}),pn(r.abortSignal),E_(m,S),ee.action==="resume-parked"&&(pn(r.abortSignal),no.resolveParkedTools(m,x)!==x.length||m.parked.length!==0))throw new Error("cursor-sdk lifecycle changed while resolving exact parked tools");let z=ee.action!=="resume-parked",te=ee.action==="send-incremental",Q=m.activeRunToken,_e=(X,de)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ce=>ce.runToken!==de),X.notifySdkMessage()},Oe=(X,de)=>{let ce=i==="bridge"?Wx(t,X,s,Te):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ce?{customTools:ce}:void 0,onDelta:({update:A})=>{let T=N$(X,A);T&&X.enqueueSdkMessage(T,de)}}},Te=R_(),Ke=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,de)=>de.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||v_(X)||T_(X)),Z=async(X,de)=>{let ce;if(await lf(X,async()=>{if(X.poisoned)throw Object.assign(new Error("cursor-sdk session is no longer safe for sends"),{retryFreshCursorSession:!0});if(X.run||X.streamIterator||X.streamNext||X.activeRunToken||X.parked.length>0)throw si(X,"cursor-sdk session became active after lifecycle admission"),Object.assign(new Error("cursor-sdk session became active before prompt send"),{retryFreshCursorSession:!0});if(X.poisoned)throw Object.assign(new Error("cursor-sdk session was retired during cancellation"),{retryFreshCursorSession:!0});let A=Ix(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:de,hostEnv:S,turnIntent:r.turnIntent});ce=Symbol("cursor-sdk-run"),X.activeRunToken=ce;try{let T=await x_(X,A,Oe(X,ce),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ce,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,pn(r.abortSignal)}catch(T){throw ce&&X.activeRunToken===ce&&(X.activeRunToken=void 0,_e(X,ce)),(r.abortSignal?.aborted||T_(T)||v_(T))&&si(X,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),s?.error?.({err:T},"cursor-sdk agent.send failed"),T}}),!ce)throw new Error("cursor-sdk agent.send did not produce a run token");return ce};if(z)try{Q=await Z(m,te)}catch(X){let de=ne(X,m);if(await Fa(m,{reason:"cursor-sdk prompt send failed before streaming"}),!de)throw Ke(X);pn(r.abortSignal),s?.warn?.({err:X,sessionKey:m.key,agentId:m.agentId},"cursor-sdk retrying failed resumed send with fresh session"),m=await no.getOrCreate(b),pn(r.abortSignal),S=w(m),k=C(m),E_(m,S);try{Q=await Z(m,!1)}catch(ce){throw await Fa(m,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ke(ce)}}Q||(Q=Symbol("cursor-sdk-run"),m.activeRunToken=Q);let ae=bx(u,new TextEncoder),Ie=[],we=Kx(t),H=0,Ee,Ze=new ReadableStream({async start(X){let de=()=>{Te.scratchViolations<=0||s?.warn?.({sessionKey:m.key,model:u,scratchViolations:Te.scratchViolations,scratchCorrections:Te.scratchCorrections,metrics:m.metrics,hostProjectRoot:S.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ce=D=>{Ie.push(D),a&&X.enqueue(ae.encode(D))},A=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=Yx(Ee,m.lastSdkUsageRaw,we),F=Vx(we,H,D);return Ee&&(m.lastSdkUsageRaw=Ee),F},R=()=>{if(m.activeRunToken!==Q)return;let F=C_(u,Ie)?.choices?.[0]?.message;!F||F.role!=="assistant"||(m.transcriptCommit=nR(t,F),m.compatibilityStamp=k)},M=D=>{let F=T();s?.debug?.({reason:D,promptTokens:F.prompt_tokens,completionTokens:F.completion_tokens,outputChars:H,sdkUsageRaw:Ee,runUsage:m.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ce(ae.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,j,B="",K=0,ie=()=>{!P||N||(ce(ae.thinkingSignature()),N=!0,L=!1)};for(;;){let ue=!1;for await(let be of F$(m,i,Q,r.abortSignal)){if(cf(m),be.kind==="host_tool"){if(i!=="bridge")continue;for(ie(),L=!1,A(be.tool.name),A(JSON.stringify(be.tool.args??{})),ce(ae.toolCall(be.tool,D)),D+=1;m.pendingEmit.length;){let he=m.pendingEmit.shift();A(he.name),A(JSON.stringify(he.args??{})),ce(ae.toolCall(he,D)),D+=1}M("tool_calls"),a&&X.enqueue(ae.encodeDone()),X.close();return}if(be.kind==="end"){if(be.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(Ox({mode:i,assistantText:B,emittedHostTools:D,continuationAttempts:K})){m.activeRunToken===Q&&(m.streamIterator=void 0,m.streamNext=void 0,m.streamNextRunToken=void 0,m.run=void 0,m.activeRunToken=void 0),K+=1,s?.warn?.({assistantText:B,attempt:K},"cursor-sdk continuing progress-only terminal turn");let he=Symbol("cursor-sdk-run");Q=he,m.activeRunToken=he,await lf(m,async()=>{if(m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let ye=await x_(m,Px(S),Oe(m,he),{abortSignal:r.abortSignal,logger:s});if(m.run=ye,m.activeRunToken=he,m.streamIterator=ye.stream()[Symbol.asyncIterator](),m.streamNext=void 0,m.streamNextRunToken=void 0,m.hasSentPrompt=!0,m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation retired during send")}),B="",ue=!0;break}ie(),M("stop"),m.activeRunToken===Q&&(m.streamIterator=void 0,m.streamNext=void 0,m.streamNextRunToken=void 0,m.run=void 0,m.activeRunToken=void 0),a&&X.enqueue(ae.encodeDone()),X.close();return}let me=be.message;if(me){if(me.type==="assistant")for(let he of me.message?.content||[])he.type==="text"&&he.text&&(ie(),L=!1,F=!0,B+=he.text,A(he.text),ce(ae.content(he.text)));else if(me.type==="thinking"){if(!L)continue;let he=be.source||"stream";if(j&&j!==he)continue;j=he;let ye=oi(me.text);ye&&(P=!0,A(ye),ce(ae.thinking(ye)))}else if(me.type==="usage")Ee=Xx(me);else if(me.type==="status"){if(me.status==="ERROR"||me.status==="CANCELLED")throw Object.assign(new Error(me.message||`Cursor run ${me.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(me.type==="tool_call"&&i!=="bridge"&&i==="agent"&&me.name){ie(),L=!1;let he=`
440
440
  [cursor tool ${me.status||"running"}: ${me.name}]
441
- `;S(he),ce(ae.content(he))}}}if(!ue)break}!F&&!D&&(ie(),M("stop")),a&&X.enqueue(ae.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:m.metrics},"cursor-sdk stream failed"),await Fa(m,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{de()}},async cancel(){await Fa(m,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=Ze.getReader();for(;;){let{done:ce}=await X.read();if(ce)break}let de=C_(u,Ie);return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(Ze,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function N$(t,e,n){return{cursorMode:t.cursorMode||af,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var pf=class{static TransformerName=m_;name=m_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=N$(this.options,r,this.logger),s={...e,messages:Ve(e.messages),tools:Ye(e.tools)},i=await sR(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};import{randomUUID as aq}from"crypto";import{existsSync as aR,mkdirSync as M$,readFileSync as B$,renameSync as U$,unlinkSync as j$,writeFileSync as L$}from"fs";import{dirname as $$,join as q$}from"path";import{homedir as H$}from"os";import{randomUUID as z$}from"crypto";var $_="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",q_="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",cR="http://localhost:51121/oauth-callback",W$=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],H_="https://daily-cloudcode-pa.sandbox.googleapis.com",uR="https://autopush-cloudcode-pa.sandbox.googleapis.com",lR="https://cloudcode-pa.googleapis.com",G$=[H_,uR,lR],L_=[lR,H_,uR],J$="1.18.3",K$=q$(H$(),".claude-code-router","antigravity_auth.json"),V$=12e4,dR="https://oauth2.googleapis.com/token",Y$="https://www.googleapis.com/oauth2/v2/userinfo",hf=null,fR=null;function pR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||K$}function Na(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${J$} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,"X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})}}function gf(){try{let t=pR();if(!aR(t))return null;let e=JSON.parse(B$(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function z_(t){let e=pR();M$($$(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{L$(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),U$(n,e)}finally{try{aR(n)&&j$(n)}catch{}}}function X$(t){return Date.now()+V$>=t.expires_at}async function Q$(t){let e=new URLSearchParams({client_id:$_,client_secret:q_,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(dR,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Antigravity token refresh failed (${n.status}). Run \`ccr antigravity-auth\` again. ${s.slice(0,200)}`)}let r=await n.json();if(!r.access_token)throw new Error("Antigravity token refresh returned no access_token. Run `ccr antigravity-auth` again.");let o={...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,expires_at:Date.now()+(r.expires_in||3600)*1e3};return z_(o),o}async function Ma(t){let e=gf();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!X$(e)?e:(hf||(hf=Q$(e).finally(()=>{hf=null})),hf)}function ii(t){let e=t?.cloudaicompanionProject;if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e.id=="string"&&e.id.trim())return e.id.trim()}function Z$(t){let e=n=>{if(n){if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="object"&&typeof n.id=="string"&&n.id.trim())return n.id.trim()}};return e(t?.paidTier)||e(t?.currentTier)||e(t?.allowedTiers?.find(n=>n?.isDefault))||e(t?.allowedTiers?.[0])||void 0}function hR(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function iR(t){await new Promise(e=>setTimeout(e,t))}async function eq(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()};for(let s=0;s<20;s++){try{let i=await fetch(r,{method:"GET",headers:o,signal:AbortSignal.timeout(15e3)});if(!i.ok){await iR(2e3);continue}let a=await i.json();if(a?.done===!0)return ii(a?.response)||ii(a)||void 0}catch{}await iR(2e3)}}async function tq(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()},body:JSON.stringify({tierId:e,metadata:hR()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=ii(o?.response)||ii(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?eq(t,n,o.name.trim()):void 0}catch{return}}function nq(t){let e=Z$(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function rq(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()},n=JSON.stringify({metadata:hR()}),r;for(let o of L_)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=await s.json();r=i;let a=ii(i);if(a)return a}catch{}for(let o of nq(r))for(let s of L_){let i=await tq(t,o,s);if(i)return i}for(let o of L_)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=ii(await s.json());if(i)return i}catch{}}async function W_(t,e){let n=t?.project_id?.trim();if(n)return n;let r=gf();if(r?.project_id?.trim())return r.project_id.trim();let o=await rq(e);if(o){let s=gf();return s&&z_({...s,project_id:o}),o}}function Ba(){return fR||H_}function gR(t){fR=t}var mR=new Set;function yR(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function _R(t){mR.add(t.replace(/\/$/,""))}function oq(t){return mR.has(t.replace(/\/$/,""))}function bR(t,e){return e?t===404||t===403||t>=500:!1}function CR(t){let e=t?.replace(/\/$/,"")||Ba(),n=[...new Set([e,...G$])],r=n.filter(o=>!oq(o));return r.length?r:n}function mf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function wR(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:z$()}}async function sq(t){try{let e=await fetch(Y$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function iq(t,e){let n=new URLSearchParams({client_id:$_,client_secret:q_,code:t,grant_type:"authorization_code",redirect_uri:cR,code_verifier:e}),r=await fetch(dR,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Antigravity token exchange failed (${r.status}): ${s.slice(0,300)}`)}let o=await r.json();if(!o.access_token||!o.refresh_token)throw new Error("Antigravity token exchange did not return access_token and refresh_token. Re-auth with prompt=consent may be required.");return{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:Date.now()+(o.expires_in||3600)*1e3}}function kR(t){try{let e=JSON.parse(t),n=e?.error?.details||e?.details;if(!Array.isArray(n))return;for(let r of n){let o=r?.retryDelay||r?.retry_delay;if(typeof o=="string"){let s=o.match(/^([\d.]+)s$/);if(s)return Math.ceil(parseFloat(s[1])*1e3)}}}catch{}}function SR(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function cq(t,e){let n=t?.req?.body?.model;return typeof n=="string"&&n?n:typeof t?.req?.model=="string"&&t.req.model?t.req.model:e?.models?.[0]||""}function uq(t){return t?.req?.body?.stream===!0}function lq(t){return CR(t)}var yf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Ma({force:o?.forceRefresh}),i=await W_(n,s.access_token),a=cq(r,n),u=uq(r),d=wR({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||aq(),{body:d,accessToken:s.access_token,projectId:i,model:a,stream:u}}buildHeaders(e,n){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-goog-api-key":void 0,...Na(),...n?{Accept:"text/event-stream"}:{}}}async sendWithFallback(e,n,r,o,s,i=!1){let a=s?.req?.server?.configService?.getHttpsProxy?.(),u=this.logger??s?.req?.log??s?.req?.server?.log,d=o?.baseUrl||o?.api_base_url||Ba(),f=lq(d),p;for(let h=0;h<f.length;h++){let g=f[h],b=mf(g,r),m=this.buildHeaders(n,r);try{let w=await ts(b,e,{httpsProxy:a,headers:Object.fromEntries(Object.entries(m).filter(([,C])=>C!==void 0)),signal:s?.signal},s,u);if(w.status===401&&!i){let C=await Ma({force:!0});return this.sendWithFallback(e,C.access_token,r,o,s,!0)}if(w.status===429){let C=await w.clone().text().catch(()=>""),A=kR(C),k={};throw A!=null&&(k["Retry-After"]=String(Math.ceil(A/1e3))),J(Ge(C)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",k)}if(!w.ok){let C=await w.clone().text().catch(()=>"");if(w.status===403&&yR(C)&&(_R(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),bR(w.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${w.status}`,w.status,"provider_error");continue}throw J(Ge(C)||`Antigravity request failed with ${w.status}`,w.status,w.status===403?"permission_error":"provider_error")}return gR(g),w}catch(w){if(w?.statusCode===429||w?.status===429||!ar(w))throw w;if(p=w,h<f.length-1)continue;throw w}}throw p||J("All Antigravity endpoints failed",502,"provider_error")}async transformRequestIn(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r),s=await this.sendWithFallback(o.body,o.accessToken,o.stream,n,r);return{body:o.body,config:{url:mf(Ba(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream),__providerResponse:s}}}async auth(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r);return{config:{url:mf(n?.baseUrl||Ba(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(ve("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=SR(i);o.controller.enqueue(ve(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}return}o.controller.enqueue(Pe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=SR(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};import{resolveXaiApiKey as Nq}from"@caeliq/ccr-shared";import{closeSync as dq,existsSync as ER,fstatSync as fq,mkdirSync as pq,openSync as hq,readFileSync as gq,renameSync as mq,statSync as vR,unlinkSync as J_,writeFileSync as yq}from"fs";import{dirname as _q,join as bq}from"path";import{homedir as Cq}from"os";var wq=bq(Cq(),".claude-code-router","xai_auth.json"),kq=2*6e4,Sq=35e3,AR={client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_authorization_endpoint:"https://auth.x.ai/oauth2/device/code",token_endpoint:"https://auth.x.ai/oauth2/token",scope:"openid profile email offline_access grok-cli:access api:access"};var qK=300*1e3;var Aq=120,_f=null;function K_(){return process.env.CCR_XAI_AUTH_FILE||wq}function G_(){return`${K_()}.refresh.lock`}function Eq(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function vq(t){if(!t)return;let e=t.split(".");if(!(e.length!==3||!e[1]))try{let n=JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"));return typeof n?.exp=="number"?n.exp:void 0}catch{return}}function Tq(t){let e=vq(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Ua(){try{let t=K_();if(!ER(t))return null;let e=JSON.parse(gq(t,"utf8"));return e.access_token?e:null}catch{return null}}function xq(t){let e=K_();pq(_q(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{yq(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),mq(n,e)}finally{try{ER(n)&&J_(n)}catch{}}}function Rq(t,e=Aq){let n=Tq(t);return n?Date.now()/1e3+e>=n:!1}function Dq(t){try{let e=JSON.parse(t),n=e?.error,r=e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function Oq(t){if(!t.refresh_token)throw new Error("xAI OAuth token cannot be refreshed because no refresh token is available. Run `ccr xai-auth` again.");let e=await fetch(AR.token_endpoint,{method:"POST",headers:Eq(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:AR.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${Dq(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("xAI OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return{access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:typeof r.expires_in=="number"?o+r.expires_in:t.expires_at,last_refresh:o}}function Pq(){let t=G_();try{return hq(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-vR(t).mtimeMs>kq&&J_(t)}catch{}return null}}async function Iq(t){let e=Date.now()+Sq,n=null;for(;n===null&&(n=Pq(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh xAI OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=fq(n).ino;dq(n);try{vR(G_()).ino===r&&J_(G_())}catch{}}}async function Fq(t){return Iq(async()=>{let e=Ua();if(!e)throw new Error("xAI OAuth credentials disappeared while refreshing. Run `ccr xai-auth` again.");if(e.access_token!==t.access_token)return e;let n=await Oq(e),r=Ua();return r&&r.access_token!==e.access_token?r:(xq(n),n)})}async function TR(t){return bf({force:!0})}async function bf(t={}){let e=Ua();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!Rq(e)?e:(_f||(_f=Fq(e).finally(()=>{_f=null})),_f)}var Cf=class{name="xai-auth";logger;async resolveAuth(e){let n=Nq(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await bf()).access_token}}buildConfig(e,n){return{url:`${n?.baseUrl||"https://api.x.ai/v1"}/responses`,headers:{Authorization:`Bearer ${e.token}`},__authRecovery:()=>this.recoverUnauthorizedAuth(e)}}async transformRequestIn(e,n){let r=await this.resolveAuth(n);return{body:e,config:this.buildConfig(r,n)}}async auth(e,n){let r=await this.resolveAuth(n);return{config:this.buildConfig(r,n)}}async recoverUnauthorizedAuth(e){if(e.mode==="pat")return null;let n=Ua();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await TR(n.refresh_token)).access_token}`}:null}};var xR={AnthropicTransformer:xu,GeminiTransformer:Nu,VertexGeminiTransformer:md,VertexClaudeTransformer:Ud,VertexOpenaiTransformer:jd,DeepseekTransformer:vd,TooluseTransformer:Td,OpenrouterTransformer:xd,OpenAITransformer:qd,MaxTokenTransformer:Rd,GroqTransformer:Dd,CleancacheTransformer:Od,EnhanceToolTransformer:Fd,ReasoningTransformer:Nd,SamplingTransformer:Md,MaxCompletionTokens:Bd,CerebrasTransformer:Ld,StreamOptionsTransformer:$d,CustomParamsTransformer:zd,VercelTransformer:Wd,OpenAIResponsesTransformer:Gd,CodexTransformer:Qd,QwenAuthTransformer:ef,ForceReasoningTransformer:tf,ExtraThinkTagTransformer:nf,MistralTransformer:rf,ChromeOnDeviceTransformer:of,OpencodeHeadersTransformer:sf,ClaudeAuthTransformer:vu,CursorSdkTransformer:pf,AntigravityAuthTransformer:yf,XaiAuthTransformer:Cf};var ai=class{constructor(e,n){this.configService=e;this.logger=n}configService;logger;transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let i=s.endPoint;if(!i)return;let a=n.get(i);if(a){this.logger?.debug?.(`transformer ${o} shares endpoint ${i} with ${a}; keeping ${a}`);return}n.set(i,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let i=new o;i&&typeof i=="object"&&(i.logger=this.logger),r(s,i)}catch(i){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${i?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=re(re.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
441
+ `;A(he),ce(ae.content(he))}}}if(!ue)break}!F&&!D&&(ie(),M("stop")),a&&X.enqueue(ae.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:m.metrics},"cursor-sdk stream failed"),await Fa(m,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{de()}},async cancel(){await Fa(m,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=Ze.getReader();for(;;){let{done:ce}=await X.read();if(ce)break}let de=C_(u,Ie);return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(Ze,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function j$(t,e,n){return{cursorMode:t.cursorMode||sf,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var ff=class{static TransformerName=m_;name=m_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=j$(this.options,r,this.logger),s={...e,messages:Ve(e.messages),tools:Ye(e.tools)},i=await iR(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};import{randomUUID as lq}from"crypto";import{existsSync as cR,mkdirSync as U$,readFileSync as L$,renameSync as $$,unlinkSync as q$,writeFileSync as H$}from"fs";import{dirname as z$,join as W$}from"path";import{homedir as G$}from"os";import{randomUUID as J$}from"crypto";var $_="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",q_="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",uR="http://localhost:51121/oauth-callback",K$=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"],H_="https://daily-cloudcode-pa.sandbox.googleapis.com",lR="https://autopush-cloudcode-pa.sandbox.googleapis.com",dR="https://cloudcode-pa.googleapis.com",V$=[H_,lR,dR],L_=[dR,H_,lR],Y$="1.18.3",X$=W$(G$(),".claude-code-router","antigravity_auth.json"),Q$=12e4,fR="https://oauth2.googleapis.com/token",Z$="https://www.googleapis.com/oauth2/v2/userinfo",pf=null,pR=null;function hR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||X$}function Na(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${Y$} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,"X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})}}function hf(){try{let t=hR();if(!cR(t))return null;let e=JSON.parse(L$(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function z_(t){let e=hR();U$(z$(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{H$(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),$$(n,e)}finally{try{cR(n)&&q$(n)}catch{}}}function eq(t){return Date.now()+Q$>=t.expires_at}async function tq(t){let e=new URLSearchParams({client_id:$_,client_secret:q_,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(fR,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e});if(!n.ok){let s=await n.text().catch(()=>"");throw new Error(`Antigravity token refresh failed (${n.status}). Run \`ccr antigravity-auth\` again. ${s.slice(0,200)}`)}let r=await n.json();if(!r.access_token)throw new Error("Antigravity token refresh returned no access_token. Run `ccr antigravity-auth` again.");let o={...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,expires_at:Date.now()+(r.expires_in||3600)*1e3};return z_(o),o}async function Ma(t){let e=hf();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!eq(e)?e:(pf||(pf=tq(e).finally(()=>{pf=null})),pf)}function ii(t){let e=t?.cloudaicompanionProject;if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e.id=="string"&&e.id.trim())return e.id.trim()}function nq(t){let e=n=>{if(n){if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="object"&&typeof n.id=="string"&&n.id.trim())return n.id.trim()}};return e(t?.paidTier)||e(t?.currentTier)||e(t?.allowedTiers?.find(n=>n?.isDefault))||e(t?.allowedTiers?.[0])||void 0}function gR(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function aR(t){await new Promise(e=>setTimeout(e,t))}async function rq(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()};for(let s=0;s<20;s++){try{let i=await fetch(r,{method:"GET",headers:o,signal:AbortSignal.timeout(15e3)});if(!i.ok){await aR(2e3);continue}let a=await i.json();if(a?.done===!0)return ii(a?.response)||ii(a)||void 0}catch{}await aR(2e3)}}async function oq(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()},body:JSON.stringify({tierId:e,metadata:gR()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=ii(o?.response)||ii(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?rq(t,n,o.name.trim()):void 0}catch{return}}function sq(t){let e=nq(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function iq(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Na()},n=JSON.stringify({metadata:gR()}),r;for(let o of L_)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=await s.json();r=i;let a=ii(i);if(a)return a}catch{}for(let o of sq(r))for(let s of L_){let i=await oq(t,o,s);if(i)return i}for(let o of L_)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=ii(await s.json());if(i)return i}catch{}}async function W_(t,e){let n=t?.project_id?.trim();if(n)return n;let r=hf();if(r?.project_id?.trim())return r.project_id.trim();let o=await iq(e);if(o){let s=hf();return s&&z_({...s,project_id:o}),o}}function Ba(){return pR||H_}function mR(t){pR=t}var yR=new Set;function _R(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function bR(t){yR.add(t.replace(/\/$/,""))}function aq(t){return yR.has(t.replace(/\/$/,""))}function CR(t,e){return e?t===404||t===403||t>=500:!1}function wR(t){let e=t?.replace(/\/$/,"")||Ba(),n=[...new Set([e,...V$])],r=n.filter(o=>!aq(o));return r.length?r:n}function gf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function kR(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:J$()}}async function cq(t){try{let e=await fetch(Z$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function uq(t,e){let n=new URLSearchParams({client_id:$_,client_secret:q_,code:t,grant_type:"authorization_code",redirect_uri:uR,code_verifier:e}),r=await fetch(fR,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n});if(!r.ok){let s=await r.text().catch(()=>"");throw new Error(`Antigravity token exchange failed (${r.status}): ${s.slice(0,300)}`)}let o=await r.json();if(!o.access_token||!o.refresh_token)throw new Error("Antigravity token exchange did not return access_token and refresh_token. Re-auth with prompt=consent may be required.");return{access_token:o.access_token,refresh_token:o.refresh_token,expires_at:Date.now()+(o.expires_in||3600)*1e3}}function SR(t){try{let e=JSON.parse(t),n=e?.error?.details||e?.details;if(!Array.isArray(n))return;for(let r of n){let o=r?.retryDelay||r?.retry_delay;if(typeof o=="string"){let s=o.match(/^([\d.]+)s$/);if(s)return Math.ceil(parseFloat(s[1])*1e3)}}}catch{}}function AR(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function dq(t,e){let n=t?.req?.body?.model;return typeof n=="string"&&n?n:typeof t?.req?.model=="string"&&t.req.model?t.req.model:e?.models?.[0]||""}function fq(t){return t?.req?.body?.stream===!0}function pq(t){return wR(t)}var mf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Ma({force:o?.forceRefresh}),i=await W_(n,s.access_token),a=dq(r,n),u=fq(r),d=kR({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||lq(),{body:d,accessToken:s.access_token,projectId:i,model:a,stream:u}}buildHeaders(e,n){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json","x-goog-api-key":void 0,...Na(),...n?{Accept:"text/event-stream"}:{}}}async sendWithFallback(e,n,r,o,s,i=!1){let a=s?.req?.server?.configService?.getHttpsProxy?.(),u=this.logger??s?.req?.log??s?.req?.server?.log,d=o?.baseUrl||o?.api_base_url||Ba(),f=pq(d),p;for(let h=0;h<f.length;h++){let g=f[h],b=gf(g,r),m=this.buildHeaders(n,r);try{let w=await ts(b,e,{httpsProxy:a,headers:Object.fromEntries(Object.entries(m).filter(([,C])=>C!==void 0)),signal:s?.signal},s,u);if(w.status===401&&!i){let C=await Ma({force:!0});return this.sendWithFallback(e,C.access_token,r,o,s,!0)}if(w.status===429){let C=await w.clone().text().catch(()=>""),S=SR(C),k={};throw S!=null&&(k["Retry-After"]=String(Math.ceil(S/1e3))),J(Ge(C)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",k)}if(!w.ok){let C=await w.clone().text().catch(()=>"");if(w.status===403&&_R(C)&&(bR(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),CR(w.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${w.status}`,w.status,"provider_error");continue}throw J(Ge(C)||`Antigravity request failed with ${w.status}`,w.status,w.status===403?"permission_error":"provider_error")}return mR(g),w}catch(w){if(w?.statusCode===429||w?.status===429||!ar(w))throw w;if(p=w,h<f.length-1)continue;throw w}}throw p||J("All Antigravity endpoints failed",502,"provider_error")}async transformRequestIn(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r),s=await this.sendWithFallback(o.body,o.accessToken,o.stream,n,r);return{body:o.body,config:{url:gf(Ba(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream),__providerResponse:s}}}async auth(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r);return{config:{url:gf(n?.baseUrl||Ba(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(ve("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=AR(i);o.controller.enqueue(ve(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}return}o.controller.enqueue(Pe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=AR(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};import{resolveXaiApiKey as jq}from"@caeliq/ccr-shared";import{closeSync as hq,existsSync as vR,fstatSync as gq,mkdirSync as mq,openSync as yq,readFileSync as _q,renameSync as bq,statSync as TR,unlinkSync as J_,writeFileSync as Cq}from"fs";import{dirname as wq,join as kq}from"path";import{homedir as Sq}from"os";var Aq=kq(Sq(),".claude-code-router","xai_auth.json"),Eq=2*6e4,vq=35e3,ER={client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_authorization_endpoint:"https://auth.x.ai/oauth2/device/code",token_endpoint:"https://auth.x.ai/oauth2/token",scope:"openid profile email offline_access grok-cli:access api:access"};var WK=300*1e3;var Tq=120,yf=null;function K_(){return process.env.CCR_XAI_AUTH_FILE||Aq}function G_(){return`${K_()}.refresh.lock`}function xq(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function Rq(t){if(!t)return;let e=t.split(".");if(!(e.length!==3||!e[1]))try{let n=JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"));return typeof n?.exp=="number"?n.exp:void 0}catch{return}}function Dq(t){let e=Rq(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function ja(){try{let t=K_();if(!vR(t))return null;let e=JSON.parse(_q(t,"utf8"));return e.access_token?e:null}catch{return null}}function Oq(t){let e=K_();mq(wq(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{Cq(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),bq(n,e)}finally{try{vR(n)&&J_(n)}catch{}}}function Pq(t,e=Tq){let n=Dq(t);return n?Date.now()/1e3+e>=n:!1}function Iq(t){try{let e=JSON.parse(t),n=e?.error,r=e?.error_description;return[n,r].filter(o=>typeof o=="string").join(": ")}catch{return t.slice(0,240).replace(/(access_token|refresh_token|id_token)["']?\s*[:=]\s*["']?[^"',\s}]+/gi,"$1=<redacted>")}}async function Fq(t){if(!t.refresh_token)throw new Error("xAI OAuth token cannot be refreshed because no refresh token is available. Run `ccr xai-auth` again.");let e=await fetch(ER.token_endpoint,{method:"POST",headers:xq(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:ER.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${Iq(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("xAI OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return{access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:typeof r.expires_in=="number"?o+r.expires_in:t.expires_at,last_refresh:o}}function Nq(){let t=G_();try{return yq(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-TR(t).mtimeMs>Eq&&J_(t)}catch{}return null}}async function Mq(t){let e=Date.now()+vq,n=null;for(;n===null&&(n=Nq(),n===null);){if(Date.now()>=e)throw new Error("Timed out waiting for another CCR process to refresh xAI OAuth credentials.");await new Promise(r=>setTimeout(r,50))}try{return await t()}finally{let r=gq(n).ino;hq(n);try{TR(G_()).ino===r&&J_(G_())}catch{}}}async function Bq(t){return Mq(async()=>{let e=ja();if(!e)throw new Error("xAI OAuth credentials disappeared while refreshing. Run `ccr xai-auth` again.");if(e.access_token!==t.access_token)return e;let n=await Fq(e),r=ja();return r&&r.access_token!==e.access_token?r:(Oq(n),n)})}async function xR(t){return _f({force:!0})}async function _f(t={}){let e=ja();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!Pq(e)?e:(yf||(yf=Bq(e).finally(()=>{yf=null})),yf)}var bf=class{name="xai-auth";logger;async resolveAuth(e){let n=jq(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await _f()).access_token}}buildConfig(e,n){return{url:`${n?.baseUrl||"https://api.x.ai/v1"}/responses`,headers:{Authorization:`Bearer ${e.token}`},__authRecovery:()=>this.recoverUnauthorizedAuth(e)}}async transformRequestIn(e,n){let r=await this.resolveAuth(n);return{body:e,config:this.buildConfig(r,n)}}async auth(e,n){let r=await this.resolveAuth(n);return{config:this.buildConfig(r,n)}}async recoverUnauthorizedAuth(e){if(e.mode==="pat")return null;let n=ja();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await xR(n.refresh_token)).access_token}`}:null}};var RR={AnthropicTransformer:xu,GeminiTransformer:Nu,VertexGeminiTransformer:md,VertexClaudeTransformer:jd,VertexOpenaiTransformer:Ud,DeepseekTransformer:vd,TooluseTransformer:Td,OpenrouterTransformer:xd,OpenAITransformer:qd,MaxTokenTransformer:Rd,GroqTransformer:Dd,CleancacheTransformer:Od,EnhanceToolTransformer:Fd,ReasoningTransformer:Nd,SamplingTransformer:Md,MaxCompletionTokens:Bd,CerebrasTransformer:Ld,StreamOptionsTransformer:$d,CustomParamsTransformer:Hd,VercelTransformer:zd,OpenAIResponsesTransformer:Wd,CodexTransformer:Xd,QwenAuthTransformer:Zd,ForceReasoningTransformer:ef,ExtraThinkTagTransformer:tf,MistralTransformer:nf,ChromeOnDeviceTransformer:rf,OpencodeHeadersTransformer:of,ClaudeAuthTransformer:vu,CursorSdkTransformer:ff,AntigravityAuthTransformer:mf,XaiAuthTransformer:bf};var ai=class{constructor(e,n){this.configService=e;this.logger=n}configService;logger;transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let i=s.endPoint;if(!i)return;let a=n.get(i);if(a){this.logger?.debug?.(`transformer ${o} shares endpoint ${i} with ${a}; keeping ${a}`);return}n.set(i,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let i=new o;i&&typeof i=="object"&&(i.logger=this.logger),r(s,i)}catch(i){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${i?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=re(re.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
442
442
  error: ${n.message}
443
443
  stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
444
- Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(xR).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};import{get_encoding as Mq}from"tiktoken";var ja=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Mq(e)}catch(n){throw new Error(`Failed to initialize tiktoken encoding: ${e}`,{cause:n})}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){if(!this.encoding)throw new Error("Encoding not initialized");let r=u=>this.encoding.encode(u,void 0,[]),o=0,{messages:s,system:i,tools:a}=e;return Array.isArray(s)&&s.forEach(u=>{typeof u.content=="string"?o+=r(u.content).length:Array.isArray(u.content)&&u.content.forEach(d=>{if(d.type==="text")o+=r(d.text).length;else if(d.type==="tool_use")o+=r(JSON.stringify(d.input)).length;else if(d.type==="tool_result"){let f=typeof d.content=="string"?d.content:JSON.stringify(d.content);o+=r(f).length}})}),typeof i=="string"?o+=r(i).length:Array.isArray(i)&&i.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?o+=r(u.text).length:Array.isArray(u.text)&&u.text.forEach(d=>{o+=r(d||"").length}))}),a&&a.forEach(u=>{u.description&&(o+=r(u.name+u.description).length),u.input_schema&&(o+=r(JSON.stringify(u.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e,void 0,[]))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Ef}from"path";import{homedir as J6}from"os";import{existsSync as Q_,mkdirSync as K6}from"fs";import{promises as vf}from"fs";var Bq=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,i=null,a=o;for(;a<n&&(s=s[t[a]]);)s.end&&(i=s.end),++a;i?(o>r&&e.push(t.slice(r,o)),e.push(i),o+=i.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},RR=Bq,Uq=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},jq=Uq,MR=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),Lq=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),$q=Lq(MR),DR=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",qq=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${DR}])]+`,` ?[^\\s${DR}]+`]]),wf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Y_=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),kf=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");n=n.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,o]of qq)n=n.replaceAll(r,o);try{return new RegExp(n,"gu")}catch(r){if(!(r instanceof SyntaxError)||!r.message.toLowerCase().includes("invalid property name"))throw r;let o=!1,s=n.replace(/(\\[pP])\{([^}=]+)\}/g,(i,a,u)=>{try{return new RegExp(`\\p{${u}}`,"u"),`${a}{${u}}`}catch{return o=!0,`${a}{Script=${u}}`}});if(!o)throw r;try{return new RegExp(s,"gu")}catch{throw r}}}else if(t.String!==void 0){let n=Hq(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Hq=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),zq=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},Wq=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,Gq=t=>Number.isInteger(t)||typeof t=="bigint",Jq=t=>{let e=0;for(let n of t)++e;return e},Kq=t=>BR(t.toLowerCase()),hn=(...t)=>Array.prototype.concat.apply([],t),X_=t=>new Map(Object.entries(t)),Vq=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},BR=t=>t.replace(new RegExp("\\p{M}","gu"),""),OR=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},Yq=t=>t.match(/\S+/g)||[],Xq=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},La=Xq,Qq=class extends La{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Sr=Qq,Zq=class extends Sr{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);Wq(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
445
- `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},e4=Zq,t4=class extends Sr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(n=>n.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},n4=t4,r4=class extends Sr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>UR(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},o4=r4,s4=class extends Sr{normalize(t){let e=kf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},i4=s4,a4=class extends Sr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Sf=a4,c4=class extends Sf{constructor(){super(...arguments),this.form="NFC"}},u4=c4,l4=class extends Sf{constructor(){super(...arguments),this.form="NFD"}},d4=l4,f4=class extends Sf{constructor(){super(...arguments),this.form="NFKC"}},p4=f4,h4=class extends Sf{constructor(){super(...arguments),this.form="NFKD"}},g4=h4,m4=class extends Sr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},y4=m4,_4=class extends Sr{normalize(t){return BR(t)}},b4=_4,C4=class extends Sr{normalize(t){return t.toLowerCase()}},w4=C4,k4=class extends Sr{normalize(t){return t=this.config.prepend+t,t}},S4=k4;function A4(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new e4(t);case"Precompiled":return new n4(t);case"Sequence":return new o4(t);case"Replace":return new i4(t);case"NFC":return new u4(t);case"NFD":return new d4(t);case"NFKC":return new p4(t);case"NFKD":return new g4(t);case"Strip":return new y4(t);case"StripAccents":return new b4(t);case"Lowercase":return new w4(t);case"Prepend":return new S4(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var UR=A4,E4=class extends La{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},gn=E4,v4=class extends gn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=MR,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),o=>this.byte_encoder[o]).join(""))}},T4=v4,x4=class extends gn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},R4=x4,D4=class extends gn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},O4=D4,P4=class extends gn{constructor(t){super(),this.config=t,this.pattern=kf(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Vq(t,this.pattern)}},I4=P4,F4=class extends gn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${wf}]+|[${wf}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},N4=F4,M4=class extends gn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},B4=M4,U4=class extends gn{constructor(){super(),this.pattern=new RegExp(`[^\\s${wf}]+|[${wf}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},j4=U4,L4=class extends gn{constructor(t){super(),this.config=t,this.pattern=kf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},$4=L4,q4=class extends gn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>jR(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},H4=q4,z4=class extends gn{pre_tokenize_text(t){return Yq(t)}},W4=z4,G4=class extends gn{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let n=0;n<t.length;n+=this._length)e.push(t.slice(n,n+this._length));return e}},J4=G4;function K4(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new j4;case"Sequence":return new H4(t);case"Whitespace":return new R4;case"WhitespaceSplit":return new W4;case"Metaspace":return new O4(t);case"ByteLevel":return new T4(t);case"Split":return new I4(t);case"Punctuation":return new N4(t);case"Digits":return new B4(t);case"Replace":return new $4(t);case"FixedLength":return new J4(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var jR=K4,V4=class extends La{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=zq(e,this.tokens_to_ids,this.unk_token_id)),e}},Af=V4,Y4=class extends Af{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=X_(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,i=[];for(;s<r.length;){let a=r.length,u=null;for(;s<a;){let d=r.slice(s,a).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){u=d;break}--a}if(u===null){o=!0;break}i.push(u),s=a}o?e.push(this.unk_token):e.push(...i)}return e}},PR=Y4,IR=class LR{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new LR(!1,new Map)}},X4=class{constructor(){this.root=IR.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=IR.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},Q4=X4,V_=class $R{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new $R(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},Z4=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new V_(this.bos_token_id??0,0,0,0,0),o=new V_(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new V_(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let a=0,u=null;for(let d of this.end_nodes[e]){let f=d.backtrace_score+i.score;(u===null||f>a)&&(u=d.clone(),a=f)}if(u!==null)i.prev=u,i.backtrace_score=a;else return[]}++e}let n=[],o=this.begin_nodes[t][0].prev;if(o===null)return[];let s=o.clone();for(;s.prev!==null;)n.push(s.clone()),s=s.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},e6=Z4;function t6(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var n6=class extends Af{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=t6(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new Q4,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],i=e.slice(r).join(""),a=this.trie.common_prefix_search(i);for(let u of a){s.push(u);let d=this.tokens_to_ids.get(u),f=this.scores[d],p=Jq(u);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new e6(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},FR=n6,r6=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},o6=r6,s6=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},i6=s6,a6=class extends Af{constructor(t){super(t),this.tokens_to_ids=X_(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new i6(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new o6((a,u)=>a.score<u.score),s={token:n[0],bias:0,prev:null,next:null},i=s;for(let a=1;a<n.length;++a){let u={bias:a/n.length,token:n[a],prev:i,next:null};i.next=u,this.add_node(o,i),i=u}for(;!o.is_empty();){let a=o.pop();if(a.deleted||!a.next||a.next.deleted)continue;if(a.deleted=!0,a.next.deleted=!0,a.prev){let d={...a.prev};a.prev.deleted=!0,a.prev=d,d.prev?d.prev.next=d:s=d}let u={token:a.token+a.next.token,bias:a.bias,prev:a.prev,next:a.next.next};u.prev?(u.prev.next=u,this.add_node(o,u.prev)):s=u,u.next&&(u.next.prev=u,this.add_node(o,u))}for(let a=s;a!==null;a=a.next)r.push(a.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(i=>`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(i=>this.tokens_to_ids.has(i))?e.push(...s):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},NR=a6,c6=class extends Af{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=X_(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},u6=c6;function l6(t,e){switch(t.type){case"WordPiece":return new PR(t);case"Unigram":return new FR(t,e.eos_token);case"BPE":return new NR(t);default:if(t.vocab)return Array.isArray(t.vocab)?new FR(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new NR(t):new PR(t):new u6(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var d6=l6,f6=class extends La{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},$a=f6,p6=class extends $a{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let i of r)"SpecialToken"in i?n&&(o.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(o=hn(o,t),s=hn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=hn(o,e),s=hn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},h6=p6,g6=class extends $a{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},m6=g6,y6=class extends $a{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},_6=y6,b6=class extends $a{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},C6=b6,w6=class extends $a{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>qR(e))}post_process(t,e=null,n=!0){let r={tokens:t,tokens_pair:e};for(let o of this.processors)r=o.post_process(r.tokens,r.tokens_pair,n);return r}},k6=w6;function S6(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new h6(t);case"ByteLevel":return new m6(t);case"BertProcessing":return new _6(t);case"RobertaProcessing":return new C6(t);case"Sequence":return new k6(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var qR=S6,A6=class extends La{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Gn=A6,E6=class extends Gn{constructor(t){super(t),this.byte_decoder=$q,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},v6=E6,T6=class extends Gn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=Y_(e)),e})}},x6=T6,R6=class extends Gn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},D6=R6,O6=class extends Gn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},P6=O6,I6=class extends Gn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let o=1;o<t.length;++o)t[o]!==e.at(-1)&&e.push(t[o]);let r=e.filter(o=>o!==this.pad_token).join("");return this.cleanup&&(r=Y_(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},F6=I6,N6=class extends Gn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>HR(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},M6=N6,B6=class extends Gn{decode_chain(t){let e=kf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},U6=B6,j6=class extends Gn{decode_chain(t){return[t.join("")]}},L6=j6,$6=class extends Gn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o){n=o+1;continue}let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},q6=$6,H6=class extends Gn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},z6=H6;function W6(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new v6(t);case"WordPiece":return new x6(t);case"Metaspace":return new D6(t);case"BPEDecoder":return new P6(t);case"CTC":return new F6(t);case"Sequence":return new M6(t);case"Replace":return new U6(t);case"Fuse":return new L6(t);case"Strip":return new q6(t);case"ByteFallback":return new z6(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var HR=W6,G6=class{constructor(t,e){let n=OR(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=OR(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=UR(this.tokenizer.normalizer),this.pre_tokenizer=jR(this.tokenizer.pre_tokenizer),this.model=d6(this.tokenizer.model,this.config),this.post_processor=qR(this.tokenizer.post_processor),this.decoder=HR(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let o=[],s=[];this.added_tokens_map=new Map;for(let i of this.tokenizer.added_tokens){let a=new jq(i);if(this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id)),this.added_tokens_map.set(a.content,a),a.normalized&&this.normalizer!==null){let u=this.normalizer(a.content);s.push(u),this.added_tokens_map.set(u,a)}else o.push(a.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new RR(o),this.splitter_normalized=new RR(s),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),i=o.map(u=>this.added_tokens_map.get(u)?.id??this.model.tokens_to_ids.get(u)??this.model.unk_token_id),a={ids:i,tokens:o,attention_mask:new Array(i.length).fill(1)};return r&&s&&(a.token_type_ids=s),a}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!Gq(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=t.map(o=>this.model.vocab[Number(o)]??this.model.unk_token);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Y_(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=Kq(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.splitter_normalized.split(n);return o.forEach((s,i)=>{let a=this.added_tokens_map.get(s);a&&(a.lstrip&&i>0&&(o[i-1]=o[i-1].trimEnd()),a.rstrip&&i<o.length-1&&(o[i+1]=o[i+1].trimStart()))}),o.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:r}):[s];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:hn(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(t||!this.added_tokens_map.has(r))&&e.set(r,n)}return e}},zR=G6;var Tf=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||Ef(J6(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Ef(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Ef(e,"tokenizer.json"),tokenizerConfig:Ef(e,"tokenizer_config.json")}}ensureDir(e){Q_(e)||K6(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Q_(e.tokenizerJson)||!Q_(e.tokenizerConfig))return null;let[n,r]=await Promise.all([vf.readFile(e.tokenizerJson,"utf-8"),vf.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[a,u]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([vf.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),vf.writeFile(e.tokenizerConfig,JSON.stringify(u,null,2))]),{tokenizerJson:a,tokenizerConfig:u}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`),this.ensureDir(this.cacheDir);let e=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new zR(e.tokenizerJson,e.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`,{cause:e})}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let i of r)if(typeof i.content=="string")n.push(i.content);else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"&&a.text?n.push(a.text):a.type==="tool_use"&&a.input?n.push(JSON.stringify(a.input)):a.type==="tool_result"&&n.push(typeof a.content=="string"?a.content:JSON.stringify(a.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let i of o)if(i.type==="text"){if(typeof i.text=="string")n.push(i.text);else if(Array.isArray(i.text))for(let a of i.text)a&&n.push(a)}}if(s)for(let i of s)i.name&&n.push(i.name),i.description&&n.push(i.description),i.input_schema&&n.push(JSON.stringify(i.input_schema));return n.join(" ")}};var xf=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch(e){throw new Error(`Invalid API URL: ${this.config.url}`,{cause:e})}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),i=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!i.ok)throw new Error(`API tokenizer request failed: ${i.status} ${i.statusText}`);let a=await i.json();return this.extractTokenCount(a)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out",{cause:n}):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`,{cause:n})}}};var ci=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new ja("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new ja(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new Tf(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new xf(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var Z_=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},WR=new Z_;var VR=nr($p(),1);e0();t0();n0();JR();var Uo=new Map;function YR(t){let e=Uo.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function XR(){return Array.from(Uo.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var o0=new Map,QR={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,VR.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)ui.registerHandlers(n.outputHandlers);else{let s=[];for(let i of r)i==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):i==="webhook"&&t.log.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&ui.registerHandlers(s)}n.outputOptions&&ui.setDefaultOptions(n.outputOptions);let o=async s=>{let i=t.tokenizerService;if(!i)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let a=s.provider,u=s.model,d=`${a}:${u}`;if(o0.has(d))return o0.get(d);let f=i.getTokenizerConfigForModel(a,u);if(!f)return t.log?.debug(`No tokenizer config for ${a}:${u}, using fallback`),null;try{let p=await i.getTokenizer(f);return o0.set(d,p),t.log?.info(`Created tokenizer for ${a}:${u} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${a}:${u}: ${p.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,i,a)=>{let u=s.requestStartTime;if(!u)return;let d=s.id||Date.now().toString(),f;try{let b=s.body?.metadata?.user_id;if(b&&typeof b=="string"){let m=b.match(/_session_([a-f0-9-]+)/i);f=m?m[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(a instanceof ReadableStream){Uo.set(d,{requestId:d,sessionId:f,startTime:u,lastTokenTime:u,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[b,m]=a.tee();return(async()=>{let C=null,A=async k=>{let E=Uo.get(d);if(!E)return;let x=performance.now();if(k){let O=(E.lastTokenTime-E.startTime)/1e3;O>0&&(E.tokensPerSecond=Math.round(E.tokenCount/O))}else{let O=x-1e3;E.tokenTimestamps=E.tokenTimestamps.filter(q=>q>O),E.tokensPerSecond=E.tokenTimestamps.length}await KR(E,r,n.outputOptions,k,t.log).catch(O=>{t.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let E=m.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader();for(C=setInterval(async()=>{Uo.get(d)&&await A(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=Uo.get(d);if(!V)continue;let j=performance.now();if(!V.firstTokenTime&&(q.event==="content_block_start"||q.event==="content_block_delta"||q.event==="text_block"||q.event==="content_block")&&(V.firstTokenTime=j,V.timeToFirstToken=Math.round(j-V.startTime)),q.event==="content_block_delta"&&q.data?.delta){let ee=q.data.delta.type,z="";if(ee==="text_delta"?z=q.data.delta.text||"":ee==="input_json_delta"?z=q.data.delta.partial_json||"":ee==="thinking_delta"&&(z=q.data.delta.thinking||""),z){let te=p&&p.encodeText?p.encodeText(z).length:Wa(z);V.tokenCount+=te,V.lastTokenTime=j;for(let Q=0;Q<te;Q++)V.tokenTimestamps.push(j)}}q.event==="message_stop"&&(C&&(clearInterval(C),C=null),await A(!0),Uo.delete(d))}}catch(k){C&&clearInterval(C),k.name!=="AbortError"&&k.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${k.message}`)}})().catch(C=>{t.log.error(C,"Background stats processing failed")}),b}let h=performance.now(),g=0;if(a&&typeof a=="string")try{let b=JSON.parse(a);if(b.usage?.output_tokens)g=b.usage.output_tokens;else{let m=b.content||b.message?.content||"";if(p)Array.isArray(m)?g=m.reduce((w,C)=>{if(C.type==="text"){let A=C.text||"";return w+(p.encodeText?p.encodeText(A).length:Wa(A))}return w},0):typeof m=="string"&&(g=p.encodeText?p.encodeText(m).length:Wa(m));else{let w=Array.isArray(m)?m.map(C=>C.text).join(""):m;g=Wa(w)}}}catch{}if(g>0){let b=(h-u)/1e3,m={requestId:d,sessionId:f,startTime:u,lastTokenTime:h,tokenCount:g,tokensPerSecond:b>0?Math.round(g/b):0,timeToFirstToken:Math.round(h-u),stream:!1,tokenTimestamps:[]};await KR(m,r,n.outputOptions,!0,t.log)}return a})})};function Wa(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function KR(t,e,n,r=!1,o){let s=r?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:s,metadata:{sessionId:t.sessionId},...n};for(let u of e)try{await ui.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function nH(t={}){let e=Z6({bodyLimit:52428800,...t});return e.setErrorHandler(nw),e.register(eH),e.register(ZR.default,{global:!0,...tH}),e}var s0=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=nH({...r,logger:r.logger??!0}),this.configService=new Qo({...e,logger:this.app.log}),this.transformerService=new ai(this.configService,this.app.log),this.tokenizerService=new ci(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new gs(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async a=>{a.decorate("configService",this.configService),a.decorate("transformerService",this.transformerService),a.decorate("providerService",this.providerService),a.decorate("tokenizerService",this.tokenizerService),await Lh(a)});return}if(!n)throw new Error("options is required");let r=new Qo({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ai(r,this.app.log);await o.initialize();let s=new gs(r,o,this.app.log),i=new ci(r,this.app.log);await i.initialize(),await this.app.register(async a=>{a.decorate("configService",r),a.decorate("transformerService",o),a.decorate("providerService",s),a.decorate("tokenizerService",i),await Lh(a)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{let i=new URL(`http://127.0.0.1${r.url}`),a=cr(r.method,i.pathname);if(a&&r.body){let u=r.body;a.protocol==="anthropic_messages"&&(r.log.info({data:u,type:"request body"}),u.stream||(u.stream=!1))}s()}),await this.registerNamespace("/");let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},tX=s0;export{$_ as ANTIGRAVITY_CLIENT_ID,q_ as ANTIGRAVITY_CLIENT_SECRET,cR as ANTIGRAVITY_REDIRECT_URI,W$ as ANTIGRAVITY_SCOPES,Qo as ConfigService,Lc as DEFAULT_LOG_BODY_MAX_BYTES,gs as ProviderService,Tn as SSEParserTransform,ms as SSESerializerTransform,ci as TokenizerService,ai as TransformerService,sk as calculateTokenCount,tX as default,MO as diffHeadersForLog,iq as exchangeAuthorizationCode,sq as fetchUserEmail,Ma as getAntigravityAccessToken,Eu as getClaudeAccessToken,Yd as getCodexAccessToken,XR as getGlobalTokenSpeedStats,f_ as getQwenAccessToken,YR as getTokenSpeedStats,Ma as getValidAccessToken,bf as getXaiAccessToken,Je as isClientAbortError,xP as isRoutedLlmPost,vh as listClientRouteRegistrations,gf as loadTokens,cr as matchClientProtocol,WR as pluginManager,Hi as protocolErrorBody,W_ as resolveProjectId,kk as rewriteStream,Mh as router,ch as sanitizeBodyForLog,ih as sanitizeHeadersForLog,z_ as saveTokens,ak as searchProjectBySession,Ih as sessionUsageCache,WO as setHealthReporter,QR as tokenSpeedPlugin};
444
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(RR).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};import{get_encoding as Uq}from"tiktoken";var Ua=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Uq(e)}catch(n){throw new Error(`Failed to initialize tiktoken encoding: ${e}`,{cause:n})}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){if(!this.encoding)throw new Error("Encoding not initialized");let r=u=>this.encoding.encode(u,void 0,[]),o=0,{messages:s,system:i,tools:a}=e;return Array.isArray(s)&&s.forEach(u=>{typeof u.content=="string"?o+=r(u.content).length:Array.isArray(u.content)&&u.content.forEach(d=>{if(d.type==="text")o+=r(d.text).length;else if(d.type==="tool_use")o+=r(JSON.stringify(d.input)).length;else if(d.type==="tool_result"){let f=typeof d.content=="string"?d.content:JSON.stringify(d.content);o+=r(f).length}})}),typeof i=="string"?o+=r(i).length:Array.isArray(i)&&i.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?o+=r(u.text).length:Array.isArray(u.text)&&u.text.forEach(d=>{o+=r(d||"").length}))}),a&&a.forEach(u=>{u.description&&(o+=r(u.name+u.description).length),u.input_schema&&(o+=r(JSON.stringify(u.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e,void 0,[]))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Af}from"path";import{homedir as Y6}from"os";import{existsSync as Q_,mkdirSync as X6}from"fs";import{promises as Ef}from"fs";var Lq=class{constructor(t){this.trie=this._build_trie(t)}_build_trie(t){let e=Object.create(null);for(let n of t){let r=e;for(let o=0;o<n.length;++o){let s=n[o];r=r[s]??=Object.create(null)}r.end=n}return e}split(t){let e=[],n=t.length,r=0,o=0;for(;o<n;){let s=this.trie,i=null,a=o;for(;a<n&&(s=s[t[a]]);)s.end&&(i=s.end),++a;i?(o>r&&e.push(t.slice(r,o)),e.push(i),o+=i.length,r=o):++o}return r<n&&e.push(t.slice(r)),e}},DR=Lq,$q=class{constructor(t){this.content=t.content,this.id=t.id,this.single_word=t.single_word??!1,this.lstrip=t.lstrip??!1,this.rstrip=t.rstrip??!1,this.special=t.special??!1,this.normalized=t.normalized??!this.special}},qq=$q,BR=(()=>{let t=[...Array.from({length:94},(o,s)=>s+33),...Array.from({length:12},(o,s)=>s+161),...Array.from({length:82},(o,s)=>s+174)],e=t.slice(),n=0;for(let o=0;o<256;++o)t.includes(o)||(t.push(o),e.push(256+n),n+=1);let r=e.map(o=>String.fromCharCode(o));return Object.fromEntries(t.map((o,s)=>[o,r[s]]))})(),Hq=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),zq=Hq(BR),OR=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",Wq=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${OR}])]+`,` ?[^\\s${OR}]+`]]),Cf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",Y_=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),wf=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");n=n.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,o]of Wq)n=n.replaceAll(r,o);try{return new RegExp(n,"gu")}catch(r){if(!(r instanceof SyntaxError)||!r.message.toLowerCase().includes("invalid property name"))throw r;let o=!1,s=n.replace(/(\\[pP])\{([^}=]+)\}/g,(i,a,u)=>{try{return new RegExp(`\\p{${u}}`,"u"),`${a}{${u}}`}catch{return o=!0,`${a}{Script=${u}}`}});if(!o)throw r;try{return new RegExp(s,"gu")}catch{throw r}}}else if(t.String!==void 0){let n=Gq(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Gq=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Jq=(t,e,n)=>{let r=[],o=0;for(;o<t.length;){if(r.push(t[o]),(e.get(t[o])??n)!==n){++o;continue}for(;++o<t.length&&(e.get(t[o])??n)===n;)e.get(r.at(-1))!==n&&(r[r.length-1]+=t[o])}return r},Kq=t=>t>=19968&&t<=40959||t>=13312&&t<=19903||t>=131072&&t<=173791||t>=173824&&t<=177983||t>=177984&&t<=178207||t>=178208&&t<=183983||t>=63744&&t<=64255||t>=194560&&t<=195103,Vq=t=>Number.isInteger(t)||typeof t=="bigint",Yq=t=>{let e=0;for(let n of t)++e;return e},Xq=t=>jR(t.toLowerCase()),hn=(...t)=>Array.prototype.concat.apply([],t),X_=t=>new Map(Object.entries(t)),Qq=(t,e)=>{let n=[],r=0;for(let o of t.matchAll(e)){let s=o[0];r<o.index&&n.push(t.slice(r,o.index)),s.length>0&&n.push(s),r=o.index+s.length}return r<t.length&&n.push(t.slice(r)),n},jR=t=>t.replace(new RegExp("\\p{M}","gu"),""),PR=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},Zq=t=>t.match(/\S+/g)||[],e4=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},La=e4,t4=class extends La{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Sr=t4,n4=class extends Sr{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);Kq(o)?(e.push(" "),e.push(r),e.push(" ")):e.push(r)}return e.join("")}strip_accents(t){return t.normalize("NFD").replace(new RegExp("\\p{Mn}","gu"),"")}is_control(t){switch(t){case" ":case`
445
+ `:case"\r":return!1;default:return new RegExp("^\\p{Cc}|\\p{Cf}|\\p{Co}|\\p{Cs}$","u").test(t)}}clean_text(t){let e=[];for(let n of t){let r=n.charCodeAt(0);r===0||r===65533||this.is_control(n)||(/^\s$/.test(n)?e.push(" "):e.push(n))}return e.join("")}normalize(t){return this.config.clean_text&&(t=this.clean_text(t)),this.config.handle_chinese_chars&&(t=this.tokenize_chinese_chars(t)),this.config.lowercase?(t=t.toLowerCase(),this.config.strip_accents!==!1&&(t=this.strip_accents(t))):this.config.strip_accents&&(t=this.strip_accents(t)),t}},r4=n4,o4=class extends Sr{constructor(t){super(t),this.charsmap=t.precompiled_charsmap??null}normalize(t){return t=t.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),t=t.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),t.includes("\uFF5E")?t=t.split("\uFF5E").map(n=>n.normalize("NFKC")).join("\uFF5E"):t=t.normalize("NFKC"),t}},s4=o4,i4=class extends Sr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>UR(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},a4=i4,c4=class extends Sr{normalize(t){let e=wf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},u4=c4,l4=class extends Sr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},kf=l4,d4=class extends kf{constructor(){super(...arguments),this.form="NFC"}},f4=d4,p4=class extends kf{constructor(){super(...arguments),this.form="NFD"}},h4=p4,g4=class extends kf{constructor(){super(...arguments),this.form="NFKC"}},m4=g4,y4=class extends kf{constructor(){super(...arguments),this.form="NFKD"}},_4=y4,b4=class extends Sr{normalize(t){return this.config.strip_left&&this.config.strip_right?t=t.trim():(this.config.strip_left&&(t=t.trimStart()),this.config.strip_right&&(t=t.trimEnd())),t}},C4=b4,w4=class extends Sr{normalize(t){return jR(t)}},k4=w4,S4=class extends Sr{normalize(t){return t.toLowerCase()}},A4=S4,E4=class extends Sr{normalize(t){return t=this.config.prepend+t,t}},v4=E4;function T4(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new r4(t);case"Precompiled":return new s4(t);case"Sequence":return new a4(t);case"Replace":return new u4(t);case"NFC":return new f4(t);case"NFD":return new h4(t);case"NFKC":return new m4(t);case"NFKD":return new _4(t);case"Strip":return new C4(t);case"StripAccents":return new k4(t);case"Lowercase":return new A4(t);case"Prepend":return new v4(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var UR=T4,x4=class extends La{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},gn=x4,R4=class extends gn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=BR,this.text_encoder=new TextEncoder}pre_tokenize_text(t,e){return this.add_prefix_space&&!t.startsWith(" ")&&(t=" "+t),(this.use_regex?t.match(this.pattern)||[]:[t]).map(r=>Array.from(this.text_encoder.encode(r),o=>this.byte_encoder[o]).join(""))}},D4=R4,O4=class extends gn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},P4=O4,I4=class extends gn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},F4=I4,N4=class extends gn{constructor(t){super(),this.config=t,this.pattern=wf(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Qq(t,this.pattern)}},M4=N4,B4=class extends gn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Cf}]+|[${Cf}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},j4=B4,U4=class extends gn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},L4=U4,$4=class extends gn{constructor(){super(),this.pattern=new RegExp(`[^\\s${Cf}]+|[${Cf}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},q4=$4,H4=class extends gn{constructor(t){super(),this.config=t,this.pattern=wf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},z4=H4,W4=class extends gn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>LR(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},G4=W4,J4=class extends gn{pre_tokenize_text(t){return Zq(t)}},K4=J4,V4=class extends gn{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let n=0;n<t.length;n+=this._length)e.push(t.slice(n,n+this._length));return e}},Y4=V4;function X4(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new q4;case"Sequence":return new G4(t);case"Whitespace":return new P4;case"WhitespaceSplit":return new K4;case"Metaspace":return new F4(t);case"ByteLevel":return new D4(t);case"Split":return new M4(t);case"Punctuation":return new j4(t);case"Digits":return new L4(t);case"Replace":return new z4(t);case"FixedLength":return new Y4(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var LR=X4,Q4=class extends La{constructor(t){super(),this.config=t,this.vocab=[],this.tokens_to_ids=new Map,this.unk_token_id=void 0,this.unk_token=void 0,this.end_of_word_suffix=void 0,this.fuse_unk=this.config.fuse_unk??!1}_call(t){let e=this.encode(t);return this.fuse_unk&&(e=Jq(e,this.tokens_to_ids,this.unk_token_id)),e}},Sf=Q4,Z4=class extends Sf{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=X_(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.max_input_chars_per_word=t.max_input_chars_per_word??100,this.vocab=new Array(this.tokens_to_ids.size);for(let[e,n]of this.tokens_to_ids)this.vocab[n]=e}encode(t){let e=[];for(let n of t){let r=[...n];if(r.length>this.max_input_chars_per_word){e.push(this.unk_token);continue}let o=!1,s=0,i=[];for(;s<r.length;){let a=r.length,u=null;for(;s<a;){let d=r.slice(s,a).join("");if(s>0&&(d=this.config.continuing_subword_prefix+d),this.tokens_to_ids.has(d)){u=d;break}--a}if(u===null){o=!0;break}i.push(u),s=a}o?e.push(this.unk_token):e.push(...i)}return e}},IR=Z4,FR=class $R{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new $R(!1,new Map)}},e6=class{constructor(){this.root=FR.default()}extend(t){for(let e of t)this.push(e)}push(t){let e=this.root;for(let n of t){let r=e.children.get(n);r===void 0&&(r=FR.default(),e.children.set(n,r)),e=r}e.is_leaf=!0}*common_prefix_search(t){let e=this.root;if(e===void 0)return;let n="";for(let r of t){if(n+=r,e=e.children.get(r),e===void 0)return;e.is_leaf&&(yield n)}}},t6=e6,V_=class qR{constructor(e,n,r,o,s){this.token_id=e,this.node_id=n,this.pos=r,this.length=o,this.score=s,this.prev=null,this.backtrace_score=0}clone(){let e=new qR(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},n6=class{constructor(t,e,n){this.chars=Array.from(t),this.len=this.chars.length,this.bos_token_id=e,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new V_(this.bos_token_id??0,0,0,0,0),o=new V_(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(o.clone()),this.begin_nodes[this.len].push(o),this.end_nodes[0].push(r)}insert(t,e,n,r){let o=this.nodes.length,s=new V_(r,o,t,e,n);this.begin_nodes[t].push(s),this.end_nodes[t+e].push(s),this.nodes.push(s)}viterbi(){let t=this.len,e=0;for(;e<=t;){if(this.begin_nodes[e].length==0)return[];for(let i of this.begin_nodes[e]){i.prev=null;let a=0,u=null;for(let d of this.end_nodes[e]){let f=d.backtrace_score+i.score;(u===null||f>a)&&(u=d.clone(),a=f)}if(u!==null)i.prev=u,i.backtrace_score=a;else return[]}++e}let n=[],o=this.begin_nodes[t][0].prev;if(o===null)return[];let s=o.clone();for(;s.prev!==null;)n.push(s.clone()),s=s.clone().prev.clone();return n.reverse(),n}piece(t){return this.chars.slice(t.pos,t.pos+t.length).join("")}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}},r6=n6;function o6(t){if(t.length===0)throw new Error("Array must not be empty");let e=t[0],n=0;for(let r=1;r<t.length;++r)t[r]<e&&(e=t[r],n=r);return[e,n]}var s6=class extends Sf{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=o6(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new t6,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(t){let e=t.chars,n=1,r=0;for(;r<e.length;){let o=!1,s=[],i=e.slice(r).join(""),a=this.trie.common_prefix_search(i);for(let u of a){s.push(u);let d=this.tokens_to_ids.get(u),f=this.scores[d],p=Yq(u);t.insert(r,p,f,d),!o&&p===n&&(o=!0)}o||t.insert(r,n,this.unk_score,this.unk_token_id),r+=n}}tokenize(t){let e=new r6(t,this.bos_token_id,this.eos_token_id);return this.populate_nodes(e),e.tokens()}encode(t){let e=[];for(let n of t){let r=this.tokenize(n);e.push(...r)}return e}},NR=s6,i6=class{constructor(t=(n,r)=>n>r,e=1/0){this._heap=[],this._comparator=t,this._max_size=e}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...t){return this.extend(t)}extend(t){for(let e of t)if(this.size<this._max_size)this._heap.push(e),this._sift_up();else{let n=this._smallest();this._comparator(e,this._heap[n])&&(this._heap[n]=e,this._sift_up_from(n))}return this.size}pop(){let t=this.peek(),e=this.size-1;return e>0&&this._swap(0,e),this._heap.pop(),this._sift_down(),t}replace(t){let e=this.peek();return this._heap[0]=t,this._sift_down(),e}_parent(t){return(t+1>>>1)-1}_left(t){return(t<<1)+1}_right(t){return t+1<<1}_greater(t,e){return this._comparator(this._heap[t],this._heap[e])}_swap(t,e){let n=this._heap[t];this._heap[t]=this._heap[e],this._heap[e]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(t){for(;t>0&&this._greater(t,this._parent(t));)this._swap(t,this._parent(t)),t=this._parent(t)}_sift_down(){let t=0;for(;this._left(t)<this.size&&this._greater(this._left(t),t)||this._right(t)<this.size&&this._greater(this._right(t),t);){let e=this._right(t)<this.size&&this._greater(this._right(t),this._left(t))?this._right(t):this._left(t);this._swap(t,e),t=e}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},a6=i6,c6=class{constructor(t){this.capacity=t,this.cache=new Map}get(t){if(!this.cache.has(t))return;let e=this.cache.get(t);return this.cache.delete(t),this.cache.set(t,e),e}put(t,e){this.cache.has(t)&&this.cache.delete(t),this.cache.set(t,e),this.cache.size>this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},u6=c6,l6=class extends Sf{constructor(t){super(t),this.tokens_to_ids=X_(t.vocab),this.unk_token_id=this.tokens_to_ids.get(t.unk_token),this.unk_token=t.unk_token,this.vocab=new Array(this.tokens_to_ids.size);for(let[n,r]of this.tokens_to_ids)this.vocab[r]=n;let e=Array.isArray(t.merges[0]);this.merges=e?t.merges:t.merges.map(n=>n.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((n,r)=>[JSON.stringify(n),r])),this.end_of_word_suffix=t.end_of_word_suffix,this.continuing_subword_suffix=t.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new u6(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(t){if(t.length===0)return[];let e=this.cache.get(t);if(e!==void 0)return e;let n=Array.from(t);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let o=new a6((a,u)=>a.score<u.score),s={token:n[0],bias:0,prev:null,next:null},i=s;for(let a=1;a<n.length;++a){let u={bias:a/n.length,token:n[a],prev:i,next:null};i.next=u,this.add_node(o,i),i=u}for(;!o.is_empty();){let a=o.pop();if(a.deleted||!a.next||a.next.deleted)continue;if(a.deleted=!0,a.next.deleted=!0,a.prev){let d={...a.prev};a.prev.deleted=!0,a.prev=d,d.prev?d.prev.next=d:s=d}let u={token:a.token+a.next.token,bias:a.bias,prev:a.prev,next:a.next.next};u.prev?(u.prev.next=u,this.add_node(o,u.prev)):s=u,u.next&&(u.next.prev=u,this.add_node(o,u))}for(let a=s;a!==null;a=a.next)r.push(a.token)}else r=n;if(this.continuing_subword_suffix)for(let o=0;o<r.length-1;++o)r[o]+=this.continuing_subword_suffix;return t.length<this.max_length_to_cache&&this.cache.put(t,r),r}add_node(t,e){let n=this.bpe_ranks.get(JSON.stringify([e.token,e.next.token]));n!==void 0&&(e.score=n+e.bias,t.push(e))}encode(t){let e=[];for(let n of t){if(this.ignore_merges&&this.tokens_to_ids.has(n)){e.push(n);continue}let r=this.bpe(n);for(let o of r)if(this.tokens_to_ids.has(o))e.push(o);else if(this.byte_fallback){let s=Array.from(this.text_encoder.encode(o)).map(i=>`<0x${i.toString(16).toUpperCase().padStart(2,"0")}>`);s.every(i=>this.tokens_to_ids.has(i))?e.push(...s):this.unk_token!=null&&e.push(this.unk_token)}else this.unk_token!=null&&e.push(this.unk_token)}return e}},MR=l6,d6=class extends Sf{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=X_(e.target_lang?n[e.target_lang]:n),this.bos_token=e.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=e.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=e.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=new Array(this.tokens_to_ids.size);for(let[r,o]of this.tokens_to_ids)this.vocab[o]=r}encode(t){return t}},f6=d6;function p6(t,e){switch(t.type){case"WordPiece":return new IR(t);case"Unigram":return new NR(t,e.eos_token);case"BPE":return new MR(t);default:if(t.vocab)return Array.isArray(t.vocab)?new NR(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new MR(t):new IR(t):new f6(t,{target_lang:e.target_lang,bos_token:e.bos_token,eos_token:e.eos_token,pad_token:e.pad_token,unk_token:e.unk_token});throw new Error(`Unknown TokenizerModel type: ${t?.type}`)}}var h6=p6,g6=class extends La{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},$a=g6,m6=class extends $a{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let i of r)"SpecialToken"in i?n&&(o.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(o=hn(o,t),s=hn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=hn(o,e),s=hn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},y6=m6,_6=class extends $a{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},b6=_6,C6=class extends $a{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},w6=C6,k6=class extends $a{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},S6=k6,A6=class extends $a{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>HR(e))}post_process(t,e=null,n=!0){let r={tokens:t,tokens_pair:e};for(let o of this.processors)r=o.post_process(r.tokens,r.tokens_pair,n);return r}},E6=A6;function v6(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new y6(t);case"ByteLevel":return new b6(t);case"BertProcessing":return new w6(t);case"RobertaProcessing":return new S6(t);case"Sequence":return new E6(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var HR=v6,T6=class extends La{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Gn=T6,x6=class extends Gn{constructor(t){super(t),this.byte_decoder=zq,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(t){let e=t.join(""),n=new Uint8Array([...e].map(r=>this.byte_decoder[r]));return this.text_decoder.decode(n)}decode_chain(t){let e=[],n=[];for(let r of t)this.added_tokens.find(o=>o.content===r)!==void 0?(n.length>0&&(e.push(this.convert_tokens_to_string(n)),n=[]),e.push(r)):n.push(r);return n.length>0&&e.push(this.convert_tokens_to_string(n)),e}},R6=x6,D6=class extends Gn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=Y_(e)),e})}},O6=D6,P6=class extends Gn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},I6=P6,F6=class extends Gn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},N6=F6,M6=class extends Gn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let o=1;o<t.length;++o)t[o]!==e.at(-1)&&e.push(t[o]);let r=e.filter(o=>o!==this.pad_token).join("");return this.cleanup&&(r=Y_(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},B6=M6,j6=class extends Gn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>zR(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},U6=j6,L6=class extends Gn{decode_chain(t){let e=wf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},$6=L6,q6=class extends Gn{decode_chain(t){return[t.join("")]}},H6=q6,z6=class extends Gn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o){n=o+1;continue}let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},W6=z6,G6=class extends Gn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},J6=G6;function K6(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new R6(t);case"WordPiece":return new O6(t);case"Metaspace":return new I6(t);case"BPEDecoder":return new N6(t);case"CTC":return new B6(t);case"Sequence":return new U6(t);case"Replace":return new $6(t);case"Fuse":return new H6(t);case"Strip":return new W6(t);case"ByteFallback":return new J6(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var zR=K6,V6=class{constructor(t,e){let n=PR(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=PR(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=UR(this.tokenizer.normalizer),this.pre_tokenizer=LR(this.tokenizer.pre_tokenizer),this.model=h6(this.tokenizer.model,this.config),this.post_processor=HR(this.tokenizer.post_processor),this.decoder=zR(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let o=[],s=[];this.added_tokens_map=new Map;for(let i of this.tokenizer.added_tokens){let a=new qq(i);if(this.added_tokens.push(a),this.model.tokens_to_ids.set(a.content,a.id),this.model.vocab[a.id]=a.content,a.special&&(this.special_tokens.push(a.content),this.all_special_ids.push(a.id)),this.added_tokens_map.set(a.content,a),a.normalized&&this.normalizer!==null){let u=this.normalizer(a.content);s.push(u),this.added_tokens_map.set(u,a)}else o.push(a.content)}(this.config.additional_special_tokens??[]).forEach(i=>{this.special_tokens.includes(i)||this.special_tokens.push(i)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new DR(o),this.splitter_normalized=new DR(s),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(t,{text_pair:e=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:o,token_type_ids:s}=this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}),i=o.map(u=>this.added_tokens_map.get(u)?.id??this.model.tokens_to_ids.get(u)??this.model.unk_token_id),a={ids:i,tokens:o,attention_mask:new Array(i.length).fill(1)};return r&&s&&(a.token_type_ids=s),a}decode(t,e={}){if(!Array.isArray(t)||t.length===0||!Vq(t[0]))throw Error("token_ids must be a non-empty array of integers.");let n=t.map(o=>this.model.vocab[Number(o)]??this.model.unk_token);e.skip_special_tokens&&(n=n.filter(o=>!this.special_tokens.includes(o)));let r=this.decoder?this.decoder(n):n.join(" ");return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix," "),e.skip_special_tokens&&(r=r.trim())),(e.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=Y_(r)),r}tokenize(t,{text_pair:e=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(t,{text_pair:e,add_special_tokens:n}).tokens}encode_text(t){if(t===null)return null;let e=this.splitter_unnormalized.split(t);return e.forEach((n,r)=>{let o=this.added_tokens_map.get(n);o&&(o.lstrip&&r>0&&(e[r-1]=e[r-1].trimEnd()),o.rstrip&&r<e.length-1&&(e[r+1]=e[r+1].trimStart()))}),e.flatMap((n,r)=>{if(n.length===0)return[];if(this.added_tokens_map.has(n))return[n];if(this.remove_space===!0&&(n=n.trim().split(/\s+/).join(" ")),this.do_lowercase_and_remove_accent&&(n=Xq(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.splitter_normalized.split(n);return o.forEach((s,i)=>{let a=this.added_tokens_map.get(s);a&&(a.lstrip&&i>0&&(o[i-1]=o[i-1].trimEnd()),a.rstrip&&i<o.length-1&&(o[i+1]=o[i+1].trimStart()))}),o.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:r}):[s];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:hn(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(t||!this.added_tokens_map.has(r))&&e.set(r,n)}return e}},WR=V6;var vf=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||Af(Y6(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Af(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Af(e,"tokenizer.json"),tokenizerConfig:Af(e,"tokenizer_config.json")}}ensureDir(e){Q_(e)||X6(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!Q_(e.tokenizerJson)||!Q_(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Ef.readFile(e.tokenizerJson,"utf-8"),Ef.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[a,u]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Ef.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),Ef.writeFile(e.tokenizerConfig,JSON.stringify(u,null,2))]),{tokenizerJson:a,tokenizerConfig:u}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`),this.ensureDir(this.cacheDir);let e=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new WR(e.tokenizerJson,e.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`,{cause:e})}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let i of r)if(typeof i.content=="string")n.push(i.content);else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"&&a.text?n.push(a.text):a.type==="tool_use"&&a.input?n.push(JSON.stringify(a.input)):a.type==="tool_result"&&n.push(typeof a.content=="string"?a.content:JSON.stringify(a.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let i of o)if(i.type==="text"){if(typeof i.text=="string")n.push(i.text);else if(Array.isArray(i.text))for(let a of i.text)a&&n.push(a)}}if(s)for(let i of s)i.name&&n.push(i.name),i.description&&n.push(i.description),i.input_schema&&n.push(JSON.stringify(i.input_schema));return n.join(" ")}};var Tf=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch(e){throw new Error(`Invalid API URL: ${this.config.url}`,{cause:e})}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),i=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!i.ok)throw new Error(`API tokenizer request failed: ${i.status} ${i.statusText}`);let a=await i.json();return this.extractTokenCount(a)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out",{cause:n}):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`,{cause:n})}}};var ci=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new Ua("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new Ua(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new vf(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Tf(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var Z_=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},GR=new Z_;var YR=nr(Lp(),1);e0();t0();n0();KR();var jo=new Map;function XR(t){let e=jo.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function QR(){return Array.from(jo.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var o0=new Map,ZR={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,YR.default)(async(t,e)=>{let n={reporter:["console","temp-file"],...e},r=Array.isArray(n.reporter)?n.reporter:[n.reporter];if(n.outputHandlers&&n.outputHandlers.length>0)ui.registerHandlers(n.outputHandlers);else{let s=[];for(let i of r)i==="console"?s.push({type:"console",enabled:!0,config:{colors:!0,level:"log"}}):i==="temp-file"?s.push({type:"temp-file",enabled:!0,config:{subdirectory:"claude-code-router",extension:"json",includeTimestamp:!0,prefix:"session"}}):i==="webhook"&&t.log.warn("[TokenSpeedPlugin] Webhook reporter requires explicit configuration in outputHandlers");s.length>0&&ui.registerHandlers(s)}n.outputOptions&&ui.setDefaultOptions(n.outputOptions);let o=async s=>{let i=t.tokenizerService;if(!i)return t.log?.warn("TokenizerService not available"),null;if(!s.provider||!s.model)return null;let a=s.provider,u=s.model,d=`${a}:${u}`;if(o0.has(d))return o0.get(d);let f=i.getTokenizerConfigForModel(a,u);if(!f)return t.log?.debug(`No tokenizer config for ${a}:${u}, using fallback`),null;try{let p=await i.getTokenizer(f);return o0.set(d,p),t.log?.info(`Created tokenizer for ${a}:${u} - ${p.name}`),p}catch(p){return t.log?.warn(`Failed to create tokenizer for ${a}:${u}: ${p.message}`),null}};t.addHook("onRequest",async s=>{new URL(`http://127.0.0.1${s.url}`).pathname.endsWith("/v1/messages")&&(s.requestStartTime=performance.now())}),t.addHook("onSend",async(s,i,a)=>{let u=s.requestStartTime;if(!u)return;let d=s.id||Date.now().toString(),f;try{let b=s.body?.metadata?.user_id;if(b&&typeof b=="string"){let m=b.match(/_session_([a-f0-9-]+)/i);f=m?m[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(a instanceof ReadableStream){jo.set(d,{requestId:d,sessionId:f,startTime:u,lastTokenTime:u,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[b,m]=a.tee();return(async()=>{let C=null,S=async k=>{let E=jo.get(d);if(!E)return;let x=performance.now();if(k){let O=(E.lastTokenTime-E.startTime)/1e3;O>0&&(E.tokensPerSecond=Math.round(E.tokenCount/O))}else{let O=x-1e3;E.tokenTimestamps=E.tokenTimestamps.filter(q=>q>O),E.tokensPerSecond=E.tokenTimestamps.length}await VR(E,r,n.outputOptions,k,t.log).catch(O=>{t.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let E=m.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader();for(C=setInterval(async()=>{jo.get(d)&&await S(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=jo.get(d);if(!V)continue;let U=performance.now();if(!V.firstTokenTime&&(q.event==="content_block_start"||q.event==="content_block_delta"||q.event==="text_block"||q.event==="content_block")&&(V.firstTokenTime=U,V.timeToFirstToken=Math.round(U-V.startTime)),q.event==="content_block_delta"&&q.data?.delta){let ee=q.data.delta.type,z="";if(ee==="text_delta"?z=q.data.delta.text||"":ee==="input_json_delta"?z=q.data.delta.partial_json||"":ee==="thinking_delta"&&(z=q.data.delta.thinking||""),z){let te=p&&p.encodeText?p.encodeText(z).length:Wa(z);V.tokenCount+=te,V.lastTokenTime=U;for(let Q=0;Q<te;Q++)V.tokenTimestamps.push(U)}}q.event==="message_stop"&&(C&&(clearInterval(C),C=null),await S(!0),jo.delete(d))}}catch(k){C&&clearInterval(C),k.name!=="AbortError"&&k.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${k.message}`)}})().catch(C=>{t.log.error(C,"Background stats processing failed")}),b}let h=performance.now(),g=0;if(a&&typeof a=="string")try{let b=JSON.parse(a);if(b.usage?.output_tokens)g=b.usage.output_tokens;else{let m=b.content||b.message?.content||"";if(p)Array.isArray(m)?g=m.reduce((w,C)=>{if(C.type==="text"){let S=C.text||"";return w+(p.encodeText?p.encodeText(S).length:Wa(S))}return w},0):typeof m=="string"&&(g=p.encodeText?p.encodeText(m).length:Wa(m));else{let w=Array.isArray(m)?m.map(C=>C.text).join(""):m;g=Wa(w)}}}catch{}if(g>0){let b=(h-u)/1e3,m={requestId:d,sessionId:f,startTime:u,lastTokenTime:h,tokenCount:g,tokensPerSecond:b>0?Math.round(g/b):0,timeToFirstToken:Math.round(h-u),stream:!1,tokenTimestamps:[]};await VR(m,r,n.outputOptions,!0,t.log)}return a})})};function Wa(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function VR(t,e,n,r=!1,o){let s=r?"[Token Speed Final]":"[Token Speed]",i={requestId:t.requestId.substring(0,8),sessionId:t.sessionId,stream:t.stream,tokenCount:t.tokenCount,tokensPerSecond:t.tokensPerSecond,timeToFirstToken:t.timeToFirstToken?`${t.timeToFirstToken}ms`:"N/A",duration:`${((t.lastTokenTime-t.startTime)/1e3).toFixed(2)}s`,timestamp:Date.now()},a={prefix:s,metadata:{sessionId:t.sessionId},...n};for(let u of e)try{await ui.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function sH(t={}){let e=nH({bodyLimit:52428800,...t});return e.setErrorHandler(nw),e.register(rH),e.register(eD.default,{global:!0,...oH}),e}var s0=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=sH({...r,logger:r.logger??!0}),this.configService=new Qo({...e,logger:this.app.log}),this.transformerService=new ai(this.configService,this.app.log),this.tokenizerService=new ci(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new gs(this.configService,this.transformerService,this.app.log)}),this.tokenizerService.initialize().catch(o=>{this.app.log.error(`Failed to initialize TokenizerService: ${o}`)})}async register(e,n){await this.app.register(e,n)}addHook(e,n){this.app.addHook(e,n)}async registerNamespace(e,n){if(!e)throw new Error("name is required");if(e==="/"){await this.app.register(async a=>{a.decorate("configService",this.configService),a.decorate("transformerService",this.transformerService),a.decorate("providerService",this.providerService),a.decorate("tokenizerService",this.tokenizerService),await Uh(a)});return}if(!n)throw new Error("options is required");let r=new Qo({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ai(r,this.app.log);await o.initialize();let s=new gs(r,o,this.app.log),i=new ci(r,this.app.log);await i.initialize(),await this.app.register(async a=>{a.decorate("configService",r),a.decorate("transformerService",o),a.decorate("providerService",s),a.decorate("tokenizerService",i),await Uh(a)},{prefix:e})}async start(){try{this.app._server=this,this.app.addHook("preHandler",(r,o,s)=>{let i=new URL(`http://127.0.0.1${r.url}`),a=cr(r.method,i.pathname);if(a&&r.body){let u=r.body;a.protocol==="anthropic_messages"&&(r.log.info({data:u,type:"request body"}),u.stream||(u.stream=!1))}s()}),await this.registerNamespace("/");let e=await this.app.listen({port:parseInt(this.configService.get("PORT")||"3000",10),host:this.configService.get("HOST")||"127.0.0.1"});this.app.log.info(`\u{1F680} LLMs API server listening on ${e}`);let n=async r=>{this.app.log.info(`Received ${r}, shutting down gracefully...`),await this.app.close(),process.exit(0)};process.on("SIGINT",()=>n("SIGINT")),process.on("SIGTERM",()=>n("SIGTERM"))}catch(e){this.app.log.error(`Error starting server: ${e}`),process.exit(1)}}},oX=s0;export{$_ as ANTIGRAVITY_CLIENT_ID,q_ as ANTIGRAVITY_CLIENT_SECRET,uR as ANTIGRAVITY_REDIRECT_URI,K$ as ANTIGRAVITY_SCOPES,Qo as ConfigService,Lc as DEFAULT_LOG_BODY_MAX_BYTES,gs as ProviderService,Tn as SSEParserTransform,ms as SSESerializerTransform,ci as TokenizerService,ai as TransformerService,sk as calculateTokenCount,oX as default,BO as diffHeadersForLog,uq as exchangeAuthorizationCode,cq as fetchUserEmail,Ma as getAntigravityAccessToken,Eu as getClaudeAccessToken,Vd as getCodexAccessToken,QR as getGlobalTokenSpeedStats,f_ as getQwenAccessToken,XR as getTokenSpeedStats,Ma as getValidAccessToken,_f as getXaiAccessToken,Je as isClientAbortError,RP as isRoutedLlmPost,Eh as listClientRouteRegistrations,hf as loadTokens,cr as matchClientProtocol,GR as pluginManager,Hi as protocolErrorBody,W_ as resolveProjectId,kk as rewriteStream,Nh as router,ah as sanitizeBodyForLog,sh as sanitizeHeadersForLog,z_ as saveTokens,ak as searchProjectBySession,Ph as sessionUsageCache,GO as setHealthReporter,ZR as tokenSpeedPlugin};
446
446
  /*! Bundled license information:
447
447
 
448
448
  toad-cache/dist/toad-cache.cjs: