@caeliq/llms 1.0.63 → 1.0.65

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
- "use strict";var jD=Object.create;var qc=Object.defineProperty;var LD=Object.getOwnPropertyDescriptor;var $D=Object.getOwnPropertyNames;var qD=Object.getPrototypeOf,HD=Object.prototype.hasOwnProperty;var Wr=(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}},sh=(t,e)=>{for(var n in e)qc(t,n,{get:e[n],enumerable:!0})},TC=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $D(e))!HD.call(t,o)&&o!==n&&qc(t,o,{get:()=>e[o],enumerable:!(r=LD(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?jD(qD(t)):{},TC(e||!t||!t.__esModule?qc(n,"default",{value:t,enumerable:!0}):n,t)),zD=t=>TC(qc({},"__esModule",{value:!0}),t);var Qi=G(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});Hc.AddressError=void 0;var ih=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};Hc.AddressError=ih});var Wc=G(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.isInSubnet=WD;vn.isHostInSubnet=xC;vn.isCorrect=GD;vn.prefixLengthFromMask=JD;vn.assertByteArray=KD;vn.numberToPaddedHex=RC;vn.stringToPaddedHex=VD;vn.testBit=YD;var zc=Qi();function WD(t){return this.subnetMask<t.subnetMask?!1:xC.call(this,t)}function xC(t){return this.mask(t.subnetMask)===t.mask()}function GD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function JD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new zc.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new zc.AddressError("Invalid subnet mask.");return r}function KD(t,e,n,r){if(t.length!==e)throw new zc.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 zc.AddressError(`All bytes must be integers between ${r} and 255`)}function RC(t){return t.toString(16).padStart(2,"0")}function VD(t){return RC(parseInt(t,10))}function YD(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var ah=G(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.RE_SUBNET_STRING=Tn.RE_ADDRESS=Tn.GROUPS=Tn.BITS=void 0;Tn.BITS=32;Tn.GROUPS=4;Tn.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;Tn.RE_SUBNET_STRING=/\/\d{1,2}$/});var ch=G(Rn=>{"use strict";var XD=Rn&&Rn.__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]})),QD=Rn&&Rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),DC=Rn&&Rn.__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 QD(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Address4=void 0;var xn=DC(Wc()),st=DC(ah()),lr=Qi(),ZD=xn.isCorrect(st.BITS),Gt=class t{constructor(e){this.addressMinusSuffix="",this.groups=st.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=ZD,this.isInSubnet=xn.isInSubnet,this.isHostInSubnet=xn.isHostInSubnet,this.address=e;let n=st.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>st.BITS)throw new lr.AddressError("Invalid subnet mask.");e=e.replace(st.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 lr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(st.RE_ADDRESS))throw new lr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=xn.prefixLengthFromMask(new t(n).bigInt(),st.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(st.BITS))-BigInt(1),s=r^o,i=xn.prefixLengthFromMask(s,st.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==st.GROUPS)throw new lr.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 lr.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=st.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 lr.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 lr.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=>xn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<st.GROUPS;n+=2)e.push(`${xn.stringToPaddedHex(this.parsedAddress[n])}${xn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>xn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(st.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(st.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(st.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(st.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new lr.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 xn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new lr.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(eO)}isPrivate(){return tO.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(nO)}isLinkLocal(){return this.isHostInSubnet(rO)}isUnspecified(){return this.isHostInSubnet(oO)}isBroadcast(){return this.isHostInSubnet(sO)}isCGNAT(){return this.isHostInSubnet(iO)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(st.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(st.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>`)}};Rn.Address4=Gt;var eO=new Gt("224.0.0.0/4"),tO=[new Gt("10.0.0.0/8"),new Gt("172.16.0.0/12"),new Gt("192.168.0.0/16")],nO=new Gt("127.0.0.0/8"),rO=new Gt("169.254.0.0/16"),oO=new Gt("0.0.0.0/32"),sO=new Gt("255.255.255.255/32"),iO=new Gt("100.64.0.0/10")});var uh=G(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.RE_URL_WITH_PORT=Ke.RE_URL=Ke.RE_ZONE_STRING=Ke.RE_SUBNET_STRING=Ke.RE_BAD_ADDRESS=Ke.RE_BAD_CHARACTERS=Ke.TYPES=Ke.SCOPES=Ke.GROUPS=Ke.BITS=void 0;Ke.BITS=128;Ke.GROUPS=8;Ke.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};Ke.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)"};Ke.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;Ke.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;Ke.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;Ke.RE_ZONE_STRING=/%.*$/;Ke.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;Ke.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var lh=G(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.escapeHtml=Gc;Co.spanAllZeroes=OC;Co.spanAll=aO;Co.spanLeadingZeroes=cO;Co.simpleGroup=uO;function Gc(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function OC(t){return Gc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function aO(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${Gc(r)} position-${o+e}">${OC(r)}</span>`).join("")}function PC(t){return Gc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function cO(t){return t.split(":").map(n=>PC(n)).join(":")}function uO(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${PC(r)}</span>`)}});var IC=G(vt=>{"use strict";var lO=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]})),dO=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),fO=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)&&lO(e,t,n);return dO(e,t),e};Object.defineProperty(vt,"__esModule",{value:!0});vt.ADDRESS_BOUNDARY=void 0;vt.groupPossibilities=Kc;vt.padGroup=Jc;vt.simpleRegularExpression=hO;vt.possibleElisions=gO;var pO=fO(uh());function Kc(t){return`(${t.join("|")})`}function Jc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}vt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function hO(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===pO.GROUPS-1?":":"";return Kc([Jc(o),i])}return Jc(o)}).join(":"));return n.push(t.map(Jc).join(":")),Kc(n)}function gO(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 Kc(s)}});var BC=G(Pn=>{"use strict";var mO=Pn&&Pn.__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]})),yO=Pn&&Pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Xc=Pn&&Pn.__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)&&mO(e,t,n);return yO(e,t),e};Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Address6=void 0;var So=Xc(Wc()),dh=Xc(ah()),Te=Xc(uh()),wo=Xc(lh()),Dn=ch(),ko=IC(),dt=Qi(),Vc=Wc(),_O=So.isCorrect(Te.BITS);function Yc(t){if(!t)throw new Error("Assertion failed.")}function bO(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function CO(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 wO(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 FC(t){return parseInt(t,16).toString(16).padStart(4,"0")}function NC(t){return t&255}var On=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=So.isInSubnet,this.isHostInSubnet=So.isHostInSubnet,this.isCorrect=_O,n===void 0?this.groups=Te.GROUPS:this.groups=n,this.address=e;let r=Te.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>Te.BITS)throw new dt.AddressError("Invalid subnet mask.");e=e.replace(Te.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new dt.AddressError("Invalid subnet mask.");let o=Te.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(Te.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(Te.BITS))-BigInt(1))throw new dt.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<Te.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=Te.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=Te.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=So.prefixLengthFromMask(new t(n).bigInt(),Te.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(Te.BITS))-BigInt(1),s=r^o,i=So.prefixLengthFromMask(s,Te.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new dt.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new dt.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=Te.GROUPS-u.length-d.length;if(f<1)throw new dt.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==Te.GROUPS)throw new dt.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 dt.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=Te.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new Dn.Address4(e),r=Te.BITS-(dh.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 dt.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=Te.BITS-this.subnetMask,r=Math.abs(e-Te.BITS),o=n-r;return o<0?"0":bO((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(Te.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(Te.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(Te.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(Te.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?Te.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<MC.length;e++){let n=MC[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,Te.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=wO(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(Te.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===dh.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(CO).join("."),a=n.slice(0,-1).map(wo.escapeHtml).join(":"),u=n.length>1?":":"";throw new dt.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(dh.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new Dn.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(Te.RE_BAD_CHARACTERS);if(n)throw new dt.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(Te.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(Te.RE_BAD_ADDRESS);if(r)throw new dt.AddressError(`Address failed regex: ${r.join("")}`,e.replace(Te.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 dt.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 dt.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new dt.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(FC).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(FC).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 Dn.Address4(`${o.join(".")}/${r}`)}return Dn.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=Dn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=Dn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Vc.testBit)(a,15),d=(0,Vc.testBit)(a,14),f=(0,Vc.testBit)(a,8),p=(0,Vc.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=Dn.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 Dn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new dt.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 dt.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 Dn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(Te.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(NC)}static fromByteArray(e){return So.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(NC))}static fromUnsignedByteArray(e){So.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(vO)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(TO)?this.to4():null}isTeredo(){return this.isHostInSubnet(kO)}is6to4(){return this.isHostInSubnet(SO)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(AO)}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(EO)}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=wo.escapeHtml(`${e.prefix}${r}`),s=wo.escapeHtml(r);if(e.className){let i=wo.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return wo.simpleGroup(this.addressMinusSuffix).join(":");Yc(typeof this.elidedGroups=="number"),Yc(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...wo.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(...wo.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Yc(this.address4 instanceof Dn.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,ko.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===Te.GROUPS)n.push((0,ko.possibleElisions)(Te.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,ko.simpleRegularExpression)(o[0].split(":"))),Yc(typeof r.elidedGroups=="number"),n.push((0,ko.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,ko.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",ko.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",ko.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Pn.Address6=On;var MC=Object.keys(Te.TYPES).map(t=>[new On(t),Te.TYPES[t]]),kO=new On("2001::/32"),SO=new On("2002::/16"),AO=new On("fc00::/7"),EO=new On("2001:db8::/32"),vO=new On("::ffff:0:0/96"),TO=new On("64:ff9b::/96")});var UC=G(yt=>{"use strict";var xO=yt&&yt.__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]})),RO=yt&&yt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),DO=yt&&yt.__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)&&xO(e,t,n);return RO(e,t),e};Object.defineProperty(yt,"__esModule",{value:!0});yt.v6=yt.AddressError=yt.Address6=yt.Address4=void 0;var OO=ch();Object.defineProperty(yt,"Address4",{enumerable:!0,get:function(){return OO.Address4}});var PO=BC();Object.defineProperty(yt,"Address6",{enumerable:!0,get:function(){return PO.Address6}});var IO=Qi();Object.defineProperty(yt,"AddressError",{enumerable:!0,get:function(){return IO.AddressError}});var FO=DO(lh());yt.v6={helpers:FO}});var LC=G((c6,fh)=>{"use strict";var NO=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,MO=/(\w*(\.\w*)*)\..*/;fh.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,jC(r.stack)}};function jC(t){let e=t.match(NO);return e?e[1].split(/[/\\]/).slice(-1)[0].match(MO)[1]:"anonymous"}fh.exports.extractPluginName=jC});var qC=G((u6,$C)=>{"use strict";$C.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var hh=G((l6,Qc)=>{"use strict";var BO=LC(),UO=qC(),jO=0;function ph(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=BO(t)+"-auto-"+jO++),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=UO(e.name);return!n&&!t[r]&&(t[r]=t),t}Qc.exports=ph;Qc.exports.default=ph;Qc.exports.fastifyPlugin=ph});var HC=G(mh=>{var LO=/^(-?(?:\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?)?)?$/,Zc=1e3,eu=Zc*60,tu=eu*60,ea=tu*24,gh=ea*365.25;function $O(t){var e,n=t.toLowerCase().match(LO);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*Zc:n[4]!=null?e*eu:n[5]!=null?e*tu:n[6]!=null?e*ea:n[7]!=null?e*ea*7:n[8]!=null?e*gh:e}function Zi(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function qO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<Zc?t+(e?" ms":"ms"):r<eu?Zi(r/Zc,n,"second",e):r<tu?Zi(r/eu,n,"minute",e):r<ea?Zi(r/tu,n,"hour",e):r<gh?Zi(r/ea,n,"day",e):Zi(r/gh,n,"year",e)}mh.format=qO;mh.parse=$O});var WC=G(In=>{"use strict";function su(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 yh=class{constructor(e=1e3,n=0){su(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}},nu=class{constructor(e=1e3,n=0){su(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 _h(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var ru=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:_h()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=_h()}getStatistics(){return this.records}},bh=class{constructor(e=1e3,n=0){su(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}},ta=class{constructor(e=1e3,n=0){su(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 zC(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var Ch=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=zC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new ru,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=_h()),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=zC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},ou=class extends ta{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Ch(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()}};In.Fifo=nu;In.FifoMap=yh;In.FifoObject=nu;In.HitStatisticsRecord=ru;In.Lru=ta;In.LruHitStatistics=ou;In.LruMap=bh;In.LruObject=ta;In.LruObjectHitStatistics=ou});var JC=G((p6,GC)=>{"use strict";var{LruMap:HO}=WC();function na(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new HO(n)}na.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)};na.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})};na.prototype.child=function(t){return new na(t.continueExceeding,t.exponentialBackoff,t.cache)};GC.exports=na});var VC=G((h6,KC)=>{"use strict";var zO=`
1
+ "use strict";var zD=Object.create;var Hc=Object.defineProperty;var WD=Object.getOwnPropertyDescriptor;var GD=Object.getOwnPropertyNames;var JD=Object.getPrototypeOf,KD=Object.prototype.hasOwnProperty;var Wr=(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}},sh=(t,e)=>{for(var n in e)Hc(t,n,{get:e[n],enumerable:!0})},RC=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GD(e))!KD.call(t,o)&&o!==n&&Hc(t,o,{get:()=>e[o],enumerable:!(r=WD(e,o))||r.enumerable});return t};var ot=(t,e,n)=>(n=t!=null?zD(JD(t)):{},RC(e||!t||!t.__esModule?Hc(n,"default",{value:t,enumerable:!0}):n,t)),VD=t=>RC(Hc({},"__esModule",{value:!0}),t);var Zi=G(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.AddressError=void 0;var ih=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};zc.AddressError=ih});var Gc=G(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.isInSubnet=YD;vn.isHostInSubnet=DC;vn.isCorrect=XD;vn.prefixLengthFromMask=QD;vn.assertByteArray=ZD;vn.numberToPaddedHex=OC;vn.stringToPaddedHex=eO;vn.testBit=tO;var Wc=Zi();function YD(t){return this.subnetMask<t.subnetMask?!1:DC.call(this,t)}function DC(t){return this.mask(t.subnetMask)===t.mask()}function XD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function QD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new Wc.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new Wc.AddressError("Invalid subnet mask.");return r}function ZD(t,e,n,r){if(t.length!==e)throw new Wc.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 Wc.AddressError(`All bytes must be integers between ${r} and 255`)}function OC(t){return t.toString(16).padStart(2,"0")}function eO(t){return OC(parseInt(t,10))}function tO(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var ah=G(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.RE_SUBNET_STRING=Tn.RE_ADDRESS=Tn.GROUPS=Tn.BITS=void 0;Tn.BITS=32;Tn.GROUPS=4;Tn.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;Tn.RE_SUBNET_STRING=/\/\d{1,2}$/});var ch=G(Rn=>{"use strict";var nO=Rn&&Rn.__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]})),rO=Rn&&Rn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),PC=Rn&&Rn.__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)&&nO(e,t,n);return rO(e,t),e};Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Address4=void 0;var xn=PC(Gc()),st=PC(ah()),lr=Zi(),oO=xn.isCorrect(st.BITS),Gt=class t{constructor(e){this.addressMinusSuffix="",this.groups=st.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=oO,this.isInSubnet=xn.isInSubnet,this.isHostInSubnet=xn.isHostInSubnet,this.address=e;let n=st.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>st.BITS)throw new lr.AddressError("Invalid subnet mask.");e=e.replace(st.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 lr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(st.RE_ADDRESS))throw new lr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=xn.prefixLengthFromMask(new t(n).bigInt(),st.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(st.BITS))-BigInt(1),s=r^o,i=xn.prefixLengthFromMask(s,st.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==st.GROUPS)throw new lr.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 lr.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=st.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 lr.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 lr.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=>xn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<st.GROUPS;n+=2)e.push(`${xn.stringToPaddedHex(this.parsedAddress[n])}${xn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>xn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(st.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(st.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(st.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(st.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new lr.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 xn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new lr.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(sO)}isPrivate(){return iO.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(aO)}isLinkLocal(){return this.isHostInSubnet(cO)}isUnspecified(){return this.isHostInSubnet(uO)}isBroadcast(){return this.isHostInSubnet(lO)}isCGNAT(){return this.isHostInSubnet(dO)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(st.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(st.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>`)}};Rn.Address4=Gt;var sO=new Gt("224.0.0.0/4"),iO=[new Gt("10.0.0.0/8"),new Gt("172.16.0.0/12"),new Gt("192.168.0.0/16")],aO=new Gt("127.0.0.0/8"),cO=new Gt("169.254.0.0/16"),uO=new Gt("0.0.0.0/32"),lO=new Gt("255.255.255.255/32"),dO=new Gt("100.64.0.0/10")});var uh=G(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.RE_URL_WITH_PORT=Ke.RE_URL=Ke.RE_ZONE_STRING=Ke.RE_SUBNET_STRING=Ke.RE_BAD_ADDRESS=Ke.RE_BAD_CHARACTERS=Ke.TYPES=Ke.SCOPES=Ke.GROUPS=Ke.BITS=void 0;Ke.BITS=128;Ke.GROUPS=8;Ke.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};Ke.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)"};Ke.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;Ke.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;Ke.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;Ke.RE_ZONE_STRING=/%.*$/;Ke.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;Ke.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var lh=G(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.escapeHtml=Jc;wo.spanAllZeroes=IC;wo.spanAll=fO;wo.spanLeadingZeroes=pO;wo.simpleGroup=hO;function Jc(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function IC(t){return Jc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function fO(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${Jc(r)} position-${o+e}">${IC(r)}</span>`).join("")}function FC(t){return Jc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function pO(t){return t.split(":").map(n=>FC(n)).join(":")}function hO(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${FC(r)}</span>`)}});var NC=G(Tt=>{"use strict";var gO=Tt&&Tt.__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]})),mO=Tt&&Tt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yO=Tt&&Tt.__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)&&gO(e,t,n);return mO(e,t),e};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.ADDRESS_BOUNDARY=void 0;Tt.groupPossibilities=Vc;Tt.padGroup=Kc;Tt.simpleRegularExpression=bO;Tt.possibleElisions=CO;var _O=yO(uh());function Vc(t){return`(${t.join("|")})`}function Kc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}Tt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function bO(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===_O.GROUPS-1?":":"";return Vc([Kc(o),i])}return Kc(o)}).join(":"));return n.push(t.map(Kc).join(":")),Vc(n)}function CO(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 Vc(s)}});var jC=G(Pn=>{"use strict";var wO=Pn&&Pn.__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]})),kO=Pn&&Pn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Qc=Pn&&Pn.__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)&&wO(e,t,n);return kO(e,t),e};Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Address6=void 0;var Ao=Qc(Gc()),dh=Qc(ah()),Te=Qc(uh()),ko=Qc(lh()),Dn=ch(),So=NC(),dt=Zi(),Yc=Gc(),SO=Ao.isCorrect(Te.BITS);function Xc(t){if(!t)throw new Error("Assertion failed.")}function AO(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function EO(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 vO(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 MC(t){return parseInt(t,16).toString(16).padStart(4,"0")}function BC(t){return t&255}var On=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=Ao.isInSubnet,this.isHostInSubnet=Ao.isHostInSubnet,this.isCorrect=SO,n===void 0?this.groups=Te.GROUPS:this.groups=n,this.address=e;let r=Te.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>Te.BITS)throw new dt.AddressError("Invalid subnet mask.");e=e.replace(Te.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new dt.AddressError("Invalid subnet mask.");let o=Te.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(Te.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(Te.BITS))-BigInt(1))throw new dt.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<Te.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=Te.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=Te.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=Ao.prefixLengthFromMask(new t(n).bigInt(),Te.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(Te.BITS))-BigInt(1),s=r^o,i=Ao.prefixLengthFromMask(s,Te.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new dt.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new dt.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=Te.GROUPS-u.length-d.length;if(f<1)throw new dt.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==Te.GROUPS)throw new dt.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 dt.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=Te.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new Dn.Address4(e),r=Te.BITS-(dh.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 dt.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=Te.BITS-this.subnetMask,r=Math.abs(e-Te.BITS),o=n-r;return o<0?"0":AO((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(Te.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(Te.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(Te.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(Te.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?Te.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<UC.length;e++){let n=UC[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,Te.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=vO(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(Te.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===dh.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(EO).join("."),a=n.slice(0,-1).map(ko.escapeHtml).join(":"),u=n.length>1?":":"";throw new dt.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(dh.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new Dn.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(Te.RE_BAD_CHARACTERS);if(n)throw new dt.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(Te.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(Te.RE_BAD_ADDRESS);if(r)throw new dt.AddressError(`Address failed regex: ${r.join("")}`,e.replace(Te.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 dt.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 dt.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new dt.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(MC).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(MC).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 Dn.Address4(`${o.join(".")}/${r}`)}return Dn.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=Dn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=Dn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Yc.testBit)(a,15),d=(0,Yc.testBit)(a,14),f=(0,Yc.testBit)(a,8),p=(0,Yc.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=Dn.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 Dn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new dt.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 dt.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 Dn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(Te.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(BC)}static fromByteArray(e){return Ao.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(BC))}static fromUnsignedByteArray(e){Ao.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(OO)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(PO)?this.to4():null}isTeredo(){return this.isHostInSubnet(TO)}is6to4(){return this.isHostInSubnet(xO)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(RO)}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(DO)}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=ko.escapeHtml(`${e.prefix}${r}`),s=ko.escapeHtml(r);if(e.className){let i=ko.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return ko.simpleGroup(this.addressMinusSuffix).join(":");Xc(typeof this.elidedGroups=="number"),Xc(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...ko.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(...ko.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Xc(this.address4 instanceof Dn.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,So.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===Te.GROUPS)n.push((0,So.possibleElisions)(Te.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,So.simpleRegularExpression)(o[0].split(":"))),Xc(typeof r.elidedGroups=="number"),n.push((0,So.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,So.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",So.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",So.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Pn.Address6=On;var UC=Object.keys(Te.TYPES).map(t=>[new On(t),Te.TYPES[t]]),TO=new On("2001::/32"),xO=new On("2002::/16"),RO=new On("fc00::/7"),DO=new On("2001:db8::/32"),OO=new On("::ffff:0:0/96"),PO=new On("64:ff9b::/96")});var LC=G(yt=>{"use strict";var IO=yt&&yt.__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]})),FO=yt&&yt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),NO=yt&&yt.__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)&&IO(e,t,n);return FO(e,t),e};Object.defineProperty(yt,"__esModule",{value:!0});yt.v6=yt.AddressError=yt.Address6=yt.Address4=void 0;var MO=ch();Object.defineProperty(yt,"Address4",{enumerable:!0,get:function(){return MO.Address4}});var BO=jC();Object.defineProperty(yt,"Address6",{enumerable:!0,get:function(){return BO.Address6}});var UO=Zi();Object.defineProperty(yt,"AddressError",{enumerable:!0,get:function(){return UO.AddressError}});var jO=NO(lh());yt.v6={helpers:jO}});var qC=G((y6,fh)=>{"use strict";var LO=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,$O=/(\w*(\.\w*)*)\..*/;fh.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,$C(r.stack)}};function $C(t){let e=t.match(LO);return e?e[1].split(/[/\\]/).slice(-1)[0].match($O)[1]:"anonymous"}fh.exports.extractPluginName=$C});var zC=G((_6,HC)=>{"use strict";HC.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var hh=G((b6,Zc)=>{"use strict";var qO=qC(),HO=zC(),zO=0;function ph(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=qO(t)+"-auto-"+zO++),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=HO(e.name);return!n&&!t[r]&&(t[r]=t),t}Zc.exports=ph;Zc.exports.default=ph;Zc.exports.fastifyPlugin=ph});var WC=G(mh=>{var WO=/^(-?(?:\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?)?)?$/,eu=1e3,tu=eu*60,nu=tu*60,ta=nu*24,gh=ta*365.25;function GO(t){var e,n=t.toLowerCase().match(WO);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*eu:n[4]!=null?e*tu:n[5]!=null?e*nu:n[6]!=null?e*ta:n[7]!=null?e*ta*7:n[8]!=null?e*gh:e}function ea(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function JO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<eu?t+(e?" ms":"ms"):r<tu?ea(r/eu,n,"second",e):r<nu?ea(r/tu,n,"minute",e):r<ta?ea(r/nu,n,"hour",e):r<gh?ea(r/ta,n,"day",e):ea(r/gh,n,"year",e)}mh.format=JO;mh.parse=GO});var JC=G(In=>{"use strict";function iu(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 yh=class{constructor(e=1e3,n=0){iu(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}},ru=class{constructor(e=1e3,n=0){iu(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 _h(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var ou=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:_h()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=_h()}getStatistics(){return this.records}},bh=class{constructor(e=1e3,n=0){iu(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}},na=class{constructor(e=1e3,n=0){iu(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 GC(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var Ch=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=GC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new ou,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=_h()),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=GC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},su=class extends na{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Ch(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()}};In.Fifo=ru;In.FifoMap=yh;In.FifoObject=ru;In.HitStatisticsRecord=ou;In.Lru=na;In.LruHitStatistics=su;In.LruMap=bh;In.LruObject=na;In.LruObjectHitStatistics=su});var VC=G((k6,KC)=>{"use strict";var{LruMap:KO}=JC();function ra(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new KO(n)}ra.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)};ra.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})};ra.prototype.child=function(t){return new ra(t.continueExceeding,t.exponentialBackoff,t.cache)};KC.exports=ra});var XC=G((S6,YC)=>{"use strict";var VO=`
2
2
  -- Key to operate on
3
3
  local key = KEYS[1]
4
4
  -- Time window for the TTL
@@ -27,7 +27,7 @@
27
27
  end
28
28
 
29
29
  return {current, timeWindow}
30
- `,WO=`
30
+ `,YO=`
31
31
  -- Key to operate on
32
32
  local key = KEYS[1]
33
33
 
@@ -49,135 +49,135 @@
49
49
  end
50
50
 
51
51
  return {tonumber(current), ttl}
52
- `;function ra(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:zO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:WO})}ra.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]})})};ra.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]})})};ra.prototype.child=function(t){return new ra(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};KC.exports=ra});var cw=G((g6,oa)=>{"use strict";var{isIPv6:GO}=require("node:net"),{Address6:YC}=UC(),JO=hh(),{parse:ZC,format:KO}=HC(),VO=JC(),YO=VC(),ew=1e3,tw=6e4,XO="onRequest",nw=64,QO={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},ZO={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},wh=()=>{};function rw(t,e=nw){if(!GO(t))return t.toLowerCase();let n=new YC(t);return n.isMapped4()?n.to4().correctForm():e<128?new YC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function ow(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):nw}var kh=(t,e)=>rw(t.ip,e),eP=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Sh(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=ZO):(n.enableDraftSpec=!1,n.labels=QO),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=ew,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=ZC(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=tw,n.hook=e.hook||XO,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:wh,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:wh,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:wh,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=ow(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:kh,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=eP,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 YO(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new VO(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=XC(r,n,o);return(i,a)=>iw.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=XC(r,n,o);return aw(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=sw(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),QC(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&QC(r,n,o)})}function sw(...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=ZC(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=tw),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=ew),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=ow(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function XC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=sw(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function QC(t,e,n){let r=e.hook,o=aw(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function iw(t,e,n,r){let{store:o}=t,s=e.keyGenerator===kh?kh(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 aw(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await iw(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:KO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}oa.exports=JO(Sh,{fastify:"5.x",name:"@fastify/rate-limit"});oa.exports.default=Sh;oa.exports.fastifyRateLimit=Sh;oa.exports.normalizeIP=rw});var uw=G((m6,iu)=>{iu.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;iu.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]/;iu.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 Eh=G((y6,lw)=>{var Ah=uw();lw.exports={isSpaceSeparator(t){return typeof t=="string"&&Ah.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Ah.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"||Ah.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 gw=G((_6,hw)=>{var it=Eh(),Th,wt,fr,cu,Gr,cn,at,Dh,ia;hw.exports=function(e,n){Th=String(e),wt="start",fr=[],cu=0,Gr=1,cn=0,at=void 0,Dh=void 0,ia=void 0;do at=tP(),oP[wt]();while(at.type!=="eof");return typeof n=="function"?xh({"":ia},"",n):ia};function xh(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=xh(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=xh(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 Se,be,sa,dr,xe;function tP(){for(Se="default",be="",sa=!1,dr=1;;){xe=pr();let t=fw[Se]();if(t)return t}}function pr(){if(Th[cu])return String.fromCodePoint(Th.codePointAt(cu))}function Y(){let t=pr();return t===`
53
- `?(Gr++,cn=0):t?cn+=t.length:cn++,t&&(cu+=t.length),t}var fw={default(){switch(xe){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
54
- `:case"\r":case"\u2028":case"\u2029":Y();return;case"/":Y(),Se="comment";return;case void 0:return Y(),$e("eof")}if(it.isSpaceSeparator(xe)){Y();return}return fw[wt]()},comment(){switch(xe){case"*":Y(),Se="multiLineComment";return;case"/":Y(),Se="singleLineComment";return}throw qe(Y())},multiLineComment(){switch(xe){case"*":Y(),Se="multiLineCommentAsterisk";return;case void 0:throw qe(Y())}Y()},multiLineCommentAsterisk(){switch(xe){case"*":Y();return;case"/":Y(),Se="default";return;case void 0:throw qe(Y())}Y(),Se="multiLineComment"},singleLineComment(){switch(xe){case`
55
- `:case"\r":case"\u2028":case"\u2029":Y(),Se="default";return;case void 0:return Y(),$e("eof")}Y()},value(){switch(xe){case"{":case"[":return $e("punctuator",Y());case"n":return Y(),Ao("ull"),$e("null",null);case"t":return Y(),Ao("rue"),$e("boolean",!0);case"f":return Y(),Ao("alse"),$e("boolean",!1);case"-":case"+":Y()==="-"&&(dr=-1),Se="sign";return;case".":be=Y(),Se="decimalPointLeading";return;case"0":be=Y(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":be=Y(),Se="decimalInteger";return;case"I":return Y(),Ao("nfinity"),$e("numeric",1/0);case"N":return Y(),Ao("aN"),$e("numeric",NaN);case'"':case"'":sa=Y()==='"',be="",Se="string";return}throw qe(Y())},identifierNameStartEscape(){if(xe!=="u")throw qe(Y());Y();let t=Rh();switch(t){case"$":case"_":break;default:if(!it.isIdStartChar(t))throw dw();break}be+=t,Se="identifierName"},identifierName(){switch(xe){case"$":case"_":case"\u200C":case"\u200D":be+=Y();return;case"\\":Y(),Se="identifierNameEscape";return}if(it.isIdContinueChar(xe)){be+=Y();return}return $e("identifier",be)},identifierNameEscape(){if(xe!=="u")throw qe(Y());Y();let t=Rh();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!it.isIdContinueChar(t))throw dw();break}be+=t,Se="identifierName"},sign(){switch(xe){case".":be=Y(),Se="decimalPointLeading";return;case"0":be=Y(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":be=Y(),Se="decimalInteger";return;case"I":return Y(),Ao("nfinity"),$e("numeric",dr*(1/0));case"N":return Y(),Ao("aN"),$e("numeric",NaN)}throw qe(Y())},zero(){switch(xe){case".":be+=Y(),Se="decimalPoint";return;case"e":case"E":be+=Y(),Se="decimalExponent";return;case"x":case"X":be+=Y(),Se="hexadecimal";return}return $e("numeric",dr*0)},decimalInteger(){switch(xe){case".":be+=Y(),Se="decimalPoint";return;case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},decimalPointLeading(){if(it.isDigit(xe)){be+=Y(),Se="decimalFraction";return}throw qe(Y())},decimalPoint(){switch(xe){case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y(),Se="decimalFraction";return}return $e("numeric",dr*Number(be))},decimalFraction(){switch(xe){case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},decimalExponent(){switch(xe){case"+":case"-":be+=Y(),Se="decimalExponentSign";return}if(it.isDigit(xe)){be+=Y(),Se="decimalExponentInteger";return}throw qe(Y())},decimalExponentSign(){if(it.isDigit(xe)){be+=Y(),Se="decimalExponentInteger";return}throw qe(Y())},decimalExponentInteger(){if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},hexadecimal(){if(it.isHexDigit(xe)){be+=Y(),Se="hexadecimalInteger";return}throw qe(Y())},hexadecimalInteger(){if(it.isHexDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},string(){switch(xe){case"\\":Y(),be+=nP();return;case'"':if(sa)return Y(),$e("string",be);be+=Y();return;case"'":if(!sa)return Y(),$e("string",be);be+=Y();return;case`
56
- `:case"\r":throw qe(Y());case"\u2028":case"\u2029":sP(xe);break;case void 0:throw qe(Y())}be+=Y()},start(){switch(xe){case"{":case"[":return $e("punctuator",Y())}Se="value"},beforePropertyName(){switch(xe){case"$":case"_":be=Y(),Se="identifierName";return;case"\\":Y(),Se="identifierNameStartEscape";return;case"}":return $e("punctuator",Y());case'"':case"'":sa=Y()==='"',Se="string";return}if(it.isIdStartChar(xe)){be+=Y(),Se="identifierName";return}throw qe(Y())},afterPropertyName(){if(xe===":")return $e("punctuator",Y());throw qe(Y())},beforePropertyValue(){Se="value"},afterPropertyValue(){switch(xe){case",":case"}":return $e("punctuator",Y())}throw qe(Y())},beforeArrayValue(){if(xe==="]")return $e("punctuator",Y());Se="value"},afterArrayValue(){switch(xe){case",":case"]":return $e("punctuator",Y())}throw qe(Y())},end(){throw qe(Y())}};function $e(t,e){return{type:t,value:e,line:Gr,column:cn}}function Ao(t){for(let e of t){if(pr()!==e)throw qe(Y());Y()}}function nP(){switch(pr()){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(),it.isDigit(pr()))throw qe(Y());return"\0";case"x":return Y(),rP();case"u":return Y(),Rh();case`
52
+ `;function oa(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:VO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:YO})}oa.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]})})};oa.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]})})};oa.prototype.child=function(t){return new oa(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};YC.exports=oa});var lw=G((A6,sa)=>{"use strict";var{isIPv6:XO}=require("node:net"),{Address6:QC}=LC(),QO=hh(),{parse:tw,format:ZO}=WC(),eP=VC(),tP=XC(),nw=1e3,rw=6e4,nP="onRequest",ow=64,rP={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},oP={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},wh=()=>{};function sw(t,e=ow){if(!XO(t))return t.toLowerCase();let n=new QC(t);return n.isMapped4()?n.to4().correctForm():e<128?new QC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function iw(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):ow}var kh=(t,e)=>sw(t.ip,e),sP=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Sh(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=oP):(n.enableDraftSpec=!1,n.labels=rP),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=nw,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=tw(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=rw,n.hook=e.hook||nP,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:wh,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:wh,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:wh,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=iw(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:kh,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=sP,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 tP(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new eP(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=ZC(r,n,o);return(i,a)=>cw.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=ZC(r,n,o);return uw(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=aw(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),ew(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&ew(r,n,o)})}function aw(...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=tw(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=rw),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=nw),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=iw(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function ZC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=aw(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function ew(t,e,n){let r=e.hook,o=uw(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function cw(t,e,n,r){let{store:o}=t,s=e.keyGenerator===kh?kh(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 uw(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await cw(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:ZO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}sa.exports=QO(Sh,{fastify:"5.x",name:"@fastify/rate-limit"});sa.exports.default=Sh;sa.exports.fastifyRateLimit=Sh;sa.exports.normalizeIP=sw});var dw=G((E6,au)=>{au.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;au.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]/;au.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 Eh=G((v6,fw)=>{var Ah=dw();fw.exports={isSpaceSeparator(t){return typeof t=="string"&&Ah.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Ah.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"||Ah.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 yw=G((T6,mw)=>{var it=Eh(),Th,wt,fr,uu,Gr,cn,at,Dh,aa;mw.exports=function(e,n){Th=String(e),wt="start",fr=[],uu=0,Gr=1,cn=0,at=void 0,Dh=void 0,aa=void 0;do at=iP(),uP[wt]();while(at.type!=="eof");return typeof n=="function"?xh({"":aa},"",n):aa};function xh(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=xh(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=xh(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 Se,be,ia,dr,xe;function iP(){for(Se="default",be="",ia=!1,dr=1;;){xe=pr();let t=hw[Se]();if(t)return t}}function pr(){if(Th[uu])return String.fromCodePoint(Th.codePointAt(uu))}function Y(){let t=pr();return t===`
53
+ `?(Gr++,cn=0):t?cn+=t.length:cn++,t&&(uu+=t.length),t}var hw={default(){switch(xe){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
54
+ `:case"\r":case"\u2028":case"\u2029":Y();return;case"/":Y(),Se="comment";return;case void 0:return Y(),$e("eof")}if(it.isSpaceSeparator(xe)){Y();return}return hw[wt]()},comment(){switch(xe){case"*":Y(),Se="multiLineComment";return;case"/":Y(),Se="singleLineComment";return}throw qe(Y())},multiLineComment(){switch(xe){case"*":Y(),Se="multiLineCommentAsterisk";return;case void 0:throw qe(Y())}Y()},multiLineCommentAsterisk(){switch(xe){case"*":Y();return;case"/":Y(),Se="default";return;case void 0:throw qe(Y())}Y(),Se="multiLineComment"},singleLineComment(){switch(xe){case`
55
+ `:case"\r":case"\u2028":case"\u2029":Y(),Se="default";return;case void 0:return Y(),$e("eof")}Y()},value(){switch(xe){case"{":case"[":return $e("punctuator",Y());case"n":return Y(),Eo("ull"),$e("null",null);case"t":return Y(),Eo("rue"),$e("boolean",!0);case"f":return Y(),Eo("alse"),$e("boolean",!1);case"-":case"+":Y()==="-"&&(dr=-1),Se="sign";return;case".":be=Y(),Se="decimalPointLeading";return;case"0":be=Y(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":be=Y(),Se="decimalInteger";return;case"I":return Y(),Eo("nfinity"),$e("numeric",1/0);case"N":return Y(),Eo("aN"),$e("numeric",NaN);case'"':case"'":ia=Y()==='"',be="",Se="string";return}throw qe(Y())},identifierNameStartEscape(){if(xe!=="u")throw qe(Y());Y();let t=Rh();switch(t){case"$":case"_":break;default:if(!it.isIdStartChar(t))throw pw();break}be+=t,Se="identifierName"},identifierName(){switch(xe){case"$":case"_":case"\u200C":case"\u200D":be+=Y();return;case"\\":Y(),Se="identifierNameEscape";return}if(it.isIdContinueChar(xe)){be+=Y();return}return $e("identifier",be)},identifierNameEscape(){if(xe!=="u")throw qe(Y());Y();let t=Rh();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!it.isIdContinueChar(t))throw pw();break}be+=t,Se="identifierName"},sign(){switch(xe){case".":be=Y(),Se="decimalPointLeading";return;case"0":be=Y(),Se="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":be=Y(),Se="decimalInteger";return;case"I":return Y(),Eo("nfinity"),$e("numeric",dr*(1/0));case"N":return Y(),Eo("aN"),$e("numeric",NaN)}throw qe(Y())},zero(){switch(xe){case".":be+=Y(),Se="decimalPoint";return;case"e":case"E":be+=Y(),Se="decimalExponent";return;case"x":case"X":be+=Y(),Se="hexadecimal";return}return $e("numeric",dr*0)},decimalInteger(){switch(xe){case".":be+=Y(),Se="decimalPoint";return;case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},decimalPointLeading(){if(it.isDigit(xe)){be+=Y(),Se="decimalFraction";return}throw qe(Y())},decimalPoint(){switch(xe){case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y(),Se="decimalFraction";return}return $e("numeric",dr*Number(be))},decimalFraction(){switch(xe){case"e":case"E":be+=Y(),Se="decimalExponent";return}if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},decimalExponent(){switch(xe){case"+":case"-":be+=Y(),Se="decimalExponentSign";return}if(it.isDigit(xe)){be+=Y(),Se="decimalExponentInteger";return}throw qe(Y())},decimalExponentSign(){if(it.isDigit(xe)){be+=Y(),Se="decimalExponentInteger";return}throw qe(Y())},decimalExponentInteger(){if(it.isDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},hexadecimal(){if(it.isHexDigit(xe)){be+=Y(),Se="hexadecimalInteger";return}throw qe(Y())},hexadecimalInteger(){if(it.isHexDigit(xe)){be+=Y();return}return $e("numeric",dr*Number(be))},string(){switch(xe){case"\\":Y(),be+=aP();return;case'"':if(ia)return Y(),$e("string",be);be+=Y();return;case"'":if(!ia)return Y(),$e("string",be);be+=Y();return;case`
56
+ `:case"\r":throw qe(Y());case"\u2028":case"\u2029":lP(xe);break;case void 0:throw qe(Y())}be+=Y()},start(){switch(xe){case"{":case"[":return $e("punctuator",Y())}Se="value"},beforePropertyName(){switch(xe){case"$":case"_":be=Y(),Se="identifierName";return;case"\\":Y(),Se="identifierNameStartEscape";return;case"}":return $e("punctuator",Y());case'"':case"'":ia=Y()==='"',Se="string";return}if(it.isIdStartChar(xe)){be+=Y(),Se="identifierName";return}throw qe(Y())},afterPropertyName(){if(xe===":")return $e("punctuator",Y());throw qe(Y())},beforePropertyValue(){Se="value"},afterPropertyValue(){switch(xe){case",":case"}":return $e("punctuator",Y())}throw qe(Y())},beforeArrayValue(){if(xe==="]")return $e("punctuator",Y());Se="value"},afterArrayValue(){switch(xe){case",":case"]":return $e("punctuator",Y())}throw qe(Y())},end(){throw qe(Y())}};function $e(t,e){return{type:t,value:e,line:Gr,column:cn}}function Eo(t){for(let e of t){if(pr()!==e)throw qe(Y());Y()}}function aP(){switch(pr()){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(),it.isDigit(pr()))throw qe(Y());return"\0";case"x":return Y(),cP();case"u":return Y(),Rh();case`
58
58
  `:case"\u2028":case"\u2029":return Y(),"";case"\r":return Y(),pr()===`
59
- `&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw qe(Y());case void 0:throw qe(Y())}return Y()}function rP(){let t="",e=pr();if(!it.isHexDigit(e)||(t+=Y(),e=pr(),!it.isHexDigit(e)))throw qe(Y());return t+=Y(),String.fromCodePoint(parseInt(t,16))}function Rh(){let t="",e=4;for(;e-- >0;){let n=pr();if(!it.isHexDigit(n))throw qe(Y());t+=Y()}return String.fromCodePoint(parseInt(t,16))}var oP={start(){if(at.type==="eof")throw Eo();vh()},beforePropertyName(){switch(at.type){case"identifier":case"string":Dh=at.value,wt="afterPropertyName";return;case"punctuator":au();return;case"eof":throw Eo()}},afterPropertyName(){if(at.type==="eof")throw Eo();wt="beforePropertyValue"},beforePropertyValue(){if(at.type==="eof")throw Eo();vh()},beforeArrayValue(){if(at.type==="eof")throw Eo();if(at.type==="punctuator"&&at.value==="]"){au();return}vh()},afterPropertyValue(){if(at.type==="eof")throw Eo();switch(at.value){case",":wt="beforePropertyName";return;case"}":au()}},afterArrayValue(){if(at.type==="eof")throw Eo();switch(at.value){case",":wt="beforeArrayValue";return;case"]":au()}},end(){}};function vh(){let t;switch(at.type){case"punctuator":switch(at.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=at.value;break}if(ia===void 0)ia=t;else{let e=fr[fr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Dh,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")fr.push(t),Array.isArray(t)?wt="beforeArrayValue":wt="beforePropertyName";else{let e=fr[fr.length-1];e==null?wt="end":Array.isArray(e)?wt="afterArrayValue":wt="afterPropertyValue"}}function au(){fr.pop();let t=fr[fr.length-1];t==null?wt="end":Array.isArray(t)?wt="afterArrayValue":wt="afterPropertyValue"}function qe(t){return uu(t===void 0?`JSON5: invalid end of input at ${Gr}:${cn}`:`JSON5: invalid character '${pw(t)}' at ${Gr}:${cn}`)}function Eo(){return uu(`JSON5: invalid end of input at ${Gr}:${cn}`)}function dw(){return cn-=5,uu(`JSON5: invalid identifier character at ${Gr}:${cn}`)}function sP(t){console.warn(`JSON5: '${pw(t)}' in strings is not valid ECMAScript; consider escaping`)}function pw(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 uu(t){let e=new SyntaxError(t);return e.lineNumber=Gr,e.columnNumber=cn,e}});var yw=G((b6,mw)=>{var Oh=Eh();mw.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=`,
59
+ `&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw qe(Y());case void 0:throw qe(Y())}return Y()}function cP(){let t="",e=pr();if(!it.isHexDigit(e)||(t+=Y(),e=pr(),!it.isHexDigit(e)))throw qe(Y());return t+=Y(),String.fromCodePoint(parseInt(t,16))}function Rh(){let t="",e=4;for(;e-- >0;){let n=pr();if(!it.isHexDigit(n))throw qe(Y());t+=Y()}return String.fromCodePoint(parseInt(t,16))}var uP={start(){if(at.type==="eof")throw vo();vh()},beforePropertyName(){switch(at.type){case"identifier":case"string":Dh=at.value,wt="afterPropertyName";return;case"punctuator":cu();return;case"eof":throw vo()}},afterPropertyName(){if(at.type==="eof")throw vo();wt="beforePropertyValue"},beforePropertyValue(){if(at.type==="eof")throw vo();vh()},beforeArrayValue(){if(at.type==="eof")throw vo();if(at.type==="punctuator"&&at.value==="]"){cu();return}vh()},afterPropertyValue(){if(at.type==="eof")throw vo();switch(at.value){case",":wt="beforePropertyName";return;case"}":cu()}},afterArrayValue(){if(at.type==="eof")throw vo();switch(at.value){case",":wt="beforeArrayValue";return;case"]":cu()}},end(){}};function vh(){let t;switch(at.type){case"punctuator":switch(at.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=at.value;break}if(aa===void 0)aa=t;else{let e=fr[fr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,Dh,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")fr.push(t),Array.isArray(t)?wt="beforeArrayValue":wt="beforePropertyName";else{let e=fr[fr.length-1];e==null?wt="end":Array.isArray(e)?wt="afterArrayValue":wt="afterPropertyValue"}}function cu(){fr.pop();let t=fr[fr.length-1];t==null?wt="end":Array.isArray(t)?wt="afterArrayValue":wt="afterPropertyValue"}function qe(t){return lu(t===void 0?`JSON5: invalid end of input at ${Gr}:${cn}`:`JSON5: invalid character '${gw(t)}' at ${Gr}:${cn}`)}function vo(){return lu(`JSON5: invalid end of input at ${Gr}:${cn}`)}function pw(){return cn-=5,lu(`JSON5: invalid identifier character at ${Gr}:${cn}`)}function lP(t){console.warn(`JSON5: '${gw(t)}' in strings is not valid ECMAScript; consider escaping`)}function gw(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 lu(t){let e=new SyntaxError(t);return e.lineNumber=Gr,e.columnNumber=cn,e}});var bw=G((x6,_w)=>{var Oh=Eh();_w.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
60
  `+s;E=A.join(x),k=`{
61
61
  `+s+E+`,
62
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
63
  `+s,E=C.join(k);A=`[
64
64
  `+s+E+`,
65
- `+w+"]"}return o.pop(),s=w,A}}});var Ph=G((C6,_w)=>{var iP=gw(),aP=yw(),cP={parse:iP,stringify:aP};_w.exports=cP});var nS=G((gz,rI)=>{rI.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 rS=G((mz,oI)=>{oI.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 oS=G((yz,sI)=>{sI.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 sS=G((_z,iI)=>{iI.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 iS=G((bz,aI)=>{aI.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 aS=G((Cz,cI)=>{cI.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 cS=G((wz,uI)=>{uI.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 uS=G((kz,lI)=>{lI.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 lS=G((Sz,dI)=>{dI.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 hS=G((Az,pS)=>{var fI=nS(),pI=rS(),dS=oS(),hI=sS(),gI=iS(),mI=aS(),yI=cS(),_I=uS(),bI=lS(),fS=function(t,e){return t[e]!==void 0?t[e]:e};function Vr(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+=fS(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=fS(n,i)}return r}pS.exports=function(t){return Object.keys(dS).forEach(function(e){var n=dS[e];t=t.replace(e,n)}),t=Vr(t,"^",pI),t=Vr(t,"_",fI),t=Vr(t,"\\bb",hI),t=Vr(t,"\\bf",gI),t=Vr(t,"\\it",_I),t=Vr(t,"\\cal",mI),t=Vr(t,"\\frak",yI),t=Vr(t,"\\mono",bI),t}});var Og=G((y3,LS)=>{"use strict";var il=Object.prototype.hasOwnProperty,jS=Object.prototype.toString,IS=Object.defineProperty,FS=Object.getOwnPropertyDescriptor,NS=function(e){return typeof Array.isArray=="function"?Array.isArray(e):jS.call(e)==="[object Array]"},MS=function(e){if(!e||jS.call(e)!=="[object Object]")return!1;var n=il.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&il.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||il.call(e,o)},BS=function(e,n){IS&&n.name==="__proto__"?IS(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},US=function(e,n){if(n==="__proto__")if(il.call(e,n)){if(FS)return FS(e,n).value}else return;return e[n]};LS.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=US(a,n),o=US(e,n),a!==o&&(f&&o&&(MS(o)||(s=NS(o)))?(s?(s=!1,i=r&&NS(r)?r:[]):i=r&&MS(r)?r:{},BS(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&BS(a,{name:n,newValue:o}));return a}});var $S=G((_3,KI)=>{KI.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 HS=G((b3,qS)=>{"use strict";var VI=$S();qS.exports={pkg:VI}});var Fg=G(Kt=>{"use strict";var WS=Kt&&Kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GaxiosError=Kt.GAXIOS_ERROR_SYMBOL=void 0;Kt.defaultErrorRedactor=GS;var zS=WS(Og()),YI=WS(HS()),Pg=YI.default.pkg;Kt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Pg.name}-gaxios-error`);var Ig=class t extends Error{config;response;code;status;error;[Kt.GAXIOS_ERROR_SYMBOL]=Pg.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Kt.GAXIOS_ERROR_SYMBOL in e&&e[Kt.GAXIOS_ERROR_SYMBOL]===Pg.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,zS.default)(!0,{},n),this.response&&(this.response.config=(0,zS.default)(!0,{},this.response.config)),this.response){try{this.response.data=XI(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}}};Kt.GaxiosError=Ig;function XI(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 GS(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&&(GS({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var KS=G(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});Ng.getRetryConfig=QI;async function QI(t){let e=JS(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||ZI)(t))return{shouldRetry:!1,config:t.config};let o=eF(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 ZI(t){let e=JS(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 JS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function eF(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 Bg=G(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.GaxiosInterceptorManager=void 0;var Mg=class extends Set{};al.GaxiosInterceptorManager=Mg});var YS=G((S3,VS)=>{var Bs=1e3,Us=Bs*60,js=Us*60,Bo=js*24,tF=Bo*7,nF=Bo*365.25;VS.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return rF(t);if(n==="number"&&isFinite(t))return e.long?sF(t):oF(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function rF(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*nF;case"weeks":case"week":case"w":return n*tF;case"days":case"day":case"d":return n*Bo;case"hours":case"hour":case"hrs":case"hr":case"h":return n*js;case"minutes":case"minute":case"mins":case"min":case"m":return n*Us;case"seconds":case"second":case"secs":case"sec":case"s":return n*Bs;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function oF(t){var e=Math.abs(t);return e>=Bo?Math.round(t/Bo)+"d":e>=js?Math.round(t/js)+"h":e>=Us?Math.round(t/Us)+"m":e>=Bs?Math.round(t/Bs)+"s":t+"ms"}function sF(t){var e=Math.abs(t);return e>=Bo?cl(t,e,Bo,"day"):e>=js?cl(t,e,js,"hour"):e>=Us?cl(t,e,Us,"minute"):e>=Bs?cl(t,e,Bs,"second"):t+" ms"}function cl(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var Ug=G((A3,XS)=>{function iF(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=YS(),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}XS.exports=iF});var QS=G((Dt,ul)=>{Dt.formatArgs=cF;Dt.save=uF;Dt.load=lF;Dt.useColors=aF;Dt.storage=dF();Dt.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`."))}})();Dt.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 aF(){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 cF(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+ul.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)}Dt.log=console.debug||console.log||(()=>{});function uF(t){try{t?Dt.storage.setItem("debug",t):Dt.storage.removeItem("debug")}catch{}}function lF(){let t;try{t=Dt.storage.getItem("debug")||Dt.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function dF(){try{return localStorage}catch{}}ul.exports=Ug()(Dt);var{formatters:fF}=ul.exports;fF.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var eA=G((E3,ZS)=>{"use strict";ZS.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 rA=G((v3,nA)=>{"use strict";var pF=require("os"),tA=require("tty"),Vt=eA(),{env:ct}=process,ll;Vt("no-color")||Vt("no-colors")||Vt("color=false")||Vt("color=never")?ll=0:(Vt("color")||Vt("colors")||Vt("color=true")||Vt("color=always"))&&(ll=1);function hF(){if("FORCE_COLOR"in ct)return ct.FORCE_COLOR==="true"?1:ct.FORCE_COLOR==="false"?0:ct.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ct.FORCE_COLOR,10),3)}function gF(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function mF(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=hF();r!==void 0&&(ll=r);let o=n?ll:r;if(o===0)return 0;if(n){if(Vt("color=16m")||Vt("color=full")||Vt("color=truecolor"))return 3;if(Vt("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(ct.TERM==="dumb")return s;if(process.platform==="win32"){let i=pF.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ct)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in ct)||ct.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in ct)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ct.TEAMCITY_VERSION)?1:0;if(ct.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ct){let i=Number.parseInt((ct.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ct.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ct.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ct.TERM)||"COLORTERM"in ct?1:s}function jg(t,e={}){let n=mF(t,{streamIsTTY:t&&t.isTTY,...e});return gF(n)}nA.exports={supportsColor:jg,stdout:jg({isTTY:tA.isatty(1)}),stderr:jg({isTTY:tA.isatty(2)})}});var sA=G((ut,fl)=>{var yF=require("tty"),dl=require("util");ut.init=AF;ut.log=wF;ut.formatArgs=bF;ut.save=kF;ut.load=SF;ut.useColors=_F;ut.destroy=dl.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ut.colors=[6,2,3,4,5,1];try{let t=rA();t&&(t.stderr||t).level>=2&&(ut.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{}ut.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 _F(){return"colors"in ut.inspectOpts?!!ut.inspectOpts.colors:yF.isatty(process.stderr.fd)}function bF(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,A}}});var Ph=G((R6,Cw)=>{var dP=yw(),fP=bw(),pP={parse:dP,stringify:fP};Cw.exports=pP});var iS=G((Ez,lI)=>{lI.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 aS=G((vz,dI)=>{dI.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 cS=G((Tz,fI)=>{fI.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 uS=G((xz,pI)=>{pI.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 lS=G((Rz,hI)=>{hI.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 dS=G((Dz,gI)=>{gI.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 fS=G((Oz,mI)=>{mI.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 pS=G((Pz,yI)=>{yI.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 hS=G((Iz,_I)=>{_I.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 _S=G((Fz,yS)=>{var bI=iS(),CI=aS(),gS=cS(),wI=uS(),kI=lS(),SI=dS(),AI=fS(),EI=pS(),vI=hS(),mS=function(t,e){return t[e]!==void 0?t[e]:e};function Yr(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+=mS(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=mS(n,i)}return r}yS.exports=function(t){return Object.keys(gS).forEach(function(e){var n=gS[e];t=t.replace(e,n)}),t=Yr(t,"^",CI),t=Yr(t,"_",bI),t=Yr(t,"\\bb",wI),t=Yr(t,"\\bf",kI),t=Yr(t,"\\it",EI),t=Yr(t,"\\cal",SI),t=Yr(t,"\\frak",AI),t=Yr(t,"\\mono",vI),t}});var Pg=G((x3,zS)=>{"use strict";var al=Object.prototype.hasOwnProperty,HS=Object.prototype.toString,BS=Object.defineProperty,US=Object.getOwnPropertyDescriptor,jS=function(e){return typeof Array.isArray=="function"?Array.isArray(e):HS.call(e)==="[object Array]"},LS=function(e){if(!e||HS.call(e)!=="[object Object]")return!1;var n=al.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&al.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||al.call(e,o)},$S=function(e,n){BS&&n.name==="__proto__"?BS(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},qS=function(e,n){if(n==="__proto__")if(al.call(e,n)){if(US)return US(e,n).value}else return;return e[n]};zS.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=qS(a,n),o=qS(e,n),a!==o&&(f&&o&&(LS(o)||(s=jS(o)))?(s?(s=!1,i=r&&jS(r)?r:[]):i=r&&LS(r)?r:{},$S(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&$S(a,{name:n,newValue:o}));return a}});var WS=G((R3,tF)=>{tF.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 JS=G((D3,GS)=>{"use strict";var nF=WS();GS.exports={pkg:nF}});var Ng=G(Kt=>{"use strict";var VS=Kt&&Kt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.GaxiosError=Kt.GAXIOS_ERROR_SYMBOL=void 0;Kt.defaultErrorRedactor=YS;var KS=VS(Pg()),rF=VS(JS()),Ig=rF.default.pkg;Kt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Ig.name}-gaxios-error`);var Fg=class t extends Error{config;response;code;status;error;[Kt.GAXIOS_ERROR_SYMBOL]=Ig.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&Kt.GAXIOS_ERROR_SYMBOL in e&&e[Kt.GAXIOS_ERROR_SYMBOL]===Ig.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,KS.default)(!0,{},n),this.response&&(this.response.config=(0,KS.default)(!0,{},this.response.config)),this.response){try{this.response.data=oF(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}}};Kt.GaxiosError=Fg;function oF(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 YS(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&&(YS({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var QS=G(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});Mg.getRetryConfig=sF;async function sF(t){let e=XS(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||iF)(t))return{shouldRetry:!1,config:t.config};let o=aF(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 iF(t){let e=XS(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 XS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function aF(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(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.GaxiosInterceptorManager=void 0;var Bg=class extends Set{};cl.GaxiosInterceptorManager=Bg});var eA=G((F3,ZS)=>{var Us=1e3,js=Us*60,Ls=js*60,Uo=Ls*24,cF=Uo*7,uF=Uo*365.25;ZS.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return lF(t);if(n==="number"&&isFinite(t))return e.long?fF(t):dF(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function lF(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*uF;case"weeks":case"week":case"w":return n*cF;case"days":case"day":case"d":return n*Uo;case"hours":case"hour":case"hrs":case"hr":case"h":return n*Ls;case"minutes":case"minute":case"mins":case"min":case"m":return n*js;case"seconds":case"second":case"secs":case"sec":case"s":return n*Us;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function dF(t){var e=Math.abs(t);return e>=Uo?Math.round(t/Uo)+"d":e>=Ls?Math.round(t/Ls)+"h":e>=js?Math.round(t/js)+"m":e>=Us?Math.round(t/Us)+"s":t+"ms"}function fF(t){var e=Math.abs(t);return e>=Uo?ul(t,e,Uo,"day"):e>=Ls?ul(t,e,Ls,"hour"):e>=js?ul(t,e,js,"minute"):e>=Us?ul(t,e,Us,"second"):t+" ms"}function ul(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var jg=G((N3,tA)=>{function pF(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=eA(),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}tA.exports=pF});var nA=G((Pt,ll)=>{Pt.formatArgs=gF;Pt.save=mF;Pt.load=yF;Pt.useColors=hF;Pt.storage=_F();Pt.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`."))}})();Pt.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 hF(){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 gF(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+ll.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)}Pt.log=console.debug||console.log||(()=>{});function mF(t){try{t?Pt.storage.setItem("debug",t):Pt.storage.removeItem("debug")}catch{}}function yF(){let t;try{t=Pt.storage.getItem("debug")||Pt.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function _F(){try{return localStorage}catch{}}ll.exports=jg()(Pt);var{formatters:bF}=ll.exports;bF.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var oA=G((M3,rA)=>{"use strict";rA.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 aA=G((B3,iA)=>{"use strict";var CF=require("os"),sA=require("tty"),Vt=oA(),{env:ct}=process,dl;Vt("no-color")||Vt("no-colors")||Vt("color=false")||Vt("color=never")?dl=0:(Vt("color")||Vt("colors")||Vt("color=true")||Vt("color=always"))&&(dl=1);function wF(){if("FORCE_COLOR"in ct)return ct.FORCE_COLOR==="true"?1:ct.FORCE_COLOR==="false"?0:ct.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(ct.FORCE_COLOR,10),3)}function kF(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function SF(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=wF();r!==void 0&&(dl=r);let o=n?dl:r;if(o===0)return 0;if(n){if(Vt("color=16m")||Vt("color=full")||Vt("color=truecolor"))return 3;if(Vt("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(ct.TERM==="dumb")return s;if(process.platform==="win32"){let i=CF.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in ct)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in ct)||ct.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in ct)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(ct.TEAMCITY_VERSION)?1:0;if(ct.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in ct){let i=Number.parseInt((ct.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(ct.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(ct.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(ct.TERM)||"COLORTERM"in ct?1:s}function Lg(t,e={}){let n=SF(t,{streamIsTTY:t&&t.isTTY,...e});return kF(n)}iA.exports={supportsColor:Lg,stdout:Lg({isTTY:sA.isatty(1)}),stderr:Lg({isTTY:sA.isatty(2)})}});var uA=G((ut,pl)=>{var AF=require("tty"),fl=require("util");ut.init=OF;ut.log=xF;ut.formatArgs=vF;ut.save=RF;ut.load=DF;ut.useColors=EF;ut.destroy=fl.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ut.colors=[6,2,3,4,5,1];try{let t=aA();t&&(t.stderr||t).level>=2&&(ut.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{}ut.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 EF(){return"colors"in ut.inspectOpts?!!ut.inspectOpts.colors:AF.isatty(process.stderr.fd)}function vF(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+"+fl.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=CF()+e+" "+t[0]}function CF(){return ut.inspectOpts.hideDate?"":new Date().toISOString()+" "}function wF(...t){return process.stderr.write(dl.formatWithOptions(ut.inspectOpts,...t)+`
69
- `)}function kF(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function SF(){return process.env.DEBUG}function AF(t){t.inspectOpts={};let e=Object.keys(ut.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=ut.inspectOpts[e[n]]}fl.exports=Ug()(ut);var{formatters:oA}=fl.exports;oA.o=function(t){return this.inspectOpts.colors=this.useColors,dl.inspect(t,this.inspectOpts).split(`
70
- `).map(e=>e.trim()).join(" ")};oA.O=function(t){return this.inspectOpts.colors=this.useColors,dl.inspect(t,this.inspectOpts)}});var $g=G((T3,Lg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Lg.exports=QS():Lg.exports=sA()});var cA=G(Ot=>{"use strict";var EF=Ot&&Ot.__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]})),vF=Ot&&Ot.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),iA=Ot&&Ot.__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)&&EF(e,t,n);return vF(e,t),e};Object.defineProperty(Ot,"__esModule",{value:!0});Ot.req=Ot.json=Ot.toBuffer=void 0;var TF=iA(require("http")),xF=iA(require("https"));async function aA(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}Ot.toBuffer=aA;async function RF(t){let n=(await aA(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}Ot.json=RF;function DF(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?xF:TF).request(t,e),o=new Promise((s,i)=>{r.once("response",s).once("error",i).end()});return r.then=o.then.bind(o),r}Ot.req=DF});var fA=G(Bt=>{"use strict";var lA=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]})),OF=Bt&&Bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),dA=Bt&&Bt.__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)&&lA(e,t,n);return OF(e,t),e},PF=Bt&&Bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&lA(e,t,n)};Object.defineProperty(Bt,"__esModule",{value:!0});Bt.Agent=void 0;var IF=dA(require("net")),uA=dA(require("http")),FF=require("https");PF(cA(),Bt);var $n=Symbol("AgentBaseInternalState"),qg=class extends uA.Agent{constructor(e){super(e),this[$n]={}}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 IF.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)?FF.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 uA.Agent)try{return a.addRequest(e,o)}catch(u){return r(u)}this[$n].currentSocket=a,super.createSocket(e,n,r)},a=>{this.decrementSockets(s,i),r(a)})}createConnection(){let e=this[$n].currentSocket;if(this[$n].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[$n].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[$n]&&(this[$n].defaultPort=e)}get protocol(){return this[$n].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[$n]&&(this[$n].protocol=e)}};Bt.Agent=qg});var pA=G(Ls=>{"use strict";var NF=Ls&&Ls.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Ls,"__esModule",{value:!0});Ls.parseProxyResponse=void 0;var MF=NF($g()),pl=(0,MF.default)("https-proxy-agent:parse-proxy-response");function BF(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(),pl("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(f){i(),pl("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+"+pl.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=TF()+e+" "+t[0]}function TF(){return ut.inspectOpts.hideDate?"":new Date().toISOString()+" "}function xF(...t){return process.stderr.write(fl.formatWithOptions(ut.inspectOpts,...t)+`
69
+ `)}function RF(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function DF(){return process.env.DEBUG}function OF(t){t.inspectOpts={};let e=Object.keys(ut.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=ut.inspectOpts[e[n]]}pl.exports=jg()(ut);var{formatters:cA}=pl.exports;cA.o=function(t){return this.inspectOpts.colors=this.useColors,fl.inspect(t,this.inspectOpts).split(`
70
+ `).map(e=>e.trim()).join(" ")};cA.O=function(t){return this.inspectOpts.colors=this.useColors,fl.inspect(t,this.inspectOpts)}});var qg=G((U3,$g)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$g.exports=nA():$g.exports=uA()});var fA=G(It=>{"use strict";var PF=It&&It.__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]})),IF=It&&It.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),lA=It&&It.__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)&&PF(e,t,n);return IF(e,t),e};Object.defineProperty(It,"__esModule",{value:!0});It.req=It.json=It.toBuffer=void 0;var FF=lA(require("http")),NF=lA(require("https"));async function dA(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}It.toBuffer=dA;async function MF(t){let n=(await dA(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}It.json=MF;function BF(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?NF: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}It.req=BF});var mA=G(Bt=>{"use strict";var hA=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]})),UF=Bt&&Bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),gA=Bt&&Bt.__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)&&hA(e,t,n);return UF(e,t),e},jF=Bt&&Bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&hA(e,t,n)};Object.defineProperty(Bt,"__esModule",{value:!0});Bt.Agent=void 0;var LF=gA(require("net")),pA=gA(require("http")),$F=require("https");jF(fA(),Bt);var $n=Symbol("AgentBaseInternalState"),Hg=class extends pA.Agent{constructor(e){super(e),this[$n]={}}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 LF.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 pA.Agent)try{return a.addRequest(e,o)}catch(u){return r(u)}this[$n].currentSocket=a,super.createSocket(e,n,r)},a=>{this.decrementSockets(s,i),r(a)})}createConnection(){let e=this[$n].currentSocket;if(this[$n].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[$n].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[$n]&&(this[$n].defaultPort=e)}get protocol(){return this[$n].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[$n]&&(this[$n].protocol=e)}};Bt.Agent=Hg});var yA=G($s=>{"use strict";var qF=$s&&$s.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty($s,"__esModule",{value:!0});$s.parseProxyResponse=void 0;var HF=qF(qg()),hl=(0,HF.default)("https-proxy-agent:parse-proxy-response");function zF(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(),hl("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(f){i(),hl("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
- `);if(h===-1){pl("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}pl("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()})}Ls.parseProxyResponse=BF});var bA=G(Yt=>{"use strict";var UF=Yt&&Yt.__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]})),jF=Yt&&Yt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yA=Yt&&Yt.__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 jF(e,t),e},_A=Yt&&Yt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.HttpsProxyAgent=void 0;var hl=yA(require("net")),hA=yA(require("tls")),LF=_A(require("assert")),$F=_A($g()),qF=fA(),HF=require("url"),zF=pA(),Sa=(0,$F.default)("https-proxy-agent"),gA=t=>t.servername===void 0&&t.host&&!hl.isIP(t.host)?{...t,servername:t.host}:t,gl=class extends qF.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new HF.URL(e):e,this.proxyHeaders=n?.headers??{},Sa("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?mA(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:"?(Sa("Creating `tls.Socket`: %o",this.connectOpts),o=hA.connect(gA(this.connectOpts))):(Sa("Creating `net.Socket`: %o",this.connectOpts),o=hl.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=hl.isIPv6(n.host)?`[${n.host}]`:n.host,a=`CONNECT ${i}:${n.port} HTTP/1.1\r
73
+ `);if(h===-1){hl("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}hl("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()})}$s.parseProxyResponse=zF});var SA=G(Yt=>{"use strict";var WF=Yt&&Yt.__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=Yt&&Yt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),wA=Yt&&Yt.__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)&&WF(e,t,n);return GF(e,t),e},kA=Yt&&Yt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Yt,"__esModule",{value:!0});Yt.HttpsProxyAgent=void 0;var gl=wA(require("net")),_A=wA(require("tls")),JF=kA(require("assert")),KF=kA(qg()),VF=mA(),YF=require("url"),XF=yA(),Aa=(0,KF.default)("https-proxy-agent"),bA=t=>t.servername===void 0&&t.host&&!gl.isIP(t.host)?{...t,servername:t.host}:t,ml=class extends VF.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new YF.URL(e):e,this.proxyHeaders=n?.headers??{},Aa("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?CA(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:"?(Aa("Creating `tls.Socket`: %o",this.connectOpts),o=_A.connect(bA(this.connectOpts))):(Aa("Creating `net.Socket`: %o",this.connectOpts),o=gl.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=gl.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,zF.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",WF),n.secureEndpoint?(Sa("Upgrading socket connection to TLS"),hA.connect({...mA(gA(n),"host","path","port"),socket:o})):o;o.destroy();let p=new hl.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{Sa("Replaying proxy buffer for failed request"),(0,LF.default)(h.listenerCount("data")>0),h.push(f),h.push(null)}),p}};gl.protocols=["http","https"];Yt.HttpsProxyAgent=gl;function WF(t){t.resume()}function mA(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function zg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var GF,JF,Hg,ml=Wr(()=>{GF=Object.defineProperty,JF=(t,e)=>GF(t,"name",{value:e,configurable:!0}),Hg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};JF(zg,"getDefaultExportFromCjs")});var AA={};sh(AA,{toFormData:()=>SA});function kA(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 SA(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 eN(n[1]||n[2]),o,s,i,a,u,d,f=[],p=new jo,h=Ut(C=>{i+=w.decode(C,{stream:!0})},"onPartData"),g=Ut(C=>{f.push(C)},"appendToFile"),b=Ut(()=>{let C=new $s(f,d,{type:u});p.append(a,C)},"appendFileToFormData"),m=Ut(()=>{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=kA(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 KF,Ut,qn,Ue,CA,Qr,yl,_l,VF,Aa,YF,XF,QF,ZF,Uo,wA,eN,EA=Wr(()=>{bl();ml();KF=Object.defineProperty,Ut=(t,e)=>KF(t,"name",{value:e,configurable:!0}),qn=0,Ue={START_BOUNDARY:qn++,HEADER_FIELD_START:qn++,HEADER_FIELD:qn++,HEADER_VALUE_START:qn++,HEADER_VALUE:qn++,HEADER_VALUE_ALMOST_DONE:qn++,HEADERS_ALMOST_DONE:qn++,PART_DATA_START:qn++,PART_DATA:qn++,END:qn++},CA=1,Qr={PART_BOUNDARY:CA,LAST_BOUNDARY:CA*=2},yl=10,_l=13,VF=32,Aa=45,YF=58,XF=97,QF=122,ZF=Ut(t=>t|32,"lower"),Uo=Ut(()=>{},"noop"),wA=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Uo,this.onHeaderField=Uo,this.onHeadersEnd=Uo,this.onHeaderValue=Uo,this.onPartBegin=Uo,this.onPartData=Uo,this.onPartEnd=Uo,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=Ut(E=>{this[E+"Mark"]=n},"mark"),C=Ut(E=>{delete this[E+"Mark"]},"clear"),A=Ut((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),k=Ut((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 Ue.START_BOUNDARY:if(u===i.length-2){if(b===Aa)f|=Qr.LAST_BOUNDARY;else if(b!==_l)return;u++;break}else if(u-1===i.length-2){if(f&Qr.LAST_BOUNDARY&&b===Aa)d=Ue.END,f=0;else if(!(f&Qr.LAST_BOUNDARY)&&b===yl)u=0,A("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===_l){C("onHeaderField"),d=Ue.HEADERS_ALMOST_DONE;break}if(u++,b===Aa)break;if(b===YF){if(u===1)return;k("onHeaderField",!0),d=Ue.HEADER_VALUE_START;break}if(m=ZF(b),m<XF||m>QF)return;break;case Ue.HEADER_VALUE_START:if(b===VF)break;w("onHeaderValue"),d=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:b===_l&&(k("onHeaderValue",!0),A("onHeaderEnd"),d=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(b!==yl)return;d=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(b!==yl)return;A("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===_l?f|=Qr.PART_BOUNDARY:b===Aa?f|=Qr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&Qr.PART_BOUNDARY){if(u=0,b===yl){f&=~Qr.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),d=Ue.HEADER_FIELD_START;break}}else f&Qr.LAST_BOUNDARY&&b===Aa?(A("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);A("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")}};Ut(wA,"MultipartParser");eN=wA;Ut(kA,"_fileName");Ut(SA,"toFormData")});function qA(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 HA(){return TA||(TA=1,(function(t,e){(function(n,r){r(e)})(nN,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 ye(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ie(c):Z(c,l._storedError)}y(ye,"ReadableStreamReaderGenericInitialize");function De(c,l){let _=c._ownerReadableStream;return zt(_,l)}y(De,"ReadableStreamReaderGenericCancel");function ve(c){let l=c._ownerReadableStream;l._state==="readable"?Pe(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Ce(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(ve,"ReadableStreamReaderGenericRelease");function Ye(c){return new TypeError("Cannot "+c+" a stream using a released reader")}y(Ye,"readerLockException");function ne(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_})}y(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Pe(c,l)}y(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ie(c){ne(c),H(c)}y(ie,"defaultReaderClosedPromiseInitializeAsResolved");function Pe(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(Pe,"defaultReaderClosedPromiseReject");function Ce(c,l){Z(c,l)}y(Ce,"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 Ae=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},tt=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 le(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}y(le,"assertDictionary");function ae(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}y(ae,"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(tt(c))}y(L,"integerPart");function P(c,l){let _=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ae(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!Ae(v)||v===0?0:v}y(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!ir(c))throw new TypeError(`${l} is not a ReadableStream.`)}y(N,"assertReadableStream");function U(c){return new ge(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 se(c){return c._reader._readRequests.length}y(se,"ReadableStreamGetNumReadRequests");function ce(c){let l=c._reader;return!(l===void 0||!pe(l))}y(ce,"ReadableStreamHasDefaultReader");let _e=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),ar(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ye(this,l),this._readRequests=new V}get closed(){return pe(this)?this._closedPromise:h(En("closed"))}cancel(l=void 0){return pe(this)?this._ownerReadableStream===void 0?h(Ye("cancel")):De(this,l):h(En("cancel"))}read(){if(!pe(this))return h(En("read"));if(this._ownerReadableStream===void 0)return h(Ye("read from"));let l,_,v=f((I,$)=>{l=I,_=$});return me(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(!pe(this))throw En("releaseLock");this._ownerReadableStream!==void 0&&Ie(this)}};y(_e,"ReadableStreamDefaultReader");let ge=_e;Object.defineProperties(ge.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(ge.prototype.cancel,"cancel"),i(ge.prototype.read,"read"),i(ge.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ge.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function pe(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof ge}y(pe,"IsReadableStreamDefaultReader");function me(c,l){let _=c._ownerReadableStream;_._disturbed=!0,_._state==="closed"?l._closeSteps():_._state==="errored"?l._errorSteps(_._storedError):_._readableStreamController[te](l)}y(me,"ReadableStreamDefaultReaderRead");function Ie(c){ve(c);let l=new TypeError("Reader was released");Ze(c,l)}y(Ie,"ReadableStreamDefaultReaderRelease");function Ze(c,l){let _=c._readRequests;c._readRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Ze,"ReadableStreamDefaultReaderErrorReadRequests");function En(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}y(En,"defaultReaderBrandCheckException");let xi=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),rs=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 me(l,{_chunkSteps:y($=>{this._ongoingPromise=void 0,k(()=>_({value:$,done:!1}))},"_chunkSteps"),_closeSteps:y(()=>{this._ongoingPromise=void 0,this._isFinished=!0,ve(l),_({value:void 0,done:!0})},"_closeSteps"),_errorSteps:y($=>{this._ongoingPromise=void 0,this._isFinished=!0,ve(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=De(_,l);return ve(_),C(v,()=>({value:l,done:!0}))}return ve(_),p({value:l,done:!0})}};y(rs,"ReadableStreamAsyncIteratorImpl");let It=rs,Pr={next(){return nt(this)?this._asyncIteratorImpl.next():h(Be("next"))},return(c){return nt(this)?this._asyncIteratorImpl.return(c):h(Be("return"))}};Object.setPrototypeOf(Pr,xi);function _t(c,l){let _=U(c),v=new It(_,l),I=Object.create(Pr);return I._asyncIteratorImpl=v,I}y(_t,"AcquireReadableStreamAsyncIterator");function nt(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof It}catch{return!1}}y(nt,"IsReadableStreamAsyncIterator");function Be(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}y(Be,"streamAsyncIteratorBrandCheckException");let P0=Number.isNaN||function(c){return c!==c};var np,rp,op;function os(c){return c.slice()}y(os,"CreateArrayFromList");function sp(c,l,_,v,I){new Uint8Array(c).set(new Uint8Array(_,v,I),l)}y(sp,"CopyDataBlockBytes");let tr=y(c=>(typeof c.transfer=="function"?tr=y(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?tr=y(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):tr=y(l=>l,"TransferArrayBuffer"),tr(c)),"TransferArrayBuffer"),Ir=y(c=>(typeof c.detached=="boolean"?Ir=y(l=>l.detached,"IsDetachedBuffer"):Ir=y(l=>l.byteLength===0,"IsDetachedBuffer"),Ir(c)),"IsDetachedBuffer");function ip(c,l,_){if(c.slice)return c.slice(l,_);let v=_-l,I=new ArrayBuffer(v);return sp(I,0,c,l,v),I}y(ip,"ArrayBufferSlice");function Ri(c,l){let _=c[l];if(_!=null){if(typeof _!="function")throw new TypeError(`${String(l)} is not a function`);return _}}y(Ri,"GetMethod");function I0(c){let l={[Symbol.iterator]:()=>c.iterator},_=(async function*(){return yield*l})(),v=_.next;return{iterator:_,nextMethod:v,done:!1}}y(I0,"CreateAsyncFromSyncIterator");let ap=(op=(np=Symbol.asyncIterator)!==null&&np!==void 0?np:(rp=Symbol.for)===null||rp===void 0?void 0:rp.call(Symbol,"Symbol.asyncIterator"))!==null&&op!==void 0?op:"@@asyncIterator";function cp(c,l="sync",_){if(_===void 0)if(l==="async"){if(_=Ri(c,ap),_===void 0){let $=Ri(c,Symbol.iterator),W=cp(c,"sync",$);return I0(W)}}else _=Ri(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(cp,"GetIterator");function F0(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(F0,"IteratorNext");function N0(c){return!!c.done}y(N0,"IteratorComplete");function M0(c){return c.value}y(M0,"IteratorValue");function B0(c){return!(typeof c!="number"||P0(c)||c<0)}y(B0,"IsNonNegativeNumber");function up(c){let l=ip(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}y(up,"CloneAsUint8Array");function gc(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}y(gc,"DequeueValue");function mc(c,l,_){if(!B0(_)||_===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:_}),c._queueTotalSize+=_}y(mc,"EnqueueValueWithSize");function U0(c){return c._queue.peek().value}y(U0,"PeekQueueValue");function nr(c){c._queue=new V,c._queueTotalSize=0}y(nr,"ResetQueue");function lp(c){return c===DataView}y(lp,"isDataViewConstructor");function j0(c){return lp(c.constructor)}y(j0,"isDataView");function L0(c){return lp(c)?1:c.BYTES_PER_ELEMENT}y(L0,"arrayBufferViewElementSize");let $0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!yc(this))throw kc("view");return this._view}respond(l){if(!yc(this))throw kc("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(Ir(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ii(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!yc(this))throw kc("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(Ir(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Fi(this._associatedReadableByteStreamController,l)}};y($0,"ReadableStreamBYOBRequest");let po=$0;Object.defineProperties(po.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(po.prototype.respond,"respond"),i(po.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(po.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let q0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Fr(this))throw is("byobRequest");return wc(this)}get desiredSize(){if(!Fr(this))throw is("desiredSize");return Cp(this)}close(){if(!Fr(this))throw is("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`);ss(this)}enqueue(l){if(!Fr(this))throw is("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`);Pi(this,l)}error(l=void 0){if(!Fr(this))throw is("error");Ft(this,l)}[z](l){dp(this),nr(this);let _=this._cancelAlgorithm(l);return Oi(this),_}[te](l){let _=this._controlledReadableByteStream;if(this._queueTotalSize>0){bp(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),Nr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};y(q0,"ReadableByteStreamController");let rr=q0;Object.defineProperties(rr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(rr.prototype.close,"close"),i(rr.prototype.enqueue,"enqueue"),i(rr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Fr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof rr}y(Fr,"IsReadableByteStreamController");function yc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof po}y(yc,"IsReadableStreamBYOBRequest");function Nr(c){if(!J0(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,Nr(c)),null),_=>(Ft(c,_),null))}y(Nr,"ReadableByteStreamControllerCallPullIfNeeded");function dp(c){bc(c),c._pendingPullIntos=new V}y(dp,"ReadableByteStreamControllerClearPendingPullIntos");function _c(c,l){let _=!1;c._state==="closed"&&(_=!0);let v=fp(l);l.readerType==="default"?K(c,v,_):Z0(c,v,_)}y(_c,"ReadableByteStreamControllerCommitPullIntoDescriptor");function fp(c){let l=c.bytesFilled,_=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/_)}y(fp,"ReadableByteStreamControllerConvertPullIntoDescriptor");function Di(c,l,_,v){c._queue.push({buffer:l,byteOffset:_,byteLength:v}),c._queueTotalSize+=v}y(Di,"ReadableByteStreamControllerEnqueueChunkToQueue");function pp(c,l,_,v){let I;try{I=ip(l,_,_+v)}catch($){throw Ft(c,$),$}Di(c,I,0,v)}y(pp,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function hp(c,l){l.bytesFilled>0&&pp(c,l.buffer,l.byteOffset,l.bytesFilled),ho(c)}y(hp,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function gp(c,l){let _=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+_,I=_,$=!1,W=v%l.elementSize,oe=v-W;oe>=l.minimumFill&&(I=oe-l.bytesFilled,$=!0);let ue=c._queue;for(;I>0;){let he=ue.peek(),we=Math.min(I,he.byteLength),ke=l.byteOffset+l.bytesFilled;sp(l.buffer,ke,he.buffer,he.byteOffset,we),he.byteLength===we?ue.shift():(he.byteOffset+=we,he.byteLength-=we),c._queueTotalSize-=we,mp(c,we,l),I-=we}return $}y(gp,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function mp(c,l,_){_.bytesFilled+=l}y(mp,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function yp(c){c._queueTotalSize===0&&c._closeRequested?(Oi(c),ps(c._controlledReadableByteStream)):Nr(c)}y(yp,"ReadableByteStreamControllerHandleQueueDrain");function bc(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}y(bc,"ReadableByteStreamControllerInvalidateBYOBRequest");function Cc(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();gp(c,l)&&(ho(c),_c(c._controlledReadableByteStream,l))}}y(Cc,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function H0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let _=l._readRequests.shift();bp(c,_)}}y(H0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function z0(c,l,_,v){let I=c._controlledReadableByteStream,$=l.constructor,W=L0($),{byteOffset:oe,byteLength:ue}=l,he=_*W,we;try{we=tr(l.buffer)}catch(Me){v._errorSteps(Me);return}let ke={buffer:we,bufferByteLength:we.byteLength,byteOffset:oe,byteLength:ue,bytesFilled:0,minimumFill:he,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(ke),Sp(I,v);return}if(I._state==="closed"){let Me=new $(ke.buffer,ke.byteOffset,0);v._closeSteps(Me);return}if(c._queueTotalSize>0){if(gp(c,ke)){let Me=fp(ke);yp(c),v._chunkSteps(Me);return}if(c._closeRequested){let Me=new TypeError("Insufficient bytes to fill elements in the given buffer");Ft(c,Me),v._errorSteps(Me);return}}c._pendingPullIntos.push(ke),Sp(I,v),Nr(c)}y(z0,"ReadableByteStreamControllerPullInto");function W0(c,l){l.readerType==="none"&&ho(c);let _=c._controlledReadableByteStream;if(Sc(_))for(;Ap(_)>0;){let v=ho(c);_c(_,v)}}y(W0,"ReadableByteStreamControllerRespondInClosedState");function G0(c,l,_){if(mp(c,l,_),_.readerType==="none"){hp(c,_),Cc(c);return}if(_.bytesFilled<_.minimumFill)return;ho(c);let v=_.bytesFilled%_.elementSize;if(v>0){let I=_.byteOffset+_.bytesFilled;pp(c,_.buffer,I-v,v)}_.bytesFilled-=v,_c(c._controlledReadableByteStream,_),Cc(c)}y(G0,"ReadableByteStreamControllerRespondInReadableState");function _p(c,l){let _=c._pendingPullIntos.peek();bc(c),c._controlledReadableByteStream._state==="closed"?W0(c,_):G0(c,l,_),Nr(c)}y(_p,"ReadableByteStreamControllerRespondInternal");function ho(c){return c._pendingPullIntos.shift()}y(ho,"ReadableByteStreamControllerShiftPendingPullInto");function J0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ce(l)&&se(l)>0||Sc(l)&&Ap(l)>0||Cp(c)>0)}y(J0,"ReadableByteStreamControllerShouldCallPull");function Oi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Oi,"ReadableByteStreamControllerClearAlgorithms");function ss(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 Ft(c,v),v}}Oi(c),ps(l)}}y(ss,"ReadableByteStreamControllerClose");function Pi(c,l){let _=c._controlledReadableByteStream;if(c._closeRequested||_._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Ir(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=tr(v);if(c._pendingPullIntos.length>0){let oe=c._pendingPullIntos.peek();if(Ir(oe.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");bc(c),oe.buffer=tr(oe.buffer),oe.readerType==="none"&&hp(c,oe)}if(ce(_))if(H0(c),se(_)===0)Di(c,W,I,$);else{c._pendingPullIntos.length>0&&ho(c);let oe=new Uint8Array(W,I,$);K(_,oe,!1)}else Sc(_)?(Di(c,W,I,$),Cc(c)):Di(c,W,I,$);Nr(c)}y(Pi,"ReadableByteStreamControllerEnqueue");function Ft(c,l){let _=c._controlledReadableByteStream;_._state==="readable"&&(dp(c),nr(c),Oi(c),Jp(_,l))}y(Ft,"ReadableByteStreamControllerError");function bp(c,l){let _=c._queue.shift();c._queueTotalSize-=_.byteLength,yp(c);let v=new Uint8Array(_.buffer,_.byteOffset,_.byteLength);l._chunkSteps(v)}y(bp,"ReadableByteStreamControllerFillReadRequestFromQueue");function wc(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(po.prototype);V0(v,c,_),c._byobRequest=v}return c._byobRequest}y(wc,"ReadableByteStreamControllerGetBYOBRequest");function Cp(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Cp,"ReadableByteStreamControllerGetDesiredSize");function Ii(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=tr(_.buffer),_p(c,l)}y(Ii,"ReadableByteStreamControllerRespond");function Fi(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=tr(l.buffer),_p(c,v)}y(Fi,"ReadableByteStreamControllerRespondWithNewView");function wp(c,l,_,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,nr(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 oe=_();b(p(oe),()=>(l._started=!0,Nr(l),null),ue=>(Ft(l,ue),null))}y(wp,"SetUpReadableByteStreamController");function K0(c,l,_){let v=Object.create(rr.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(ue=>l.cancel(ue),"cancelAlgorithm"):W=y(()=>p(void 0),"cancelAlgorithm");let oe=l.autoAllocateChunkSize;if(oe===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");wp(c,v,I,$,W,_,oe)}y(K0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function V0(c,l,_){c._associatedReadableByteStreamController=l,c._view=_}y(V0,"SetUpReadableStreamBYOBRequest");function kc(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}y(kc,"byobRequestBrandCheckException");function is(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}y(is,"byteStreamControllerBrandCheckException");function Y0(c,l){le(c,l);let _=c?.mode;return{mode:_===void 0?void 0:X0(_,`${l} has member 'mode' that`)}}y(Y0,"convertReaderOptions");function X0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}y(X0,"convertReadableStreamReaderMode");function Q0(c,l){var _;le(c,l);let v=(_=c?.min)!==null&&_!==void 0?_:1;return{min:P(v,`${l} has member 'min' that`)}}y(Q0,"convertByobReadOptions");function kp(c){return new Mr(c)}y(kp,"AcquireReadableStreamBYOBReader");function Sp(c,l){c._reader._readIntoRequests.push(l)}y(Sp,"ReadableStreamAddReadIntoRequest");function Z0(c,l,_){let v=c._reader._readIntoRequests.shift();_?v._closeSteps(l):v._chunkSteps(l)}y(Z0,"ReadableStreamFulfillReadIntoRequest");function Ap(c){return c._reader._readIntoRequests.length}y(Ap,"ReadableStreamGetNumReadIntoRequests");function Sc(c){let l=c._reader;return!(l===void 0||!Br(l))}y(Sc,"ReadableStreamHasBYOBReader");let eb=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),ar(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Fr(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ye(this,l),this._readIntoRequests=new V}get closed(){return Br(this)?this._closedPromise:h(Ni("closed"))}cancel(l=void 0){return Br(this)?this._ownerReadableStream===void 0?h(Ye("cancel")):De(this,l):h(Ni("cancel"))}read(l,_={}){if(!Br(this))return h(Ni("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(Ir(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=Q0(_,"options")}catch(ue){return h(ue)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(j0(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(Ye("read from"));let $,W,oe=f((ue,he)=>{$=ue,W=he});return Ep(this,l,I,{_chunkSteps:y(ue=>$({value:ue,done:!1}),"_chunkSteps"),_closeSteps:y(ue=>$({value:ue,done:!0}),"_closeSteps"),_errorSteps:y(ue=>W(ue),"_errorSteps")}),oe}releaseLock(){if(!Br(this))throw Ni("releaseLock");this._ownerReadableStream!==void 0&&tb(this)}};y(eb,"ReadableStreamBYOBReader");let Mr=eb;Object.defineProperties(Mr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(Mr.prototype.cancel,"cancel"),i(Mr.prototype.read,"read"),i(Mr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Br(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof Mr}y(Br,"IsReadableStreamBYOBReader");function Ep(c,l,_,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):z0(I._readableStreamController,l,_,v)}y(Ep,"ReadableStreamBYOBReaderRead");function tb(c){ve(c);let l=new TypeError("Reader was released");vp(c,l)}y(tb,"ReadableStreamBYOBReaderRelease");function vp(c,l){let _=c._readIntoRequests;c._readIntoRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(vp,"ReadableStreamBYOBReaderErrorReadIntoRequests");function Ni(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}y(Ni,"byobReaderBrandCheckException");function as(c,l){let{highWaterMark:_}=c;if(_===void 0)return l;if(P0(_)||_<0)throw new RangeError("Invalid highWaterMark");return _}y(as,"ExtractHighWaterMark");function Mi(c){let{size:l}=c;return l||(()=>1)}y(Mi,"ExtractSizeAlgorithm");function Bi(c,l){le(c,l);let _=c?.highWaterMark,v=c?.size;return{highWaterMark:_===void 0?void 0:D(_),size:v===void 0?void 0:nb(v,`${l} has member 'size' that`)}}y(Bi,"convertQueuingStrategy");function nb(c,l){return ae(c,l),_=>D(c(_))}y(nb,"convertQueuingStrategySize");function rb(c,l){le(c,l);let _=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:_===void 0?void 0:ob(_,c,`${l} has member 'abort' that`),close:v===void 0?void 0:sb(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:ib(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:ab(W,c,`${l} has member 'write' that`),type:$}}y(rb,"convertUnderlyingSink");function ob(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(ob,"convertUnderlyingSinkAbortCallback");function sb(c,l,_){return ae(c,_),()=>x(c,l,[])}y(sb,"convertUnderlyingSinkCloseCallback");function ib(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(ib,"convertUnderlyingSinkStartCallback");function ab(c,l,_){return ae(c,_),(v,I)=>x(c,l,[v,I])}y(ab,"convertUnderlyingSinkWriteCallback");function Tp(c,l){if(!go(c))throw new TypeError(`${l} is not a WritableStream.`)}y(Tp,"assertWritableStream");function cb(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}y(cb,"isAbortSignal");let MD=typeof AbortController=="function";function ub(){if(MD)return new AbortController}y(ub,"createAbortController");let lb=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=Bi(_,"Second parameter"),I=rb(l,"First parameter");if(Rp(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=Mi(v),W=as(v,1);Tb(this,I,W,$)}get locked(){if(!go(this))throw qi("locked");return mo(this)}abort(l=void 0){return go(this)?mo(this)?h(new TypeError("Cannot abort a stream that already has a writer")):Ui(this,l):h(qi("abort"))}close(){return go(this)?mo(this)?h(new TypeError("Cannot close a stream that already has a writer")):sn(this)?h(new TypeError("Cannot close an already-closing stream")):Dp(this):h(qi("close"))}getWriter(){if(!go(this))throw qi("getWriter");return xp(this)}};y(lb,"WritableStream");let Ur=lb;Object.defineProperties(Ur.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Ur.prototype.abort,"abort"),i(Ur.prototype.close,"close"),i(Ur.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ur.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function xp(c){return new or(c)}y(xp,"AcquireWritableStreamDefaultWriter");function db(c,l,_,v,I=1,$=()=>1){let W=Object.create(Ur.prototype);Rp(W);let oe=Object.create(cs.prototype);return Np(W,oe,c,l,_,v,I,$),W}y(db,"CreateWritableStream");function Rp(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(Rp,"InitializeWritableStream");function go(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Ur}y(go,"IsWritableStream");function mo(c){return c._writer!==void 0}y(mo,"IsWritableStreamLocked");function Ui(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,oe)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:oe,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||Ec(c,l),$}y(Ui,"WritableStreamAbort");function Dp(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"&&Ic(v),xb(c._writableStreamController),_}y(Dp,"WritableStreamClose");function fb(c){return f((l,_)=>{let v={_resolve:l,_reject:_};c._writeRequests.push(v)})}y(fb,"WritableStreamAddWriteRequest");function Ac(c,l){if(c._state==="writable"){Ec(c,l);return}vc(c)}y(Ac,"WritableStreamDealWithRejection");function Ec(c,l){let _=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&Pp(v,l),!yb(c)&&_._started&&vc(c)}y(Ec,"WritableStreamStartErroring");function vc(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){ji(c);return}let _=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,_._wasAlreadyErroring){_._reject(l),ji(c);return}let v=c._writableStreamController[j](_._reason);b(v,()=>(_._resolve(),ji(c),null),I=>(_._reject(I),ji(c),null))}y(vc,"WritableStreamFinishErroring");function pb(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}y(pb,"WritableStreamFinishInFlightWrite");function hb(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,Ac(c,l)}y(hb,"WritableStreamFinishInFlightWriteWithError");function gb(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&&jp(l)}y(gb,"WritableStreamFinishInFlightClose");function mb(c,l){c._inFlightCloseRequest._reject(l),c._inFlightCloseRequest=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._reject(l),c._pendingAbortRequest=void 0),Ac(c,l)}y(mb,"WritableStreamFinishInFlightCloseWithError");function sn(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}y(sn,"WritableStreamCloseQueuedOrInFlight");function yb(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}y(yb,"WritableStreamHasOperationMarkedInFlight");function _b(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}y(_b,"WritableStreamMarkCloseRequestInFlight");function bb(c){c._inFlightWriteRequest=c._writeRequests.shift()}y(bb,"WritableStreamMarkFirstWriteRequestInFlight");function ji(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&Oc(l,c._storedError)}y(ji,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function Tc(c,l){let _=c._writer;_!==void 0&&l!==c._backpressure&&(l?Nb(_):Ic(_)),c._backpressure=l}y(Tc,"WritableStreamUpdateBackpressure");let Cb=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Tp(l,"First parameter"),mo(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")!sn(l)&&l._backpressure?zi(this):Lp(this),Hi(this);else if(_==="erroring")Pc(this,l._storedError),Hi(this);else if(_==="closed")Lp(this),Ib(this);else{let v=l._storedError;Pc(this,v),Up(this,v)}}get closed(){return jr(this)?this._closedPromise:h(Lr("closed"))}get desiredSize(){if(!jr(this))throw Lr("desiredSize");if(this._ownerWritableStream===void 0)throw ls("desiredSize");return Ab(this)}get ready(){return jr(this)?this._readyPromise:h(Lr("ready"))}abort(l=void 0){return jr(this)?this._ownerWritableStream===void 0?h(ls("abort")):wb(this,l):h(Lr("abort"))}close(){if(!jr(this))return h(Lr("close"));let l=this._ownerWritableStream;return l===void 0?h(ls("close")):sn(l)?h(new TypeError("Cannot close an already-closing stream")):Op(this)}releaseLock(){if(!jr(this))throw Lr("releaseLock");this._ownerWritableStream!==void 0&&Ip(this)}write(l=void 0){return jr(this)?this._ownerWritableStream===void 0?h(ls("write to")):Fp(this,l):h(Lr("write"))}};y(Cb,"WritableStreamDefaultWriter");let or=Cb;Object.defineProperties(or.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(or.prototype.abort,"abort"),i(or.prototype.close,"close"),i(or.prototype.releaseLock,"releaseLock"),i(or.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function jr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof or}y(jr,"IsWritableStreamDefaultWriter");function wb(c,l){let _=c._ownerWritableStream;return Ui(_,l)}y(wb,"WritableStreamDefaultWriterAbort");function Op(c){let l=c._ownerWritableStream;return Dp(l)}y(Op,"WritableStreamDefaultWriterClose");function kb(c){let l=c._ownerWritableStream,_=l._state;return sn(l)||_==="closed"?p(void 0):_==="errored"?h(l._storedError):Op(c)}y(kb,"WritableStreamDefaultWriterCloseWithErrorPropagation");function Sb(c,l){c._closedPromiseState==="pending"?Oc(c,l):Fb(c,l)}y(Sb,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function Pp(c,l){c._readyPromiseState==="pending"?$p(c,l):Mb(c,l)}y(Pp,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function Ab(c){let l=c._ownerWritableStream,_=l._state;return _==="errored"||_==="erroring"?null:_==="closed"?0:Mp(l._writableStreamController)}y(Ab,"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");Pp(c,_),Sb(c,_),l._writer=void 0,c._ownerWritableStream=void 0}y(Ip,"WritableStreamDefaultWriterRelease");function Fp(c,l){let _=c._ownerWritableStream,v=_._writableStreamController,I=Rb(v,l);if(_!==c._ownerWritableStream)return h(ls("write to"));let $=_._state;if($==="errored")return h(_._storedError);if(sn(_)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(_._storedError);let W=fb(_);return Db(v,l,I),W}y(Fp,"WritableStreamDefaultWriterWrite");let Eb={},vb=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!xc(this))throw Dc("abortReason");return this._abortReason}get signal(){if(!xc(this))throw Dc("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!xc(this))throw Dc("error");this._controlledWritableStream._state==="writable"&&Bp(this,l)}[j](l){let _=this._abortAlgorithm(l);return Li(this),_}[ee](){nr(this)}};y(vb,"WritableStreamDefaultController");let cs=vb;Object.defineProperties(cs.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(cs.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function xc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof cs}y(xc,"IsWritableStreamDefaultController");function Np(c,l,_,v,I,$,W,oe){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,nr(l),l._abortReason=void 0,l._abortController=ub(),l._started=!1,l._strategySizeAlgorithm=oe,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let ue=Rc(l);Tc(c,ue);let he=_(),we=p(he);b(we,()=>(l._started=!0,$i(l),null),ke=>(l._started=!0,Ac(c,ke),null))}y(Np,"SetUpWritableStreamDefaultController");function Tb(c,l,_,v){let I=Object.create(cs.prototype),$,W,oe,ue;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.write!==void 0?W=y(he=>l.write(he,I),"writeAlgorithm"):W=y(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?oe=y(()=>l.close(),"closeAlgorithm"):oe=y(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?ue=y(he=>l.abort(he),"abortAlgorithm"):ue=y(()=>p(void 0),"abortAlgorithm"),Np(c,I,$,W,oe,ue,_,v)}y(Tb,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function Li(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(Li,"WritableStreamDefaultControllerClearAlgorithms");function xb(c){mc(c,Eb,0),$i(c)}y(xb,"WritableStreamDefaultControllerClose");function Rb(c,l){try{return c._strategySizeAlgorithm(l)}catch(_){return us(c,_),1}}y(Rb,"WritableStreamDefaultControllerGetChunkSize");function Mp(c){return c._strategyHWM-c._queueTotalSize}y(Mp,"WritableStreamDefaultControllerGetDesiredSize");function Db(c,l,_){try{mc(c,l,_)}catch(I){us(c,I);return}let v=c._controlledWritableStream;if(!sn(v)&&v._state==="writable"){let I=Rc(c);Tc(v,I)}$i(c)}y(Db,"WritableStreamDefaultControllerWrite");function $i(c){let l=c._controlledWritableStream;if(!c._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){vc(l);return}if(c._queue.length===0)return;let _=U0(c);_===Eb?Ob(c):Pb(c,_)}y($i,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function us(c,l){c._controlledWritableStream._state==="writable"&&Bp(c,l)}y(us,"WritableStreamDefaultControllerErrorIfNeeded");function Ob(c){let l=c._controlledWritableStream;_b(l),gc(c);let _=c._closeAlgorithm();Li(c),b(_,()=>(gb(l),null),v=>(mb(l,v),null))}y(Ob,"WritableStreamDefaultControllerProcessClose");function Pb(c,l){let _=c._controlledWritableStream;bb(_);let v=c._writeAlgorithm(l);b(v,()=>{pb(_);let I=_._state;if(gc(c),!sn(_)&&I==="writable"){let $=Rc(c);Tc(_,$)}return $i(c),null},I=>(_._state==="writable"&&Li(c),hb(_,I),null))}y(Pb,"WritableStreamDefaultControllerProcessWrite");function Rc(c){return Mp(c)<=0}y(Rc,"WritableStreamDefaultControllerGetBackpressure");function Bp(c,l){let _=c._controlledWritableStream;Li(c),Ec(_,l)}y(Bp,"WritableStreamDefaultControllerError");function qi(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}y(qi,"streamBrandCheckException$2");function Dc(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}y(Dc,"defaultControllerBrandCheckException$2");function Lr(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}y(Lr,"defaultWriterBrandCheckException");function ls(c){return new TypeError("Cannot "+c+" a stream using a released writer")}y(ls,"defaultWriterLockException");function Hi(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_,c._closedPromiseState="pending"})}y(Hi,"defaultWriterClosedPromiseInitialize");function Up(c,l){Hi(c),Oc(c,l)}y(Up,"defaultWriterClosedPromiseInitializeAsRejected");function Ib(c){Hi(c),jp(c)}y(Ib,"defaultWriterClosedPromiseInitializeAsResolved");function Oc(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(Oc,"defaultWriterClosedPromiseReject");function Fb(c,l){Up(c,l)}y(Fb,"defaultWriterClosedPromiseResetToRejected");function jp(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(jp,"defaultWriterClosedPromiseResolve");function zi(c){c._readyPromise=f((l,_)=>{c._readyPromise_resolve=l,c._readyPromise_reject=_}),c._readyPromiseState="pending"}y(zi,"defaultWriterReadyPromiseInitialize");function Pc(c,l){zi(c),$p(c,l)}y(Pc,"defaultWriterReadyPromiseInitializeAsRejected");function Lp(c){zi(c),Ic(c)}y(Lp,"defaultWriterReadyPromiseInitializeAsResolved");function $p(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($p,"defaultWriterReadyPromiseReject");function Nb(c){zi(c)}y(Nb,"defaultWriterReadyPromiseReset");function Mb(c,l){Pc(c,l)}y(Mb,"defaultWriterReadyPromiseResetToRejected");function Ic(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(Ic,"defaultWriterReadyPromiseResolve");function Bb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof Hg<"u")return Hg}y(Bb,"getGlobals");let BD=Bb();function Ub(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}y(Ub,"isDOMExceptionConstructor");function jb(){let c=BD?.DOMException;return Ub(c)?c:void 0}y(jb,"getFromGlobal");function Lb(){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(Lb,"createPolyfill");let UD=jb()||Lb();function qp(c,l,_,v,I,$){let W=U(c),oe=xp(l);c._disturbed=!0;let ue=!1,he=p(void 0);return f((we,ke)=>{let Me;if($!==void 0){if(Me=y(()=>{let de=$.reason!==void 0?$.reason:new UD("Aborted","AbortError"),Re=[];v||Re.push(()=>l._state==="writable"?Ui(l,de):p(void 0)),I||Re.push(()=>c._state==="readable"?zt(c,de):p(void 0)),bt(()=>Promise.all(Re.map(Ne=>Ne())),!0,de)},"abortAlgorithm"),$.aborted){Me();return}$.addEventListener("abort",Me)}function At(){return f((de,Re)=>{function Ne(Ct){Ct?de():g(cr(),Ne,Re)}y(Ne,"next"),Ne(!1)})}y(At,"pipeLoop");function cr(){return ue?p(!0):g(oe._readyPromise,()=>f((de,Re)=>{me(W,{_chunkSteps:y(Ne=>{he=g(Fp(oe,Ne),void 0,r),de(!1)},"_chunkSteps"),_closeSteps:y(()=>de(!0),"_closeSteps"),_errorSteps:Re})}))}if(y(cr,"pipeStep"),Wt(c,W._closedPromise,de=>(v?Et(!0,de):bt(()=>Ui(l,de),!0,de),null)),Wt(l,oe._closedPromise,de=>(I?Et(!0,de):bt(()=>zt(c,de),!0,de),null)),rt(c,W._closedPromise,()=>(_?Et():bt(()=>kb(oe)),null)),sn(l)||l._state==="closed"){let de=new TypeError("the destination writable stream closed before all data could be piped to it");I?Et(!0,de):bt(()=>zt(c,de),!0,de)}A(At());function an(){let de=he;return g(he,()=>de!==he?an():void 0)}y(an,"waitForWritesToFinish");function Wt(de,Re,Ne){de._state==="errored"?Ne(de._storedError):w(Re,Ne)}y(Wt,"isOrBecomesErrored");function rt(de,Re,Ne){de._state==="closed"?Ne():m(Re,Ne)}y(rt,"isOrBecomesClosed");function bt(de,Re,Ne){if(ue)return;ue=!0,l._state==="writable"&&!sn(l)?m(an(),Ct):Ct();function Ct(){return b(de(),()=>ur(Re,Ne),zr=>ur(!0,zr)),null}y(Ct,"doTheRest")}y(bt,"shutdownWithAction");function Et(de,Re){ue||(ue=!0,l._state==="writable"&&!sn(l)?m(an(),()=>ur(de,Re)):ur(de,Re))}y(Et,"shutdown");function ur(de,Re){return Ip(oe),ve(W),$!==void 0&&$.removeEventListener("abort",Me),de?ke(Re):we(void 0),null}y(ur,"finalize")})}y(qp,"ReadableStreamPipeTo");let $b=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Wi(this))throw Ji("desiredSize");return Fc(this)}close(){if(!Wi(this))throw Ji("close");if(!_o(this))throw new TypeError("The stream is not in a state that permits close");$r(this)}enqueue(l=void 0){if(!Wi(this))throw Ji("enqueue");if(!_o(this))throw new TypeError("The stream is not in a state that permits enqueue");return yo(this,l)}error(l=void 0){if(!Wi(this))throw Ji("error");Ht(this,l)}[z](l){nr(this);let _=this._cancelAlgorithm(l);return Gi(this),_}[te](l){let _=this._controlledReadableStream;if(this._queue.length>0){let v=gc(this);this._closeRequested&&this._queue.length===0?(Gi(this),ps(_)):ds(this),l._chunkSteps(v)}else B(_,l),ds(this)}[Q](){}};y($b,"ReadableStreamDefaultController");let sr=$b;Object.defineProperties(sr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(sr.prototype.close,"close"),i(sr.prototype.enqueue,"enqueue"),i(sr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Wi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof sr}y(Wi,"IsReadableStreamDefaultController");function ds(c){if(!Hp(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,ds(c)),null),_=>(Ht(c,_),null))}y(ds,"ReadableStreamDefaultControllerCallPullIfNeeded");function Hp(c){let l=c._controlledReadableStream;return!_o(c)||!c._started?!1:!!(ar(l)&&se(l)>0||Fc(c)>0)}y(Hp,"ReadableStreamDefaultControllerShouldCallPull");function Gi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(Gi,"ReadableStreamDefaultControllerClearAlgorithms");function $r(c){if(!_o(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(Gi(c),ps(l))}y($r,"ReadableStreamDefaultControllerClose");function yo(c,l){if(!_o(c))return;let _=c._controlledReadableStream;if(ar(_)&&se(_)>0)K(_,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Ht(c,I),I}try{mc(c,l,v)}catch(I){throw Ht(c,I),I}}ds(c)}y(yo,"ReadableStreamDefaultControllerEnqueue");function Ht(c,l){let _=c._controlledReadableStream;_._state==="readable"&&(nr(c),Gi(c),Jp(_,l))}y(Ht,"ReadableStreamDefaultControllerError");function Fc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Fc,"ReadableStreamDefaultControllerGetDesiredSize");function qb(c){return!Hp(c)}y(qb,"ReadableStreamDefaultControllerHasBackpressure");function _o(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}y(_o,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function zp(c,l,_,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,nr(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 oe=_();b(p(oe),()=>(l._started=!0,ds(l),null),ue=>(Ht(l,ue),null))}y(zp,"SetUpReadableStreamDefaultController");function Hb(c,l,_,v){let I=Object.create(sr.prototype),$,W,oe;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?oe=y(ue=>l.cancel(ue),"cancelAlgorithm"):oe=y(()=>p(void 0),"cancelAlgorithm"),zp(c,I,$,W,oe,_,v)}y(Hb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function Ji(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}y(Ji,"defaultControllerBrandCheckException$1");function zb(c,l){return Fr(c._readableStreamController)?Gb(c):Wb(c)}y(zb,"ReadableStreamTee");function Wb(c,l){let _=U(c),v=!1,I=!1,$=!1,W=!1,oe,ue,he,we,ke,Me=f(rt=>{ke=rt});function At(){return v?(I=!0,p(void 0)):(v=!0,me(_,{_chunkSteps:y(rt=>{k(()=>{I=!1;let bt=rt,Et=rt;$||yo(he._readableStreamController,bt),W||yo(we._readableStreamController,Et),v=!1,I&&At()})},"_chunkSteps"),_closeSteps:y(()=>{v=!1,$||$r(he._readableStreamController),W||$r(we._readableStreamController),(!$||!W)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{v=!1},"_errorSteps")}),p(void 0))}y(At,"pullAlgorithm");function cr(rt){if($=!0,oe=rt,W){let bt=os([oe,ue]),Et=zt(c,bt);ke(Et)}return Me}y(cr,"cancel1Algorithm");function an(rt){if(W=!0,ue=rt,$){let bt=os([oe,ue]),Et=zt(c,bt);ke(Et)}return Me}y(an,"cancel2Algorithm");function Wt(){}return y(Wt,"startAlgorithm"),he=fs(Wt,At,cr),we=fs(Wt,At,an),w(_._closedPromise,rt=>(Ht(he._readableStreamController,rt),Ht(we._readableStreamController,rt),(!$||!W)&&ke(void 0),null)),[he,we]}y(Wb,"ReadableStreamDefaultTee");function Gb(c){let l=U(c),_=!1,v=!1,I=!1,$=!1,W=!1,oe,ue,he,we,ke,Me=f(de=>{ke=de});function At(de){w(de._closedPromise,Re=>(de!==l||(Ft(he._readableStreamController,Re),Ft(we._readableStreamController,Re),(!$||!W)&&ke(void 0)),null))}y(At,"forwardReaderError");function cr(){Br(l)&&(ve(l),l=U(c),At(l)),me(l,{_chunkSteps:y(de=>{k(()=>{v=!1,I=!1;let Re=de,Ne=de;if(!$&&!W)try{Ne=up(de)}catch(Ct){Ft(he._readableStreamController,Ct),Ft(we._readableStreamController,Ct),ke(zt(c,Ct));return}$||Pi(he._readableStreamController,Re),W||Pi(we._readableStreamController,Ne),_=!1,v?Wt():I&&rt()})},"_chunkSteps"),_closeSteps:y(()=>{_=!1,$||ss(he._readableStreamController),W||ss(we._readableStreamController),he._readableStreamController._pendingPullIntos.length>0&&Ii(he._readableStreamController,0),we._readableStreamController._pendingPullIntos.length>0&&Ii(we._readableStreamController,0),(!$||!W)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(cr,"pullWithDefaultReader");function an(de,Re){pe(l)&&(ve(l),l=kp(c),At(l));let Ne=Re?we:he,Ct=Re?he:we;Ep(l,de,1,{_chunkSteps:y(zr=>{k(()=>{v=!1,I=!1;let hs=Re?W:$;if(Re?$:W)hs||Fi(Ne._readableStreamController,zr);else{let gs;try{gs=up(zr)}catch(oh){Ft(Ne._readableStreamController,oh),Ft(Ct._readableStreamController,oh),ke(zt(c,oh));return}hs||Fi(Ne._readableStreamController,zr),Pi(Ct._readableStreamController,gs)}_=!1,v?Wt():I&&rt()})},"_chunkSteps"),_closeSteps:y(zr=>{_=!1;let hs=Re?W:$,gs=Re?$:W;hs||ss(Ne._readableStreamController),gs||ss(Ct._readableStreamController),zr!==void 0&&(hs||Fi(Ne._readableStreamController,zr),!gs&&Ct._readableStreamController._pendingPullIntos.length>0&&Ii(Ct._readableStreamController,0)),(!hs||!gs)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(an,"pullWithBYOBReader");function Wt(){if(_)return v=!0,p(void 0);_=!0;let de=wc(he._readableStreamController);return de===null?cr():an(de._view,!1),p(void 0)}y(Wt,"pull1Algorithm");function rt(){if(_)return I=!0,p(void 0);_=!0;let de=wc(we._readableStreamController);return de===null?cr():an(de._view,!0),p(void 0)}y(rt,"pull2Algorithm");function bt(de){if($=!0,oe=de,W){let Re=os([oe,ue]),Ne=zt(c,Re);ke(Ne)}return Me}y(bt,"cancel1Algorithm");function Et(de){if(W=!0,ue=de,$){let Re=os([oe,ue]),Ne=zt(c,Re);ke(Ne)}return Me}y(Et,"cancel2Algorithm");function ur(){}return y(ur,"startAlgorithm"),he=Gp(ur,Wt,bt),we=Gp(ur,rt,Et),At(l),[he,we]}y(Gb,"ReadableByteStreamTee");function Jb(c){return o(c)&&typeof c.getReader<"u"}y(Jb,"isReadableStreamLike");function Kb(c){return Jb(c)?Yb(c.getReader()):Vb(c)}y(Kb,"ReadableStreamFrom");function Vb(c){let l,_=cp(c,"async"),v=r;function I(){let W;try{W=F0(_)}catch(ue){return h(ue)}let oe=p(W);return C(oe,ue=>{if(!o(ue))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(N0(ue))$r(l._readableStreamController);else{let he=M0(ue);yo(l._readableStreamController,he)}})}y(I,"pullAlgorithm");function $(W){let oe=_.iterator,ue;try{ue=Ri(oe,"return")}catch(ke){return h(ke)}if(ue===void 0)return p(void 0);let he;try{he=E(ue,oe,[W])}catch(ke){return h(ke)}let we=p(he);return C(we,ke=>{if(!o(ke))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return y($,"cancelAlgorithm"),l=fs(v,I,$,0),l}y(Vb,"ReadableStreamFromIterable");function Yb(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)$r(l._readableStreamController);else{let oe=W.value;yo(l._readableStreamController,oe)}})}y(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return y(I,"cancelAlgorithm"),l=fs(_,v,I,0),l}y(Yb,"ReadableStreamFromDefaultReader");function Xb(c,l){le(c,l);let _=c,v=_?.autoAllocateChunkSize,I=_?.cancel,$=_?.pull,W=_?.start,oe=_?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:Qb(I,_,`${l} has member 'cancel' that`),pull:$===void 0?void 0:Zb($,_,`${l} has member 'pull' that`),start:W===void 0?void 0:eC(W,_,`${l} has member 'start' that`),type:oe===void 0?void 0:tC(oe,`${l} has member 'type' that`)}}y(Xb,"convertUnderlyingDefaultOrByteSource");function Qb(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(Qb,"convertUnderlyingSourceCancelCallback");function Zb(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(Zb,"convertUnderlyingSourcePullCallback");function eC(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(eC,"convertUnderlyingSourceStartCallback");function tC(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}y(tC,"convertReadableStreamType");function nC(c,l){return le(c,l),{preventCancel:!!c?.preventCancel}}y(nC,"convertIteratorOptions");function Wp(c,l){le(c,l);let _=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&rC($,`${l} has member 'signal' that`),{preventAbort:!!_,preventCancel:!!v,preventClose:!!I,signal:$}}y(Wp,"convertPipeOptions");function rC(c,l){if(!cb(c))throw new TypeError(`${l} is not an AbortSignal.`)}y(rC,"assertAbortSignal");function oC(c,l){le(c,l);let _=c?.readable;M(_,"readable","ReadableWritablePair"),N(_,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),Tp(v,`${l} has member 'writable' that`),{readable:_,writable:v}}y(oC,"convertReadableWritablePair");let sC=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=Bi(_,"Second parameter"),I=Xb(l,"First parameter");if(Nc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=as(v,0);K0(this,I,$)}else{let $=Mi(v),W=as(v,1);Hb(this,I,W,$)}}get locked(){if(!ir(this))throw qr("locked");return ar(this)}cancel(l=void 0){return ir(this)?ar(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):zt(this,l):h(qr("cancel"))}getReader(l=void 0){if(!ir(this))throw qr("getReader");return Y0(l,"First parameter").mode===void 0?U(this):kp(this)}pipeThrough(l,_={}){if(!ir(this))throw qr("pipeThrough");R(l,1,"pipeThrough");let v=oC(l,"First parameter"),I=Wp(_,"Second parameter");if(ar(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(mo(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=qp(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return A($),v.readable}pipeTo(l,_={}){if(!ir(this))return h(qr("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!go(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=Wp(_,"Second parameter")}catch(I){return h(I)}return ar(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):mo(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):qp(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!ir(this))throw qr("tee");let l=zb(this);return os(l)}values(l=void 0){if(!ir(this))throw qr("values");let _=nC(l,"First parameter");return _t(this,_.preventCancel)}[ap](l){return this.values(l)}static from(l){return Kb(l)}};y(sC,"ReadableStream");let mt=sC;Object.defineProperties(mt,{from:{enumerable:!0}}),Object.defineProperties(mt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(mt.from,"from"),i(mt.prototype.cancel,"cancel"),i(mt.prototype.getReader,"getReader"),i(mt.prototype.pipeThrough,"pipeThrough"),i(mt.prototype.pipeTo,"pipeTo"),i(mt.prototype.tee,"tee"),i(mt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(mt.prototype,ap,{value:mt.prototype.values,writable:!0,configurable:!0});function fs(c,l,_,v=1,I=()=>1){let $=Object.create(mt.prototype);Nc($);let W=Object.create(sr.prototype);return zp($,W,c,l,_,v,I),$}y(fs,"CreateReadableStream");function Gp(c,l,_){let v=Object.create(mt.prototype);Nc(v);let I=Object.create(rr.prototype);return wp(v,I,c,l,_,0,void 0),v}y(Gp,"CreateReadableByteStream");function Nc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}y(Nc,"InitializeReadableStream");function ir(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof mt}y(ir,"IsReadableStream");function ar(c){return c._reader!==void 0}y(ar,"IsReadableStreamLocked");function zt(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);ps(c);let _=c._reader;if(_!==void 0&&Br(_)){let I=_._readIntoRequests;_._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return C(v,r)}y(zt,"ReadableStreamCancel");function ps(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),pe(l))){let _=l._readRequests;l._readRequests=new V,_.forEach(v=>{v._closeSteps()})}}y(ps,"ReadableStreamClose");function Jp(c,l){c._state="errored",c._storedError=l;let _=c._reader;_!==void 0&&(Pe(_,l),pe(_)?Ze(_,l):vp(_,l))}y(Jp,"ReadableStreamError");function qr(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}y(qr,"streamBrandCheckException$1");function Kp(c,l){le(c,l);let _=c?.highWaterMark;return M(_,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(_)}}y(Kp,"convertQueuingStrategyInit");let iC=y(c=>c.byteLength,"byteLengthSizeFunction");i(iC,"size");let aC=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=Kp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Yp(this))throw Vp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Yp(this))throw Vp("size");return iC}};y(aC,"ByteLengthQueuingStrategy");let Mc=aC;Object.defineProperties(Mc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Vp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}y(Vp,"byteLengthBrandCheckException");function Yp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof Mc}y(Yp,"IsByteLengthQueuingStrategy");let cC=y(()=>1,"countSizeFunction");i(cC,"size");let uC=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=Kp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Qp(this))throw Xp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Qp(this))throw Xp("size");return cC}};y(uC,"CountQueuingStrategy");let Bc=uC;Object.defineProperties(Bc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Bc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Xp(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}y(Xp,"countBrandCheckException");function Qp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof Bc}y(Qp,"IsCountQueuingStrategy");function lC(c,l){le(c,l);let _=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,oe=c?.writableType;return{cancel:_===void 0?void 0:hC(_,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:dC(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:fC($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:pC(W,c,`${l} has member 'transform' that`),writableType:oe}}y(lC,"convertTransformer");function dC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(dC,"convertTransformerFlushCallback");function fC(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(fC,"convertTransformerStartCallback");function pC(c,l,_){return ae(c,_),(v,I)=>x(c,l,[v,I])}y(pC,"convertTransformerTransformCallback");function hC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(hC,"convertTransformerCancelCallback");let gC=class{constructor(l={},_={},v={}){l===void 0&&(l=null);let I=Bi(_,"Second parameter"),$=Bi(v,"Third parameter"),W=lC(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 oe=as($,0),ue=Mi($),he=as(I,1),we=Mi(I),ke,Me=f(At=>{ke=At});mC(this,Me,he,we,oe,ue),bC(this,W),W.start!==void 0?ke(W.start(this._transformStreamController)):ke(void 0)}get readable(){if(!Zp(this))throw rh("readable");return this._readable}get writable(){if(!Zp(this))throw rh("writable");return this._writable}};y(gC,"TransformStream");let Uc=gC;Object.defineProperties(Uc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Uc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function mC(c,l,_,v,I,$){function W(){return l}y(W,"startAlgorithm");function oe(Me){return kC(c,Me)}y(oe,"writeAlgorithm");function ue(Me){return SC(c,Me)}y(ue,"abortAlgorithm");function he(){return AC(c)}y(he,"closeAlgorithm"),c._writable=db(W,oe,he,ue,_,v);function we(){return EC(c)}y(we,"pullAlgorithm");function ke(Me){return vC(c,Me)}y(ke,"cancelAlgorithm"),c._readable=fs(W,we,ke,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Ki(c,!0),c._transformStreamController=void 0}y(mC,"InitializeTransformStream");function Zp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof Uc}y(Zp,"IsTransformStream");function eh(c,l){Ht(c._readable._readableStreamController,l),jc(c,l)}y(eh,"TransformStreamError");function jc(c,l){Yi(c._transformStreamController),us(c._writable._writableStreamController,l),Lc(c)}y(jc,"TransformStreamErrorWritableAndUnblockWrite");function Lc(c){c._backpressure&&Ki(c,!1)}y(Lc,"TransformStreamUnblockWrite");function Ki(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(_=>{c._backpressureChangePromise_resolve=_}),c._backpressure=l}y(Ki,"TransformStreamSetBackpressure");let yC=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Vi(this))throw Xi("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return Fc(l)}enqueue(l=void 0){if(!Vi(this))throw Xi("enqueue");th(this,l)}error(l=void 0){if(!Vi(this))throw Xi("error");CC(this,l)}terminate(){if(!Vi(this))throw Xi("terminate");wC(this)}};y(yC,"TransformStreamDefaultController");let Hr=yC;Object.defineProperties(Hr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Hr.prototype.enqueue,"enqueue"),i(Hr.prototype.error,"error"),i(Hr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Hr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Vi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Hr}y(Vi,"IsTransformStreamDefaultController");function _C(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(_C,"SetUpTransformStreamDefaultController");function bC(c,l){let _=Object.create(Hr.prototype),v,I,$;l.transform!==void 0?v=y(W=>l.transform(W,_),"transformAlgorithm"):v=y(W=>{try{return th(_,W),p(void 0)}catch(oe){return h(oe)}},"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"),_C(c,_,v,I,$)}y(bC,"SetUpTransformStreamDefaultControllerFromTransformer");function Yi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Yi,"TransformStreamDefaultControllerClearAlgorithms");function th(c,l){let _=c._controlledTransformStream,v=_._readable._readableStreamController;if(!_o(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{yo(v,l)}catch(I){throw jc(_,I),_._readable._storedError}qb(v)!==_._backpressure&&Ki(_,!0)}y(th,"TransformStreamDefaultControllerEnqueue");function CC(c,l){eh(c._controlledTransformStream,l)}y(CC,"TransformStreamDefaultControllerError");function nh(c,l){let _=c._transformAlgorithm(l);return C(_,void 0,v=>{throw eh(c._controlledTransformStream,v),v})}y(nh,"TransformStreamDefaultControllerPerformTransform");function wC(c){let l=c._controlledTransformStream,_=l._readable._readableStreamController;$r(_);let v=new TypeError("TransformStream terminated");jc(l,v)}y(wC,"TransformStreamDefaultControllerTerminate");function kC(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 nh(_,l)})}return nh(_,l)}y(kC,"TransformStreamDefaultSinkWriteAlgorithm");function SC(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 Yi(_),b(I,()=>(v._state==="errored"?bo(_,v._storedError):(Ht(v._readableStreamController,l),$c(_)),null),$=>(Ht(v._readableStreamController,$),bo(_,$),null)),_._finishPromise}y(SC,"TransformStreamDefaultSinkAbortAlgorithm");function AC(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 Yi(l),b(v,()=>(_._state==="errored"?bo(l,_._storedError):($r(_._readableStreamController),$c(l)),null),I=>(Ht(_._readableStreamController,I),bo(l,I),null)),l._finishPromise}y(AC,"TransformStreamDefaultSinkCloseAlgorithm");function EC(c){return Ki(c,!1),c._backpressureChangePromise}y(EC,"TransformStreamDefaultSourcePullAlgorithm");function vC(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 Yi(_),b(I,()=>(v._state==="errored"?bo(_,v._storedError):(us(v._writableStreamController,l),Lc(c),$c(_)),null),$=>(us(v._writableStreamController,$),Lc(c),bo(_,$),null)),_._finishPromise}y(vC,"TransformStreamDefaultSourceCancelAlgorithm");function Xi(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}y(Xi,"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 bo(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(bo,"defaultControllerFinishPromiseReject");function rh(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}y(rh,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=Mc,n.CountQueuingStrategy=Bc,n.ReadableByteStreamController=rr,n.ReadableStream=mt,n.ReadableStreamBYOBReader=Mr,n.ReadableStreamBYOBRequest=po,n.ReadableStreamDefaultController=sr,n.ReadableStreamDefaultReader=ge,n.TransformStream=Uc,n.TransformStreamDefaultController=Hr,n.WritableStream=Ur,n.WritableStreamDefaultController=cs,n.WritableStreamDefaultWriter=or})})(Sl,Sl.exports)),Sl.exports}function RA(){if(xA)return vA;xA=1;let t=65536;if(!globalThis.ReadableStream)try{let e=require("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,HA())}try{let{Blob:e}=require("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 vA}async function*Al(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,DA),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+DA)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function WA(t,e=zo){var n=`${OA()}${OA()}`.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+Vg(i)+`"\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",QF),n.secureEndpoint?(Aa("Upgrading socket connection to TLS"),_A.connect({...CA(bA(n),"host","path","port"),socket:o})):o;o.destroy();let p=new gl.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{Aa("Replaying proxy buffer for failed request"),(0,JF.default)(h.listenerCount("data")>0),h.push(f),h.push(null)}),p}};ml.protocols=["http","https"];Yt.HttpsProxyAgent=ml;function QF(t){t.resume()}function CA(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function Wg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ZF,eN,zg,yl=Wr(()=>{ZF=Object.defineProperty,eN=(t,e)=>ZF(t,"name",{value:e,configurable:!0}),zg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};eN(Wg,"getDefaultExportFromCjs")});var xA={};sh(xA,{toFormData:()=>TA});function vA(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 TA(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 aN(n[1]||n[2]),o,s,i,a,u,d,f=[],p=new Lo,h=Ut(C=>{i+=w.decode(C,{stream:!0})},"onPartData"),g=Ut(C=>{f.push(C)},"appendToFile"),b=Ut(()=>{let C=new qs(f,d,{type:u});p.append(a,C)},"appendFileToFormData"),m=Ut(()=>{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=vA(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 tN,Ut,qn,Ue,AA,Zr,_l,bl,nN,Ea,rN,oN,sN,iN,jo,EA,aN,RA=Wr(()=>{Cl();yl();tN=Object.defineProperty,Ut=(t,e)=>tN(t,"name",{value:e,configurable:!0}),qn=0,Ue={START_BOUNDARY:qn++,HEADER_FIELD_START:qn++,HEADER_FIELD:qn++,HEADER_VALUE_START:qn++,HEADER_VALUE:qn++,HEADER_VALUE_ALMOST_DONE:qn++,HEADERS_ALMOST_DONE:qn++,PART_DATA_START:qn++,PART_DATA:qn++,END:qn++},AA=1,Zr={PART_BOUNDARY:AA,LAST_BOUNDARY:AA*=2},_l=10,bl=13,nN=32,Ea=45,rN=58,oN=97,sN=122,iN=Ut(t=>t|32,"lower"),jo=Ut(()=>{},"noop"),EA=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=jo,this.onHeaderField=jo,this.onHeadersEnd=jo,this.onHeaderValue=jo,this.onPartBegin=jo,this.onPartData=jo,this.onPartEnd=jo,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=Ut(E=>{this[E+"Mark"]=n},"mark"),C=Ut(E=>{delete this[E+"Mark"]},"clear"),A=Ut((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),k=Ut((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 Ue.START_BOUNDARY:if(u===i.length-2){if(b===Ea)f|=Zr.LAST_BOUNDARY;else if(b!==bl)return;u++;break}else if(u-1===i.length-2){if(f&Zr.LAST_BOUNDARY&&b===Ea)d=Ue.END,f=0;else if(!(f&Zr.LAST_BOUNDARY)&&b===_l)u=0,A("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===bl){C("onHeaderField"),d=Ue.HEADERS_ALMOST_DONE;break}if(u++,b===Ea)break;if(b===rN){if(u===1)return;k("onHeaderField",!0),d=Ue.HEADER_VALUE_START;break}if(m=iN(b),m<oN||m>sN)return;break;case Ue.HEADER_VALUE_START:if(b===nN)break;w("onHeaderValue"),d=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:b===bl&&(k("onHeaderValue",!0),A("onHeaderEnd"),d=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(b!==_l)return;d=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(b!==_l)return;A("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===bl?f|=Zr.PART_BOUNDARY:b===Ea?f|=Zr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&Zr.PART_BOUNDARY){if(u=0,b===_l){f&=~Zr.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),d=Ue.HEADER_FIELD_START;break}}else f&Zr.LAST_BOUNDARY&&b===Ea?(A("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);A("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")}};Ut(EA,"MultipartParser");aN=EA;Ut(vA,"_fileName");Ut(TA,"toFormData")});function GA(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 JA(){return OA||(OA=1,(function(t,e){(function(n,r){r(e)})(uN,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 ye(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ie(c):Z(c,l._storedError)}y(ye,"ReadableStreamReaderGenericInitialize");function De(c,l){let _=c._ownerReadableStream;return zt(_,l)}y(De,"ReadableStreamReaderGenericCancel");function ve(c){let l=c._ownerReadableStream;l._state==="readable"?Pe(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):Ce(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(ve,"ReadableStreamReaderGenericRelease");function Ye(c){return new TypeError("Cannot "+c+" a stream using a released reader")}y(Ye,"readerLockException");function ne(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_})}y(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Pe(c,l)}y(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ie(c){ne(c),H(c)}y(ie,"defaultReaderClosedPromiseInitializeAsResolved");function Pe(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(Pe,"defaultReaderClosedPromiseReject");function Ce(c,l){Z(c,l)}y(Ce,"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 Ae=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},tt=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 le(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}y(le,"assertDictionary");function ae(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}y(ae,"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(tt(c))}y(L,"integerPart");function P(c,l){let _=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ae(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!Ae(v)||v===0?0:v}y(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!ir(c))throw new TypeError(`${l} is not a ReadableStream.`)}y(N,"assertReadableStream");function U(c){return new ge(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 se(c){return c._reader._readRequests.length}y(se,"ReadableStreamGetNumReadRequests");function ce(c){let l=c._reader;return!(l===void 0||!pe(l))}y(ce,"ReadableStreamHasDefaultReader");let _e=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),ar(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ye(this,l),this._readRequests=new V}get closed(){return pe(this)?this._closedPromise:h(En("closed"))}cancel(l=void 0){return pe(this)?this._ownerReadableStream===void 0?h(Ye("cancel")):De(this,l):h(En("cancel"))}read(){if(!pe(this))return h(En("read"));if(this._ownerReadableStream===void 0)return h(Ye("read from"));let l,_,v=f((I,$)=>{l=I,_=$});return me(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(!pe(this))throw En("releaseLock");this._ownerReadableStream!==void 0&&Ie(this)}};y(_e,"ReadableStreamDefaultReader");let ge=_e;Object.defineProperties(ge.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(ge.prototype.cancel,"cancel"),i(ge.prototype.read,"read"),i(ge.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ge.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function pe(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof ge}y(pe,"IsReadableStreamDefaultReader");function me(c,l){let _=c._ownerReadableStream;_._disturbed=!0,_._state==="closed"?l._closeSteps():_._state==="errored"?l._errorSteps(_._storedError):_._readableStreamController[te](l)}y(me,"ReadableStreamDefaultReaderRead");function Ie(c){ve(c);let l=new TypeError("Reader was released");Ze(c,l)}y(Ie,"ReadableStreamDefaultReaderRelease");function Ze(c,l){let _=c._readRequests;c._readRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(Ze,"ReadableStreamDefaultReaderErrorReadRequests");function En(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}y(En,"defaultReaderBrandCheckException");let Ri=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),os=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 me(l,{_chunkSteps:y($=>{this._ongoingPromise=void 0,k(()=>_({value:$,done:!1}))},"_chunkSteps"),_closeSteps:y(()=>{this._ongoingPromise=void 0,this._isFinished=!0,ve(l),_({value:void 0,done:!0})},"_closeSteps"),_errorSteps:y($=>{this._ongoingPromise=void 0,this._isFinished=!0,ve(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=De(_,l);return ve(_),C(v,()=>({value:l,done:!0}))}return ve(_),p({value:l,done:!0})}};y(os,"ReadableStreamAsyncIteratorImpl");let Nt=os,Pr={next(){return nt(this)?this._asyncIteratorImpl.next():h(Be("next"))},return(c){return nt(this)?this._asyncIteratorImpl.return(c):h(Be("return"))}};Object.setPrototypeOf(Pr,Ri);function _t(c,l){let _=U(c),v=new Nt(_,l),I=Object.create(Pr);return I._asyncIteratorImpl=v,I}y(_t,"AcquireReadableStreamAsyncIterator");function nt(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof Nt}catch{return!1}}y(nt,"IsReadableStreamAsyncIterator");function Be(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}y(Be,"streamAsyncIteratorBrandCheckException");let F0=Number.isNaN||function(c){return c!==c};var np,rp,op;function ss(c){return c.slice()}y(ss,"CreateArrayFromList");function sp(c,l,_,v,I){new Uint8Array(c).set(new Uint8Array(_,v,I),l)}y(sp,"CopyDataBlockBytes");let tr=y(c=>(typeof c.transfer=="function"?tr=y(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?tr=y(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):tr=y(l=>l,"TransferArrayBuffer"),tr(c)),"TransferArrayBuffer"),Ir=y(c=>(typeof c.detached=="boolean"?Ir=y(l=>l.detached,"IsDetachedBuffer"):Ir=y(l=>l.byteLength===0,"IsDetachedBuffer"),Ir(c)),"IsDetachedBuffer");function ip(c,l,_){if(c.slice)return c.slice(l,_);let v=_-l,I=new ArrayBuffer(v);return sp(I,0,c,l,v),I}y(ip,"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 N0(c){let l={[Symbol.iterator]:()=>c.iterator},_=(async function*(){return yield*l})(),v=_.next;return{iterator:_,nextMethod:v,done:!1}}y(N0,"CreateAsyncFromSyncIterator");let ap=(op=(np=Symbol.asyncIterator)!==null&&np!==void 0?np:(rp=Symbol.for)===null||rp===void 0?void 0:rp.call(Symbol,"Symbol.asyncIterator"))!==null&&op!==void 0?op:"@@asyncIterator";function cp(c,l="sync",_){if(_===void 0)if(l==="async"){if(_=Di(c,ap),_===void 0){let $=Di(c,Symbol.iterator),W=cp(c,"sync",$);return N0(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(cp,"GetIterator");function M0(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(M0,"IteratorNext");function B0(c){return!!c.done}y(B0,"IteratorComplete");function U0(c){return c.value}y(U0,"IteratorValue");function j0(c){return!(typeof c!="number"||F0(c)||c<0)}y(j0,"IsNonNegativeNumber");function up(c){let l=ip(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}y(up,"CloneAsUint8Array");function mc(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}y(mc,"DequeueValue");function yc(c,l,_){if(!j0(_)||_===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:_}),c._queueTotalSize+=_}y(yc,"EnqueueValueWithSize");function L0(c){return c._queue.peek().value}y(L0,"PeekQueueValue");function nr(c){c._queue=new V,c._queueTotalSize=0}y(nr,"ResetQueue");function lp(c){return c===DataView}y(lp,"isDataViewConstructor");function $0(c){return lp(c.constructor)}y($0,"isDataView");function q0(c){return lp(c)?1:c.BYTES_PER_ELEMENT}y(q0,"arrayBufferViewElementSize");let H0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!_c(this))throw Sc("view");return this._view}respond(l){if(!_c(this))throw Sc("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(Ir(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Fi(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!_c(this))throw Sc("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(Ir(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ni(this._associatedReadableByteStreamController,l)}};y(H0,"ReadableStreamBYOBRequest");let ho=H0;Object.defineProperties(ho.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(ho.prototype.respond,"respond"),i(ho.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ho.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let z0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Fr(this))throw as("byobRequest");return kc(this)}get desiredSize(){if(!Fr(this))throw as("desiredSize");return Cp(this)}close(){if(!Fr(this))throw as("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`);is(this)}enqueue(l){if(!Fr(this))throw as("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`);Ii(this,l)}error(l=void 0){if(!Fr(this))throw as("error");Mt(this,l)}[z](l){dp(this),nr(this);let _=this._cancelAlgorithm(l);return Pi(this),_}[te](l){let _=this._controlledReadableByteStream;if(this._queueTotalSize>0){bp(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),Nr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};y(z0,"ReadableByteStreamController");let rr=z0;Object.defineProperties(rr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(rr.prototype.close,"close"),i(rr.prototype.enqueue,"enqueue"),i(rr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(rr.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Fr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof rr}y(Fr,"IsReadableByteStreamController");function _c(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof ho}y(_c,"IsReadableStreamBYOBRequest");function Nr(c){if(!V0(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,Nr(c)),null),_=>(Mt(c,_),null))}y(Nr,"ReadableByteStreamControllerCallPullIfNeeded");function dp(c){Cc(c),c._pendingPullIntos=new V}y(dp,"ReadableByteStreamControllerClearPendingPullIntos");function bc(c,l){let _=!1;c._state==="closed"&&(_=!0);let v=fp(l);l.readerType==="default"?K(c,v,_):tb(c,v,_)}y(bc,"ReadableByteStreamControllerCommitPullIntoDescriptor");function fp(c){let l=c.bytesFilled,_=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/_)}y(fp,"ReadableByteStreamControllerConvertPullIntoDescriptor");function Oi(c,l,_,v){c._queue.push({buffer:l,byteOffset:_,byteLength:v}),c._queueTotalSize+=v}y(Oi,"ReadableByteStreamControllerEnqueueChunkToQueue");function pp(c,l,_,v){let I;try{I=ip(l,_,_+v)}catch($){throw Mt(c,$),$}Oi(c,I,0,v)}y(pp,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function hp(c,l){l.bytesFilled>0&&pp(c,l.buffer,l.byteOffset,l.bytesFilled),go(c)}y(hp,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function gp(c,l){let _=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+_,I=_,$=!1,W=v%l.elementSize,oe=v-W;oe>=l.minimumFill&&(I=oe-l.bytesFilled,$=!0);let ue=c._queue;for(;I>0;){let he=ue.peek(),we=Math.min(I,he.byteLength),ke=l.byteOffset+l.bytesFilled;sp(l.buffer,ke,he.buffer,he.byteOffset,we),he.byteLength===we?ue.shift():(he.byteOffset+=we,he.byteLength-=we),c._queueTotalSize-=we,mp(c,we,l),I-=we}return $}y(gp,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function mp(c,l,_){_.bytesFilled+=l}y(mp,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function yp(c){c._queueTotalSize===0&&c._closeRequested?(Pi(c),hs(c._controlledReadableByteStream)):Nr(c)}y(yp,"ReadableByteStreamControllerHandleQueueDrain");function Cc(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}y(Cc,"ReadableByteStreamControllerInvalidateBYOBRequest");function wc(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();gp(c,l)&&(go(c),bc(c._controlledReadableByteStream,l))}}y(wc,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function W0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let _=l._readRequests.shift();bp(c,_)}}y(W0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function G0(c,l,_,v){let I=c._controlledReadableByteStream,$=l.constructor,W=q0($),{byteOffset:oe,byteLength:ue}=l,he=_*W,we;try{we=tr(l.buffer)}catch(Me){v._errorSteps(Me);return}let ke={buffer:we,bufferByteLength:we.byteLength,byteOffset:oe,byteLength:ue,bytesFilled:0,minimumFill:he,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(ke),Sp(I,v);return}if(I._state==="closed"){let Me=new $(ke.buffer,ke.byteOffset,0);v._closeSteps(Me);return}if(c._queueTotalSize>0){if(gp(c,ke)){let Me=fp(ke);yp(c),v._chunkSteps(Me);return}if(c._closeRequested){let Me=new TypeError("Insufficient bytes to fill elements in the given buffer");Mt(c,Me),v._errorSteps(Me);return}}c._pendingPullIntos.push(ke),Sp(I,v),Nr(c)}y(G0,"ReadableByteStreamControllerPullInto");function J0(c,l){l.readerType==="none"&&go(c);let _=c._controlledReadableByteStream;if(Ac(_))for(;Ap(_)>0;){let v=go(c);bc(_,v)}}y(J0,"ReadableByteStreamControllerRespondInClosedState");function K0(c,l,_){if(mp(c,l,_),_.readerType==="none"){hp(c,_),wc(c);return}if(_.bytesFilled<_.minimumFill)return;go(c);let v=_.bytesFilled%_.elementSize;if(v>0){let I=_.byteOffset+_.bytesFilled;pp(c,_.buffer,I-v,v)}_.bytesFilled-=v,bc(c._controlledReadableByteStream,_),wc(c)}y(K0,"ReadableByteStreamControllerRespondInReadableState");function _p(c,l){let _=c._pendingPullIntos.peek();Cc(c),c._controlledReadableByteStream._state==="closed"?J0(c,_):K0(c,l,_),Nr(c)}y(_p,"ReadableByteStreamControllerRespondInternal");function go(c){return c._pendingPullIntos.shift()}y(go,"ReadableByteStreamControllerShiftPendingPullInto");function V0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ce(l)&&se(l)>0||Ac(l)&&Ap(l)>0||Cp(c)>0)}y(V0,"ReadableByteStreamControllerShouldCallPull");function Pi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Pi,"ReadableByteStreamControllerClearAlgorithms");function is(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 Mt(c,v),v}}Pi(c),hs(l)}}y(is,"ReadableByteStreamControllerClose");function Ii(c,l){let _=c._controlledReadableByteStream;if(c._closeRequested||_._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Ir(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=tr(v);if(c._pendingPullIntos.length>0){let oe=c._pendingPullIntos.peek();if(Ir(oe.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Cc(c),oe.buffer=tr(oe.buffer),oe.readerType==="none"&&hp(c,oe)}if(ce(_))if(W0(c),se(_)===0)Oi(c,W,I,$);else{c._pendingPullIntos.length>0&&go(c);let oe=new Uint8Array(W,I,$);K(_,oe,!1)}else Ac(_)?(Oi(c,W,I,$),wc(c)):Oi(c,W,I,$);Nr(c)}y(Ii,"ReadableByteStreamControllerEnqueue");function Mt(c,l){let _=c._controlledReadableByteStream;_._state==="readable"&&(dp(c),nr(c),Pi(c),Jp(_,l))}y(Mt,"ReadableByteStreamControllerError");function bp(c,l){let _=c._queue.shift();c._queueTotalSize-=_.byteLength,yp(c);let v=new Uint8Array(_.buffer,_.byteOffset,_.byteLength);l._chunkSteps(v)}y(bp,"ReadableByteStreamControllerFillReadRequestFromQueue");function kc(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(ho.prototype);X0(v,c,_),c._byobRequest=v}return c._byobRequest}y(kc,"ReadableByteStreamControllerGetBYOBRequest");function Cp(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Cp,"ReadableByteStreamControllerGetDesiredSize");function Fi(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=tr(_.buffer),_p(c,l)}y(Fi,"ReadableByteStreamControllerRespond");function Ni(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=tr(l.buffer),_p(c,v)}y(Ni,"ReadableByteStreamControllerRespondWithNewView");function wp(c,l,_,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,nr(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 oe=_();b(p(oe),()=>(l._started=!0,Nr(l),null),ue=>(Mt(l,ue),null))}y(wp,"SetUpReadableByteStreamController");function Y0(c,l,_){let v=Object.create(rr.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(ue=>l.cancel(ue),"cancelAlgorithm"):W=y(()=>p(void 0),"cancelAlgorithm");let oe=l.autoAllocateChunkSize;if(oe===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");wp(c,v,I,$,W,_,oe)}y(Y0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function X0(c,l,_){c._associatedReadableByteStreamController=l,c._view=_}y(X0,"SetUpReadableStreamBYOBRequest");function Sc(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}y(Sc,"byobRequestBrandCheckException");function as(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}y(as,"byteStreamControllerBrandCheckException");function Q0(c,l){le(c,l);let _=c?.mode;return{mode:_===void 0?void 0:Z0(_,`${l} has member 'mode' that`)}}y(Q0,"convertReaderOptions");function Z0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}y(Z0,"convertReadableStreamReaderMode");function eb(c,l){var _;le(c,l);let v=(_=c?.min)!==null&&_!==void 0?_:1;return{min:P(v,`${l} has member 'min' that`)}}y(eb,"convertByobReadOptions");function kp(c){return new Mr(c)}y(kp,"AcquireReadableStreamBYOBReader");function Sp(c,l){c._reader._readIntoRequests.push(l)}y(Sp,"ReadableStreamAddReadIntoRequest");function tb(c,l,_){let v=c._reader._readIntoRequests.shift();_?v._closeSteps(l):v._chunkSteps(l)}y(tb,"ReadableStreamFulfillReadIntoRequest");function Ap(c){return c._reader._readIntoRequests.length}y(Ap,"ReadableStreamGetNumReadIntoRequests");function Ac(c){let l=c._reader;return!(l===void 0||!Br(l))}y(Ac,"ReadableStreamHasBYOBReader");let nb=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),ar(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Fr(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");ye(this,l),this._readIntoRequests=new V}get closed(){return Br(this)?this._closedPromise:h(Mi("closed"))}cancel(l=void 0){return Br(this)?this._ownerReadableStream===void 0?h(Ye("cancel")):De(this,l):h(Mi("cancel"))}read(l,_={}){if(!Br(this))return h(Mi("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(Ir(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=eb(_,"options")}catch(ue){return h(ue)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if($0(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(Ye("read from"));let $,W,oe=f((ue,he)=>{$=ue,W=he});return Ep(this,l,I,{_chunkSteps:y(ue=>$({value:ue,done:!1}),"_chunkSteps"),_closeSteps:y(ue=>$({value:ue,done:!0}),"_closeSteps"),_errorSteps:y(ue=>W(ue),"_errorSteps")}),oe}releaseLock(){if(!Br(this))throw Mi("releaseLock");this._ownerReadableStream!==void 0&&rb(this)}};y(nb,"ReadableStreamBYOBReader");let Mr=nb;Object.defineProperties(Mr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(Mr.prototype.cancel,"cancel"),i(Mr.prototype.read,"read"),i(Mr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Mr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function Br(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof Mr}y(Br,"IsReadableStreamBYOBReader");function Ep(c,l,_,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):G0(I._readableStreamController,l,_,v)}y(Ep,"ReadableStreamBYOBReaderRead");function rb(c){ve(c);let l=new TypeError("Reader was released");vp(c,l)}y(rb,"ReadableStreamBYOBReaderRelease");function vp(c,l){let _=c._readIntoRequests;c._readIntoRequests=new V,_.forEach(v=>{v._errorSteps(l)})}y(vp,"ReadableStreamBYOBReaderErrorReadIntoRequests");function Mi(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}y(Mi,"byobReaderBrandCheckException");function cs(c,l){let{highWaterMark:_}=c;if(_===void 0)return l;if(F0(_)||_<0)throw new RangeError("Invalid highWaterMark");return _}y(cs,"ExtractHighWaterMark");function Bi(c){let{size:l}=c;return l||(()=>1)}y(Bi,"ExtractSizeAlgorithm");function Ui(c,l){le(c,l);let _=c?.highWaterMark,v=c?.size;return{highWaterMark:_===void 0?void 0:D(_),size:v===void 0?void 0:ob(v,`${l} has member 'size' that`)}}y(Ui,"convertQueuingStrategy");function ob(c,l){return ae(c,l),_=>D(c(_))}y(ob,"convertQueuingStrategySize");function sb(c,l){le(c,l);let _=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:_===void 0?void 0:ib(_,c,`${l} has member 'abort' that`),close:v===void 0?void 0:ab(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:cb(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:ub(W,c,`${l} has member 'write' that`),type:$}}y(sb,"convertUnderlyingSink");function ib(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(ib,"convertUnderlyingSinkAbortCallback");function ab(c,l,_){return ae(c,_),()=>x(c,l,[])}y(ab,"convertUnderlyingSinkCloseCallback");function cb(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(cb,"convertUnderlyingSinkStartCallback");function ub(c,l,_){return ae(c,_),(v,I)=>x(c,l,[v,I])}y(ub,"convertUnderlyingSinkWriteCallback");function Tp(c,l){if(!mo(c))throw new TypeError(`${l} is not a WritableStream.`)}y(Tp,"assertWritableStream");function lb(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}y(lb,"isAbortSignal");let $D=typeof AbortController=="function";function db(){if($D)return new AbortController}y(db,"createAbortController");let fb=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=Ui(_,"Second parameter"),I=sb(l,"First parameter");if(Rp(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=Bi(v),W=cs(v,1);Rb(this,I,W,$)}get locked(){if(!mo(this))throw Hi("locked");return yo(this)}abort(l=void 0){return mo(this)?yo(this)?h(new TypeError("Cannot abort a stream that already has a writer")):ji(this,l):h(Hi("abort"))}close(){return mo(this)?yo(this)?h(new TypeError("Cannot close a stream that already has a writer")):sn(this)?h(new TypeError("Cannot close an already-closing stream")):Dp(this):h(Hi("close"))}getWriter(){if(!mo(this))throw Hi("getWriter");return xp(this)}};y(fb,"WritableStream");let Ur=fb;Object.defineProperties(Ur.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Ur.prototype.abort,"abort"),i(Ur.prototype.close,"close"),i(Ur.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ur.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function xp(c){return new or(c)}y(xp,"AcquireWritableStreamDefaultWriter");function pb(c,l,_,v,I=1,$=()=>1){let W=Object.create(Ur.prototype);Rp(W);let oe=Object.create(us.prototype);return Np(W,oe,c,l,_,v,I,$),W}y(pb,"CreateWritableStream");function Rp(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(Rp,"InitializeWritableStream");function mo(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Ur}y(mo,"IsWritableStream");function yo(c){return c._writer!==void 0}y(yo,"IsWritableStreamLocked");function ji(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,oe)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:oe,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||vc(c,l),$}y(ji,"WritableStreamAbort");function Dp(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"&&Fc(v),Db(c._writableStreamController),_}y(Dp,"WritableStreamClose");function hb(c){return f((l,_)=>{let v={_resolve:l,_reject:_};c._writeRequests.push(v)})}y(hb,"WritableStreamAddWriteRequest");function Ec(c,l){if(c._state==="writable"){vc(c,l);return}Tc(c)}y(Ec,"WritableStreamDealWithRejection");function vc(c,l){let _=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&Pp(v,l),!bb(c)&&_._started&&Tc(c)}y(vc,"WritableStreamStartErroring");function Tc(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){Li(c);return}let _=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,_._wasAlreadyErroring){_._reject(l),Li(c);return}let v=c._writableStreamController[j](_._reason);b(v,()=>(_._resolve(),Li(c),null),I=>(_._reject(I),Li(c),null))}y(Tc,"WritableStreamFinishErroring");function gb(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}y(gb,"WritableStreamFinishInFlightWrite");function mb(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,Ec(c,l)}y(mb,"WritableStreamFinishInFlightWriteWithError");function yb(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&&jp(l)}y(yb,"WritableStreamFinishInFlightClose");function _b(c,l){c._inFlightCloseRequest._reject(l),c._inFlightCloseRequest=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._reject(l),c._pendingAbortRequest=void 0),Ec(c,l)}y(_b,"WritableStreamFinishInFlightCloseWithError");function sn(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}y(sn,"WritableStreamCloseQueuedOrInFlight");function bb(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}y(bb,"WritableStreamHasOperationMarkedInFlight");function Cb(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}y(Cb,"WritableStreamMarkCloseRequestInFlight");function wb(c){c._inFlightWriteRequest=c._writeRequests.shift()}y(wb,"WritableStreamMarkFirstWriteRequestInFlight");function Li(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&Pc(l,c._storedError)}y(Li,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function xc(c,l){let _=c._writer;_!==void 0&&l!==c._backpressure&&(l?Bb(_):Fc(_)),c._backpressure=l}y(xc,"WritableStreamUpdateBackpressure");let kb=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Tp(l,"First parameter"),yo(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")!sn(l)&&l._backpressure?Wi(this):Lp(this),zi(this);else if(_==="erroring")Ic(this,l._storedError),zi(this);else if(_==="closed")Lp(this),Nb(this);else{let v=l._storedError;Ic(this,v),Up(this,v)}}get closed(){return jr(this)?this._closedPromise:h(Lr("closed"))}get desiredSize(){if(!jr(this))throw Lr("desiredSize");if(this._ownerWritableStream===void 0)throw ds("desiredSize");return vb(this)}get ready(){return jr(this)?this._readyPromise:h(Lr("ready"))}abort(l=void 0){return jr(this)?this._ownerWritableStream===void 0?h(ds("abort")):Sb(this,l):h(Lr("abort"))}close(){if(!jr(this))return h(Lr("close"));let l=this._ownerWritableStream;return l===void 0?h(ds("close")):sn(l)?h(new TypeError("Cannot close an already-closing stream")):Op(this)}releaseLock(){if(!jr(this))throw Lr("releaseLock");this._ownerWritableStream!==void 0&&Ip(this)}write(l=void 0){return jr(this)?this._ownerWritableStream===void 0?h(ds("write to")):Fp(this,l):h(Lr("write"))}};y(kb,"WritableStreamDefaultWriter");let or=kb;Object.defineProperties(or.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(or.prototype.abort,"abort"),i(or.prototype.close,"close"),i(or.prototype.releaseLock,"releaseLock"),i(or.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(or.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function jr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof or}y(jr,"IsWritableStreamDefaultWriter");function Sb(c,l){let _=c._ownerWritableStream;return ji(_,l)}y(Sb,"WritableStreamDefaultWriterAbort");function Op(c){let l=c._ownerWritableStream;return Dp(l)}y(Op,"WritableStreamDefaultWriterClose");function Ab(c){let l=c._ownerWritableStream,_=l._state;return sn(l)||_==="closed"?p(void 0):_==="errored"?h(l._storedError):Op(c)}y(Ab,"WritableStreamDefaultWriterCloseWithErrorPropagation");function Eb(c,l){c._closedPromiseState==="pending"?Pc(c,l):Mb(c,l)}y(Eb,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function Pp(c,l){c._readyPromiseState==="pending"?$p(c,l):Ub(c,l)}y(Pp,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function vb(c){let l=c._ownerWritableStream,_=l._state;return _==="errored"||_==="erroring"?null:_==="closed"?0:Mp(l._writableStreamController)}y(vb,"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");Pp(c,_),Eb(c,_),l._writer=void 0,c._ownerWritableStream=void 0}y(Ip,"WritableStreamDefaultWriterRelease");function Fp(c,l){let _=c._ownerWritableStream,v=_._writableStreamController,I=Ob(v,l);if(_!==c._ownerWritableStream)return h(ds("write to"));let $=_._state;if($==="errored")return h(_._storedError);if(sn(_)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(_._storedError);let W=hb(_);return Pb(v,l,I),W}y(Fp,"WritableStreamDefaultWriterWrite");let Tb={},xb=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!Rc(this))throw Oc("abortReason");return this._abortReason}get signal(){if(!Rc(this))throw Oc("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!Rc(this))throw Oc("error");this._controlledWritableStream._state==="writable"&&Bp(this,l)}[j](l){let _=this._abortAlgorithm(l);return $i(this),_}[ee](){nr(this)}};y(xb,"WritableStreamDefaultController");let us=xb;Object.defineProperties(us.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(us.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function Rc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof us}y(Rc,"IsWritableStreamDefaultController");function Np(c,l,_,v,I,$,W,oe){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,nr(l),l._abortReason=void 0,l._abortController=db(),l._started=!1,l._strategySizeAlgorithm=oe,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let ue=Dc(l);xc(c,ue);let he=_(),we=p(he);b(we,()=>(l._started=!0,qi(l),null),ke=>(l._started=!0,Ec(c,ke),null))}y(Np,"SetUpWritableStreamDefaultController");function Rb(c,l,_,v){let I=Object.create(us.prototype),$,W,oe,ue;l.start!==void 0?$=y(()=>l.start(I),"startAlgorithm"):$=y(()=>{},"startAlgorithm"),l.write!==void 0?W=y(he=>l.write(he,I),"writeAlgorithm"):W=y(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?oe=y(()=>l.close(),"closeAlgorithm"):oe=y(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?ue=y(he=>l.abort(he),"abortAlgorithm"):ue=y(()=>p(void 0),"abortAlgorithm"),Np(c,I,$,W,oe,ue,_,v)}y(Rb,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function $i(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y($i,"WritableStreamDefaultControllerClearAlgorithms");function Db(c){yc(c,Tb,0),qi(c)}y(Db,"WritableStreamDefaultControllerClose");function Ob(c,l){try{return c._strategySizeAlgorithm(l)}catch(_){return ls(c,_),1}}y(Ob,"WritableStreamDefaultControllerGetChunkSize");function Mp(c){return c._strategyHWM-c._queueTotalSize}y(Mp,"WritableStreamDefaultControllerGetDesiredSize");function Pb(c,l,_){try{yc(c,l,_)}catch(I){ls(c,I);return}let v=c._controlledWritableStream;if(!sn(v)&&v._state==="writable"){let I=Dc(c);xc(v,I)}qi(c)}y(Pb,"WritableStreamDefaultControllerWrite");function qi(c){let l=c._controlledWritableStream;if(!c._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){Tc(l);return}if(c._queue.length===0)return;let _=L0(c);_===Tb?Ib(c):Fb(c,_)}y(qi,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function ls(c,l){c._controlledWritableStream._state==="writable"&&Bp(c,l)}y(ls,"WritableStreamDefaultControllerErrorIfNeeded");function Ib(c){let l=c._controlledWritableStream;Cb(l),mc(c);let _=c._closeAlgorithm();$i(c),b(_,()=>(yb(l),null),v=>(_b(l,v),null))}y(Ib,"WritableStreamDefaultControllerProcessClose");function Fb(c,l){let _=c._controlledWritableStream;wb(_);let v=c._writeAlgorithm(l);b(v,()=>{gb(_);let I=_._state;if(mc(c),!sn(_)&&I==="writable"){let $=Dc(c);xc(_,$)}return qi(c),null},I=>(_._state==="writable"&&$i(c),mb(_,I),null))}y(Fb,"WritableStreamDefaultControllerProcessWrite");function Dc(c){return Mp(c)<=0}y(Dc,"WritableStreamDefaultControllerGetBackpressure");function Bp(c,l){let _=c._controlledWritableStream;$i(c),vc(_,l)}y(Bp,"WritableStreamDefaultControllerError");function Hi(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}y(Hi,"streamBrandCheckException$2");function Oc(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}y(Oc,"defaultControllerBrandCheckException$2");function Lr(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}y(Lr,"defaultWriterBrandCheckException");function ds(c){return new TypeError("Cannot "+c+" a stream using a released writer")}y(ds,"defaultWriterLockException");function zi(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_,c._closedPromiseState="pending"})}y(zi,"defaultWriterClosedPromiseInitialize");function Up(c,l){zi(c),Pc(c,l)}y(Up,"defaultWriterClosedPromiseInitializeAsRejected");function Nb(c){zi(c),jp(c)}y(Nb,"defaultWriterClosedPromiseInitializeAsResolved");function Pc(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(Pc,"defaultWriterClosedPromiseReject");function Mb(c,l){Up(c,l)}y(Mb,"defaultWriterClosedPromiseResetToRejected");function jp(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(jp,"defaultWriterClosedPromiseResolve");function Wi(c){c._readyPromise=f((l,_)=>{c._readyPromise_resolve=l,c._readyPromise_reject=_}),c._readyPromiseState="pending"}y(Wi,"defaultWriterReadyPromiseInitialize");function Ic(c,l){Wi(c),$p(c,l)}y(Ic,"defaultWriterReadyPromiseInitializeAsRejected");function Lp(c){Wi(c),Fc(c)}y(Lp,"defaultWriterReadyPromiseInitializeAsResolved");function $p(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($p,"defaultWriterReadyPromiseReject");function Bb(c){Wi(c)}y(Bb,"defaultWriterReadyPromiseReset");function Ub(c,l){Ic(c,l)}y(Ub,"defaultWriterReadyPromiseResetToRejected");function Fc(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(Fc,"defaultWriterReadyPromiseResolve");function jb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof zg<"u")return zg}y(jb,"getGlobals");let qD=jb();function Lb(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}y(Lb,"isDOMExceptionConstructor");function $b(){let c=qD?.DOMException;return Lb(c)?c:void 0}y($b,"getFromGlobal");function qb(){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(qb,"createPolyfill");let HD=$b()||qb();function qp(c,l,_,v,I,$){let W=U(c),oe=xp(l);c._disturbed=!0;let ue=!1,he=p(void 0);return f((we,ke)=>{let Me;if($!==void 0){if(Me=y(()=>{let de=$.reason!==void 0?$.reason:new HD("Aborted","AbortError"),Re=[];v||Re.push(()=>l._state==="writable"?ji(l,de):p(void 0)),I||Re.push(()=>c._state==="readable"?zt(c,de):p(void 0)),bt(()=>Promise.all(Re.map(Ne=>Ne())),!0,de)},"abortAlgorithm"),$.aborted){Me();return}$.addEventListener("abort",Me)}function Et(){return f((de,Re)=>{function Ne(Ct){Ct?de():g(cr(),Ne,Re)}y(Ne,"next"),Ne(!1)})}y(Et,"pipeLoop");function cr(){return ue?p(!0):g(oe._readyPromise,()=>f((de,Re)=>{me(W,{_chunkSteps:y(Ne=>{he=g(Fp(oe,Ne),void 0,r),de(!1)},"_chunkSteps"),_closeSteps:y(()=>de(!0),"_closeSteps"),_errorSteps:Re})}))}if(y(cr,"pipeStep"),Wt(c,W._closedPromise,de=>(v?vt(!0,de):bt(()=>ji(l,de),!0,de),null)),Wt(l,oe._closedPromise,de=>(I?vt(!0,de):bt(()=>zt(c,de),!0,de),null)),rt(c,W._closedPromise,()=>(_?vt():bt(()=>Ab(oe)),null)),sn(l)||l._state==="closed"){let de=new TypeError("the destination writable stream closed before all data could be piped to it");I?vt(!0,de):bt(()=>zt(c,de),!0,de)}A(Et());function an(){let de=he;return g(he,()=>de!==he?an():void 0)}y(an,"waitForWritesToFinish");function Wt(de,Re,Ne){de._state==="errored"?Ne(de._storedError):w(Re,Ne)}y(Wt,"isOrBecomesErrored");function rt(de,Re,Ne){de._state==="closed"?Ne():m(Re,Ne)}y(rt,"isOrBecomesClosed");function bt(de,Re,Ne){if(ue)return;ue=!0,l._state==="writable"&&!sn(l)?m(an(),Ct):Ct();function Ct(){return b(de(),()=>ur(Re,Ne),zr=>ur(!0,zr)),null}y(Ct,"doTheRest")}y(bt,"shutdownWithAction");function vt(de,Re){ue||(ue=!0,l._state==="writable"&&!sn(l)?m(an(),()=>ur(de,Re)):ur(de,Re))}y(vt,"shutdown");function ur(de,Re){return Ip(oe),ve(W),$!==void 0&&$.removeEventListener("abort",Me),de?ke(Re):we(void 0),null}y(ur,"finalize")})}y(qp,"ReadableStreamPipeTo");let Hb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Gi(this))throw Ki("desiredSize");return Nc(this)}close(){if(!Gi(this))throw Ki("close");if(!bo(this))throw new TypeError("The stream is not in a state that permits close");$r(this)}enqueue(l=void 0){if(!Gi(this))throw Ki("enqueue");if(!bo(this))throw new TypeError("The stream is not in a state that permits enqueue");return _o(this,l)}error(l=void 0){if(!Gi(this))throw Ki("error");Ht(this,l)}[z](l){nr(this);let _=this._cancelAlgorithm(l);return Ji(this),_}[te](l){let _=this._controlledReadableStream;if(this._queue.length>0){let v=mc(this);this._closeRequested&&this._queue.length===0?(Ji(this),hs(_)):fs(this),l._chunkSteps(v)}else B(_,l),fs(this)}[Q](){}};y(Hb,"ReadableStreamDefaultController");let sr=Hb;Object.defineProperties(sr.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(sr.prototype.close,"close"),i(sr.prototype.enqueue,"enqueue"),i(sr.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(sr.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function Gi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof sr}y(Gi,"IsReadableStreamDefaultController");function fs(c){if(!Hp(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,fs(c)),null),_=>(Ht(c,_),null))}y(fs,"ReadableStreamDefaultControllerCallPullIfNeeded");function Hp(c){let l=c._controlledReadableStream;return!bo(c)||!c._started?!1:!!(ar(l)&&se(l)>0||Nc(c)>0)}y(Hp,"ReadableStreamDefaultControllerShouldCallPull");function Ji(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}y(Ji,"ReadableStreamDefaultControllerClearAlgorithms");function $r(c){if(!bo(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(Ji(c),hs(l))}y($r,"ReadableStreamDefaultControllerClose");function _o(c,l){if(!bo(c))return;let _=c._controlledReadableStream;if(ar(_)&&se(_)>0)K(_,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Ht(c,I),I}try{yc(c,l,v)}catch(I){throw Ht(c,I),I}}fs(c)}y(_o,"ReadableStreamDefaultControllerEnqueue");function Ht(c,l){let _=c._controlledReadableStream;_._state==="readable"&&(nr(c),Ji(c),Jp(_,l))}y(Ht,"ReadableStreamDefaultControllerError");function Nc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}y(Nc,"ReadableStreamDefaultControllerGetDesiredSize");function zb(c){return!Hp(c)}y(zb,"ReadableStreamDefaultControllerHasBackpressure");function bo(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}y(bo,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function zp(c,l,_,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,nr(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 oe=_();b(p(oe),()=>(l._started=!0,fs(l),null),ue=>(Ht(l,ue),null))}y(zp,"SetUpReadableStreamDefaultController");function Wb(c,l,_,v){let I=Object.create(sr.prototype),$,W,oe;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?oe=y(ue=>l.cancel(ue),"cancelAlgorithm"):oe=y(()=>p(void 0),"cancelAlgorithm"),zp(c,I,$,W,oe,_,v)}y(Wb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function Ki(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}y(Ki,"defaultControllerBrandCheckException$1");function Gb(c,l){return Fr(c._readableStreamController)?Kb(c):Jb(c)}y(Gb,"ReadableStreamTee");function Jb(c,l){let _=U(c),v=!1,I=!1,$=!1,W=!1,oe,ue,he,we,ke,Me=f(rt=>{ke=rt});function Et(){return v?(I=!0,p(void 0)):(v=!0,me(_,{_chunkSteps:y(rt=>{k(()=>{I=!1;let bt=rt,vt=rt;$||_o(he._readableStreamController,bt),W||_o(we._readableStreamController,vt),v=!1,I&&Et()})},"_chunkSteps"),_closeSteps:y(()=>{v=!1,$||$r(he._readableStreamController),W||$r(we._readableStreamController),(!$||!W)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{v=!1},"_errorSteps")}),p(void 0))}y(Et,"pullAlgorithm");function cr(rt){if($=!0,oe=rt,W){let bt=ss([oe,ue]),vt=zt(c,bt);ke(vt)}return Me}y(cr,"cancel1Algorithm");function an(rt){if(W=!0,ue=rt,$){let bt=ss([oe,ue]),vt=zt(c,bt);ke(vt)}return Me}y(an,"cancel2Algorithm");function Wt(){}return y(Wt,"startAlgorithm"),he=ps(Wt,Et,cr),we=ps(Wt,Et,an),w(_._closedPromise,rt=>(Ht(he._readableStreamController,rt),Ht(we._readableStreamController,rt),(!$||!W)&&ke(void 0),null)),[he,we]}y(Jb,"ReadableStreamDefaultTee");function Kb(c){let l=U(c),_=!1,v=!1,I=!1,$=!1,W=!1,oe,ue,he,we,ke,Me=f(de=>{ke=de});function Et(de){w(de._closedPromise,Re=>(de!==l||(Mt(he._readableStreamController,Re),Mt(we._readableStreamController,Re),(!$||!W)&&ke(void 0)),null))}y(Et,"forwardReaderError");function cr(){Br(l)&&(ve(l),l=U(c),Et(l)),me(l,{_chunkSteps:y(de=>{k(()=>{v=!1,I=!1;let Re=de,Ne=de;if(!$&&!W)try{Ne=up(de)}catch(Ct){Mt(he._readableStreamController,Ct),Mt(we._readableStreamController,Ct),ke(zt(c,Ct));return}$||Ii(he._readableStreamController,Re),W||Ii(we._readableStreamController,Ne),_=!1,v?Wt():I&&rt()})},"_chunkSteps"),_closeSteps:y(()=>{_=!1,$||is(he._readableStreamController),W||is(we._readableStreamController),he._readableStreamController._pendingPullIntos.length>0&&Fi(he._readableStreamController,0),we._readableStreamController._pendingPullIntos.length>0&&Fi(we._readableStreamController,0),(!$||!W)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(cr,"pullWithDefaultReader");function an(de,Re){pe(l)&&(ve(l),l=kp(c),Et(l));let Ne=Re?we:he,Ct=Re?he:we;Ep(l,de,1,{_chunkSteps:y(zr=>{k(()=>{v=!1,I=!1;let gs=Re?W:$;if(Re?$:W)gs||Ni(Ne._readableStreamController,zr);else{let ms;try{ms=up(zr)}catch(oh){Mt(Ne._readableStreamController,oh),Mt(Ct._readableStreamController,oh),ke(zt(c,oh));return}gs||Ni(Ne._readableStreamController,zr),Ii(Ct._readableStreamController,ms)}_=!1,v?Wt():I&&rt()})},"_chunkSteps"),_closeSteps:y(zr=>{_=!1;let gs=Re?W:$,ms=Re?$:W;gs||is(Ne._readableStreamController),ms||is(Ct._readableStreamController),zr!==void 0&&(gs||Ni(Ne._readableStreamController,zr),!ms&&Ct._readableStreamController._pendingPullIntos.length>0&&Fi(Ct._readableStreamController,0)),(!gs||!ms)&&ke(void 0)},"_closeSteps"),_errorSteps:y(()=>{_=!1},"_errorSteps")})}y(an,"pullWithBYOBReader");function Wt(){if(_)return v=!0,p(void 0);_=!0;let de=kc(he._readableStreamController);return de===null?cr():an(de._view,!1),p(void 0)}y(Wt,"pull1Algorithm");function rt(){if(_)return I=!0,p(void 0);_=!0;let de=kc(we._readableStreamController);return de===null?cr():an(de._view,!0),p(void 0)}y(rt,"pull2Algorithm");function bt(de){if($=!0,oe=de,W){let Re=ss([oe,ue]),Ne=zt(c,Re);ke(Ne)}return Me}y(bt,"cancel1Algorithm");function vt(de){if(W=!0,ue=de,$){let Re=ss([oe,ue]),Ne=zt(c,Re);ke(Ne)}return Me}y(vt,"cancel2Algorithm");function ur(){}return y(ur,"startAlgorithm"),he=Gp(ur,Wt,bt),we=Gp(ur,rt,vt),Et(l),[he,we]}y(Kb,"ReadableByteStreamTee");function Vb(c){return o(c)&&typeof c.getReader<"u"}y(Vb,"isReadableStreamLike");function Yb(c){return Vb(c)?Qb(c.getReader()):Xb(c)}y(Yb,"ReadableStreamFrom");function Xb(c){let l,_=cp(c,"async"),v=r;function I(){let W;try{W=M0(_)}catch(ue){return h(ue)}let oe=p(W);return C(oe,ue=>{if(!o(ue))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(B0(ue))$r(l._readableStreamController);else{let he=U0(ue);_o(l._readableStreamController,he)}})}y(I,"pullAlgorithm");function $(W){let oe=_.iterator,ue;try{ue=Di(oe,"return")}catch(ke){return h(ke)}if(ue===void 0)return p(void 0);let he;try{he=E(ue,oe,[W])}catch(ke){return h(ke)}let we=p(he);return C(we,ke=>{if(!o(ke))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return y($,"cancelAlgorithm"),l=ps(v,I,$,0),l}y(Xb,"ReadableStreamFromIterable");function Qb(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)$r(l._readableStreamController);else{let oe=W.value;_o(l._readableStreamController,oe)}})}y(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return y(I,"cancelAlgorithm"),l=ps(_,v,I,0),l}y(Qb,"ReadableStreamFromDefaultReader");function Zb(c,l){le(c,l);let _=c,v=_?.autoAllocateChunkSize,I=_?.cancel,$=_?.pull,W=_?.start,oe=_?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:eC(I,_,`${l} has member 'cancel' that`),pull:$===void 0?void 0:tC($,_,`${l} has member 'pull' that`),start:W===void 0?void 0:nC(W,_,`${l} has member 'start' that`),type:oe===void 0?void 0:rC(oe,`${l} has member 'type' that`)}}y(Zb,"convertUnderlyingDefaultOrByteSource");function eC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(eC,"convertUnderlyingSourceCancelCallback");function tC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(tC,"convertUnderlyingSourcePullCallback");function nC(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(nC,"convertUnderlyingSourceStartCallback");function rC(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}y(rC,"convertReadableStreamType");function oC(c,l){return le(c,l),{preventCancel:!!c?.preventCancel}}y(oC,"convertIteratorOptions");function Wp(c,l){le(c,l);let _=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&sC($,`${l} has member 'signal' that`),{preventAbort:!!_,preventCancel:!!v,preventClose:!!I,signal:$}}y(Wp,"convertPipeOptions");function sC(c,l){if(!lb(c))throw new TypeError(`${l} is not an AbortSignal.`)}y(sC,"assertAbortSignal");function iC(c,l){le(c,l);let _=c?.readable;M(_,"readable","ReadableWritablePair"),N(_,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),Tp(v,`${l} has member 'writable' that`),{readable:_,writable:v}}y(iC,"convertReadableWritablePair");let aC=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=Ui(_,"Second parameter"),I=Zb(l,"First parameter");if(Mc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=cs(v,0);Y0(this,I,$)}else{let $=Bi(v),W=cs(v,1);Wb(this,I,W,$)}}get locked(){if(!ir(this))throw qr("locked");return ar(this)}cancel(l=void 0){return ir(this)?ar(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):zt(this,l):h(qr("cancel"))}getReader(l=void 0){if(!ir(this))throw qr("getReader");return Q0(l,"First parameter").mode===void 0?U(this):kp(this)}pipeThrough(l,_={}){if(!ir(this))throw qr("pipeThrough");R(l,1,"pipeThrough");let v=iC(l,"First parameter"),I=Wp(_,"Second parameter");if(ar(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(yo(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=qp(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return A($),v.readable}pipeTo(l,_={}){if(!ir(this))return h(qr("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!mo(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=Wp(_,"Second parameter")}catch(I){return h(I)}return ar(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):yo(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):qp(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!ir(this))throw qr("tee");let l=Gb(this);return ss(l)}values(l=void 0){if(!ir(this))throw qr("values");let _=oC(l,"First parameter");return _t(this,_.preventCancel)}[ap](l){return this.values(l)}static from(l){return Yb(l)}};y(aC,"ReadableStream");let mt=aC;Object.defineProperties(mt,{from:{enumerable:!0}}),Object.defineProperties(mt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(mt.from,"from"),i(mt.prototype.cancel,"cancel"),i(mt.prototype.getReader,"getReader"),i(mt.prototype.pipeThrough,"pipeThrough"),i(mt.prototype.pipeTo,"pipeTo"),i(mt.prototype.tee,"tee"),i(mt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(mt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(mt.prototype,ap,{value:mt.prototype.values,writable:!0,configurable:!0});function ps(c,l,_,v=1,I=()=>1){let $=Object.create(mt.prototype);Mc($);let W=Object.create(sr.prototype);return zp($,W,c,l,_,v,I),$}y(ps,"CreateReadableStream");function Gp(c,l,_){let v=Object.create(mt.prototype);Mc(v);let I=Object.create(rr.prototype);return wp(v,I,c,l,_,0,void 0),v}y(Gp,"CreateReadableByteStream");function Mc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}y(Mc,"InitializeReadableStream");function ir(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof mt}y(ir,"IsReadableStream");function ar(c){return c._reader!==void 0}y(ar,"IsReadableStreamLocked");function zt(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);hs(c);let _=c._reader;if(_!==void 0&&Br(_)){let I=_._readIntoRequests;_._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return C(v,r)}y(zt,"ReadableStreamCancel");function hs(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),pe(l))){let _=l._readRequests;l._readRequests=new V,_.forEach(v=>{v._closeSteps()})}}y(hs,"ReadableStreamClose");function Jp(c,l){c._state="errored",c._storedError=l;let _=c._reader;_!==void 0&&(Pe(_,l),pe(_)?Ze(_,l):vp(_,l))}y(Jp,"ReadableStreamError");function qr(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}y(qr,"streamBrandCheckException$1");function Kp(c,l){le(c,l);let _=c?.highWaterMark;return M(_,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(_)}}y(Kp,"convertQueuingStrategyInit");let cC=y(c=>c.byteLength,"byteLengthSizeFunction");i(cC,"size");let uC=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=Kp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Yp(this))throw Vp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Yp(this))throw Vp("size");return cC}};y(uC,"ByteLengthQueuingStrategy");let Bc=uC;Object.defineProperties(Bc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Bc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function Vp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}y(Vp,"byteLengthBrandCheckException");function Yp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof Bc}y(Yp,"IsByteLengthQueuingStrategy");let lC=y(()=>1,"countSizeFunction");i(lC,"size");let dC=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=Kp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Qp(this))throw Xp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Qp(this))throw Xp("size");return lC}};y(dC,"CountQueuingStrategy");let Uc=dC;Object.defineProperties(Uc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Uc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Xp(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}y(Xp,"countBrandCheckException");function Qp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof Uc}y(Qp,"IsCountQueuingStrategy");function fC(c,l){le(c,l);let _=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,oe=c?.writableType;return{cancel:_===void 0?void 0:mC(_,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:pC(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:hC($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:gC(W,c,`${l} has member 'transform' that`),writableType:oe}}y(fC,"convertTransformer");function pC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(pC,"convertTransformerFlushCallback");function hC(c,l,_){return ae(c,_),v=>E(c,l,[v])}y(hC,"convertTransformerStartCallback");function gC(c,l,_){return ae(c,_),(v,I)=>x(c,l,[v,I])}y(gC,"convertTransformerTransformCallback");function mC(c,l,_){return ae(c,_),v=>x(c,l,[v])}y(mC,"convertTransformerCancelCallback");let yC=class{constructor(l={},_={},v={}){l===void 0&&(l=null);let I=Ui(_,"Second parameter"),$=Ui(v,"Third parameter"),W=fC(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 oe=cs($,0),ue=Bi($),he=cs(I,1),we=Bi(I),ke,Me=f(Et=>{ke=Et});_C(this,Me,he,we,oe,ue),wC(this,W),W.start!==void 0?ke(W.start(this._transformStreamController)):ke(void 0)}get readable(){if(!Zp(this))throw rh("readable");return this._readable}get writable(){if(!Zp(this))throw rh("writable");return this._writable}};y(yC,"TransformStream");let jc=yC;Object.defineProperties(jc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(jc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function _C(c,l,_,v,I,$){function W(){return l}y(W,"startAlgorithm");function oe(Me){return AC(c,Me)}y(oe,"writeAlgorithm");function ue(Me){return EC(c,Me)}y(ue,"abortAlgorithm");function he(){return vC(c)}y(he,"closeAlgorithm"),c._writable=pb(W,oe,he,ue,_,v);function we(){return TC(c)}y(we,"pullAlgorithm");function ke(Me){return xC(c,Me)}y(ke,"cancelAlgorithm"),c._readable=ps(W,we,ke,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Vi(c,!0),c._transformStreamController=void 0}y(_C,"InitializeTransformStream");function Zp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof jc}y(Zp,"IsTransformStream");function eh(c,l){Ht(c._readable._readableStreamController,l),Lc(c,l)}y(eh,"TransformStreamError");function Lc(c,l){Xi(c._transformStreamController),ls(c._writable._writableStreamController,l),$c(c)}y(Lc,"TransformStreamErrorWritableAndUnblockWrite");function $c(c){c._backpressure&&Vi(c,!1)}y($c,"TransformStreamUnblockWrite");function Vi(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(_=>{c._backpressureChangePromise_resolve=_}),c._backpressure=l}y(Vi,"TransformStreamSetBackpressure");let bC=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Yi(this))throw Qi("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return Nc(l)}enqueue(l=void 0){if(!Yi(this))throw Qi("enqueue");th(this,l)}error(l=void 0){if(!Yi(this))throw Qi("error");kC(this,l)}terminate(){if(!Yi(this))throw Qi("terminate");SC(this)}};y(bC,"TransformStreamDefaultController");let Hr=bC;Object.defineProperties(Hr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Hr.prototype.enqueue,"enqueue"),i(Hr.prototype.error,"error"),i(Hr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Hr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Yi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Hr}y(Yi,"IsTransformStreamDefaultController");function CC(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(CC,"SetUpTransformStreamDefaultController");function wC(c,l){let _=Object.create(Hr.prototype),v,I,$;l.transform!==void 0?v=y(W=>l.transform(W,_),"transformAlgorithm"):v=y(W=>{try{return th(_,W),p(void 0)}catch(oe){return h(oe)}},"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"),CC(c,_,v,I,$)}y(wC,"SetUpTransformStreamDefaultControllerFromTransformer");function Xi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}y(Xi,"TransformStreamDefaultControllerClearAlgorithms");function th(c,l){let _=c._controlledTransformStream,v=_._readable._readableStreamController;if(!bo(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{_o(v,l)}catch(I){throw Lc(_,I),_._readable._storedError}zb(v)!==_._backpressure&&Vi(_,!0)}y(th,"TransformStreamDefaultControllerEnqueue");function kC(c,l){eh(c._controlledTransformStream,l)}y(kC,"TransformStreamDefaultControllerError");function nh(c,l){let _=c._transformAlgorithm(l);return C(_,void 0,v=>{throw eh(c._controlledTransformStream,v),v})}y(nh,"TransformStreamDefaultControllerPerformTransform");function SC(c){let l=c._controlledTransformStream,_=l._readable._readableStreamController;$r(_);let v=new TypeError("TransformStream terminated");Lc(l,v)}y(SC,"TransformStreamDefaultControllerTerminate");function AC(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 nh(_,l)})}return nh(_,l)}y(AC,"TransformStreamDefaultSinkWriteAlgorithm");function EC(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 Xi(_),b(I,()=>(v._state==="errored"?Co(_,v._storedError):(Ht(v._readableStreamController,l),qc(_)),null),$=>(Ht(v._readableStreamController,$),Co(_,$),null)),_._finishPromise}y(EC,"TransformStreamDefaultSinkAbortAlgorithm");function vC(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 Xi(l),b(v,()=>(_._state==="errored"?Co(l,_._storedError):($r(_._readableStreamController),qc(l)),null),I=>(Ht(_._readableStreamController,I),Co(l,I),null)),l._finishPromise}y(vC,"TransformStreamDefaultSinkCloseAlgorithm");function TC(c){return Vi(c,!1),c._backpressureChangePromise}y(TC,"TransformStreamDefaultSourcePullAlgorithm");function xC(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 Xi(_),b(I,()=>(v._state==="errored"?Co(_,v._storedError):(ls(v._writableStreamController,l),$c(c),qc(_)),null),$=>(ls(v._writableStreamController,$),$c(c),Co(_,$),null)),_._finishPromise}y(xC,"TransformStreamDefaultSourceCancelAlgorithm");function Qi(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}y(Qi,"defaultControllerBrandCheckException");function qc(c){c._finishPromise_resolve!==void 0&&(c._finishPromise_resolve(),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}y(qc,"defaultControllerFinishPromiseResolve");function Co(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(Co,"defaultControllerFinishPromiseReject");function rh(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}y(rh,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=Bc,n.CountQueuingStrategy=Uc,n.ReadableByteStreamController=rr,n.ReadableStream=mt,n.ReadableStreamBYOBReader=Mr,n.ReadableStreamBYOBRequest=ho,n.ReadableStreamDefaultController=sr,n.ReadableStreamDefaultReader=ge,n.TransformStream=jc,n.TransformStreamDefaultController=Hr,n.WritableStream=Ur,n.WritableStreamDefaultController=us,n.WritableStreamDefaultWriter=or})})(Al,Al.exports)),Al.exports}function IA(){if(PA)return DA;PA=1;let t=65536;if(!globalThis.ReadableStream)try{let e=require("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,require("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,JA())}try{let{Blob:e}=require("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 DA}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,FA),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+FA)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function VA(t,e=Wo){var n=`${NA()}${NA()}`.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+Yg(i)+`"\r
80
80
  \r
81
81
  ${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
82
82
  `)}\r
83
- `):r.push(o+Vg(i)+`"; filename="${Vg(s.name,1)}"\r
83
+ `):r.push(o+Yg(i)+`"; filename="${Yg(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 El(t){if(t[Pt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[Pt].disturbed=!0,t[Pt].error)throw t[Pt].error;let{body:e}=t;if(e===null)return ht.Buffer.alloc(0);if(!(e instanceof Je.default))return ht.Buffer.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 Xt(`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 Il?o:new Xt(`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")?ht.Buffer.from(n.join("")):ht.Buffer.concat(n,r)}catch(o){throw new Xt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new Xt(`Premature close of server response while trying to fetch ${t.url}`)}function ZA(t=[]){return new Cr(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return vl(e),Xg(e,String(n)),!0}catch{return!1}}))}function Qg(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 nE(t){if(!tE.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function rE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,LA.isIP)(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 qo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:rE(t)}function oE(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=Qg(o),i=Qg(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 qo(s)&&!qo(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===a.origin?s:qo(s)&&!qo(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 qo(s)&&!qo(a)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function sE(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&tE.has(r)&&(n=r);return n}function uE(){if(IA)return Yg;if(IA=1,!globalThis.DOMException)try{let{MessageChannel:t}=require("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 Yg=globalThis.DOMException,Yg}async function cm(t,e){return new Promise((n,r)=>{let o=new Oa(t,e),{parsedURL:s,options:i}=_N(o);if(!wN.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=qA(o.url),m=new Hn(b,{headers:{"Content-Type":b.typeFull}});n(m);return}let a=(s.protocol==="https:"?UA.default:Gs.default).request,{signal:u}=o,d=null,f=y(()=>{let b=new im("The operation was aborted.");r(b),o.body&&o.body instanceof Je.default.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 Xt(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),g()}),bE(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=ZA(b.rawHeaders);if(Fl(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 Xt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":r(new Xt(`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 Xt(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let O={headers:new Cr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:sm(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!cN(o.url,x)||!uN(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 Je.default.Readable){r(new Xt("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=sE(m);q&&(O.referrerPolicy=q),n(cm(new Oa(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=(0,Je.pipeline)(b,new Je.PassThrough,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 Hn(w,C),n(d);return}let k={flush:$o.default.Z_SYNC_FLUSH,finishFlush:$o.default.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){w=(0,Je.pipeline)(w,$o.default.createGunzip(k),E=>{E&&r(E)}),d=new Hn(w,C),n(d);return}if(A==="deflate"||A==="x-deflate"){let E=(0,Je.pipeline)(b,new Je.PassThrough,x=>{x&&r(x)});E.once("data",x=>{(x[0]&15)===8?w=(0,Je.pipeline)(w,$o.default.createInflate(),O=>{O&&r(O)}):w=(0,Je.pipeline)(w,$o.default.createInflateRaw(),O=>{O&&r(O)}),d=new Hn(w,C),n(d)}),E.once("end",()=>{d||(d=new Hn(w,C),n(d))});return}if(A==="br"){w=(0,Je.pipeline)(w,$o.default.createBrotliDecompress(),E=>{E&&r(E)}),d=new Hn(w,C),n(d);return}d=new Hn(w,C),n(d)}),pN(h,o).catch(r)})}function bE(t,e){let n=ht.Buffer.from(`0\r
87
+ `)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function vl(t){if(t[Ft].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[Ft].disturbed=!0,t[Ft].error)throw t[Ft].error;let{body:e}=t;if(e===null)return ht.Buffer.alloc(0);if(!(e instanceof Je.default))return ht.Buffer.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 Xt(`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 Xt(`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")?ht.Buffer.from(n.join("")):ht.Buffer.concat(n,r)}catch(o){throw new Xt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new Xt(`Premature close of server response while trying to fetch ${t.url}`)}function rE(t=[]){return new Cr(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return Tl(e),Qg(e,String(n)),!0}catch{return!1}}))}function Zg(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 iE(t){if(!sE.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function aE(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=(0,zA.isIP)(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 Ho(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:aE(t)}function cE(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=Zg(o),i=Zg(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 Ho(s)&&!Ho(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===a.origin?s:Ho(s)&&!Ho(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 Ho(s)&&!Ho(a)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function uE(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&sE.has(r)&&(n=r);return n}function pE(){if(BA)return Xg;if(BA=1,!globalThis.DOMException)try{let{MessageChannel:t}=require("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 Xg=globalThis.DOMException,Xg}async function um(t,e){return new Promise((n,r)=>{let o=new Pa(t,e),{parsedURL:s,options:i}=EN(o);if(!xN.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=GA(o.url),m=new Hn(b,{headers:{"Content-Type":b.typeFull}});n(m);return}let a=(s.protocol==="https:"?qA.default:Js.default).request,{signal:u}=o,d=null,f=y(()=>{let b=new am("The operation was aborted.");r(b),o.body&&o.body instanceof Je.default.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 Xt(`request to ${o.url} failed, reason: ${b.message}`,"system",b)),g()}),SE(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=rE(b.rawHeaders);if(Nl(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 Xt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":r(new Xt(`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 Xt(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let O={headers:new Cr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:im(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!gN(o.url,x)||!mN(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 Je.default.Readable){r(new Xt("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=uE(m);q&&(O.referrerPolicy=q),n(um(new Pa(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=(0,Je.pipeline)(b,new Je.PassThrough,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 Hn(w,C),n(d);return}let k={flush:qo.default.Z_SYNC_FLUSH,finishFlush:qo.default.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){w=(0,Je.pipeline)(w,qo.default.createGunzip(k),E=>{E&&r(E)}),d=new Hn(w,C),n(d);return}if(A==="deflate"||A==="x-deflate"){let E=(0,Je.pipeline)(b,new Je.PassThrough,x=>{x&&r(x)});E.once("data",x=>{(x[0]&15)===8?w=(0,Je.pipeline)(w,qo.default.createInflate(),O=>{O&&r(O)}):w=(0,Je.pipeline)(w,qo.default.createInflateRaw(),O=>{O&&r(O)}),d=new Hn(w,C),n(d)}),E.once("end",()=>{d||(d=new Hn(w,C),n(d))});return}if(A==="br"){w=(0,Je.pipeline)(w,qo.default.createBrotliDecompress(),E=>{E&&r(E)}),d=new Hn(w,C),n(d);return}d=new Hn(w,C),n(d)}),CN(h,o).catch(r)})}function SE(t,e){let n=ht.Buffer.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=ht.Buffer.compare(d.slice(-5),n)===0,!o&&s&&(o=ht.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&ht.Buffer.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 je(t){let e=CE.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function em(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 Ho(t,e){CE.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,um(o))}}function um(t){return{get(){return je(this).event[t]},set(e){je(this).event[t]=e},configurable:!0,enumerable:!0}}function wE(t){return{value(){let e=je(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function kE(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?wE(s):um(s))}}return r}function lm(t){if(t==null||t===Object.prototype)return Ho;let e=Zg.get(t);return e==null&&(e=kE(lm(Object.getPrototypeOf(t)),t),Zg.set(t,e)),e}function SE(t,e){let n=lm(Object.getPrototypeOf(e));return new n(t,e)}function AE(t){return je(t).immediateStopped}function EE(t,e){je(t).eventPhase=e}function vE(t,e){je(t).currentTarget=e}function tm(t,e){je(t).passiveListener=e}function Da(t){return t!==null&&typeof t=="object"}function Ws(t){let e=TE.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function xE(t){return{get(){let e=Ws(this).get(t);for(;e!=null;){if(e.listenerType===Tl)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!Da(e)&&(e=null);let n=Ws(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===Tl?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:Tl,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function dm(t,e){Object.defineProperty(t,`on${e}`,xE(e))}function nm(t){function e(){zn.call(this)}y(e,"CustomEventTarget"),e.prototype=Object.create(zn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)dm(e.prototype,t[n]);return e}function zn(){if(this instanceof zn){TE.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return nm(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 nm(t)}throw new TypeError("Cannot call a class as a function")}function DE(){let t=Object.create(Dl.prototype);return zn.call(t),Ol.set(t,!1),t}function OE(t){Ol.get(t)===!1&&(Ol.set(t,!0),t.dispatchEvent({type:"abort"}))}function rm(t){let e=PE.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 om(){!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 Gs,UA,$o,Je,ht,Qt,jA,LA,Wo,$A,tN,MA,y,BA,Ge,br,pn,Zr,Cl,qs,Wg,Ea,wl,kl,Gg,dn,Jg,Hs,zs,Kg,vA,Sl,nN,TA,xA,DA,zA,zo,rN,$s,xa,oN,sN,OA,iN,PA,Vg,Lo,jo,GA,Il,JA,Xt,xl,KA,Rl,aN,cN,uN,lN,Pt,VA,Ra,sm,dN,YA,fN,pN,vl,Xg,XA,Cr,hN,Fl,fn,eE,Hn,gN,tE,mN,lt,va,yN,iE,Oa,_N,cE,im,Yg,IA,bN,CN,am,lE,dE,fE,pE,hE,gE,mE,_E,wN,CE,Zg,TE,FA,NA,Tl,RE,Dl,Ol,Pl,PE,kN,SN,IE,bl=Wr(()=>{Gs=ot(require("node:http"),1),UA=ot(require("node:https"),1),$o=ot(require("node:zlib"),1),Je=ot(require("node:stream"),1),ht=require("node:buffer"),Qt=require("node:util");ml();jA=require("node:url"),LA=require("node:net"),Wo=require("node:fs"),$A=require("node:path"),tN=Object.defineProperty,MA=t=>{throw TypeError(t)},y=(t,e)=>tN(t,"name",{value:e,configurable:!0}),BA=(t,e,n)=>e.has(t)||MA("Cannot "+n),Ge=(t,e,n)=>(BA(t,e,"read from private field"),n?n.call(t):e.get(t)),br=(t,e,n)=>e.has(t)?MA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),pn=(t,e,n,r)=>(BA(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);y(qA,"dataUriToBuffer");vA={},Sl={exports:{}};nN=Sl.exports;y(HA,"requirePonyfill_es2018");y(RA,"requireStreams"),RA();DA=65536;y(Al,"toIterator");zA=(Ea=class{constructor(t=[],e={}){if(br(this,Zr,[]),br(this,Cl,""),br(this,qs,0),br(this,Wg,"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 Ea?s=o:s=n.encode(`${o}`),pn(this,qs,Ge(this,qs)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),Ge(this,Zr).push(s)}pn(this,Wg,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);pn(this,Cl,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return Ge(this,qs)}get type(){return Ge(this,Cl)}async text(){let t=new TextDecoder,e="";for await(let n of Al(Ge(this,Zr),!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 Al(Ge(this,Zr),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=Al(Ge(this,Zr),!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=Ge(this,Zr),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 Ea([],{type:String(n).toLowerCase()});return pn(f,qs,i),pn(f,Zr,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])}},Zr=new WeakMap,Cl=new WeakMap,qs=new WeakMap,Wg=new WeakMap,y(Ea,"Blob"),Ea);Object.defineProperties(zA.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});zo=zA,rN=(Gg=class extends zo{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),br(this,wl,0),br(this,kl,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||pn(this,wl,r),pn(this,kl,String(e))}get name(){return Ge(this,kl)}get lastModified(){return Ge(this,wl)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof zo&&/^(File)$/.test(t[Symbol.toStringTag])}},wl=new WeakMap,kl=new WeakMap,y(Gg,"File"),Gg),$s=rN;({toStringTag:xa,iterator:oN,hasInstance:sN}=Symbol),OA=Math.random,iN="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),PA=y((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[xa])?[(n=n!==void 0?n+"":e[xa]=="File"?e.name:"blob",t),e.name!==n||e[xa]=="blob"?new $s([e],n,e):e]:[t,e+""]),"f"),Vg=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"),Lo=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"),jo=(Jg=class{constructor(...t){if(br(this,dn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[xa](){return"FormData"}[oN](){return this.entries()}static[sN](t){return t&&typeof t=="object"&&t[xa]==="FormData"&&!iN.some(e=>typeof t[e]!="function")}append(...t){Lo("append",arguments,2),Ge(this,dn).push(PA(...t))}delete(t){Lo("delete",arguments,1),t+="",pn(this,dn,Ge(this,dn).filter(([e])=>e!==t))}get(t){Lo("get",arguments,1),t+="";for(var e=Ge(this,dn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return Lo("getAll",arguments,1),e=[],t+="",Ge(this,dn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return Lo("has",arguments,1),t+="",Ge(this,dn).some(e=>e[0]===t)}forEach(t,e){Lo("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){Lo("set",arguments,2);var e=[],n=!0;t=PA(...t),Ge(this,dn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),pn(this,dn,e)}*entries(){yield*Ge(this,dn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},dn=new WeakMap,y(Jg,"FormData"),Jg);y(WA,"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");Il=GA,JA=class extends Il{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};y(JA,"FetchError");Xt=JA,xl=Symbol.toStringTag,KA=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[xl]==="URLSearchParams","isURLSearchParameters"),Rl=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[xl]),"isBlob"),aN=y(t=>typeof t=="object"&&(t[xl]==="AbortSignal"||t[xl]==="EventTarget"),"isAbortSignal"),cN=y((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),uN=y((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),lN=(0,Qt.promisify)(Je.default.pipeline),Pt=Symbol("Body internals"),VA=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:KA(e)?e=ht.Buffer.from(e.toString()):Rl(e)||ht.Buffer.isBuffer(e)||(Qt.types.isAnyArrayBuffer(e)?e=ht.Buffer.from(e):ArrayBuffer.isView(e)?e=ht.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Je.default||(e instanceof jo?(e=WA(e),r=e.type.split("=")[1]):e=ht.Buffer.from(String(e))));let o=e;ht.Buffer.isBuffer(e)?o=Je.default.Readable.from(e):Rl(e)&&(o=Je.default.Readable.from(e.stream())),this[Pt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Je.default&&e.on("error",s=>{let i=s instanceof Il?s:new Xt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Pt].error=i})}get body(){return this[Pt].stream}get bodyUsed(){return this[Pt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await El(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 jo,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(()=>(EA(),AA));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Pt].body&&this[Pt].body.type||"",n=await this.arrayBuffer();return new zo([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await El(this);return new TextDecoder().decode(e)}buffer(){return El(this)}};y(VA,"Body");Ra=VA;Ra.prototype.buffer=(0,Qt.deprecate)(Ra.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Ra.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Qt.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});y(El,"consumeBody");sm=y((t,e)=>{let n,r,{body:o}=t[Pt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Je.default&&typeof o.getBoundary!="function"&&(n=new Je.PassThrough({highWaterMark:e}),r=new Je.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Pt].stream=n,o=r),o},"clone"),dN=(0,Qt.deprecate)(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"),YA=y((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":KA(t)?"application/x-www-form-urlencoded;charset=UTF-8":Rl(t)?t.type||null:ht.Buffer.isBuffer(t)||Qt.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof jo?`multipart/form-data; boundary=${e[Pt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${dN(t)}`:t instanceof Je.default?null:"text/plain;charset=UTF-8","extractContentType"),fN=y(t=>{let{body:e}=t[Pt];return e===null?0:Rl(e)?e.size:ht.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),pN=y(async(t,{body:e})=>{e===null?t.end():await lN(e,t)},"writeToStream"),vl=typeof Gs.default.validateHeaderName=="function"?Gs.default.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}},Xg=typeof Gs.default.validateHeaderValue=="function"?Gs.default.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}},XA=class QA extends URLSearchParams{constructor(e){let n=[];if(e instanceof QA){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"&&!Qt.types.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"||Qt.types.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])=>(vl(r),Xg(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)=>(vl(i),Xg(i,String(a)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(a)));case"delete":case"has":case"getAll":return i=>(vl(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(XA,"Headers");Cr=XA;Object.defineProperties(Cr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));y(ZA,"fromRawHeaders");hN=new Set([301,302,303,307,308]),Fl=y(t=>hN.has(t),"isRedirect"),fn=Symbol("Response internals"),eE=class Ta extends Ra{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new Cr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=YA(e,this);s&&o.append("Content-Type",s)}this[fn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[fn].type}get url(){return this[fn].url||""}get status(){return this[fn].status}get ok(){return this[fn].status>=200&&this[fn].status<300}get redirected(){return this[fn].counter>0}get statusText(){return this[fn].statusText}get headers(){return this[fn].headers}get highWaterMark(){return this[fn].highWaterMark}clone(){return new Ta(sm(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(!Fl(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new Ta(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new Ta(null,{status:0,statusText:""});return e[fn].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 Cr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new Ta(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};y(eE,"Response");Hn=eE;Object.defineProperties(Hn.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}});gN=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(Qg,"stripURLForUseAsAReferrer");tE=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),mN="strict-origin-when-cross-origin";y(nE,"validateReferrerPolicy");y(rE,"isOriginPotentiallyTrustworthy");y(qo,"isUrlPotentiallyTrustworthy");y(oE,"determineRequestsReferrer");y(sE,"parseReferrerPolicyFromHeader");lt=Symbol("Request internals"),va=y(t=>typeof t=="object"&&typeof t[lt]=="object","isRequest"),yN=(0,Qt.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),iE=class aE extends Ra{constructor(e,n={}){let r;if(va(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()),!va(n)&&"data"in n&&yN(),(n.body!=null||va(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:va(e)&&e.body!==null?sm(e):null;super(s,{size:n.size||e.size||0});let i=new Cr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=YA(s,this);d&&i.set("Content-Type",d)}let a=va(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!aN(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[lt]={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[lt].method}get url(){return(0,jA.format)(this[lt].parsedURL)}get headers(){return this[lt].headers}get redirect(){return this[lt].redirect}get signal(){return this[lt].signal}get referrer(){if(this[lt].referrer==="no-referrer")return"";if(this[lt].referrer==="client")return"about:client";if(this[lt].referrer)return this[lt].referrer.toString()}get referrerPolicy(){return this[lt].referrerPolicy}set referrerPolicy(e){this[lt].referrerPolicy=nE(e)}clone(){return new aE(this)}get[Symbol.toStringTag](){return"Request"}};y(iE,"Request");Oa=iE;Object.defineProperties(Oa.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}});_N=y(t=>{let{parsedURL:e}=t[lt],n=new Cr(t[lt].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=fN(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=mN),t.referrer&&t.referrer!=="no-referrer"?t[lt].referrer=oE(t):t[lt].referrer="no-referrer",t[lt].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=gN(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"),cE=class extends Il{constructor(e,n="aborted"){super(e,n)}};y(cE,"AbortError");im=cE;y(uE,"requireNodeDomexception");bN=uE(),CN=zg(bN),{stat:am}=Wo.promises,lE=y((t,e)=>hE((0,Wo.statSync)(t),t,e),"blobFromSync"),dE=y((t,e)=>am(t).then(n=>hE(n,t,e)),"blobFrom"),fE=y((t,e)=>am(t).then(n=>gE(n,t,e)),"fileFrom"),pE=y((t,e)=>gE((0,Wo.statSync)(t),t,e),"fileFromSync"),hE=y((t,e,n="")=>new zo([new _E({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),gE=y((t,e,n="")=>new $s([new _E({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,$A.basename)(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),mE=class yE{constructor(e){br(this,Hs),br(this,zs),pn(this,Hs,e.path),pn(this,zs,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new yE({path:Ge(this,Hs),lastModified:this.lastModified,size:n-e,start:Ge(this,zs)+e})}async*stream(){let{mtimeMs:e}=await am(Ge(this,Hs));if(e>this.lastModified)throw new CN("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*(0,Wo.createReadStream)(Ge(this,Hs),{start:Ge(this,zs),end:Ge(this,zs)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};Hs=new WeakMap,zs=new WeakMap,y(mE,"BlobDataItem");_E=mE,wN=new Set(["data:","http:","https:"]);y(cm,"fetch$1");y(bE,"fixResponseChunkedTransferBadEnding");CE=new WeakMap,Zg=new WeakMap;y(je,"pd");y(em,"setCancelFlag");y(Ho,"Event"),Ho.prototype={get type(){return je(this).event.type},get target(){return je(this).eventTarget},get currentTarget(){return je(this).currentTarget},composedPath(){let t=je(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 je(this).eventPhase},stopPropagation(){let t=je(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=je(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!je(this).event.bubbles},get cancelable(){return!!je(this).event.cancelable},preventDefault(){em(je(this))},get defaultPrevented(){return je(this).canceled},get composed(){return!!je(this).event.composed},get timeStamp(){return je(this).timeStamp},get srcElement(){return je(this).eventTarget},get cancelBubble(){return je(this).stopped},set cancelBubble(t){if(!t)return;let e=je(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!je(this).canceled},set returnValue(t){t||em(je(this))},initEvent(){}},Object.defineProperty(Ho.prototype,"constructor",{value:Ho,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Ho.prototype,window.Event.prototype),Zg.set(window.Event.prototype,Ho));y(um,"defineRedirectDescriptor");y(wE,"defineCallDescriptor");y(kE,"defineWrapper");y(lm,"getWrapper");y(SE,"wrapEvent");y(AE,"isStopped");y(EE,"setEventPhase");y(vE,"setCurrentTarget");y(tm,"setPassiveListener");TE=new WeakMap,FA=1,NA=2,Tl=3;y(Da,"isObject");y(Ws,"getListeners");y(xE,"defineEventAttributeDescriptor");y(dm,"defineEventAttribute");y(nm,"defineCustomEventTarget");y(zn,"EventTarget"),zn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!Da(e))throw new TypeError("'listener' should be a function or an object.");let r=Ws(this),o=Da(n),s=(o?n.capture:n)?FA:NA,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=Ws(this),o=(Da(n)?n.capture:n)?FA:NA,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=Ws(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=SE(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,tm(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!==Tl&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(AE(o))break;r=r.next}return tm(o,null),EE(o,0),vE(o,null),!o.defaultPrevented}},Object.defineProperty(zn.prototype,"constructor",{value:zn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(zn.prototype,window.EventTarget.prototype);RE=class extends zn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=Ol.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(RE,"AbortSignal");Dl=RE;dm(Dl.prototype,"abort");y(DE,"createAbortSignal");y(OE,"abortSignal");Ol=new WeakMap;Object.defineProperties(Dl.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Dl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});Pl=(Kg=class{constructor(){PE.set(this,DE())}get signal(){return rm(this)}abort(){OE(rm(this))}},y(Kg,"AbortController"),Kg),PE=new WeakMap;y(rm,"getSignal"),Object.defineProperties(Pl.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Pl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});kN=Object.defineProperty,SN=y((t,e)=>kN(t,"name",{value:e,configurable:!0}),"e"),IE=cm;om();y(om,"s"),SN(om,"checkNodeEnvironment")});var FE={};sh(FE,{AbortController:()=>ON,AbortError:()=>im,Blob:()=>EN,FetchError:()=>Xt,File:()=>vN,FormData:()=>TN,Headers:()=>xN,Request:()=>RN,Response:()=>DN,blobFrom:()=>dE,blobFromSync:()=>lE,default:()=>AN,fetch:()=>AN,fileFrom:()=>fE,fileFromSync:()=>pE,isRedirect:()=>Fl});var eo,AN,EN,vN,TN,xN,RN,DN,ON,NE=Wr(()=>{bl();bl();ml();eo=!!globalThis.process?.env?.FORCE_NODE_FETCH,AN=!eo&&globalThis.fetch||IE,EN=!eo&&globalThis.Blob||zo,vN=!eo&&globalThis.File||$s,TN=!eo&&globalThis.FormData||jo,xN=!eo&&globalThis.Headers||Cr,RN=!eo&&globalThis.Request||Oa,DN=!eo&&globalThis.Response||Hn,ON=!eo&&globalThis.AbortController||Pl});var UE=G(Ks=>{"use strict";var PN=Ks&&Ks.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Js;Object.defineProperty(Ks,"__esModule",{value:!0});Ks.Gaxios=void 0;var IN=PN(Og()),FN=require("https"),Go=Fg(),NN=KS(),ME=require("stream"),BE=Bg(),MN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),BN=204,Nl=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new BE.GaxiosInterceptorManager,response:new BE.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&&Js.mergeHeaders(s,n.headers),r&&Js.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 Js.#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=Go.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Go.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Go.GaxiosError?r=n:n instanceof Error?r=new Go.GaxiosError(n.message,e,void 0,n):r=new Go.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,NN.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===BN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Go.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);Js.mergeHeaders(n,e.headers);let r=(0,IN.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 ME.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 MN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=ME.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 Js.#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 FN.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Go.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=ht.Buffer.compare(d.slice(-5),n)===0,!o&&s&&(o=ht.Buffer.compare(s.slice(-3),n.slice(0,3))===0&&ht.Buffer.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 je(t){let e=AE.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function tm(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 zo(t,e){AE.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,lm(o))}}function lm(t){return{get(){return je(this).event[t]},set(e){je(this).event[t]=e},configurable:!0,enumerable:!0}}function EE(t){return{value(){let e=je(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function vE(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?EE(s):lm(s))}}return r}function dm(t){if(t==null||t===Object.prototype)return zo;let e=em.get(t);return e==null&&(e=vE(dm(Object.getPrototypeOf(t)),t),em.set(t,e)),e}function TE(t,e){let n=dm(Object.getPrototypeOf(e));return new n(t,e)}function xE(t){return je(t).immediateStopped}function RE(t,e){je(t).eventPhase=e}function DE(t,e){je(t).currentTarget=e}function nm(t,e){je(t).passiveListener=e}function Oa(t){return t!==null&&typeof t=="object"}function Gs(t){let e=OE.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function PE(t){return{get(){let e=Gs(this).get(t);for(;e!=null;){if(e.listenerType===xl)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!Oa(e)&&(e=null);let n=Gs(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===xl?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:xl,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function fm(t,e){Object.defineProperty(t,`on${e}`,PE(e))}function rm(t){function e(){zn.call(this)}y(e,"CustomEventTarget"),e.prototype=Object.create(zn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)fm(e.prototype,t[n]);return e}function zn(){if(this instanceof zn){OE.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return rm(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 rm(t)}throw new TypeError("Cannot call a class as a function")}function FE(){let t=Object.create(Ol.prototype);return zn.call(t),Pl.set(t,!1),t}function NE(t){Pl.get(t)===!1&&(Pl.set(t,!0),t.dispatchEvent({type:"abort"}))}function om(t){let e=ME.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 sm(){!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 Js,qA,qo,Je,ht,Qt,HA,zA,Go,WA,cN,LA,y,$A,Ge,br,pn,eo,wl,Hs,Gg,va,kl,Sl,Jg,dn,Kg,zs,Ws,Vg,DA,Al,uN,OA,PA,FA,KA,Wo,lN,qs,Ra,dN,fN,NA,pN,MA,Yg,$o,Lo,YA,Fl,XA,Xt,Rl,QA,Dl,hN,gN,mN,yN,Ft,ZA,Da,im,_N,eE,bN,CN,Tl,Qg,tE,Cr,wN,Nl,fn,oE,Hn,kN,sE,SN,lt,Ta,AN,lE,Pa,EN,fE,am,Xg,BA,vN,TN,cm,hE,gE,mE,yE,_E,bE,CE,kE,xN,AE,em,OE,UA,jA,xl,IE,Ol,Pl,Il,ME,RN,DN,BE,Cl=Wr(()=>{Js=ot(require("node:http"),1),qA=ot(require("node:https"),1),qo=ot(require("node:zlib"),1),Je=ot(require("node:stream"),1),ht=require("node:buffer"),Qt=require("node:util");yl();HA=require("node:url"),zA=require("node:net"),Go=require("node:fs"),WA=require("node:path"),cN=Object.defineProperty,LA=t=>{throw TypeError(t)},y=(t,e)=>cN(t,"name",{value:e,configurable:!0}),$A=(t,e,n)=>e.has(t)||LA("Cannot "+n),Ge=(t,e,n)=>($A(t,e,"read from private field"),n?n.call(t):e.get(t)),br=(t,e,n)=>e.has(t)?LA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),pn=(t,e,n,r)=>($A(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);y(GA,"dataUriToBuffer");DA={},Al={exports:{}};uN=Al.exports;y(JA,"requirePonyfill_es2018");y(IA,"requireStreams"),IA();FA=65536;y(El,"toIterator");KA=(va=class{constructor(t=[],e={}){if(br(this,eo,[]),br(this,wl,""),br(this,Hs,0),br(this,Gg,"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 va?s=o:s=n.encode(`${o}`),pn(this,Hs,Ge(this,Hs)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),Ge(this,eo).push(s)}pn(this,Gg,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);pn(this,wl,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return Ge(this,Hs)}get type(){return Ge(this,wl)}async text(){let t=new TextDecoder,e="";for await(let n of El(Ge(this,eo),!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(Ge(this,eo),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=El(Ge(this,eo),!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=Ge(this,eo),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 va([],{type:String(n).toLowerCase()});return pn(f,Hs,i),pn(f,eo,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])}},eo=new WeakMap,wl=new WeakMap,Hs=new WeakMap,Gg=new WeakMap,y(va,"Blob"),va);Object.defineProperties(KA.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Wo=KA,lN=(Jg=class extends Wo{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),br(this,kl,0),br(this,Sl,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||pn(this,kl,r),pn(this,Sl,String(e))}get name(){return Ge(this,Sl)}get lastModified(){return Ge(this,kl)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Wo&&/^(File)$/.test(t[Symbol.toStringTag])}},kl=new WeakMap,Sl=new WeakMap,y(Jg,"File"),Jg),qs=lN;({toStringTag:Ra,iterator:dN,hasInstance:fN}=Symbol),NA=Math.random,pN="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),MA=y((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[Ra])?[(n=n!==void 0?n+"":e[Ra]=="File"?e.name:"blob",t),e.name!==n||e[Ra]=="blob"?new qs([e],n,e):e]:[t,e+""]),"f"),Yg=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"),$o=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"),Lo=(Kg=class{constructor(...t){if(br(this,dn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[Ra](){return"FormData"}[dN](){return this.entries()}static[fN](t){return t&&typeof t=="object"&&t[Ra]==="FormData"&&!pN.some(e=>typeof t[e]!="function")}append(...t){$o("append",arguments,2),Ge(this,dn).push(MA(...t))}delete(t){$o("delete",arguments,1),t+="",pn(this,dn,Ge(this,dn).filter(([e])=>e!==t))}get(t){$o("get",arguments,1),t+="";for(var e=Ge(this,dn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return $o("getAll",arguments,1),e=[],t+="",Ge(this,dn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return $o("has",arguments,1),t+="",Ge(this,dn).some(e=>e[0]===t)}forEach(t,e){$o("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){$o("set",arguments,2);var e=[],n=!0;t=MA(...t),Ge(this,dn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),pn(this,dn,e)}*entries(){yield*Ge(this,dn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},dn=new WeakMap,y(Kg,"FormData"),Kg);y(VA,"formDataToBlob");YA=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(YA,"FetchBaseError");Fl=YA,XA=class extends Fl{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};y(XA,"FetchError");Xt=XA,Rl=Symbol.toStringTag,QA=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[Rl]==="URLSearchParams","isURLSearchParameters"),Dl=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[Rl]),"isBlob"),hN=y(t=>typeof t=="object"&&(t[Rl]==="AbortSignal"||t[Rl]==="EventTarget"),"isAbortSignal"),gN=y((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),mN=y((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),yN=(0,Qt.promisify)(Je.default.pipeline),Ft=Symbol("Body internals"),ZA=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:QA(e)?e=ht.Buffer.from(e.toString()):Dl(e)||ht.Buffer.isBuffer(e)||(Qt.types.isAnyArrayBuffer(e)?e=ht.Buffer.from(e):ArrayBuffer.isView(e)?e=ht.Buffer.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Je.default||(e instanceof Lo?(e=VA(e),r=e.type.split("=")[1]):e=ht.Buffer.from(String(e))));let o=e;ht.Buffer.isBuffer(e)?o=Je.default.Readable.from(e):Dl(e)&&(o=Je.default.Readable.from(e.stream())),this[Ft]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Je.default&&e.on("error",s=>{let i=s instanceof Fl?s:new Xt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Ft].error=i})}get body(){return this[Ft].stream}get bodyUsed(){return this[Ft].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await vl(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 Lo,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(()=>(RA(),xA));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Ft].body&&this[Ft].body.type||"",n=await this.arrayBuffer();return new Wo([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await vl(this);return new TextDecoder().decode(e)}buffer(){return vl(this)}};y(ZA,"Body");Da=ZA;Da.prototype.buffer=(0,Qt.deprecate)(Da.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(Da.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:(0,Qt.deprecate)(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});y(vl,"consumeBody");im=y((t,e)=>{let n,r,{body:o}=t[Ft];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Je.default&&typeof o.getBoundary!="function"&&(n=new Je.PassThrough({highWaterMark:e}),r=new Je.PassThrough({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Ft].stream=n,o=r),o},"clone"),_N=(0,Qt.deprecate)(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"),eE=y((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":QA(t)?"application/x-www-form-urlencoded;charset=UTF-8":Dl(t)?t.type||null:ht.Buffer.isBuffer(t)||Qt.types.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof Lo?`multipart/form-data; boundary=${e[Ft].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${_N(t)}`:t instanceof Je.default?null:"text/plain;charset=UTF-8","extractContentType"),bN=y(t=>{let{body:e}=t[Ft];return e===null?0:Dl(e)?e.size:ht.Buffer.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),CN=y(async(t,{body:e})=>{e===null?t.end():await yN(e,t)},"writeToStream"),Tl=typeof Js.default.validateHeaderName=="function"?Js.default.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}},Qg=typeof Js.default.validateHeaderValue=="function"?Js.default.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}},tE=class nE extends URLSearchParams{constructor(e){let n=[];if(e instanceof nE){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"&&!Qt.types.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"||Qt.types.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])=>(Tl(r),Qg(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)=>(Tl(i),Qg(i,String(a)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(a)));case"delete":case"has":case"getAll":return i=>(Tl(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(tE,"Headers");Cr=tE;Object.defineProperties(Cr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));y(rE,"fromRawHeaders");wN=new Set([301,302,303,307,308]),Nl=y(t=>wN.has(t),"isRedirect"),fn=Symbol("Response internals"),oE=class xa extends Da{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new Cr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=eE(e,this);s&&o.append("Content-Type",s)}this[fn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[fn].type}get url(){return this[fn].url||""}get status(){return this[fn].status}get ok(){return this[fn].status>=200&&this[fn].status<300}get redirected(){return this[fn].counter>0}get statusText(){return this[fn].statusText}get headers(){return this[fn].headers}get highWaterMark(){return this[fn].highWaterMark}clone(){return new xa(im(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(!Nl(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new xa(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new xa(null,{status:0,statusText:""});return e[fn].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 Cr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new xa(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};y(oE,"Response");Hn=oE;Object.defineProperties(Hn.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}});kN=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(Zg,"stripURLForUseAsAReferrer");sE=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),SN="strict-origin-when-cross-origin";y(iE,"validateReferrerPolicy");y(aE,"isOriginPotentiallyTrustworthy");y(Ho,"isUrlPotentiallyTrustworthy");y(cE,"determineRequestsReferrer");y(uE,"parseReferrerPolicyFromHeader");lt=Symbol("Request internals"),Ta=y(t=>typeof t=="object"&&typeof t[lt]=="object","isRequest"),AN=(0,Qt.deprecate)(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),lE=class dE extends Da{constructor(e,n={}){let r;if(Ta(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()),!Ta(n)&&"data"in n&&AN(),(n.body!=null||Ta(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:Ta(e)&&e.body!==null?im(e):null;super(s,{size:n.size||e.size||0});let i=new Cr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=eE(s,this);d&&i.set("Content-Type",d)}let a=Ta(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!hN(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[lt]={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[lt].method}get url(){return(0,HA.format)(this[lt].parsedURL)}get headers(){return this[lt].headers}get redirect(){return this[lt].redirect}get signal(){return this[lt].signal}get referrer(){if(this[lt].referrer==="no-referrer")return"";if(this[lt].referrer==="client")return"about:client";if(this[lt].referrer)return this[lt].referrer.toString()}get referrerPolicy(){return this[lt].referrerPolicy}set referrerPolicy(e){this[lt].referrerPolicy=iE(e)}clone(){return new dE(this)}get[Symbol.toStringTag](){return"Request"}};y(lE,"Request");Pa=lE;Object.defineProperties(Pa.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}});EN=y(t=>{let{parsedURL:e}=t[lt],n=new Cr(t[lt].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=bN(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=SN),t.referrer&&t.referrer!=="no-referrer"?t[lt].referrer=cE(t):t[lt].referrer="no-referrer",t[lt].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=kN(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"),fE=class extends Fl{constructor(e,n="aborted"){super(e,n)}};y(fE,"AbortError");am=fE;y(pE,"requireNodeDomexception");vN=pE(),TN=Wg(vN),{stat:cm}=Go.promises,hE=y((t,e)=>_E((0,Go.statSync)(t),t,e),"blobFromSync"),gE=y((t,e)=>cm(t).then(n=>_E(n,t,e)),"blobFrom"),mE=y((t,e)=>cm(t).then(n=>bE(n,t,e)),"fileFrom"),yE=y((t,e)=>bE((0,Go.statSync)(t),t,e),"fileFromSync"),_E=y((t,e,n="")=>new Wo([new kE({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),bE=y((t,e,n="")=>new qs([new kE({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],(0,WA.basename)(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),CE=class wE{constructor(e){br(this,zs),br(this,Ws),pn(this,zs,e.path),pn(this,Ws,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new wE({path:Ge(this,zs),lastModified:this.lastModified,size:n-e,start:Ge(this,Ws)+e})}async*stream(){let{mtimeMs:e}=await cm(Ge(this,zs));if(e>this.lastModified)throw new TN("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*(0,Go.createReadStream)(Ge(this,zs),{start:Ge(this,Ws),end:Ge(this,Ws)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};zs=new WeakMap,Ws=new WeakMap,y(CE,"BlobDataItem");kE=CE,xN=new Set(["data:","http:","https:"]);y(um,"fetch$1");y(SE,"fixResponseChunkedTransferBadEnding");AE=new WeakMap,em=new WeakMap;y(je,"pd");y(tm,"setCancelFlag");y(zo,"Event"),zo.prototype={get type(){return je(this).event.type},get target(){return je(this).eventTarget},get currentTarget(){return je(this).currentTarget},composedPath(){let t=je(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 je(this).eventPhase},stopPropagation(){let t=je(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=je(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!je(this).event.bubbles},get cancelable(){return!!je(this).event.cancelable},preventDefault(){tm(je(this))},get defaultPrevented(){return je(this).canceled},get composed(){return!!je(this).event.composed},get timeStamp(){return je(this).timeStamp},get srcElement(){return je(this).eventTarget},get cancelBubble(){return je(this).stopped},set cancelBubble(t){if(!t)return;let e=je(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!je(this).canceled},set returnValue(t){t||tm(je(this))},initEvent(){}},Object.defineProperty(zo.prototype,"constructor",{value:zo,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(zo.prototype,window.Event.prototype),em.set(window.Event.prototype,zo));y(lm,"defineRedirectDescriptor");y(EE,"defineCallDescriptor");y(vE,"defineWrapper");y(dm,"getWrapper");y(TE,"wrapEvent");y(xE,"isStopped");y(RE,"setEventPhase");y(DE,"setCurrentTarget");y(nm,"setPassiveListener");OE=new WeakMap,UA=1,jA=2,xl=3;y(Oa,"isObject");y(Gs,"getListeners");y(PE,"defineEventAttributeDescriptor");y(fm,"defineEventAttribute");y(rm,"defineCustomEventTarget");y(zn,"EventTarget"),zn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!Oa(e))throw new TypeError("'listener' should be a function or an object.");let r=Gs(this),o=Oa(n),s=(o?n.capture:n)?UA:jA,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=Gs(this),o=(Oa(n)?n.capture:n)?UA:jA,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=Gs(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=TE(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,nm(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!==xl&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(xE(o))break;r=r.next}return nm(o,null),RE(o,0),DE(o,null),!o.defaultPrevented}},Object.defineProperty(zn.prototype,"constructor",{value:zn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(zn.prototype,window.EventTarget.prototype);IE=class extends zn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=Pl.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(IE,"AbortSignal");Ol=IE;fm(Ol.prototype,"abort");y(FE,"createAbortSignal");y(NE,"abortSignal");Pl=new WeakMap;Object.defineProperties(Ol.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Ol.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});Il=(Vg=class{constructor(){ME.set(this,FE())}get signal(){return om(this)}abort(){NE(om(this))}},y(Vg,"AbortController"),Vg),ME=new WeakMap;y(om,"getSignal"),Object.defineProperties(Il.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Il.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});RN=Object.defineProperty,DN=y((t,e)=>RN(t,"name",{value:e,configurable:!0}),"e"),BE=um;sm();y(sm,"s"),DN(sm,"checkNodeEnvironment")});var UE={};sh(UE,{AbortController:()=>UN,AbortError:()=>am,Blob:()=>PN,FetchError:()=>Xt,File:()=>IN,FormData:()=>FN,Headers:()=>NN,Request:()=>MN,Response:()=>BN,blobFrom:()=>gE,blobFromSync:()=>hE,default:()=>ON,fetch:()=>ON,fileFrom:()=>mE,fileFromSync:()=>yE,isRedirect:()=>Nl});var to,ON,PN,IN,FN,NN,MN,BN,UN,jE=Wr(()=>{Cl();Cl();yl();to=!!globalThis.process?.env?.FORCE_NODE_FETCH,ON=!to&&globalThis.fetch||BE,PN=!to&&globalThis.Blob||Wo,IN=!to&&globalThis.File||qs,FN=!to&&globalThis.FormData||Lo,NN=!to&&globalThis.Headers||Cr,MN=!to&&globalThis.Request||Pa,BN=!to&&globalThis.Response||Hn,UN=!to&&globalThis.AbortController||Il});var qE=G(Vs=>{"use strict";var jN=Vs&&Vs.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Ks;Object.defineProperty(Vs,"__esModule",{value:!0});Vs.Gaxios=void 0;var LN=jN(Pg()),$N=require("https"),Jo=Ng(),qN=QS(),LE=require("stream"),$E=Ug(),HN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),zN=204,Ml=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new $E.GaxiosInterceptorManager,response:new $E.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&&Ks.mergeHeaders(s,n.headers),r&&Ks.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 Ks.#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=Jo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Jo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Jo.GaxiosError?r=n:n instanceof Error?r=new Jo.GaxiosError(n.message,e,void 0,n):r=new Jo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,qN.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===zN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Jo.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);Ks.mergeHeaders(n,e.headers);let r=(0,LN.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 LE.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 HN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=LE.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 Ks.#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 $N.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Jo.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(()=>ot(bA()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(NE(),FE))).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}};Ks.Gaxios=Nl;Js=Nl});var gt=G(St=>{"use strict";var UN=St&&St.__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=St&&St.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&UN(e,t,n)};Object.defineProperty(St,"__esModule",{value:!0});St.instance=St.Gaxios=St.GaxiosError=void 0;St.request=$N;var jE=UE();Object.defineProperty(St,"Gaxios",{enumerable:!0,get:function(){return jE.Gaxios}});var LN=Fg();Object.defineProperty(St,"GaxiosError",{enumerable:!0,get:function(){return LN.GaxiosError}});jN(Bg(),St);St.instance=new jE.Gaxios;async function $N(t){return St.instance.request(t)}});var fm=G((LE,Ml)=>{(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,ye=21,De=-1e7,ve=1e7,Ye=!1,ne=1,Z=0,ie={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Pe="0123456789abcdefghijklmnopqrstuvwxyz",Ce=!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>ve?B.c=B.e=null:S.e<De?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>ve?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,Pe.length,"Base"),T==10&&Ce)return B=new H(S),le(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=Pe.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)>ve)B.c=B.e=null;else if(F<De)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],ye=R[1]):(C(R,-h,h,T),Q=-(ye=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),De=R[0],ve=R[1];else if(C(R,-h,h,T),R)De=-(ve=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))Ye=R;else throw Ye=!R,Error(s+"crypto unavailable");else Ye=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")ie=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))Ce=R.slice(0,10)=="0123456789",Pe=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,ye],RANGE:[De,ve],CRYPTO:Ye,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ie,ALPHABET:Pe}},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 tt(arguments,-1)},H.minimum=H.min=function(){return tt(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),Ye)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 Ye=!1,Error(s+"crypto unavailable");if(!Ye)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,se,ce,_e,ge=R.indexOf("."),pe=z,me=te;for(ge>=0&&(B=Z,Z=0,R=R.replace(".",""),_e=new H(M),se=_e.pow(R.length-ge),Z=B,_e.c=T(E(m(se.c),se.e,"0"),10,D,S),_e.e=_e.c.length),ce=T(R,M,D,L?(P=Pe,S):(P=S,Pe)),U=B=ce.length;ce[--B]==0;ce.pop());if(!ce[0])return P.charAt(0);if(ge<0?--U:(se.c=ce,se.e=U,se.s=F,se=O(se,_e,pe,me,D),ce=se.c,K=se.r,U=se.e),N=U+pe+1,ge=ce[N],B=D/2,K=K||N<0||ce[N+1]!=null,K=me<4?(ge!=null||K)&&(me==0||me==(se.s<0?3:2)):ge>B||ge==B&&(me==4||K||me==6&&ce[N-1]&1||me==(se.s<0?8:7)),N<1||!ce[0])R=K?E(P.charAt(1),-pe,P.charAt(0)):P.charAt(0);else{if(ce.length=N,K)for(--D;++ce[--N]>D;)ce[N]=0,N||(++U,ce=[1].concat(ce));for(B=ce.length;!ce[--B];);for(ge=0,R="";ge<=B;R+=P.charAt(ce[ge++]));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,se=D%p,ce=D/p|0;for(M=M.slice();K--;)N=M[K]%p,U=M[K]/p|0,L=ce*N+U*se,P=se*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ce*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,se,ce,_e,ge,pe,me,Ie,Ze,En,xi,rs,It,Pr,_t=M.s==D.s?1:-1,nt=M.c,Be=D.c;if(!nt||!nt[0]||!Be||!Be[0])return new H(!M.s||!D.s||(nt?Be&&nt[0]==Be[0]:!Be)?NaN:nt&&nt[0]==0||!Be?_t*0:_t/0);for(ge=new H(_t),pe=ge.c=[],U=M.e-D.e,_t=F+U+1,P||(P=a,U=b(M.e/u)-b(D.e/u),_t=_t/u|0),B=0;Be[B]==(nt[B]||0);B++);if(Be[B]>(nt[B]||0)&&U--,_t<0)pe.push(1),K=!0;else{for(xi=nt.length,It=Be.length,B=0,_t+=2,se=o(P/(Be[0]+1)),se>1&&(Be=S(Be,se,P),nt=S(nt,se,P),It=Be.length,xi=nt.length),En=It,me=nt.slice(0,It),Ie=me.length;Ie<It;me[Ie++]=0);Pr=Be.slice(),Pr=[0].concat(Pr),rs=Be[0],Be[1]>=P/2&&rs++;do{if(se=0,N=T(Be,me,It,Ie),N<0){if(Ze=me[0],It!=Ie&&(Ze=Ze*P+(me[1]||0)),se=o(Ze/rs),se>1)for(se>=P&&(se=P-1),ce=S(Be,se,P),_e=ce.length,Ie=me.length;T(ce,me,_e,Ie)==1;)se--,R(ce,It<_e?Pr:Be,_e,P),_e=ce.length,N=1;else se==0&&(N=se=1),ce=Be.slice(),_e=ce.length;if(_e<Ie&&(ce=[0].concat(ce)),R(me,ce,Ie,P),Ie=me.length,N==-1)for(;T(Be,me,It,Ie)<1;)se++,R(me,It<Ie?Pr:Be,Ie,P),Ie=me.length}else N===0&&(se++,me=[0]);pe[B++]=se,me[0]?me[Ie++]=nt[En]||0:(me=[nt[En]],Ie=1)}while((En++<xi||me[0]!=null)&&_t--);K=me[0]!=null,pe[0]||pe.splice(0,1)}if(P==a){for(B=1,_t=pe[0];_t>=10;_t/=10,B++);le(ge,F+(ge.e=B+U*u-1)+1,L,K)}else ge.e=U,ge.r=+K;return ge}})();function Ae(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>=ye)?k(N,L):E(N,L,"0");else if(S=le(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 tt(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)>ve?S.c=S.e=null:R<De?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,se,ce){return U=(ce=ce.toLowerCase())=="x"?16:ce=="b"?2:8,!N||N==U?se: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 le(S,T,R,M){var D,F,L,P,N,U,B,K=S.c,se=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/se[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/se[D-L-1]%10)}if(M=M||T<0||K[U+1]!=null||(L<0?N:N%se[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/se[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]=se[(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=se[u-F],K[U]=L>0?o(N/se[D-L]%se[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>ve?S.c=S.e=null:S.e<De&&(S.c=[S.e=0])}return S}function ae(S){var T,R=S.e;return R===null?S.toString():(T=m(S.c),T=R<=Q||R>=ye?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),le(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: "+ae(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(+ae(K),P?S.s*(2-A(S)):+ae(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(+ae(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),le(S,S.e+1,1),S.e>14)U=A(S);else{if(D=+ae(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?le(B,Z,te,L):B)},j.integerValue=function(S){var T=new H(this);return S==null?S=te:C(S,0,8),le(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,se,ce,_e,ge,pe,me=this,Ie=me.c,Ze=(S=new H(S,T)).c;if(!Ie||!Ze||!Ie[0]||!Ze[0])return!me.s||!S.s||Ie&&!Ie[0]&&!Ze||Ze&&!Ze[0]&&!Ie?S.c=S.e=S.s=null:(S.s*=me.s,!Ie||!Ze?S.c=S.e=null:(S.c=[0],S.e=0)),S;for(M=b(me.e/u)+b(S.e/u),S.s*=me.s,N=Ie.length,K=Ze.length,N<K&&(_e=Ie,Ie=Ze,Ze=_e,D=N,N=K,K=D),D=N+K,_e=[];D--;_e.push(0));for(ge=a,pe=p,D=K;--D>=0;){for(R=0,se=Ze[D]%pe,ce=Ze[D]/pe|0,L=N,F=D+L;F>D;)U=Ie[--L]%pe,B=Ie[L]/pe|0,P=ce*U+B*se,U=se*U+P%pe*pe+_e[F]+R,R=(U/ge|0)+(P/pe|0)+ce*B,_e[F--]=U%ge;_e[F]=R}return R?++M:_e.splice(0,1),X(S,_e,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),le(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(+ae(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&&(le(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")&&(le(R,R.e+z+2,1),S=!R.times(R).eq(F));break}}return le(R,R.e+z+1,te,S)},j.toExponential=function(S,T){return S!=null&&(C(S,0,h),S++),Ae(this,S,T,1)},j.toFixed=function(S,T){return S!=null&&(C(S,0,h),S=S+this.e+1),Ae(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=ie;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],se=D.s<0,ce=se?B.slice(1):B,_e=ce.length;if(N&&(F=P,P=N,N=F,_e-=F),P>0&&_e>0){for(F=_e%P||P,B=ce.substr(0,F);F<_e;F+=P)B+=U+ce.substr(F,P);N>0&&(B+=U+ce.slice(F)),se&&(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,se,ce=this,_e=ce.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: ")+ae(P));if(!_e)return new H(ce);for(T=new H(ee),U=R=new H(ee),M=N=new H(ee),se=m(_e),F=T.e=se.length-ce.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=ve,ve=1/0,P=new H(se),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=ce.s,F=F*2,K=O(U,M,F,te).minus(ce).abs().comparedTo(O(N,R,F,te).minus(ce).abs())<1?[U,M]:[N,R],ve=L,K},j.toNumber=function(){return+ae(this)},j.toPrecision=function(S,T){return S!=null&&C(S,1,h),Ae(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>=ye?k(m(R.c),D):E(m(R.c),D,"0"):S===10&&Ce?(R=le(new H(R),z+D+1,te),T=E(m(R.c),R.e,"0")):(C(S,2,Pe.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 ae(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,ye=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==ye,!j||!ee)return V?0:!j^q?1:-1;if(!V)return Q>ye^q?1:-1;for(te=(Q=j.length)<(ye=ee.length)?Q:ye,z=0;z<te;z++)if(j[z]!=ee[z])return j[z]>ee[z]^q?1:-1;return Q==ye?0:Q>ye^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 Ml<"u"&&Ml.exports?Ml.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(LE)});var zE=G((p8,HE)=>{var $E=fm(),qE=HE.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 $E||$E.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(()=>ot(SA()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(jE(),UE))).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}};Vs.Gaxios=Ml;Ks=Ml});var gt=G(At=>{"use strict";var WN=At&&At.__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=At&&At.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&WN(e,t,n)};Object.defineProperty(At,"__esModule",{value:!0});At.instance=At.Gaxios=At.GaxiosError=void 0;At.request=KN;var HE=qE();Object.defineProperty(At,"Gaxios",{enumerable:!0,get:function(){return HE.Gaxios}});var JN=Ng();Object.defineProperty(At,"GaxiosError",{enumerable:!0,get:function(){return JN.GaxiosError}});GN(Ug(),At);At.instance=new HE.Gaxios;async function KN(t){return At.instance.request(t)}});var pm=G((zE,Bl)=>{(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,ye=21,De=-1e7,ve=1e7,Ye=!1,ne=1,Z=0,ie={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Pe="0123456789abcdefghijklmnopqrstuvwxyz",Ce=!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>ve?B.c=B.e=null:S.e<De?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>ve?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,Pe.length,"Base"),T==10&&Ce)return B=new H(S),le(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=Pe.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)>ve)B.c=B.e=null;else if(F<De)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],ye=R[1]):(C(R,-h,h,T),Q=-(ye=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),De=R[0],ve=R[1];else if(C(R,-h,h,T),R)De=-(ve=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))Ye=R;else throw Ye=!R,Error(s+"crypto unavailable");else Ye=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")ie=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))Ce=R.slice(0,10)=="0123456789",Pe=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,ye],RANGE:[De,ve],CRYPTO:Ye,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ie,ALPHABET:Pe}},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 tt(arguments,-1)},H.minimum=H.min=function(){return tt(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),Ye)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 Ye=!1,Error(s+"crypto unavailable");if(!Ye)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,se,ce,_e,ge=R.indexOf("."),pe=z,me=te;for(ge>=0&&(B=Z,Z=0,R=R.replace(".",""),_e=new H(M),se=_e.pow(R.length-ge),Z=B,_e.c=T(E(m(se.c),se.e,"0"),10,D,S),_e.e=_e.c.length),ce=T(R,M,D,L?(P=Pe,S):(P=S,Pe)),U=B=ce.length;ce[--B]==0;ce.pop());if(!ce[0])return P.charAt(0);if(ge<0?--U:(se.c=ce,se.e=U,se.s=F,se=O(se,_e,pe,me,D),ce=se.c,K=se.r,U=se.e),N=U+pe+1,ge=ce[N],B=D/2,K=K||N<0||ce[N+1]!=null,K=me<4?(ge!=null||K)&&(me==0||me==(se.s<0?3:2)):ge>B||ge==B&&(me==4||K||me==6&&ce[N-1]&1||me==(se.s<0?8:7)),N<1||!ce[0])R=K?E(P.charAt(1),-pe,P.charAt(0)):P.charAt(0);else{if(ce.length=N,K)for(--D;++ce[--N]>D;)ce[N]=0,N||(++U,ce=[1].concat(ce));for(B=ce.length;!ce[--B];);for(ge=0,R="";ge<=B;R+=P.charAt(ce[ge++]));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,se=D%p,ce=D/p|0;for(M=M.slice();K--;)N=M[K]%p,U=M[K]/p|0,L=ce*N+U*se,P=se*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ce*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,se,ce,_e,ge,pe,me,Ie,Ze,En,Ri,os,Nt,Pr,_t=M.s==D.s?1:-1,nt=M.c,Be=D.c;if(!nt||!nt[0]||!Be||!Be[0])return new H(!M.s||!D.s||(nt?Be&&nt[0]==Be[0]:!Be)?NaN:nt&&nt[0]==0||!Be?_t*0:_t/0);for(ge=new H(_t),pe=ge.c=[],U=M.e-D.e,_t=F+U+1,P||(P=a,U=b(M.e/u)-b(D.e/u),_t=_t/u|0),B=0;Be[B]==(nt[B]||0);B++);if(Be[B]>(nt[B]||0)&&U--,_t<0)pe.push(1),K=!0;else{for(Ri=nt.length,Nt=Be.length,B=0,_t+=2,se=o(P/(Be[0]+1)),se>1&&(Be=S(Be,se,P),nt=S(nt,se,P),Nt=Be.length,Ri=nt.length),En=Nt,me=nt.slice(0,Nt),Ie=me.length;Ie<Nt;me[Ie++]=0);Pr=Be.slice(),Pr=[0].concat(Pr),os=Be[0],Be[1]>=P/2&&os++;do{if(se=0,N=T(Be,me,Nt,Ie),N<0){if(Ze=me[0],Nt!=Ie&&(Ze=Ze*P+(me[1]||0)),se=o(Ze/os),se>1)for(se>=P&&(se=P-1),ce=S(Be,se,P),_e=ce.length,Ie=me.length;T(ce,me,_e,Ie)==1;)se--,R(ce,Nt<_e?Pr:Be,_e,P),_e=ce.length,N=1;else se==0&&(N=se=1),ce=Be.slice(),_e=ce.length;if(_e<Ie&&(ce=[0].concat(ce)),R(me,ce,Ie,P),Ie=me.length,N==-1)for(;T(Be,me,Nt,Ie)<1;)se++,R(me,Nt<Ie?Pr:Be,Ie,P),Ie=me.length}else N===0&&(se++,me=[0]);pe[B++]=se,me[0]?me[Ie++]=nt[En]||0:(me=[nt[En]],Ie=1)}while((En++<Ri||me[0]!=null)&&_t--);K=me[0]!=null,pe[0]||pe.splice(0,1)}if(P==a){for(B=1,_t=pe[0];_t>=10;_t/=10,B++);le(ge,F+(ge.e=B+U*u-1)+1,L,K)}else ge.e=U,ge.r=+K;return ge}})();function Ae(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>=ye)?k(N,L):E(N,L,"0");else if(S=le(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 tt(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)>ve?S.c=S.e=null:R<De?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,se,ce){return U=(ce=ce.toLowerCase())=="x"?16:ce=="b"?2:8,!N||N==U?se: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 le(S,T,R,M){var D,F,L,P,N,U,B,K=S.c,se=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/se[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/se[D-L-1]%10)}if(M=M||T<0||K[U+1]!=null||(L<0?N:N%se[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/se[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]=se[(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=se[u-F],K[U]=L>0?o(N/se[D-L]%se[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>ve?S.c=S.e=null:S.e<De&&(S.c=[S.e=0])}return S}function ae(S){var T,R=S.e;return R===null?S.toString():(T=m(S.c),T=R<=Q||R>=ye?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),le(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: "+ae(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(+ae(K),P?S.s*(2-A(S)):+ae(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(+ae(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),le(S,S.e+1,1),S.e>14)U=A(S);else{if(D=+ae(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?le(B,Z,te,L):B)},j.integerValue=function(S){var T=new H(this);return S==null?S=te:C(S,0,8),le(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,se,ce,_e,ge,pe,me=this,Ie=me.c,Ze=(S=new H(S,T)).c;if(!Ie||!Ze||!Ie[0]||!Ze[0])return!me.s||!S.s||Ie&&!Ie[0]&&!Ze||Ze&&!Ze[0]&&!Ie?S.c=S.e=S.s=null:(S.s*=me.s,!Ie||!Ze?S.c=S.e=null:(S.c=[0],S.e=0)),S;for(M=b(me.e/u)+b(S.e/u),S.s*=me.s,N=Ie.length,K=Ze.length,N<K&&(_e=Ie,Ie=Ze,Ze=_e,D=N,N=K,K=D),D=N+K,_e=[];D--;_e.push(0));for(ge=a,pe=p,D=K;--D>=0;){for(R=0,se=Ze[D]%pe,ce=Ze[D]/pe|0,L=N,F=D+L;F>D;)U=Ie[--L]%pe,B=Ie[L]/pe|0,P=ce*U+B*se,U=se*U+P%pe*pe+_e[F]+R,R=(U/ge|0)+(P/pe|0)+ce*B,_e[F--]=U%ge;_e[F]=R}return R?++M:_e.splice(0,1),X(S,_e,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),le(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(+ae(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&&(le(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")&&(le(R,R.e+z+2,1),S=!R.times(R).eq(F));break}}return le(R,R.e+z+1,te,S)},j.toExponential=function(S,T){return S!=null&&(C(S,0,h),S++),Ae(this,S,T,1)},j.toFixed=function(S,T){return S!=null&&(C(S,0,h),S=S+this.e+1),Ae(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=ie;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],se=D.s<0,ce=se?B.slice(1):B,_e=ce.length;if(N&&(F=P,P=N,N=F,_e-=F),P>0&&_e>0){for(F=_e%P||P,B=ce.substr(0,F);F<_e;F+=P)B+=U+ce.substr(F,P);N>0&&(B+=U+ce.slice(F)),se&&(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,se,ce=this,_e=ce.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: ")+ae(P));if(!_e)return new H(ce);for(T=new H(ee),U=R=new H(ee),M=N=new H(ee),se=m(_e),F=T.e=se.length-ce.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=ve,ve=1/0,P=new H(se),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=ce.s,F=F*2,K=O(U,M,F,te).minus(ce).abs().comparedTo(O(N,R,F,te).minus(ce).abs())<1?[U,M]:[N,R],ve=L,K},j.toNumber=function(){return+ae(this)},j.toPrecision=function(S,T){return S!=null&&C(S,1,h),Ae(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>=ye?k(m(R.c),D):E(m(R.c),D,"0"):S===10&&Ce?(R=le(new H(R),z+D+1,te),T=E(m(R.c),R.e,"0")):(C(S,2,Pe.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 ae(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,ye=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==ye,!j||!ee)return V?0:!j^q?1:-1;if(!V)return Q>ye^q?1:-1;for(te=(Q=j.length)<(ye=ee.length)?Q:ye,z=0;z<te;z++)if(j[z]!=ee[z])return j[z]>ee[z]^q?1:-1;return Q==ye?0:Q>ye^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 Bl<"u"&&Bl.exports?Bl.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(zE)});var KE=G((A8,JE)=>{var WE=pm(),GE=JE.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 WE||WE.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?`[
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 qE.stringify!="function"&&(qE.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((h8,WE)=>{var Bl=null,qN=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,HN=/(?: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)/,zN=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 Bl==null&&(Bl=fm()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new Bl(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new Bl(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+'"'),qN.test(m)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():w[m]=h():HN.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}};WE.exports=zN});var VE=G((g8,Ul)=>{var JE=zE().stringify,KE=GE();Ul.exports=function(t){return{parse:KE(t),stringify:JE}};Ul.exports.parse=KE();Ul.exports.stringify=JE});var pm=G(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.GCE_LINUX_BIOS_PATHS=void 0;hn.isGoogleCloudServerless=QE;hn.isGoogleComputeEngineLinux=ZE;hn.isGoogleComputeEngineMACAddress=ev;hn.isGoogleComputeEngine=tv;hn.detectGCPResidency=GN;var YE=require("fs"),XE=require("os");hn.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var WN=/^42:01/;function QE(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function ZE(){if((0,XE.platform)()!=="linux")return!1;try{(0,YE.statSync)(hn.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,YE.readFileSync)(hn.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function ev(){let t=(0,XE.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(WN.test(n))return!0}return!1}function tv(){return ZE()||ev()}function GN(){return QE()||tv()}});var nv=G(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.Colours=void 0;var jl=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="")}};Ll.Colours=jl;jl.refresh()});var ov=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.LogSeverity=void 0;var rv;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(rv||($l.LogSeverity=rv={}))});var cv=G(Le=>{"use strict";var JN=Le&&Le.__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]})),KN=Le&&Le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),sv=Le&&Le.__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"&&JN(n,e,r[o]);return KN(n,e),n}})();Object.defineProperty(Le,"__esModule",{value:!0});Le.env=Le.DebugLogBackendBase=Le.placeholder=Le.AdhocDebugLogger=void 0;Le.getNodeBackend=gm;Le.getDebugBackend=YN;Le.getStructuredBackend=XN;Le.setBackend=QN;Le.log=av;var VN=require("events"),Pa=sv(require("process")),iv=sv(require("util")),jt=nv(),wr=ov(),Ia=class extends VN.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(wr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(wr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(wr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(wr.LogSeverity.ERROR,...r),this.func.sublog=r=>av(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)}};Le.AdhocDebugLogger=Ia;Le.placeholder=new Ia("",()=>{}).func;var Vs=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=Pa.env[Le.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)}}};Le.DebugLogBackendBase=Vs;var hm=class extends Vs{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${jt.Colours.green}${e}${jt.Colours.reset}`,s=`${jt.Colours.yellow}${Pa.pid}${jt.Colours.reset}`,i;switch(n.severity){case wr.LogSeverity.ERROR:i=`${jt.Colours.red}${n.severity}${jt.Colours.reset}`;break;case wr.LogSeverity.INFO:i=`${jt.Colours.magenta}${n.severity}${jt.Colours.reset}`;break;case wr.LogSeverity.WARNING:i=`${jt.Colours.yellow}${n.severity}${jt.Colours.reset}`;break;default:i=n.severity??wr.LogSeverity.DEFAULT;break}let a=iv.formatWithOptions({colors:jt.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${jt.Colours.grey}${d}${jt.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 gm(){return new hm}var mm=class extends Vs{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=Pa.env.NODE_DEBUG??"";Pa.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function YN(t){return new mm(t)}var ym=class extends Vs{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??wr.LogSeverity.INFO,i=Object.assign({severity:s,message:iv.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function XN(t){return new ym(t)}Le.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var _m=new Map,gn;function QN(t){gn=t,_m.clear()}function av(t,e){if(!gn&&!Pa.env[Le.env.nodeEnables]||!t)return Le.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=_m.get(t);if(n)return n.func;if(gn===null)return Le.placeholder;gn===void 0&&(gn=gm());let r=(()=>{let o;return new Ia(t,(i,...a)=>{if(o!==gn){if(gn===null)return;gn===void 0&&(gn=gm()),o=gn}gn?.log(t,i,...a)})})();return _m.set(t,r),r.func}});var bm=G(Jo=>{"use strict";var ZN=Jo&&Jo.__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]})),eM=Jo&&Jo.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&ZN(e,t,n)};Object.defineProperty(Jo,"__esModule",{value:!0});eM(cv(),Jo)});var Na=G(fe=>{"use strict";var lv=fe&&fe.__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]})),tM=fe&&fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),nM=fe&&fe.__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"&&lv(n,e,r[o]);return tM(n,e),n}})(),rM=fe&&fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&lv(e,t,n)};Object.defineProperty(fe,"__esModule",{value:!0});fe.gcpResidencyCache=fe.METADATA_SERVER_DETECTION=fe.HEADERS=fe.HEADER_VALUE=fe.HEADER_NAME=fe.SECONDARY_HOST_ADDRESS=fe.HOST_ADDRESS=fe.BASE_PATH=void 0;fe.instance=uM;fe.project=lM;fe.universe=dM;fe.bulk=fM;fe.isAvailable=hM;fe.resetIsAvailableCache=gM;fe.getGCPResidency=km;fe.setGCPResidency=dv;fe.requestTimeout=fv;var Cm=gt(),oM=VE(),sM=pm(),iM=nM(bm());fe.BASE_PATH="/computeMetadata/v1";fe.HOST_ADDRESS="http://169.254.169.254";fe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";fe.HEADER_NAME="Metadata-Flavor";fe.HEADER_VALUE="Google";fe.HEADERS=Object.freeze({[fe.HEADER_NAME]:fe.HEADER_VALUE});var uv=iM.log("gcp-metadata");fe.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 wm(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||fe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(fe.BASE_PATH,t).href}function aM(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 Fa(t,e={},n=3,r=!1){let o=new Headers(fe.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}`:(aM(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?cM:Cm.request,u={url:`${wm()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:fv()};uv.info("instance request %j",u);let d=await a(u);uv.info("instance metadata is %s",d.data);let f=d.headers.get(fe.HEADER_NAME);if(f!==fe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${fe.HEADER_NAME} header. Expected '${fe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return oM.parse(d.data)}catch{}return d.data}async function cM(t){let e={...t,url:t.url?.toString().replace(wm(),wm(fe.SECONDARY_HOST_ADDRESS))},n=(0,Cm.request)(t),r=(0,Cm.request)(e);return Promise.any([n,r])}function uM(t){return Fa("instance",t)}function lM(t){return Fa("project",t)}function dM(t){return Fa("universe",t)}async function fM(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await Fa(n),o=n.metadataKey;e[o]=r})())),e}function pM(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var ql;async function hM(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in fe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(fe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return km();case"ping-only":}}try{return ql===void 0&&(ql=(async()=>{try{return await Fa("instance",void 0,pM(),!(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 ql}catch{return!1}}function gM(){ql=void 0}fe.gcpResidencyCache=null;function km(){return fe.gcpResidencyCache===null&&dv(),fe.gcpResidencyCache}function dv(t=null){fe.gcpResidencyCache=t!==null?t:(0,sM.detectGCPResidency)()}function fv(){return km()?0:3e3}rM(pm(),fe)});var gv=G(Hl=>{"use strict";Hl.byteLength=yM;Hl.toByteArray=bM;Hl.fromByteArray=kM;var Wn=[],Zt=[],mM=typeof Uint8Array<"u"?Uint8Array:Array,Sm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Ko=0,pv=Sm.length;Ko<pv;++Ko)Wn[Ko]=Sm[Ko],Zt[Sm.charCodeAt(Ko)]=Ko;var Ko,pv;Zt[45]=62;Zt[95]=63;function hv(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 yM(t){var e=hv(t),n=e[0],r=e[1];return(n+r)*3/4-r}function _M(t,e,n){return(e+n)*3/4-n}function bM(t){var e,n=hv(t),r=n[0],o=n[1],s=new mM(_M(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Zt[t.charCodeAt(u)]<<18|Zt[t.charCodeAt(u+1)]<<12|Zt[t.charCodeAt(u+2)]<<6|Zt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Zt[t.charCodeAt(u)]<<2|Zt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Zt[t.charCodeAt(u)]<<10|Zt[t.charCodeAt(u+1)]<<4|Zt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function CM(t){return Wn[t>>18&63]+Wn[t>>12&63]+Wn[t>>6&63]+Wn[t&63]}function wM(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(CM(r));return o.join("")}function kM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(wM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Wn[e>>2]+Wn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Wn[e>>10]+Wn[e>>4&63]+Wn[e<<2&63]+"=")),o.join("")}});var Em=G(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.fromArrayBufferToHex=SM;function SM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var mv=G(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});zl.BrowserCrypto=void 0;var Ys=gv(),AM=Em(),vm=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 Ys.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Ys.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=Ys.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 Ys.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Ys.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Ys.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,AM.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))}};zl.BrowserCrypto=vm});var yv=G(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.NodeCrypto=void 0;var Xs=require("crypto"),Tm=class{async sha256DigestBase64(e){return Xs.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Xs.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Xs.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Xs.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 Xs.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:vM(e);return EM(Xs.createHmac("sha256",r).update(n).digest())}};Wl.NodeCrypto=Tm;function EM(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 vM(t){return Buffer.from(t)}});var Ma=G(kr=>{"use strict";var TM=kr&&kr.__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]})),xM=kr&&kr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&TM(e,t,n)};Object.defineProperty(kr,"__esModule",{value:!0});kr.createCrypto=OM;kr.hasBrowserCrypto=_v;var RM=mv(),DM=yv();xM(Em(),kr);function OM(){return _v()?new RM.BrowserCrypto:new DM.NodeCrypto}function _v(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Qs=G((xm,Cv)=>{var Gl=require("buffer"),Gn=Gl.Buffer;function bv(t,e){for(var n in t)e[n]=t[n]}Gn.from&&Gn.alloc&&Gn.allocUnsafe&&Gn.allocUnsafeSlow?Cv.exports=Gl:(bv(Gl,xm),xm.Buffer=Vo);function Vo(t,e,n){return Gn(t,e,n)}Vo.prototype=Object.create(Gn.prototype);bv(Gn,Vo);Vo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Gn(t,e,n)};Vo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=Gn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Vo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Gn(t)};Vo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Gl.SlowBuffer(t)}});var kv=G((T8,wv)=>{"use strict";function Rm(t){var e=(t/8|0)+(t%8===0?0:1);return e}var PM={ES256:Rm(256),ES384:Rm(384),ES512:Rm(521)};function IM(t){var e=PM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}wv.exports=IM});var Dm=G((x8,xv)=>{"use strict";var Jl=Qs().Buffer,Av=kv(),Kl=128,Ev=0,FM=32,NM=16,MM=2,vv=NM|FM|Ev<<6,Vl=MM|Ev<<6;function BM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Tv(t){if(Jl.isBuffer(t))return t;if(typeof t=="string")return Jl.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function UM(t,e){t=Tv(t);var n=Av(e),r=n+1,o=t.length,s=0;if(t[s++]!==vv)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(Kl|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==Vl)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++]!==Vl)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=Jl.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=BM(g),g}function Sv(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Kl;return o&&--r,r}function jM(t,e){t=Tv(t);var n=Av(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Sv(t,0,n),s=Sv(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<Kl,f=Jl.allocUnsafe((d?2:3)+u),p=0;return f[p++]=vv,d?f[p++]=u:(f[p++]=Kl|1,f[p++]=u&255),f[p++]=Vl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Vl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}xv.exports={derToJose:UM,joseToDer:jM}});var mn=G(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.LRUCache=void 0;Sr.snakeToCamel=Dv;Sr.originalOrCamelOptions=HM;Sr.removeUndefinedValuesInObject=zM;Sr.isValidFile=WM;Sr.getWellKnownCertificateConfigFileLocation=GM;var LM=require("fs"),$M=require("os"),Om=require("path"),qM="certificate_config.json",Rv="gcloud";function Dv(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function HM(t){function e(n){let r=t||{};return r[n]??r[Dv(n)]}return{get:e}}var Pm=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()}};Sr.LRUCache=Pm;function zM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function WM(t){try{return(await LM.promises.lstat(t)).isFile()}catch{return!1}}function GM(){let t=process.env.CLOUDSDK_CONFIG||(JM()?Om.join(process.env.APPDATA||"",Rv):Om.join(process.env.HOME||"",".config",Rv));return Om.join(t,qM)}function JM(){return $M.platform().startsWith("win")}});var Ov=G((D8,KM)=>{KM.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(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.USER_AGENT=to.PRODUCT_NAME=to.pkg=void 0;var Pv=Ov();to.pkg=Pv;var Iv="google-api-nodejs-client";to.PRODUCT_NAME=Iv;var VM=`${Iv}/${Pv.version}`;to.USER_AGENT=VM});var Lt=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.AuthClient=yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=yn.DEFAULT_UNIVERSE=void 0;var YM=require("events"),Fm=gt(),XM=mn(),QM=bm(),Nm=Im();yn.DEFAULT_UNIVERSE="googleapis.com";yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Mm=class t extends YM.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=yn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,XM.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")??yn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Fm.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&&Fm.Gaxios.mergeHeaders(s,n.headers),r&&Fm.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,QM.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(`${Nm.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Nm.USER_AGENT}`):e.headers.set("User-Agent",Nm.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"]}}}};yn.AuthClient=Mm});var Um=G(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});Yl.LoginTicket=void 0;var Bm=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()}}};Yl.LoginTicket=Bm});var no=G(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.OAuth2Client=Jn.ClientAuthentication=Jn.CertificateFormat=Jn.CodeChallengeMethod=void 0;var Fv=gt(),ZM=require("querystring"),eB=require("stream"),tB=Dm(),Nv=mn(),jm=Ma(),Zs=Lt(),nB=Um(),Mv;(function(t){t.Plain="plain",t.S256="S256"})(Mv||(Jn.CodeChallengeMethod=Mv={}));var Ar;(function(t){t.PEM="PEM",t.JWK="JWK"})(Ar||(Jn.CertificateFormat=Ar={}));var Ba;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Ba||(Jn.ClientAuthentication=Ba={}));var Lm=class t extends Zs.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ar.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||Ba.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,jm.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===Ba.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===Ba.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,Nv.removeUndefinedValuesInObject)(o)),headers:r};Zs.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,Nv.removeUndefinedValuesInObject)(r))};Zs.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof Fv.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(Zs.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=Fv.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 eB.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,jm.hasBrowserCrypto)()?Ar.JWK:Ar.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Ar.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ar.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Zs.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 Ar.PEM:a=r.data;break;case Ar.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};Zs.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,jm.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=tB.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 nB.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=Lm});var qm=G(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});Xl.Compute=void 0;var rB=gt(),Bv=Na(),oB=no(),$m=class extends oB.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 Bv.instance(o)}catch(o){throw o instanceof rB.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 Bv.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))}};Xl.Compute=$m});var zm=G(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.IdTokenClient=void 0;var sB=no(),Hm=class extends sB.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}};Ql.IdTokenClient=Hm});var Wm=G(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.GCPEnv=void 0;ei.clear=iB;ei.getEnv=aB;var Uv=Na(),Kn;(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"})(Kn||(ei.GCPEnv=Kn={}));var Ua;function iB(){Ua=void 0}async function aB(){return Ua||(Ua=cB(),Ua)}async function cB(){let t=Kn.NONE;return uB()?t=Kn.APP_ENGINE:lB()?t=Kn.CLOUD_FUNCTIONS:await hB()?await pB()?t=Kn.KUBERNETES_ENGINE:dB()?t=Kn.CLOUD_RUN:fB()?t=Kn.CLOUD_RUN_JOBS:t=Kn.COMPUTE_ENGINE:t=Kn.NONE,t}function uB(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function lB(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function dB(){return!!process.env.K_CONFIGURATION}function fB(){return!!process.env.CLOUD_RUN_JOB}async function pB(){try{return await Uv.instance("attributes/cluster-name"),!0}catch{return!1}}async function hB(){return Uv.isAvailable()}});var Gm=G((U8,jv)=>{var Zl=Qs().Buffer,gB=require("stream"),mB=require("util");function ed(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Zl.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Zl.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+")")}mB.inherits(ed,gB);ed.prototype.write=function(e){this.buffer=Zl.concat([this.buffer,Zl.from(e)]),this.emit("data",e)};ed.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};jv.exports=ed});var $v=G((j8,Lv)=>{"use strict";var ja=require("buffer").Buffer,Jm=require("buffer").SlowBuffer;Lv.exports=td;function td(t,e){if(!ja.isBuffer(t)||!ja.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}td.install=function(){ja.prototype.equal=Jm.prototype.equal=function(e){return td(this,e)}};var yB=ja.prototype.equal,_B=Jm.prototype.equal;td.restore=function(){ja.prototype.equal=yB,Jm.prototype.equal=_B}});var Xm=G((L8,Yv)=>{var ni=Qs().Buffer,en=require("crypto"),Hv=Dm(),qv=require("util"),bB=`"%s" is not a valid algorithm.
100
+ `+m+"}":"{"+w.join(",")+"}",r=m,g}}typeof GE.stringify!="function"&&(GE.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 YE=G((E8,VE)=>{var Ul=null,VN=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,YN=/(?: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)/,XN=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 Ul==null&&(Ul=pm()),w.length>15?e.storeAsString?w:e.useNativeBigInt?BigInt(w):new Ul(w):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(m):new Ul(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+'"'),VN.test(m)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():w[m]=h():YN.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}};VE.exports=XN});var ZE=G((v8,jl)=>{var XE=KE().stringify,QE=YE();jl.exports=function(t){return{parse:QE(t),stringify:XE}};jl.exports.parse=QE();jl.exports.stringify=XE});var hm=G(hn=>{"use strict";Object.defineProperty(hn,"__esModule",{value:!0});hn.GCE_LINUX_BIOS_PATHS=void 0;hn.isGoogleCloudServerless=nv;hn.isGoogleComputeEngineLinux=rv;hn.isGoogleComputeEngineMACAddress=ov;hn.isGoogleComputeEngine=sv;hn.detectGCPResidency=ZN;var ev=require("fs"),tv=require("os");hn.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var QN=/^42:01/;function nv(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function rv(){if((0,tv.platform)()!=="linux")return!1;try{(0,ev.statSync)(hn.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,ev.readFileSync)(hn.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function ov(){let t=(0,tv.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(QN.test(n))return!0}return!1}function sv(){return rv()||ov()}function ZN(){return nv()||sv()}});var iv=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.Colours=void 0;var Ll=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="")}};$l.Colours=Ll;Ll.refresh()});var cv=G(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});ql.LogSeverity=void 0;var av;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(av||(ql.LogSeverity=av={}))});var fv=G(Le=>{"use strict";var eM=Le&&Le.__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]})),tM=Le&&Le.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uv=Le&&Le.__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"&&eM(n,e,r[o]);return tM(n,e),n}})();Object.defineProperty(Le,"__esModule",{value:!0});Le.env=Le.DebugLogBackendBase=Le.placeholder=Le.AdhocDebugLogger=void 0;Le.getNodeBackend=mm;Le.getDebugBackend=rM;Le.getStructuredBackend=oM;Le.setBackend=sM;Le.log=dv;var nM=require("events"),Ia=uv(require("process")),lv=uv(require("util")),jt=iv(),wr=cv(),Fa=class extends nM.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(wr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(wr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(wr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(wr.LogSeverity.ERROR,...r),this.func.sublog=r=>dv(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)}};Le.AdhocDebugLogger=Fa;Le.placeholder=new Fa("",()=>{}).func;var Ys=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=Ia.env[Le.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)}}};Le.DebugLogBackendBase=Ys;var gm=class extends Ys{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${jt.Colours.green}${e}${jt.Colours.reset}`,s=`${jt.Colours.yellow}${Ia.pid}${jt.Colours.reset}`,i;switch(n.severity){case wr.LogSeverity.ERROR:i=`${jt.Colours.red}${n.severity}${jt.Colours.reset}`;break;case wr.LogSeverity.INFO:i=`${jt.Colours.magenta}${n.severity}${jt.Colours.reset}`;break;case wr.LogSeverity.WARNING:i=`${jt.Colours.yellow}${n.severity}${jt.Colours.reset}`;break;default:i=n.severity??wr.LogSeverity.DEFAULT;break}let a=lv.formatWithOptions({colors:jt.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${jt.Colours.grey}${d}${jt.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 mm(){return new gm}var ym=class extends Ys{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=Ia.env.NODE_DEBUG??"";Ia.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function rM(t){return new ym(t)}var _m=class extends Ys{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??wr.LogSeverity.INFO,i=Object.assign({severity:s,message:lv.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function oM(t){return new _m(t)}Le.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var bm=new Map,gn;function sM(t){gn=t,bm.clear()}function dv(t,e){if(!gn&&!Ia.env[Le.env.nodeEnables]||!t)return Le.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=bm.get(t);if(n)return n.func;if(gn===null)return Le.placeholder;gn===void 0&&(gn=mm());let r=(()=>{let o;return new Fa(t,(i,...a)=>{if(o!==gn){if(gn===null)return;gn===void 0&&(gn=mm()),o=gn}gn?.log(t,i,...a)})})();return bm.set(t,r),r.func}});var Cm=G(Ko=>{"use strict";var iM=Ko&&Ko.__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]})),aM=Ko&&Ko.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&iM(e,t,n)};Object.defineProperty(Ko,"__esModule",{value:!0});aM(fv(),Ko)});var Ma=G(fe=>{"use strict";var hv=fe&&fe.__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=fe&&fe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),uM=fe&&fe.__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"&&hv(n,e,r[o]);return cM(n,e),n}})(),lM=fe&&fe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&hv(e,t,n)};Object.defineProperty(fe,"__esModule",{value:!0});fe.gcpResidencyCache=fe.METADATA_SERVER_DETECTION=fe.HEADERS=fe.HEADER_VALUE=fe.HEADER_NAME=fe.SECONDARY_HOST_ADDRESS=fe.HOST_ADDRESS=fe.BASE_PATH=void 0;fe.instance=mM;fe.project=yM;fe.universe=_M;fe.bulk=bM;fe.isAvailable=wM;fe.resetIsAvailableCache=kM;fe.getGCPResidency=Sm;fe.setGCPResidency=gv;fe.requestTimeout=mv;var wm=gt(),dM=ZE(),fM=hm(),pM=uM(Cm());fe.BASE_PATH="/computeMetadata/v1";fe.HOST_ADDRESS="http://169.254.169.254";fe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";fe.HEADER_NAME="Metadata-Flavor";fe.HEADER_VALUE="Google";fe.HEADERS=Object.freeze({[fe.HEADER_NAME]:fe.HEADER_VALUE});var pv=pM.log("gcp-metadata");fe.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 km(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||fe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(fe.BASE_PATH,t).href}function hM(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 Na(t,e={},n=3,r=!1){let o=new Headers(fe.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}`:(hM(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?gM:wm.request,u={url:`${km()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:mv()};pv.info("instance request %j",u);let d=await a(u);pv.info("instance metadata is %s",d.data);let f=d.headers.get(fe.HEADER_NAME);if(f!==fe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${fe.HEADER_NAME} header. Expected '${fe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return dM.parse(d.data)}catch{}return d.data}async function gM(t){let e={...t,url:t.url?.toString().replace(km(),km(fe.SECONDARY_HOST_ADDRESS))},n=(0,wm.request)(t),r=(0,wm.request)(e);return Promise.any([n,r])}function mM(t){return Na("instance",t)}function yM(t){return Na("project",t)}function _M(t){return Na("universe",t)}async function bM(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await Na(n),o=n.metadataKey;e[o]=r})())),e}function CM(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Hl;async function wM(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in fe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(fe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Sm();case"ping-only":}}try{return Hl===void 0&&(Hl=(async()=>{try{return await Na("instance",void 0,CM(),!(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 Hl}catch{return!1}}function kM(){Hl=void 0}fe.gcpResidencyCache=null;function Sm(){return fe.gcpResidencyCache===null&&gv(),fe.gcpResidencyCache}function gv(t=null){fe.gcpResidencyCache=t!==null?t:(0,fM.detectGCPResidency)()}function mv(){return Sm()?0:3e3}lM(hm(),fe)});var bv=G(zl=>{"use strict";zl.byteLength=AM;zl.toByteArray=vM;zl.fromByteArray=RM;var Wn=[],Zt=[],SM=typeof Uint8Array<"u"?Uint8Array:Array,Am="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Vo=0,yv=Am.length;Vo<yv;++Vo)Wn[Vo]=Am[Vo],Zt[Am.charCodeAt(Vo)]=Vo;var Vo,yv;Zt[45]=62;Zt[95]=63;function _v(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 AM(t){var e=_v(t),n=e[0],r=e[1];return(n+r)*3/4-r}function EM(t,e,n){return(e+n)*3/4-n}function vM(t){var e,n=_v(t),r=n[0],o=n[1],s=new SM(EM(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Zt[t.charCodeAt(u)]<<18|Zt[t.charCodeAt(u+1)]<<12|Zt[t.charCodeAt(u+2)]<<6|Zt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Zt[t.charCodeAt(u)]<<2|Zt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Zt[t.charCodeAt(u)]<<10|Zt[t.charCodeAt(u+1)]<<4|Zt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function TM(t){return Wn[t>>18&63]+Wn[t>>12&63]+Wn[t>>6&63]+Wn[t&63]}function xM(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(TM(r));return o.join("")}function RM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(xM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Wn[e>>2]+Wn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Wn[e>>10]+Wn[e>>4&63]+Wn[e<<2&63]+"=")),o.join("")}});var vm=G(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.fromArrayBufferToHex=DM;function DM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var Cv=G(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.BrowserCrypto=void 0;var Xs=bv(),OM=vm(),Tm=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 Xs.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Xs.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=Xs.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 Xs.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Xs.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Xs.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,OM.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))}};Wl.BrowserCrypto=Tm});var wv=G(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});Gl.NodeCrypto=void 0;var Qs=require("crypto"),xm=class{async sha256DigestBase64(e){return Qs.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Qs.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Qs.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Qs.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 Qs.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:IM(e);return PM(Qs.createHmac("sha256",r).update(n).digest())}};Gl.NodeCrypto=xm;function PM(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 IM(t){return Buffer.from(t)}});var Ba=G(kr=>{"use strict";var FM=kr&&kr.__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]})),NM=kr&&kr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&FM(e,t,n)};Object.defineProperty(kr,"__esModule",{value:!0});kr.createCrypto=UM;kr.hasBrowserCrypto=kv;var MM=Cv(),BM=wv();NM(vm(),kr);function UM(){return kv()?new MM.BrowserCrypto:new BM.NodeCrypto}function kv(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Zs=G((Rm,Av)=>{var Jl=require("buffer"),Gn=Jl.Buffer;function Sv(t,e){for(var n in t)e[n]=t[n]}Gn.from&&Gn.alloc&&Gn.allocUnsafe&&Gn.allocUnsafeSlow?Av.exports=Jl:(Sv(Jl,Rm),Rm.Buffer=Yo);function Yo(t,e,n){return Gn(t,e,n)}Yo.prototype=Object.create(Gn.prototype);Sv(Gn,Yo);Yo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Gn(t,e,n)};Yo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=Gn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Yo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Gn(t)};Yo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Jl.SlowBuffer(t)}});var vv=G((U8,Ev)=>{"use strict";function Dm(t){var e=(t/8|0)+(t%8===0?0:1);return e}var jM={ES256:Dm(256),ES384:Dm(384),ES512:Dm(521)};function LM(t){var e=jM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}Ev.exports=LM});var Om=G((j8,Pv)=>{"use strict";var Kl=Zs().Buffer,xv=vv(),Vl=128,Rv=0,$M=32,qM=16,HM=2,Dv=qM|$M|Rv<<6,Yl=HM|Rv<<6;function zM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Ov(t){if(Kl.isBuffer(t))return t;if(typeof t=="string")return Kl.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function WM(t,e){t=Ov(t);var n=xv(e),r=n+1,o=t.length,s=0;if(t[s++]!==Dv)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(Vl|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==Yl)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++]!==Yl)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=Kl.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=zM(g),g}function Tv(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Vl;return o&&--r,r}function GM(t,e){t=Ov(t);var n=xv(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=Tv(t,0,n),s=Tv(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<Vl,f=Kl.allocUnsafe((d?2:3)+u),p=0;return f[p++]=Dv,d?f[p++]=u:(f[p++]=Vl|1,f[p++]=u&255),f[p++]=Yl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Yl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}Pv.exports={derToJose:WM,joseToDer:GM}});var mn=G(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.LRUCache=void 0;Sr.snakeToCamel=Fv;Sr.originalOrCamelOptions=YM;Sr.removeUndefinedValuesInObject=XM;Sr.isValidFile=QM;Sr.getWellKnownCertificateConfigFileLocation=ZM;var JM=require("fs"),KM=require("os"),Pm=require("path"),VM="certificate_config.json",Iv="gcloud";function Fv(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function YM(t){function e(n){let r=t||{};return r[n]??r[Fv(n)]}return{get:e}}var Im=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()}};Sr.LRUCache=Im;function XM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function QM(t){try{return(await JM.promises.lstat(t)).isFile()}catch{return!1}}function ZM(){let t=process.env.CLOUDSDK_CONFIG||(eB()?Pm.join(process.env.APPDATA||"",Iv):Pm.join(process.env.HOME||"",".config",Iv));return Pm.join(t,VM)}function eB(){return KM.platform().startsWith("win")}});var Nv=G(($8,tB)=>{tB.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 Fm=G(no=>{"use strict";Object.defineProperty(no,"__esModule",{value:!0});no.USER_AGENT=no.PRODUCT_NAME=no.pkg=void 0;var Mv=Nv();no.pkg=Mv;var Bv="google-api-nodejs-client";no.PRODUCT_NAME=Bv;var nB=`${Bv}/${Mv.version}`;no.USER_AGENT=nB});var Lt=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.AuthClient=yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=yn.DEFAULT_UNIVERSE=void 0;var rB=require("events"),Nm=gt(),oB=mn(),sB=Cm(),Mm=Fm();yn.DEFAULT_UNIVERSE="googleapis.com";yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var Bm=class t extends rB.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=yn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=yn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,oB.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")??yn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Nm.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&&Nm.Gaxios.mergeHeaders(s,n.headers),r&&Nm.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,sB.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(`${Mm.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Mm.USER_AGENT}`):e.headers.set("User-Agent",Mm.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"]}}}};yn.AuthClient=Bm});var jm=G(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});Xl.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()}}};Xl.LoginTicket=Um});var ro=G(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.OAuth2Client=Jn.ClientAuthentication=Jn.CertificateFormat=Jn.CodeChallengeMethod=void 0;var Uv=gt(),iB=require("querystring"),aB=require("stream"),cB=Om(),jv=mn(),Lm=Ba(),ei=Lt(),uB=jm(),Lv;(function(t){t.Plain="plain",t.S256="S256"})(Lv||(Jn.CodeChallengeMethod=Lv={}));var Ar;(function(t){t.PEM="PEM",t.JWK="JWK"})(Ar||(Jn.CertificateFormat=Ar={}));var Ua;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(Ua||(Jn.ClientAuthentication=Ua={}));var $m=class t extends ei.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=Ar.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||Ua.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()+"?"+iB.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,Lm.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===Ua.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===Ua.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,jv.removeUndefinedValuesInObject)(o)),headers:r};ei.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,jv.removeUndefinedValuesInObject)(r))};ei.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof Uv.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(ei.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=Uv.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 aB.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,Lm.hasBrowserCrypto)()?Ar.JWK:Ar.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case Ar.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case Ar.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};ei.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 Ar.PEM:a=r.data;break;case Ar.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};ei.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,Lm.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=cB.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 uB.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=$m});var Hm=G(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});Ql.Compute=void 0;var lB=gt(),$v=Ma(),dB=ro(),qm=class extends dB.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 $v.instance(o)}catch(o){throw o instanceof lB.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 $v.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))}};Ql.Compute=qm});var Wm=G(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});Zl.IdTokenClient=void 0;var fB=ro(),zm=class extends fB.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}};Zl.IdTokenClient=zm});var Gm=G(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.GCPEnv=void 0;ti.clear=pB;ti.getEnv=hB;var qv=Ma(),Kn;(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"})(Kn||(ti.GCPEnv=Kn={}));var ja;function pB(){ja=void 0}async function hB(){return ja||(ja=gB(),ja)}async function gB(){let t=Kn.NONE;return mB()?t=Kn.APP_ENGINE:yB()?t=Kn.CLOUD_FUNCTIONS:await wB()?await CB()?t=Kn.KUBERNETES_ENGINE:_B()?t=Kn.CLOUD_RUN:bB()?t=Kn.CLOUD_RUN_JOBS:t=Kn.COMPUTE_ENGINE:t=Kn.NONE,t}function mB(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function yB(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function _B(){return!!process.env.K_CONFIGURATION}function bB(){return!!process.env.CLOUD_RUN_JOB}async function CB(){try{return await qv.instance("attributes/cluster-name"),!0}catch{return!1}}async function wB(){return qv.isAvailable()}});var Jm=G((V8,Hv)=>{var ed=Zs().Buffer,kB=require("stream"),SB=require("util");function td(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=ed.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=ed.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+")")}SB.inherits(td,kB);td.prototype.write=function(e){this.buffer=ed.concat([this.buffer,ed.from(e)]),this.emit("data",e)};td.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};Hv.exports=td});var Wv=G((Y8,zv)=>{"use strict";var La=require("buffer").Buffer,Km=require("buffer").SlowBuffer;zv.exports=nd;function nd(t,e){if(!La.isBuffer(t)||!La.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}nd.install=function(){La.prototype.equal=Km.prototype.equal=function(e){return nd(this,e)}};var AB=La.prototype.equal,EB=Km.prototype.equal;nd.restore=function(){La.prototype.equal=AB,Km.prototype.equal=EB}});var Qm=G((X8,eT)=>{var ri=Zs().Buffer,en=require("crypto"),Jv=Om(),Gv=require("util"),vB=`"%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".`,La="secret must be a string or buffer",ti="key must be a string or a buffer",CB="key must be a string, a buffer or an object",Vm=typeof en.createPublicKey=="function";Vm&&(ti+=" or a KeyObject",La+="or a KeyObject");function zv(t){if(!ni.isBuffer(t)&&typeof t!="string"&&(!Vm||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw _n(ti)}function Wv(t){if(!ni.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw _n(CB)}function wB(t){if(!ni.isBuffer(t)){if(typeof t=="string")return t;if(!Vm||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw _n(La)}}function Ym(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 _n(t){var e=[].slice.call(arguments,1),n=qv.format.bind(qv,t).apply(null,e);return new TypeError(n)}function kB(t){return ni.isBuffer(t)||typeof t=="string"}function $a(t){return kB(t)||(t=JSON.stringify(t)),t}function Jv(t){return function(n,r){wB(r),n=$a(n);var o=en.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Ym(s)}}var Km,SB="timingSafeEqual"in en?function(e,n){return e.byteLength!==n.byteLength?!1:en.timingSafeEqual(e,n)}:function(e,n){return Km||(Km=$v()),Km(e,n)};function AB(t){return function(n,r,o){var s=Jv(t)(n,o);return SB(ni.from(r),ni.from(s))}}function Kv(t){return function(n,r){Wv(r),n=$a(n);var o=en.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Ym(s)}}function Vv(t){return function(n,r,o){zv(o),n=$a(n),r=Gv(r);var s=en.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function EB(t){return function(n,r){Wv(r),n=$a(n);var o=en.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:en.constants.RSA_PKCS1_PSS_PADDING,saltLength:en.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Ym(s)}}function vB(t){return function(n,r,o){zv(o),n=$a(n),r=Gv(r);var s=en.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:en.constants.RSA_PKCS1_PSS_PADDING,saltLength:en.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function TB(t){var e=Kv(t);return function(){var r=e.apply(null,arguments);return r=Hv.derToJose(r,"ES"+t),r}}function xB(t){var e=Vv(t);return function(r,o,s){o=Hv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function RB(){return function(){return""}}function DB(){return function(e,n){return n===""}}Yv.exports=function(e){var n={hs:Jv,rs:Kv,ps:EB,es:TB,none:RB},r={hs:AB,rs:Vv,ps:vB,es:xB,none:DB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw _n(bB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var Qm=G(($8,Xv)=>{var OB=require("buffer").Buffer;Xv.exports=function(e){return typeof e=="string"?e:typeof e=="number"||OB.isBuffer(e)?e.toString():JSON.stringify(e)}});var rT=G((q8,nT)=>{var PB=Qs().Buffer,Qv=Gm(),IB=Xm(),FB=require("stream"),Zv=Qm(),Zm=require("util");function eT(t,e){return PB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function NB(t,e,n){n=n||"utf8";var r=eT(Zv(t),"binary"),o=eT(Zv(e),n);return Zm.format("%s.%s",r,o)}function tT(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=IB(e.alg),i=NB(e,n,o),a=s.sign(i,r);return Zm.format("%s.%s",i,a)}function nd(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 Qv(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new Qv(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))}Zm.inherits(nd,FB);nd.prototype.sign=function(){try{var e=tT({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")}};nd.sign=tT;nT.exports=nd});var pT=G((H8,fT)=>{var sT=Qs().Buffer,oT=Gm(),MB=Xm(),BB=require("stream"),iT=Qm(),UB=require("util"),jB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function LB(t){return Object.prototype.toString.call(t)==="[object Object]"}function $B(t){if(LB(t))return t;try{return JSON.parse(t)}catch{return}}function aT(t){var e=t.split(".",1)[0];return $B(sT.from(e,"base64").toString("binary"))}function qB(t){return t.split(".",2).join(".")}function cT(t){return t.split(".")[2]}function HB(t,e){e=e||"utf8";var n=t.split(".")[1];return sT.from(n,"base64").toString(e)}function uT(t){return jB.test(t)&&!!aT(t)}function lT(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=iT(t);var o=cT(t),s=qB(t),i=MB(e);return i.verify(s,o,n)}function dT(t,e){if(e=e||{},t=iT(t),!uT(t))return null;var n=aT(t);if(!n)return null;var r=HB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:cT(t)}}function ri(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 oT(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new oT(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))}UB.inherits(ri,BB);ri.prototype.verify=function(){try{var e=lT(this.signature.buffer,this.algorithm,this.key.buffer),n=dT(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")}};ri.decode=dT;ri.isValid=uT;ri.verify=lT;fT.exports=ri});var ey=G(ro=>{var hT=rT(),rd=pT(),zB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];ro.ALGORITHMS=zB;ro.sign=hT.sign;ro.verify=rd.verify;ro.decode=rd.decode;ro.isValid=rd.isValid;ro.createSign=function(e){return new hT(e)};ro.createVerify=function(e){return new rd(e)}});var mT=G(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});od.buildPayloadForJwsSign=gT;od.getJwsSign=KB;var WB=ey(),GB="RS256",JB="https://oauth2.googleapis.com/token";function gT(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:JB,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function KB(t){let e=gT(t);return(0,WB.sign)({header:{alg:GB},payload:e,secret:t.key})}});var yT=G(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});ty.getToken=ZB;var VB=mT(),YB="https://oauth2.googleapis.com/token",XB="urn:ietf:params:oauth:grant-type:jwt-bearer",QB=t=>({method:"POST",url:YB,data:new URLSearchParams({grant_type:XB,assertion:(0,VB.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function ZB(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=QB(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 _T=G(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});sd.ErrorWithCode=void 0;var ny=class extends Error{code;constructor(e,n){super(e),this.code=n}};sd.ErrorWithCode=ny});var cy=G(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});ay.getCredentials=nU;var eU=require("path"),bT=require("fs"),tU=require("util"),id=_T(),CT=bT.readFile?(0,tU.promisify)(bT.readFile):async()=>{throw new id.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},oo;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(oo||(oo={}));var ry=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await CT(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 id.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},oy=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await CT(this.keyFilePath,"utf8")}}},sy=class{async getCredentials(){throw new id.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")}},iy=class{static create(e){switch(eU.extname(e)){case oo.JSON:return new ry(e);case oo.DER:case oo.CRT:case oo.PEM:return new oy(e);case oo.P12:case oo.PFX:return new sy;default:throw new id.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function nU(t){return iy.create(t).getCredentials()}});var wT=G(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});ad.TokenHandler=void 0;var rU=yT(),oU=cy(),uy=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,oU.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,rU.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}}};ad.TokenHandler=uy});var kT=G(ly=>{"use strict";Object.defineProperty(ly,"__esModule",{value:!0});ly.revokeToken=aU;var sU="https://oauth2.googleapis.com/revoke?token=",iU=!0;async function aU(t,e){let n=sU+t;return await e.request({url:n,retry:iU})}});var fy=G(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.GoogleToken=void 0;var cU=gt(),ST=wT(),uU=kT(),dy=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,cU.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 ST.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,uU.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new ST.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};cd.GoogleToken=dy});var hy=G(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.JWTAccess=void 0;var lU=ey(),dU=mn(),AT={alg:"RS256",typ:"JWT"},py=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new dU.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?{...AT,kid:this.keyId}:AT,p=Object.assign(d,n),h=lU.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)}})})}};ud.JWTAccess=py});var my=G(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});dd.JWT=void 0;var ET=fy(),fU=cy(),pU=hy(),hU=no(),ld=Lt(),gy=class t extends hU.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!==ld.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ld.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ld.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 pU.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!==ld.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 ET.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 ET.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,fU.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.")}};dd.JWT=gy});var _y=G(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.UserRefreshClient=oi.USER_REFRESH_ACCOUNT_TYPE=void 0;var gU=no(),mU=Lt();oi.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var yy=class t extends gU.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 mU.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}};oi.UserRefreshClient=yy});var Cy=G(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.Impersonated=si.IMPERSONATED_ACCOUNT_TYPE=void 0;var vT=no(),yU=gt(),_U=mn();si.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var by=class t extends vT.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 vT.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,_U.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 yU.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}};si.Impersonated=by});var ky=G(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.OAuthClientAuthHandler=void 0;qa.getErrorFromOAuthErrorResponse=wU;var ii=gt(),bU=Ma(),CU=["PUT","POST","PATCH"],wy=class{#e=(0,bU.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ii.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ii.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=ii.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=ii.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ii.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);ii.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!CU.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"]}}}};qa.OAuthClientAuthHandler=wy;function wU(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 pd=G(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.StsCredentials=void 0;var kU=gt(),SU=Lt(),TT=ky(),AU=mn(),Sy=class t extends TT.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,AU.removeUndefinedValuesInObject)(o)),responseType:"json"};SU.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 kU.GaxiosError&&i.response?(0,TT.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};fd.StsCredentials=Sy});var so=G(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.BaseExternalAccountClient=tn.CLOUD_RESOURCE_MANAGER=tn.EXTERNAL_ACCOUNT_TYPE=tn.EXPIRATION_TIME_OFFSET=void 0;var EU=gt(),vU=require("stream"),Ay=Lt(),TU=pd(),xT=mn(),xU=Im(),RU="urn:ietf:params:oauth:grant-type:token-exchange",DU="urn:ietf:params:oauth:token-type:access_token",Ey="https://www.googleapis.com/auth/cloud-platform",OU=3600;tn.EXPIRATION_TIME_OFFSET=300*1e3;tn.EXTERNAL_ACCOUNT_TYPE="external_account";tn.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var PU="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",IU="https://sts.{universeDomain}/v1/token",vy=class t extends Ay.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,xT.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==tn.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${tn.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")??IU.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,xT.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 TU.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Ey],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(PU);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=OU),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"};Ay.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=EU.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 vU.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:RU,audience:this.audience,requestedTokenType:DU,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Ey]: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"};Ay.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||[Ey]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${xU.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};tn.BaseExternalAccountClient=vy});var RT=G(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});hd.FileSubjectTokenSupplier=void 0;var xy=require("util"),Ry=require("fs"),FU=(0,xy.promisify)(Ry.readFile??(()=>{})),NU=(0,xy.promisify)(Ry.realpath??(()=>{})),MU=(0,xy.promisify)(Ry.lstat??(()=>{})),Ty=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 NU(e),!(await MU(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 FU(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}};hd.FileSubjectTokenSupplier=Ty});var DT=G(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.UrlSubjectTokenSupplier=void 0;var BU=Lt(),Dy=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};BU.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}};gd.UrlSubjectTokenSupplier=Dy});var OT=G($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.CertificateSubjectTokenSupplier=$t.InvalidConfigurationError=$t.CertificateSourceUnavailableError=$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var md=mn(),yd=require("fs"),_d=require("crypto"),UU=require("https");$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Vn=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};$t.CertificateSourceUnavailableError=Vn;var nn=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};$t.InvalidConfigurationError=nn;var Oy=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new nn("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new nn("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new nn("Cannot create mTLS Agent with missing certificate or key");return new UU.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,md.isValidFile)(e))return e;throw new Vn(`Provided certificate config path is invalid: ${e}`)}let n=process.env[$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,md.isValidFile)(n))return n;throw new Vn(`Path from environment variable "${$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,md.getWellKnownCertificateConfigFileLocation)();if(await(0,md.isValidFile)(r))return r;throw new Vn(`Could not find certificate configuration file. Searched override path, the "${$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await yd.promises.readFile(e,"utf8")}catch{throw new Vn(`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 nn(`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 nn?r:new nn(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await yd.promises.readFile(e),new _d.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Vn(`Failed to read certificate file at ${e}: ${i}`)}try{o=await yd.promises.readFile(n),(0,_d.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Vn(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new _d.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await yd.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new _d.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new nn(`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 nn(`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 nn)throw r;let o=r instanceof Error?r.message:String(r);throw new Vn(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};$t.CertificateSubjectTokenSupplier=Oy});var Fy=G(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});bd.IdentityPoolClient=void 0;var jU=so(),Py=mn(),LU=RT(),$U=DT(),PT=OT(),qU=pd(),IT=gt(),Iy=class t extends jU.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Py.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,Py.originalOrCamelOptions)(r),i=(0,Py.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 LU.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new $U.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new PT.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 PT.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new qU.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new IT.Gaxios({agent:n})}),this.transporter=new IT.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};bd.IdentityPoolClient=Iy});var My=G(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});wd.AwsRequestSigner=void 0;var Cd=gt(),NT=Ma(),FT="AWS4-HMAC-SHA256",HU="aws4_request",Ny=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,NT.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 WU({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=Cd.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&Cd.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}};wd.AwsRequestSigner=Ny;async function Ha(t,e,n){return await t.signWithHmacSha256(e,n)}async function zU(t,e,n,r,o){let s=await Ha(t,`AWS4${e}`,n),i=await Ha(t,s,r),a=await Ha(t,i,o);return await Ha(t,a,"aws4_request")}async function WU(t){let e=Cd.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=Cd.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".`,$a="secret must be a string or buffer",ni="key must be a string or a buffer",TB="key must be a string, a buffer or an object",Ym=typeof en.createPublicKey=="function";Ym&&(ni+=" or a KeyObject",$a+="or a KeyObject");function Kv(t){if(!ri.isBuffer(t)&&typeof t!="string"&&(!Ym||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw _n(ni)}function Vv(t){if(!ri.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw _n(TB)}function xB(t){if(!ri.isBuffer(t)){if(typeof t=="string")return t;if(!Ym||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw _n($a)}}function Xm(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function Yv(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 _n(t){var e=[].slice.call(arguments,1),n=Gv.format.bind(Gv,t).apply(null,e);return new TypeError(n)}function RB(t){return ri.isBuffer(t)||typeof t=="string"}function qa(t){return RB(t)||(t=JSON.stringify(t)),t}function Xv(t){return function(n,r){xB(r),n=qa(n);var o=en.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return Xm(s)}}var Vm,DB="timingSafeEqual"in en?function(e,n){return e.byteLength!==n.byteLength?!1:en.timingSafeEqual(e,n)}:function(e,n){return Vm||(Vm=Wv()),Vm(e,n)};function OB(t){return function(n,r,o){var s=Xv(t)(n,o);return DB(ri.from(r),ri.from(s))}}function Qv(t){return function(n,r){Vv(r),n=qa(n);var o=en.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return Xm(s)}}function Zv(t){return function(n,r,o){Kv(o),n=qa(n),r=Yv(r);var s=en.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function PB(t){return function(n,r){Vv(r),n=qa(n);var o=en.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:en.constants.RSA_PKCS1_PSS_PADDING,saltLength:en.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return Xm(s)}}function IB(t){return function(n,r,o){Kv(o),n=qa(n),r=Yv(r);var s=en.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:en.constants.RSA_PKCS1_PSS_PADDING,saltLength:en.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function FB(t){var e=Qv(t);return function(){var r=e.apply(null,arguments);return r=Jv.derToJose(r,"ES"+t),r}}function NB(t){var e=Zv(t);return function(r,o,s){o=Jv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function MB(){return function(){return""}}function BB(){return function(e,n){return n===""}}eT.exports=function(e){var n={hs:Xv,rs:Qv,ps:PB,es:FB,none:MB},r={hs:OB,rs:Zv,ps:IB,es:NB,none:BB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw _n(vB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var Zm=G((Q8,tT)=>{var UB=require("buffer").Buffer;tT.exports=function(e){return typeof e=="string"?e:typeof e=="number"||UB.isBuffer(e)?e.toString():JSON.stringify(e)}});var aT=G((Z8,iT)=>{var jB=Zs().Buffer,nT=Jm(),LB=Qm(),$B=require("stream"),rT=Zm(),ey=require("util");function oT(t,e){return jB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function qB(t,e,n){n=n||"utf8";var r=oT(rT(t),"binary"),o=oT(rT(e),n);return ey.format("%s.%s",r,o)}function sT(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=LB(e.alg),i=qB(e,n,o),a=s.sign(i,r);return ey.format("%s.%s",i,a)}function rd(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 nT(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new nT(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))}ey.inherits(rd,$B);rd.prototype.sign=function(){try{var e=sT({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")}};rd.sign=sT;iT.exports=rd});var yT=G((eW,mT)=>{var uT=Zs().Buffer,cT=Jm(),HB=Qm(),zB=require("stream"),lT=Zm(),WB=require("util"),GB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function JB(t){return Object.prototype.toString.call(t)==="[object Object]"}function KB(t){if(JB(t))return t;try{return JSON.parse(t)}catch{return}}function dT(t){var e=t.split(".",1)[0];return KB(uT.from(e,"base64").toString("binary"))}function VB(t){return t.split(".",2).join(".")}function fT(t){return t.split(".")[2]}function YB(t,e){e=e||"utf8";var n=t.split(".")[1];return uT.from(n,"base64").toString(e)}function pT(t){return GB.test(t)&&!!dT(t)}function hT(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=lT(t);var o=fT(t),s=VB(t),i=HB(e);return i.verify(s,o,n)}function gT(t,e){if(e=e||{},t=lT(t),!pT(t))return null;var n=dT(t);if(!n)return null;var r=YB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:fT(t)}}function oi(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 cT(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new cT(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))}WB.inherits(oi,zB);oi.prototype.verify=function(){try{var e=hT(this.signature.buffer,this.algorithm,this.key.buffer),n=gT(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")}};oi.decode=gT;oi.isValid=pT;oi.verify=hT;mT.exports=oi});var ty=G(oo=>{var _T=aT(),od=yT(),XB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];oo.ALGORITHMS=XB;oo.sign=_T.sign;oo.verify=od.verify;oo.decode=od.decode;oo.isValid=od.isValid;oo.createSign=function(e){return new _T(e)};oo.createVerify=function(e){return new od(e)}});var CT=G(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});sd.buildPayloadForJwsSign=bT;sd.getJwsSign=tU;var QB=ty(),ZB="RS256",eU="https://oauth2.googleapis.com/token";function bT(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:eU,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function tU(t){let e=bT(t);return(0,QB.sign)({header:{alg:ZB},payload:e,secret:t.key})}});var wT=G(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});ny.getToken=iU;var nU=CT(),rU="https://oauth2.googleapis.com/token",oU="urn:ietf:params:oauth:grant-type:jwt-bearer",sU=t=>({method:"POST",url:rU,data:new URLSearchParams({grant_type:oU,assertion:(0,nU.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function iU(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=sU(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 kT=G(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});id.ErrorWithCode=void 0;var ry=class extends Error{code;constructor(e,n){super(e),this.code=n}};id.ErrorWithCode=ry});var uy=G(cy=>{"use strict";Object.defineProperty(cy,"__esModule",{value:!0});cy.getCredentials=uU;var aU=require("path"),ST=require("fs"),cU=require("util"),ad=kT(),AT=ST.readFile?(0,cU.promisify)(ST.readFile):async()=>{throw new ad.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},so;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(so||(so={}));var oy=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await AT(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 ad.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},sy=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await AT(this.keyFilePath,"utf8")}}},iy=class{async getCredentials(){throw new ad.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")}},ay=class{static create(e){switch(aU.extname(e)){case so.JSON:return new oy(e);case so.DER:case so.CRT:case so.PEM:return new sy(e);case so.P12:case so.PFX:return new iy;default:throw new ad.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function uU(t){return ay.create(t).getCredentials()}});var ET=G(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});cd.TokenHandler=void 0;var lU=wT(),dU=uy(),ly=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,dU.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,lU.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}}};cd.TokenHandler=ly});var vT=G(dy=>{"use strict";Object.defineProperty(dy,"__esModule",{value:!0});dy.revokeToken=hU;var fU="https://oauth2.googleapis.com/revoke?token=",pU=!0;async function hU(t,e){let n=fU+t;return await e.request({url:n,retry:pU})}});var py=G(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.GoogleToken=void 0;var gU=gt(),TT=ET(),mU=vT(),fy=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,gU.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 TT.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,mU.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new TT.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};ud.GoogleToken=fy});var gy=G(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.JWTAccess=void 0;var yU=ty(),_U=mn(),xT={alg:"RS256",typ:"JWT"},hy=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new _U.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?{...xT,kid:this.keyId}:xT,p=Object.assign(d,n),h=yU.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)}})})}};ld.JWTAccess=hy});var yy=G(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.JWT=void 0;var RT=py(),bU=uy(),CU=gy(),wU=ro(),dd=Lt(),my=class t extends wU.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!==dd.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==dd.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${dd.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 CU.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!==dd.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 RT.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 RT.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,bU.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.")}};fd.JWT=my});var by=G(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.UserRefreshClient=si.USER_REFRESH_ACCOUNT_TYPE=void 0;var kU=ro(),SU=Lt();si.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var _y=class t extends kU.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 SU.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}};si.UserRefreshClient=_y});var wy=G(ii=>{"use strict";Object.defineProperty(ii,"__esModule",{value:!0});ii.Impersonated=ii.IMPERSONATED_ACCOUNT_TYPE=void 0;var DT=ro(),AU=gt(),EU=mn();ii.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Cy=class t extends DT.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 DT.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,EU.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 AU.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}};ii.Impersonated=Cy});var Sy=G(Ha=>{"use strict";Object.defineProperty(Ha,"__esModule",{value:!0});Ha.OAuthClientAuthHandler=void 0;Ha.getErrorFromOAuthErrorResponse=xU;var ai=gt(),vU=Ba(),TU=["PUT","POST","PATCH"],ky=class{#e=(0,vU.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new ai.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new ai.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=ai.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=ai.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=ai.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);ai.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!TU.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"]}}}};Ha.OAuthClientAuthHandler=ky;function xU(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 hd=G(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.StsCredentials=void 0;var RU=gt(),DU=Lt(),OT=Sy(),OU=mn(),Ay=class t extends OT.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,OU.removeUndefinedValuesInObject)(o)),responseType:"json"};DU.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 RU.GaxiosError&&i.response?(0,OT.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};pd.StsCredentials=Ay});var io=G(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.BaseExternalAccountClient=tn.CLOUD_RESOURCE_MANAGER=tn.EXTERNAL_ACCOUNT_TYPE=tn.EXPIRATION_TIME_OFFSET=void 0;var PU=gt(),IU=require("stream"),Ey=Lt(),FU=hd(),PT=mn(),NU=Fm(),MU="urn:ietf:params:oauth:grant-type:token-exchange",BU="urn:ietf:params:oauth:token-type:access_token",vy="https://www.googleapis.com/auth/cloud-platform",UU=3600;tn.EXPIRATION_TIME_OFFSET=300*1e3;tn.EXTERNAL_ACCOUNT_TYPE="external_account";tn.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var jU="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",LU="https://sts.{universeDomain}/v1/token",Ty=class t extends Ey.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,PT.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==tn.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${tn.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")??LU.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,PT.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 FU.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[vy],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(jU);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=UU),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"};Ey.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=PU.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 IU.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:MU,audience:this.audience,requestedTokenType:BU,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[vy]: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"};Ey.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||[vy]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${NU.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};tn.BaseExternalAccountClient=Ty});var IT=G(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.FileSubjectTokenSupplier=void 0;var Ry=require("util"),Dy=require("fs"),$U=(0,Ry.promisify)(Dy.readFile??(()=>{})),qU=(0,Ry.promisify)(Dy.realpath??(()=>{})),HU=(0,Ry.promisify)(Dy.lstat??(()=>{})),xy=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 qU(e),!(await HU(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 $U(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}};gd.FileSubjectTokenSupplier=xy});var FT=G(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});md.UrlSubjectTokenSupplier=void 0;var zU=Lt(),Oy=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};zU.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}};md.UrlSubjectTokenSupplier=Oy});var NT=G($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.CertificateSubjectTokenSupplier=$t.InvalidConfigurationError=$t.CertificateSourceUnavailableError=$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var yd=mn(),_d=require("fs"),bd=require("crypto"),WU=require("https");$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var Vn=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};$t.CertificateSourceUnavailableError=Vn;var nn=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};$t.InvalidConfigurationError=nn;var Py=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new nn("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new nn("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new nn("Cannot create mTLS Agent with missing certificate or key");return new WU.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,yd.isValidFile)(e))return e;throw new Vn(`Provided certificate config path is invalid: ${e}`)}let n=process.env[$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,yd.isValidFile)(n))return n;throw new Vn(`Path from environment variable "${$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,yd.getWellKnownCertificateConfigFileLocation)();if(await(0,yd.isValidFile)(r))return r;throw new Vn(`Could not find certificate configuration file. Searched override path, the "${$t.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await _d.promises.readFile(e,"utf8")}catch{throw new Vn(`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 nn(`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 nn?r:new nn(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await _d.promises.readFile(e),new bd.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Vn(`Failed to read certificate file at ${e}: ${i}`)}try{o=await _d.promises.readFile(n),(0,bd.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Vn(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new bd.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await _d.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new bd.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new nn(`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 nn(`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 nn)throw r;let o=r instanceof Error?r.message:String(r);throw new Vn(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};$t.CertificateSubjectTokenSupplier=Py});var Ny=G(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.IdentityPoolClient=void 0;var GU=io(),Iy=mn(),JU=IT(),KU=FT(),MT=NT(),VU=hd(),BT=gt(),Fy=class t extends GU.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Iy.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,Iy.originalOrCamelOptions)(r),i=(0,Iy.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 JU.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new KU.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new MT.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 MT.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new VU.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new BT.Gaxios({agent:n})}),this.transporter=new BT.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Cd.IdentityPoolClient=Fy});var By=G(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});kd.AwsRequestSigner=void 0;var wd=gt(),jT=Ba(),UT="AWS4-HMAC-SHA256",YU="aws4_request",My=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,jT.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 QU({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=wd.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&wd.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}};kd.AwsRequestSigner=My;async function za(t,e,n){return await t.signWithHmacSha256(e,n)}async function XU(t,e,n,r,o){let s=await za(t,`AWS4${e}`,n),i=await za(t,s,r),a=await za(t,i,o);return await za(t,a,"aws4_request")}async function QU(t){let e=wd.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=wd.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)}
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}/${HU}`,b=`${FT}
109
+ ${p}`,g=`${i}/${t.region}/${r}/${YU}`,b=`${UT}
110
110
  ${s}
111
111
  ${g}
112
- `+await t.crypto.sha256DigestHex(h),m=await zU(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),w=await Ha(t.crypto,m,b),C=`${FT} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,NT.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:C,canonicalQuerystring:t.canonicalQuerystring}}});var MT=G(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});Sd.DefaultAwsSecurityCredentialsSupplier=void 0;var kd=Lt(),By=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};kd.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 kd.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 kd.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 kd.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}};Sd.DefaultAwsSecurityCredentialsSupplier=By});var jy=G(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.AwsClient=void 0;var GU=My(),JU=so(),KU=MT(),BT=mn(),VU=gt(),Uy=class t extends JU.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,BT.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,BT.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 KU.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 GU.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 VU.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}))}};Ad.AwsClient=Uy});var zy=G(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.InvalidSubjectTokenError=et.InvalidMessageFieldError=et.InvalidCodeFieldError=et.InvalidTokenTypeFieldError=et.InvalidExpirationTimeFieldError=et.InvalidSuccessFieldError=et.InvalidVersionFieldError=et.ExecutableResponseError=et.ExecutableResponse=void 0;var Ed="urn:ietf:params:oauth:token-type:saml2",Ly="urn:ietf:params:oauth:token-type:id_token",$y="urn:ietf:params:oauth:token-type:jwt",qy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new vd("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Td("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!==Ed&&this.tokenType!==Ly&&this.tokenType!==$y)throw new xd(`Executable response must contain a 'token_type' field when successful and it must be one of ${Ly}, ${$y}, or ${Ed}.`);if(this.tokenType===Ed){if(!e.saml_response)throw new za(`Executable response must contain a 'saml_response' field when token_type=${Ed}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new za(`Executable response must contain a 'id_token' field when token_type=${Ly} or ${$y}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Rd("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Dd("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)}};et.ExecutableResponse=qy;var Yn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};et.ExecutableResponseError=Yn;var vd=class extends Yn{};et.InvalidVersionFieldError=vd;var Td=class extends Yn{};et.InvalidSuccessFieldError=Td;var Hy=class extends Yn{};et.InvalidExpirationTimeFieldError=Hy;var xd=class extends Yn{};et.InvalidTokenTypeFieldError=xd;var Rd=class extends Yn{};et.InvalidCodeFieldError=Rd;var Dd=class extends Yn{};et.InvalidMessageFieldError=Dd;var za=class extends Yn{};et.InvalidSubjectTokenError=za});var Jy=G(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.PluggableAuthHandler=ai.ExecutableError=void 0;var Yo=zy(),YU=require("child_process"),Wy=require("fs"),Od=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)}};ai.ExecutableError=Od;var Gy=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=YU.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 Yo.ExecutableResponse(u);return n(d)}catch(u){return u instanceof Yo.ExecutableResponseError?r(u):r(new Yo.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Od(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Wy.promises.realpath(this.outputFile)}catch{return}if(!(await Wy.promises.lstat(e)).isFile())return;let n=await Wy.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Yo.ExecutableResponse(r).isValid()?new Yo.ExecutableResponse(r):void 0}catch(r){throw r instanceof Yo.ExecutableResponseError?r:new Yo.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}};ai.PluggableAuthHandler=Gy});var Vy=G(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.PluggableAuthClient=ci.ExecutableError=void 0;var XU=so(),QU=zy(),UT=Jy(),ZU=Jy();Object.defineProperty(ci,"ExecutableError",{enumerable:!0,get:function(){return ZU.ExecutableError}});var ej=30*1e3,jT=5*1e3,LT=120*1e3,tj="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",$T=1,Ky=class extends XU.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=ej;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<jT||this.timeoutMillis>LT)throw new Error(`Timeout must be between ${jT} and ${LT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new UT.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[tj]!=="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>$T)throw new Error(`Version of executable is not currently supported, maximum supported version is ${$T}.`);if(!e.success)throw new UT.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new QU.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}};ci.PluggableAuthClient=Ky});var Xy=G(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.ExternalAccountClient=void 0;var nj=so(),rj=Fy(),oj=jy(),sj=Vy(),Yy=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===nj.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new oj.AwsClient(e):e.credential_source?.executable?new sj.PluggableAuthClient(e):new rj.IdentityPoolClient(e):null}};Pd.ExternalAccountClient=Yy});var e_=G(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.ExternalAccountAuthorizedUserClient=ui.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var HT=Lt(),qT=ky(),zT=gt(),ij=require("stream"),aj=so();ui.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var cj="https://sts.{universeDomain}/v1/oauthtoken",Qy=class t extends qT.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"};HT.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 zT.GaxiosError&&o.response?(0,qT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Zy=class extends HT.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 Qy({tokenRefreshEndpoint:e.token_url??cj.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=aj.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=zT.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 ij.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}};ui.ExternalAccountAuthorizedUserClient=Zy});var n_=G(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.GdchClient=io.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var uj=require("crypto"),lj=require("fs"),dj=require("https"),fj=no(),pj=3600;io.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var t_=class t extends fj.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||pj,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!==io.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${io.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=uj.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 lj.promises.readFile(r);return new dj.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")}};io.GdchClient=t_});var KT=G(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.GoogleAuth=bn.GoogleAuthExceptionMessages=void 0;var hj=require("child_process"),Wa=require("fs"),gj=gt(),Ga=Na(),mj=require("os"),Id=require("path"),yj=Ma(),_j=qm(),bj=zm(),Cj=Wm(),li=my(),WT=_y(),di=Cy(),wj=Xy(),Ja=so(),r_=Lt(),GT=e_(),o_=n_(),JT=mn();bn.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 XU(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),w=await za(t.crypto,m,b),C=`${UT} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,jT.fromArrayBufferToHex)(w)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:C,canonicalQuerystring:t.canonicalQuerystring}}});var LT=G(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});Ad.DefaultAwsSecurityCredentialsSupplier=void 0;var Sd=Lt(),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};Sd.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 Sd.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 Sd.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 Sd.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}};Ad.DefaultAwsSecurityCredentialsSupplier=Uy});var Ly=G(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});Ed.AwsClient=void 0;var ZU=By(),ej=io(),tj=LT(),$T=mn(),nj=gt(),jy=class t extends ej.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,$T.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,$T.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 tj.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 ZU.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 nj.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}))}};Ed.AwsClient=jy});var Wy=G(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.InvalidSubjectTokenError=et.InvalidMessageFieldError=et.InvalidCodeFieldError=et.InvalidTokenTypeFieldError=et.InvalidExpirationTimeFieldError=et.InvalidSuccessFieldError=et.InvalidVersionFieldError=et.ExecutableResponseError=et.ExecutableResponse=void 0;var vd="urn:ietf:params:oauth:token-type:saml2",$y="urn:ietf:params:oauth:token-type:id_token",qy="urn:ietf:params:oauth:token-type:jwt",Hy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Td("Executable response must contain a 'version' field.");if(e.success===void 0)throw new xd("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!==vd&&this.tokenType!==$y&&this.tokenType!==qy)throw new Rd(`Executable response must contain a 'token_type' field when successful and it must be one of ${$y}, ${qy}, or ${vd}.`);if(this.tokenType===vd){if(!e.saml_response)throw new Wa(`Executable response must contain a 'saml_response' field when token_type=${vd}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Wa(`Executable response must contain a 'id_token' field when token_type=${$y} or ${qy}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new Dd("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new Od("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)}};et.ExecutableResponse=Hy;var Yn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};et.ExecutableResponseError=Yn;var Td=class extends Yn{};et.InvalidVersionFieldError=Td;var xd=class extends Yn{};et.InvalidSuccessFieldError=xd;var zy=class extends Yn{};et.InvalidExpirationTimeFieldError=zy;var Rd=class extends Yn{};et.InvalidTokenTypeFieldError=Rd;var Dd=class extends Yn{};et.InvalidCodeFieldError=Dd;var Od=class extends Yn{};et.InvalidMessageFieldError=Od;var Wa=class extends Yn{};et.InvalidSubjectTokenError=Wa});var Ky=G(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.PluggableAuthHandler=ci.ExecutableError=void 0;var Xo=Wy(),rj=require("child_process"),Gy=require("fs"),Pd=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)}};ci.ExecutableError=Pd;var Jy=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=rj.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 Xo.ExecutableResponse(u);return n(d)}catch(u){return u instanceof Xo.ExecutableResponseError?r(u):r(new Xo.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new Pd(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await Gy.promises.realpath(this.outputFile)}catch{return}if(!(await Gy.promises.lstat(e)).isFile())return;let n=await Gy.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new Xo.ExecutableResponse(r).isValid()?new Xo.ExecutableResponse(r):void 0}catch(r){throw r instanceof Xo.ExecutableResponseError?r:new Xo.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}};ci.PluggableAuthHandler=Jy});var Yy=G(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.PluggableAuthClient=ui.ExecutableError=void 0;var oj=io(),sj=Wy(),qT=Ky(),ij=Ky();Object.defineProperty(ui,"ExecutableError",{enumerable:!0,get:function(){return ij.ExecutableError}});var aj=30*1e3,HT=5*1e3,zT=120*1e3,cj="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",WT=1,Vy=class extends oj.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=aj;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<HT||this.timeoutMillis>zT)throw new Error(`Timeout must be between ${HT} and ${zT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new qT.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[cj]!=="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>WT)throw new Error(`Version of executable is not currently supported, maximum supported version is ${WT}.`);if(!e.success)throw new qT.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new sj.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}};ui.PluggableAuthClient=Vy});var Qy=G(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});Id.ExternalAccountClient=void 0;var uj=io(),lj=Ny(),dj=Ly(),fj=Yy(),Xy=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===uj.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new dj.AwsClient(e):e.credential_source?.executable?new fj.PluggableAuthClient(e):new lj.IdentityPoolClient(e):null}};Id.ExternalAccountClient=Xy});var t_=G(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.ExternalAccountAuthorizedUserClient=li.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var JT=Lt(),GT=Sy(),KT=gt(),pj=require("stream"),hj=io();li.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var gj="https://sts.{universeDomain}/v1/oauthtoken",Zy=class t extends GT.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"};JT.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 KT.GaxiosError&&o.response?(0,GT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},e_=class extends JT.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 Zy({tokenRefreshEndpoint:e.token_url??gj.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=hj.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=KT.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 pj.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}};li.ExternalAccountAuthorizedUserClient=e_});var r_=G(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.GdchClient=ao.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var mj=require("crypto"),yj=require("fs"),_j=require("https"),bj=ro(),Cj=3600;ao.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var n_=class t extends bj.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||Cj,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!==ao.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${ao.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=mj.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 yj.promises.readFile(r);return new _j.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")}};ao.GdchClient=n_});var QT=G(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.GoogleAuth=bn.GoogleAuthExceptionMessages=void 0;var wj=require("child_process"),Ga=require("fs"),kj=gt(),Ja=Ma(),Sj=require("os"),Fd=require("path"),Aj=Ba(),Ej=Hm(),vj=Wm(),Tj=Gm(),di=yy(),VT=by(),fi=wy(),xj=Qy(),Ka=io(),o_=Lt(),YT=t_(),s_=r_(),XT=mn();bn.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 s_=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(bn.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===bn.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(bn.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 Ga.universe("universe-domain"),e||=r_.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=r_.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,JT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=r_.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 li.JWT?n.scopes=this.scopes:n instanceof Ja.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof li.JWT?n.scopes=this.scopes:n instanceof Ja.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new _j.Compute(e));throw new Error(bn.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=Ga.getGCPResidency()||await Ga.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=Id.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=Id.join(s,".config","gcloud"))}if(!n)return null;let r=Id.join(n,"application_default_credentials.json");return Wa.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=Wa.realpathSync(e),!Wa.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=Wa.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!==di.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${di.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 di.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,JT.originalOrCamelOptions)(n).get("universe_domain");return e.type===WT.USER_REFRESH_ACCOUNT_TYPE?(r=new WT.UserRefreshClient(n),r.fromJSON(e)):e.type===di.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ja.EXTERNAL_ACCOUNT_TYPE?(r=wj.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===GT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new GT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===o_.GDCH_SERVICE_ACCOUNT_TYPE?(r=new o_.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new li.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 li.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 li.JWT({...n,apiKey:e})}_isWindows(){let e=mj.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,hj.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!==Ja.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ga.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 di.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ja.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([Ga.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(bn.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 o_.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=Id.resolve(this.keyFilename),n=Wa.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 bj.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=gj.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,Cj.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 di.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,yj.createCrypto)();if(r instanceof li.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}};bn.GoogleAuth=s_});var VT=G(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});Fd.IAMAuth=void 0;var i_=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}}};Fd.IAMAuth=i_});var YT=G(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.DownscopedClient=Xn.EXPIRATION_TIME_OFFSET=Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var kj=gt(),Sj=require("stream"),a_=Lt(),Aj=pd(),Ej="urn:ietf:params:oauth:grant-type:token-exchange",vj="urn:ietf:params:oauth:token-type:access_token",Tj="urn:ietf:params:oauth:token-type:access_token";Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Xn.EXPIRATION_TIME_OFFSET=300*1e3;var c_=class extends a_.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof a_.AuthClient?{}:e),e instanceof a_.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>Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Xn.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 Aj.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=kj.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 Sj.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:Ej,requestedTokenType:vj,subjectToken:e,subjectTokenType:Tj},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}};Xn.DownscopedClient=c_});var XT=G(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.PassThroughClient=void 0;var xj=Lt(),u_=class extends xj.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Nd.PassThroughClient=u_});var Md=G(re=>{"use strict";var Rj=re&&re.__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]})),Dj=re&&re.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Rj(e,t,n)};Object.defineProperty(re,"__esModule",{value:!0});re.GoogleAuth=re.auth=re.GDCH_SERVICE_ACCOUNT_TYPE=re.GdchClient=re.PassThroughClient=re.ExternalAccountAuthorizedUserClient=re.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=re.ExecutableError=re.PluggableAuthClient=re.DownscopedClient=re.BaseExternalAccountClient=re.ExternalAccountClient=re.IdentityPoolClient=re.AwsRequestSigner=re.AwsClient=re.UserRefreshClient=re.LoginTicket=re.ClientAuthentication=re.OAuth2Client=re.CodeChallengeMethod=re.Impersonated=re.JWT=re.JWTAccess=re.IdTokenClient=re.IAMAuth=re.GCPEnv=re.Compute=re.DEFAULT_UNIVERSE=re.AuthClient=re.gaxios=re.gcpMetadata=void 0;var QT=KT();Object.defineProperty(re,"GoogleAuth",{enumerable:!0,get:function(){return QT.GoogleAuth}});re.gcpMetadata=Na();re.gaxios=gt();var ZT=Lt();Object.defineProperty(re,"AuthClient",{enumerable:!0,get:function(){return ZT.AuthClient}});Object.defineProperty(re,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return ZT.DEFAULT_UNIVERSE}});var Oj=qm();Object.defineProperty(re,"Compute",{enumerable:!0,get:function(){return Oj.Compute}});var Pj=Wm();Object.defineProperty(re,"GCPEnv",{enumerable:!0,get:function(){return Pj.GCPEnv}});var Ij=VT();Object.defineProperty(re,"IAMAuth",{enumerable:!0,get:function(){return Ij.IAMAuth}});var Fj=zm();Object.defineProperty(re,"IdTokenClient",{enumerable:!0,get:function(){return Fj.IdTokenClient}});var Nj=hy();Object.defineProperty(re,"JWTAccess",{enumerable:!0,get:function(){return Nj.JWTAccess}});var Mj=my();Object.defineProperty(re,"JWT",{enumerable:!0,get:function(){return Mj.JWT}});var Bj=Cy();Object.defineProperty(re,"Impersonated",{enumerable:!0,get:function(){return Bj.Impersonated}});var l_=no();Object.defineProperty(re,"CodeChallengeMethod",{enumerable:!0,get:function(){return l_.CodeChallengeMethod}});Object.defineProperty(re,"OAuth2Client",{enumerable:!0,get:function(){return l_.OAuth2Client}});Object.defineProperty(re,"ClientAuthentication",{enumerable:!0,get:function(){return l_.ClientAuthentication}});var Uj=Um();Object.defineProperty(re,"LoginTicket",{enumerable:!0,get:function(){return Uj.LoginTicket}});var jj=_y();Object.defineProperty(re,"UserRefreshClient",{enumerable:!0,get:function(){return jj.UserRefreshClient}});var Lj=jy();Object.defineProperty(re,"AwsClient",{enumerable:!0,get:function(){return Lj.AwsClient}});var $j=My();Object.defineProperty(re,"AwsRequestSigner",{enumerable:!0,get:function(){return $j.AwsRequestSigner}});var qj=Fy();Object.defineProperty(re,"IdentityPoolClient",{enumerable:!0,get:function(){return qj.IdentityPoolClient}});var Hj=Xy();Object.defineProperty(re,"ExternalAccountClient",{enumerable:!0,get:function(){return Hj.ExternalAccountClient}});var zj=so();Object.defineProperty(re,"BaseExternalAccountClient",{enumerable:!0,get:function(){return zj.BaseExternalAccountClient}});var Wj=YT();Object.defineProperty(re,"DownscopedClient",{enumerable:!0,get:function(){return Wj.DownscopedClient}});var ex=Vy();Object.defineProperty(re,"PluggableAuthClient",{enumerable:!0,get:function(){return ex.PluggableAuthClient}});Object.defineProperty(re,"ExecutableError",{enumerable:!0,get:function(){return ex.ExecutableError}});var tx=e_();Object.defineProperty(re,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return tx.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(re,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return tx.ExternalAccountAuthorizedUserClient}});var Gj=XT();Object.defineProperty(re,"PassThroughClient",{enumerable:!0,get:function(){return Gj.PassThroughClient}});var nx=n_();Object.defineProperty(re,"GdchClient",{enumerable:!0,get:function(){return nx.GdchClient}});Object.defineProperty(re,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return nx.GDCH_SERVICE_ACCOUNT_TYPE}});Dj(fy(),re);var Jj=new QT.GoogleAuth;re.auth=Jj});var dc,k0=Wr(()=>{"use strict";dc=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 i_=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(bn.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===bn.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(bn.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 Ja.universe("universe-domain"),e||=o_.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=o_.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,XT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=o_.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 di.JWT?n.scopes=this.scopes:n instanceof Ka.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof di.JWT?n.scopes=this.scopes:n instanceof Ka.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new Ej.Compute(e));throw new Error(bn.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=Ja.getGCPResidency()||await Ja.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 Ga.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=Ga.realpathSync(e),!Ga.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=Ga.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!==fi.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${fi.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 fi.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,XT.originalOrCamelOptions)(n).get("universe_domain");return e.type===VT.USER_REFRESH_ACCOUNT_TYPE?(r=new VT.UserRefreshClient(n),r.fromJSON(e)):e.type===fi.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===Ka.EXTERNAL_ACCOUNT_TYPE?(r=xj.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===YT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new YT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===s_.GDCH_SERVICE_ACCOUNT_TYPE?(r=new s_.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new di.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 di.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 di.JWT({...n,apiKey:e})}_isWindows(){let e=Sj.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,wj.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!==Ka.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ja.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 fi.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof Ka.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([Ja.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(bn.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 s_.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=Ga.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 vj.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=kj.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,Tj.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 fi.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,Aj.createCrypto)();if(r instanceof di.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}};bn.GoogleAuth=i_});var ZT=G(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});Nd.IAMAuth=void 0;var a_=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}}};Nd.IAMAuth=a_});var ex=G(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.DownscopedClient=Xn.EXPIRATION_TIME_OFFSET=Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var Rj=gt(),Dj=require("stream"),c_=Lt(),Oj=hd(),Pj="urn:ietf:params:oauth:grant-type:token-exchange",Ij="urn:ietf:params:oauth:token-type:access_token",Fj="urn:ietf:params:oauth:token-type:access_token";Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Xn.EXPIRATION_TIME_OFFSET=300*1e3;var u_=class extends c_.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof c_.AuthClient?{}:e),e instanceof c_.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>Xn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Xn.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 Oj.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=Rj.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 Dj.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:Pj,requestedTokenType:Ij,subjectToken:e,subjectTokenType:Fj},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}};Xn.DownscopedClient=u_});var tx=G(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.PassThroughClient=void 0;var Nj=Lt(),l_=class extends Nj.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};Md.PassThroughClient=l_});var Bd=G(re=>{"use strict";var Mj=re&&re.__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]})),Bj=re&&re.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&Mj(e,t,n)};Object.defineProperty(re,"__esModule",{value:!0});re.GoogleAuth=re.auth=re.GDCH_SERVICE_ACCOUNT_TYPE=re.GdchClient=re.PassThroughClient=re.ExternalAccountAuthorizedUserClient=re.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=re.ExecutableError=re.PluggableAuthClient=re.DownscopedClient=re.BaseExternalAccountClient=re.ExternalAccountClient=re.IdentityPoolClient=re.AwsRequestSigner=re.AwsClient=re.UserRefreshClient=re.LoginTicket=re.ClientAuthentication=re.OAuth2Client=re.CodeChallengeMethod=re.Impersonated=re.JWT=re.JWTAccess=re.IdTokenClient=re.IAMAuth=re.GCPEnv=re.Compute=re.DEFAULT_UNIVERSE=re.AuthClient=re.gaxios=re.gcpMetadata=void 0;var nx=QT();Object.defineProperty(re,"GoogleAuth",{enumerable:!0,get:function(){return nx.GoogleAuth}});re.gcpMetadata=Ma();re.gaxios=gt();var rx=Lt();Object.defineProperty(re,"AuthClient",{enumerable:!0,get:function(){return rx.AuthClient}});Object.defineProperty(re,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return rx.DEFAULT_UNIVERSE}});var Uj=Hm();Object.defineProperty(re,"Compute",{enumerable:!0,get:function(){return Uj.Compute}});var jj=Gm();Object.defineProperty(re,"GCPEnv",{enumerable:!0,get:function(){return jj.GCPEnv}});var Lj=ZT();Object.defineProperty(re,"IAMAuth",{enumerable:!0,get:function(){return Lj.IAMAuth}});var $j=Wm();Object.defineProperty(re,"IdTokenClient",{enumerable:!0,get:function(){return $j.IdTokenClient}});var qj=gy();Object.defineProperty(re,"JWTAccess",{enumerable:!0,get:function(){return qj.JWTAccess}});var Hj=yy();Object.defineProperty(re,"JWT",{enumerable:!0,get:function(){return Hj.JWT}});var zj=wy();Object.defineProperty(re,"Impersonated",{enumerable:!0,get:function(){return zj.Impersonated}});var d_=ro();Object.defineProperty(re,"CodeChallengeMethod",{enumerable:!0,get:function(){return d_.CodeChallengeMethod}});Object.defineProperty(re,"OAuth2Client",{enumerable:!0,get:function(){return d_.OAuth2Client}});Object.defineProperty(re,"ClientAuthentication",{enumerable:!0,get:function(){return d_.ClientAuthentication}});var Wj=jm();Object.defineProperty(re,"LoginTicket",{enumerable:!0,get:function(){return Wj.LoginTicket}});var Gj=by();Object.defineProperty(re,"UserRefreshClient",{enumerable:!0,get:function(){return Gj.UserRefreshClient}});var Jj=Ly();Object.defineProperty(re,"AwsClient",{enumerable:!0,get:function(){return Jj.AwsClient}});var Kj=By();Object.defineProperty(re,"AwsRequestSigner",{enumerable:!0,get:function(){return Kj.AwsRequestSigner}});var Vj=Ny();Object.defineProperty(re,"IdentityPoolClient",{enumerable:!0,get:function(){return Vj.IdentityPoolClient}});var Yj=Qy();Object.defineProperty(re,"ExternalAccountClient",{enumerable:!0,get:function(){return Yj.ExternalAccountClient}});var Xj=io();Object.defineProperty(re,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Xj.BaseExternalAccountClient}});var Qj=ex();Object.defineProperty(re,"DownscopedClient",{enumerable:!0,get:function(){return Qj.DownscopedClient}});var ox=Yy();Object.defineProperty(re,"PluggableAuthClient",{enumerable:!0,get:function(){return ox.PluggableAuthClient}});Object.defineProperty(re,"ExecutableError",{enumerable:!0,get:function(){return ox.ExecutableError}});var sx=t_();Object.defineProperty(re,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return sx.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(re,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return sx.ExternalAccountAuthorizedUserClient}});var Zj=tx();Object.defineProperty(re,"PassThroughClient",{enumerable:!0,get:function(){return Zj.PassThroughClient}});var ix=r_();Object.defineProperty(re,"GdchClient",{enumerable:!0,get:function(){return ix.GdchClient}});Object.defineProperty(re,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return ix.GDCH_SERVICE_ACCOUNT_TYPE}});Bj(py(),re);var eL=new nx.GoogleAuth;re.auth=eL});var fc,A0=Wr(()=>{"use strict";fc=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 fc,S0=Wr(()=>{"use strict";fc=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})}}}});var vi,A0,xD,pc,E0=Wr(()=>{"use strict";vi=require("fs"),A0=require("path"),xD=require("os"),pc=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,xD.tmpdir)();this.baseDir=(0,A0.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,vi.existsSync)(this.baseDir)||(0,vi.mkdirSync)(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(0,A0.join)(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(0,vi.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var v0,Ti,RD=Wr(()=>{"use strict";k0();S0();E0();v0=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 dc(e.config);break;case"webhook":n=new fc(e.config);break;case"temp-file":n=new pc(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)}},Ti=new v0});var X4={};sh(X4,{ANTIGRAVITY_CLIENT_ID:()=>$f,ANTIGRAVITY_CLIENT_SECRET:()=>qf,ANTIGRAVITY_REDIRECT_URI:()=>p0,ANTIGRAVITY_SCOPES:()=>LR,ConfigService:()=>vo,DEFAULT_LOG_BODY_MAX_BYTES:()=>ca,ProviderService:()=>Fo,SSEParserTransform:()=>ln,SSESerializerTransform:()=>No,TokenizerService:()=>ts,TransformerService:()=>es,calculateTokenCount:()=>sg,default:()=>Y4,diffHeadersForLog:()=>ww,exchangeAuthorizationCode:()=>tD,fetchUserEmail:()=>eD,getAntigravityAccessToken:()=>Ai,getClaudeAccessToken:()=>ba,getCodexAccessToken:()=>Ka,getGlobalTokenSpeedStats:()=>R0,getQwenAccessToken:()=>Sf,getTokenSpeedStats:()=>x0,getValidAccessToken:()=>Ai,getXaiAccessToken:()=>sc,isClientAbortError:()=>We,isRoutedLlmPost:()=>rk,listClientRouteRegistrations:()=>Au,loadTokens:()=>tc,matchClientProtocol:()=>Mn,pluginManager:()=>w0,protocolErrorBody:()=>_s,resolveProjectId:()=>zf,rewriteStream:()=>pg,router:()=>Ou,sanitizeBodyForLog:()=>du,sanitizeHeadersForLog:()=>lu,saveTokens:()=>Hf,searchProjectBySession:()=>ig,sessionUsageCache:()=>Ru,setHealthReporter:()=>Ow,tokenSpeedPlugin:()=>D0});module.exports=zD(X4);var PD=ot(require("fastify"),1),ID=ot(require("@fastify/cors"),1),FD=ot(cw(),1),ND=require("@caeliq/ccr-shared");var aa=require("fs"),Ih=require("path"),bw=require("dotenv"),Cw=ot(Ph(),1),vo=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:(0,Ih.join)(process.cwd(),this.options.jsonPath);if((0,aa.existsSync)(e))try{let n=(0,aa.readFileSync)(e,"utf-8"),r=Cw.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:(0,Ih.join)(process.cwd(),this.options.envPath);if((0,aa.existsSync)(e))try{let n=(0,bw.config)({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 Fh="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Ve(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(`"(${Fh})"\\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 uP=new RegExp(`^(?:${Fh})$`,"i"),lP=6,dP=20;function ms(t,e=0){if(t==null)return t;if(!(e>lP)){if(typeof t=="string")return Ve(t);if(Array.isArray(t))return t.slice(0,dP).map(n=>ms(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=uP.test(r)?"[redacted]":ms(o,e+1);return n}return t}}var ca=32768;function du(t,e=ca){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(`"(${Fh})"\\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 fP(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 pc,E0=Wr(()=>{"use strict";pc=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})}}}});var Ti,v0,ID,hc,T0=Wr(()=>{"use strict";Ti=require("fs"),v0=require("path"),ID=require("os"),hc=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=(0,ID.tmpdir)();this.baseDir=(0,v0.join)(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{(0,Ti.existsSync)(this.baseDir)||(0,Ti.mkdirSync)(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(0,v0.join)(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(0,Ti.writeFileSync)(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var x0,xi,FD=Wr(()=>{"use strict";A0();E0();T0();x0=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 fc(e.config);break;case"webhook":n=new pc(e.config);break;case"temp-file":n=new hc(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)}},xi=new x0});var i6={};sh(i6,{ANTIGRAVITY_CLIENT_ID:()=>$f,ANTIGRAVITY_CLIENT_SECRET:()=>qf,ANTIGRAVITY_REDIRECT_URI:()=>g0,ANTIGRAVITY_SCOPES:()=>WR,ConfigService:()=>To,DEFAULT_LOG_BODY_MAX_BYTES:()=>ua,ProviderService:()=>No,SSEParserTransform:()=>ln,SSESerializerTransform:()=>Mo,TokenizerService:()=>ns,TransformerService:()=>ts,calculateTokenCount:()=>ig,default:()=>s6,diffHeadersForLog:()=>Sw,exchangeAuthorizationCode:()=>iD,fetchUserEmail:()=>sD,getAntigravityAccessToken:()=>Ei,getClaudeAccessToken:()=>Ca,getCodexAccessToken:()=>Va,getGlobalTokenSpeedStats:()=>O0,getQwenAccessToken:()=>Sf,getTokenSpeedStats:()=>D0,getValidAccessToken:()=>Ei,getXaiAccessToken:()=>ic,isClientAbortError:()=>We,isRoutedLlmPost:()=>ak,listClientRouteRegistrations:()=>Eu,loadTokens:()=>nc,matchClientProtocol:()=>Mn,pluginManager:()=>S0,protocolErrorBody:()=>bs,resolveProjectId:()=>zf,rewriteStream:()=>hg,router:()=>Pu,sanitizeBodyForLog:()=>fu,sanitizeHeadersForLog:()=>du,saveTokens:()=>Hf,searchProjectBySession:()=>ag,sessionUsageCache:()=>Du,setHealthReporter:()=>Iw,tokenSpeedPlugin:()=>P0});module.exports=VD(i6);var BD=ot(require("fastify"),1),UD=ot(require("@fastify/cors"),1),jD=ot(lw(),1),LD=require("@caeliq/ccr-shared");var ca=require("fs"),Ih=require("path"),ww=require("dotenv"),kw=ot(Ph(),1),To=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:(0,Ih.join)(process.cwd(),this.options.jsonPath);if((0,ca.existsSync)(e))try{let n=(0,ca.readFileSync)(e,"utf-8"),r=kw.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:(0,Ih.join)(process.cwd(),this.options.envPath);if((0,ca.existsSync)(e))try{let n=(0,ww.config)({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 Fh="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Ve(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(`"(${Fh})"\\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 hP=new RegExp(`^(?:${Fh})$`,"i"),gP=6,mP=20;function ys(t,e=0){if(t==null)return t;if(!(e>gP)){if(typeof t=="string")return Ve(t);if(Array.isArray(t))return t.slice(0,mP).map(n=>ys(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=hP.test(r)?"[redacted]":ys(o,e+1);return n}return t}}var ua=32768;function fu(t,e=ua){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(`"(${Fh})"\\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 yP(t,e){return t.split(`
124
124
  `).map(n=>Ve(n)).filter(Boolean).join(`
125
- `).slice(0,e)}function Fn(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:Ve(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"?fP(e.stack,4e3):void 0,cause:r?Ve(r):void 0}}var pP=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function hP(t){return pP.test(t)}function gP(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 lu(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=gP(o);if(s!=null){if(hP(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function ww(t,e){let n=lu(t),r=lu(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 Tt="client disconnected";function ys(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 Aw(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(a=Tt)=>{n.signal.aborted||n.abort(a)},i=()=>{if(!o&&(o=!0,!!r)){if(Nh(r)){s(`${Tt} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&Nh(r)&&s(`${Tt} (response close)`)}),r.on("error",a=>{(a?.code==="EPIPE"||a?.code==="ECONNRESET"||a?.code==="ERR_STREAM_PREMATURE_CLOSE"||We(a))&&s(`${Tt} (response error)`)})}};return{signal:n.signal,arm:i}}function mP(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 yP(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function Mh(t,e){let n=mP(e);return n!==void 0&&n>0?n:yP(t)}function Ew(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var kw=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 vw(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 Nn(t=Tt){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:Tt;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function Sw(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 We(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(Tt)||Sw(t);let e=t;if(vw(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(Tt)||typeof e.message=="string"&&e.message.startsWith(Tt)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return Sw(r)}function Nh(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 Nh(t.raw)}function hr(t){if(!t||We(t))return!1;if(vw(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&kw.has(e.code)||e.cause?.code&&kw.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 Bh(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function Uh(t){let e=t;if(!e||We(e))return!1;if(hr(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?Bh(n):e.code==="provider_response_error"}function _s(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(Ve(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function xw(t,e,n){if(We(t)||n.raw.destroyed||n.sent)return e.log.debug(Fn(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(Fn(t),"request error");let r=t.statusCode||500,o=Ve(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=_s(a,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}var Jk=require("stream");var Dw=require("undici");function _P(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function bP(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 CP(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 wP(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=_P(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=kP(i);if(a.startsWith(".")){if(n.endsWith(a)||n===a.slice(1))return!0;continue}if(a.includes("/")&&bP(n)){if(CP(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 kP(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 bs(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&&!wP(d)&&(u.dispatcher=new Dw.ProxyAgent(new URL(n.httpsProxy).toString()));try{return await fetch(d,u)}catch(p){if(We(p))throw typeof p=="string"?Nn(p):p;if(n.signal?.aborted&&We(n.signal.reason??Tt))throw Nn(n.signal.reason??p);if(hr(p)){let h=J(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var jh;function Ow(t){jh=t}function Pw(){if(jh)try{return jh()}catch{return}}var Iw="1.0.63";var Nw=require("crypto"),Lh={type:"ephemeral"};function Xe(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 Qe(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function Fw(t){return`ccr_${(0,Nw.createHash)("sha256").update(t).digest("hex").slice(0,48)}`}function AP(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 EP(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 un(t,e){let n=t?.req?.sessionId||AP(e?.metadata?.user_id);if(typeof n=="string"&&n)return Fw(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?EP(r.content):"",s=[e.model||"",o].join(`
127
- `);return s.trim()?Fw(s):void 0}function fu(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}:Lh}return r}function To(t){let e=Xe(t.messages||[]),n=Qe(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:Lh}];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:Lh},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function pu(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 Mw(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 Bw(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function vP(t){for(let e=t.length-1;e>=0;e-=1)if(Bw(t[e]))return e;return-1}function ua(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=un(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),Mw(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=vP(i.content);u>=0&&s.push({messageIndex:a,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,d)=>{u?.cache_control&&Bw(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=Xe(r.messages),r.tools=Qe(r.tools),r}function hu(t,e){return Mw(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function TP(t){return String(t?.name||"").trim().toLowerCase()}function xP(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function $h(t,e){let n={...t,messages:Xe(t.messages||[]),tools:Qe(t.tools)},r=un(e,t);return r&&(n.prompt_cache_key=r),n}function gu(t,e,n){let r=TP(e),o=xP(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?ua(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?To(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?$h(t,n):{...t,messages:Xe(t.messages||[]),tools:Qe(t.tools)}}function Nt(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e||void 0}function Mt(t,e){return e?.type==="disabled"||t?.enabled===!1||Nt(t?.effort)==="none"}function Cs(t,e){let n=Nt(t);if(!(!n&&e===void 0))return{...n?{effort:n}:{},enabled:n==="none"?!1:e??!0}}function mu(t){if(!t.reasoning)return t;let e=Mt(t.reasoning,t.thinking)?"none":Nt(t.reasoning.effort);return e&&(t.reasoning_effort=e),delete t.reasoning,t}function Uw(t){let e=Nt(t);if(!(!e||e==="none"))return e==="minimal"?"low":e==="ultra"?"max":e}var ln=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 jw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function yu(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=jw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var RP=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function _u(t){let e={};return t&&t.forEach((n,r)=>{RP.has(r.toLowerCase())||(e[r]=n)}),e}var DP=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),OP=["anthropic-ratelimit-","x-ratelimit-"];function qh(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();!(DP.has(s)||OP.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function Lw(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=jw(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"))}var Gw=require("crypto"),PP=512,IP=16,FP=4,xo=new Map;function Jw(t){let e=JSON.stringify(Hh(t))??"";return{hash:(0,Gw.createHash)("sha256").update(e).digest("hex").slice(0,IP),approxTokens:Math.ceil(e.length/FP)}}function Kw(t){return Jw(t).hash}function Hh(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Hh);let e={};for(let n of Object.keys(t).sort())e[n]=Hh(t[n]);return e}function Vw(t){if(!t||typeof t!="object")return!1;let e=t.cache_control;return!!(e&&typeof e=="object"&&e.type==="ephemeral")}function Yw(t){return!!(t&&typeof t=="object"&&t.prompt_cache_breakpoint)}function zh(t){if(!t||typeof t!="object")return 0;let e=0;if((Vw(t)||Yw(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=zh(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=zh(n));return e}function la(t,e,n){if(!(!t||typeof t!="object")){if((Vw(t)||Yw(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>la(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&la(o,`${e}.${r}`,n)}}function $w(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 qw(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 NP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function Wh(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)Wh(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&NP(o)?e.add(String(o)):o&&typeof o=="object"&&Wh(o,e,n+1)}}function bu(t,e,n){let r=e,{hash:o,approxTokens:s}=Jw(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:zh(e),...qw(r)?{reasoningId:qw(r)}:{}}}function MP(t,e){for(xo.has(t)&&xo.delete(t),xo.set(t,e);xo.size>PP;){let n=xo.keys().next().value;if(n===void 0)break;xo.delete(n)}}function BP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=bu("system",t.system,{type:"system"});o=p.hash,n.push(p),la(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=bu("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=bu("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),la(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(bu(g,p)),la(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=$w(p.content)||$w(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 Wh(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 zw(t){return t?Kw(t):""}function Ww(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=zw(e.affinity)!==zw(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"?Ww(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:Ww(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 jP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${Kw([t.systemHash||"",t.toolsHash||"",e?.hash||""])}`}function LP(t,e){return typeof t=="string"&&t?{id:t,source:"session"}:e.prompt_cache_key?{id:e.prompt_cache_key,source:"cache_key"}:{id:jP(e),source:"fingerprint"}}function Xw(t,e,n,r){let o=BP(e,n);if(!o)return null;let s=r?.stage??"wire",{id:i,source:a}=LP(t,o),u=[s,r?.provider||"-",r?.model||o.model||"-",i].join("|"),d=xo.get(u),f=UP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&MP(u,o),f}function Gh(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function Jh(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 Qw(t,e){let n=_u(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function $P(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function Cu(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??ca,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:du(e,o)}),n!==void 0&&r.debug({...s,response:ms(n),tppe:"Original Response"})}function xt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Jt(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Zw(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=Jt(Jt(xt(s.cache_read_input_tokens),xt(s.prompt_tokens_details?.cached_tokens)),Jt(Jt(xt(s.input_tokens_details?.cached_tokens),xt(s.cachedContentTokenCount)),xt(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||xt(s.cache_read_input_tokens)!==void 0||xt(s.cache_creation_input_tokens)!==void 0,promptTokens:Jt(o.promptTokens,Jt(Jt(xt(s.input_tokens),xt(s.prompt_tokens)),xt(s.promptTokenCount))),cachedTokens:Jt(o.cachedTokens,i),cacheWriteTokens:Jt(o.cacheWriteTokens,xt(s.cache_creation_input_tokens)),outputTokens:Jt(o.outputTokens,Jt(Jt(xt(s.output_tokens),xt(s.completion_tokens)),xt(s.candidatesTokenCount)))}}return o}function qP(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(!Jh(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?Gh(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:qP(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 ln).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"){Cu(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);Cu(e,f),await s();continue}o=Zw(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}Cu(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}Kh(e,o)}})()}async function zP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return Cu(e,n,r),Kh(e,Zw({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:Qw(t.headers,"application/json")})}async function ek(t,e){if(!Jh(e.logger)||!t.body)return t;let n=$P(t);if(n.includes("application/json"))try{return await zP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return Kh(e,{cachedExcludedFromPrompt:!1}),t;try{let r=WP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:Qw(t.headers,"text/event-stream")})}catch{return t}}function WP(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 da(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function GP(t){return Array.isArray(t)?t.reduce((e,n)=>e+da(n),0):0}function JP(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 KP(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=da(i);else t.system&&typeof t.system=="object"&&(e+=da(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=da(i),n+=GP(i.content),i.role==="assistant"&&(r=JP(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=da(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 Vh(t,e){if(!Jh(e.logger))return null;let n=KP(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=Xw(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=Gh(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var VP=new TextEncoder().encode(`: keepalive
125
+ `).slice(0,e)}function Fn(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:Ve(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"?yP(e.stack,4e3):void 0,cause:r?Ve(r):void 0}}var _P=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function bP(t){return _P.test(t)}function CP(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 du(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=CP(o);if(s!=null){if(bP(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function Sw(t,e){let n=du(t),r=du(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 xt="client disconnected";function _s(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 vw(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(a=xt)=>{n.signal.aborted||n.abort(a)},i=()=>{if(!o&&(o=!0,!!r)){if(Nh(r)){s(`${xt} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&Nh(r)&&s(`${xt} (response close)`)}),r.on("error",a=>{(a?.code==="EPIPE"||a?.code==="ECONNRESET"||a?.code==="ERR_STREAM_PREMATURE_CLOSE"||We(a))&&s(`${xt} (response error)`)})}};return{signal:n.signal,arm:i}}function wP(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 kP(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function Mh(t,e){let n=wP(e);return n!==void 0&&n>0?n:kP(t)}function Tw(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var Aw=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 xw(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 Nn(t=xt){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:xt;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function Ew(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 We(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(xt)||Ew(t);let e=t;if(xw(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(xt)||typeof e.message=="string"&&e.message.startsWith(xt)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return Ew(r)}function Nh(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function Rw(t){return Nh(t.raw)}function hr(t){if(!t||We(t))return!1;if(xw(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&Aw.has(e.code)||e.cause?.code&&Aw.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 Bh(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function Uh(t){let e=t;if(!e||We(e))return!1;if(hr(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?Bh(n):e.code==="provider_response_error"}function bs(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(Ve(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function Dw(t,e,n){if(We(t)||n.raw.destroyed||n.sent)return e.log.debug(Fn(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(Fn(t),"request error");let r=t.statusCode||500,o=Ve(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=bs(a,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}var Xk=require("stream");var Pw=require("undici");function SP(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function AP(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function Ow(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 EP(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=Ow(t),i=Ow(n);if(s===null||i===null)return!1;let a=o===0?0:-1<<32-o>>>0;return(s&a)===(i&a)}function vP(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=SP(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=TP(i);if(a.startsWith(".")){if(n.endsWith(a)||n===a.slice(1))return!0;continue}if(a.includes("/")&&AP(n)){if(EP(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 TP(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 Cs(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&&!vP(d)&&(u.dispatcher=new Pw.ProxyAgent(new URL(n.httpsProxy).toString()));try{return await fetch(d,u)}catch(p){if(We(p))throw typeof p=="string"?Nn(p):p;if(n.signal?.aborted&&We(n.signal.reason??xt))throw Nn(n.signal.reason??p);if(hr(p)){let h=J(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var jh;function Iw(t){jh=t}function Fw(){if(jh)try{return jh()}catch{return}}var Nw="1.0.65";var Bw=require("crypto"),Lh={type:"ephemeral"};function Xe(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 Qe(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function Mw(t){return`ccr_${(0,Bw.createHash)("sha256").update(t).digest("hex").slice(0,48)}`}function RP(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 DP(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 un(t,e){let n=t?.req?.sessionId||RP(e?.metadata?.user_id);if(typeof n=="string"&&n)return Mw(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?DP(r.content):"",s=[e.model||"",o].join(`
127
+ `);return s.trim()?Mw(s):void 0}function pu(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}:Lh}return r}function xo(t){let e=Xe(t.messages||[]),n=Qe(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:Lh}];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:Lh},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function hu(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 Uw(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 jw(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function OP(t){for(let e=t.length-1;e>=0;e-=1)if(jw(t[e]))return e;return-1}function la(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=un(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),Uw(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=OP(i.content);u>=0&&s.push({messageIndex:a,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,d)=>{u?.cache_control&&jw(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=Xe(r.messages),r.tools=Qe(r.tools),r}function gu(t,e){return Uw(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function PP(t){return String(t?.name||"").trim().toLowerCase()}function IP(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function $h(t,e){let n={...t,messages:Xe(t.messages||[]),tools:Qe(t.tools)},r=un(e,t);return r&&(n.prompt_cache_key=r),n}function mu(t,e,n){let r=PP(e),o=IP(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?la(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?xo(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?$h(t,n):{...t,messages:Xe(t.messages||[]),tools:Qe(t.tools)}}var Lw=new Set(["auto","detailed","concise"]);function Rt(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e||void 0}function FP(t){if(t===!0||t===1)return"detailed";if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true"||e==="1"||e==="yes"||e==="on")return"detailed";if(Lw.has(e))return e}}function qh(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();if(e==="none")return"none";if(Lw.has(e))return e}function NP(t,e){if(kt(t,e)||!t)return!1;let n=Rt(t.effort);return n&&n!=="none"?!0:t.enabled===!0}function $w(t,e){let n=FP(e);return!n||!t.reasoning||!NP(t.reasoning,t.thinking)||qh(t.reasoning.summary)||(t.reasoning.summary=n),t}function Jr(t,e){if(kt(t.reasoning,t.thinking))return;let n=qh(t.reasoning?.summary);if(n==="none")return;if(n)return n;let r=qh(e?.reasoningSummary);if(r!=="none"&&r)return r}function kt(t,e){return e?.type==="disabled"||t?.enabled===!1||Rt(t?.effort)==="none"}function ws(t,e){let n=Rt(t);if(!(!n&&e===void 0))return{...n?{effort:n}:{},enabled:n==="none"?!1:e??!0}}function yu(t){if(!t.reasoning)return t;let e=kt(t.reasoning,t.thinking)?"none":Rt(t.reasoning.effort);return e&&(t.reasoning_effort=e),delete t.reasoning,t}function qw(t){let e=Rt(t);if(!(!e||e==="none"))return e==="minimal"?"low":e==="ultra"?"max":e}var ln=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 Hw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function _u(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=Hw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var MP=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function bu(t){let e={};return t&&t.forEach((n,r)=>{MP.has(r.toLowerCase())||(e[r]=n)}),e}var BP=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),UP=["anthropic-ratelimit-","x-ratelimit-"];function Hh(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();!(BP.has(s)||UP.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function zw(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=Hw(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"))}var Yw=require("crypto"),jP=512,LP=16,$P=4,Ro=new Map;function Xw(t){let e=JSON.stringify(zh(t))??"";return{hash:(0,Yw.createHash)("sha256").update(e).digest("hex").slice(0,LP),approxTokens:Math.ceil(e.length/$P)}}function Qw(t){return Xw(t).hash}function zh(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(zh);let e={};for(let n of Object.keys(t).sort())e[n]=zh(t[n]);return e}function Zw(t){if(!t||typeof t!="object")return!1;let e=t.cache_control;return!!(e&&typeof e=="object"&&e.type==="ephemeral")}function ek(t){return!!(t&&typeof t=="object"&&t.prompt_cache_breakpoint)}function Wh(t){if(!t||typeof t!="object")return 0;let e=0;if((Zw(t)||ek(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=Wh(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=Wh(n));return e}function da(t,e,n){if(!(!t||typeof t!="object")){if((Zw(t)||ek(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>da(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&da(o,`${e}.${r}`,n)}}function Ww(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 Gw(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 qP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function Gh(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)Gh(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&qP(o)?e.add(String(o)):o&&typeof o=="object"&&Gh(o,e,n+1)}}function Cu(t,e,n){let r=e,{hash:o,approxTokens:s}=Xw(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:Wh(e),...Gw(r)?{reasoningId:Gw(r)}:{}}}function HP(t,e){for(Ro.has(t)&&Ro.delete(t),Ro.set(t,e);Ro.size>jP;){let n=Ro.keys().next().value;if(n===void 0)break;Ro.delete(n)}}function zP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=Cu("system",t.system,{type:"system"});o=p.hash,n.push(p),da(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=Cu("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=Cu("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),da(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(Cu(g,p)),da(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=Ww(p.content)||Ww(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 Gh(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 Jw(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 Kw(t){return t?Qw(t):""}function Vw(t){return t.reduce((e,n)=>e+n.approxTokens,0)}function WP(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=Kw(e.affinity)!==Kw(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:Jw(b[C]),current:Jw(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"?Vw(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:Vw(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 GP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${Qw([t.systemHash||"",t.toolsHash||"",e?.hash||""])}`}function JP(t,e){return typeof t=="string"&&t?{id:t,source:"session"}:e.prompt_cache_key?{id:e.prompt_cache_key,source:"cache_key"}:{id:GP(e),source:"fingerprint"}}function tk(t,e,n,r){let o=zP(e,n);if(!o)return null;let s=r?.stage??"wire",{id:i,source:a}=JP(t,o),u=[s,r?.provider||"-",r?.model||o.model||"-",i].join("|"),d=Ro.get(u),f=WP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&HP(u,o),f}function Jh(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function Kh(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 nk(t,e){let n=bu(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function KP(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function wu(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??ua,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:fu(e,o)}),n!==void 0&&r.debug({...s,response:ys(n),tppe:"Original Response"})}function Dt(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Jt(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function rk(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=Jt(Jt(Dt(s.cache_read_input_tokens),Dt(s.prompt_tokens_details?.cached_tokens)),Jt(Jt(Dt(s.input_tokens_details?.cached_tokens),Dt(s.cachedContentTokenCount)),Dt(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||Dt(s.cache_read_input_tokens)!==void 0||Dt(s.cache_creation_input_tokens)!==void 0,promptTokens:Jt(o.promptTokens,Jt(Jt(Dt(s.input_tokens),Dt(s.prompt_tokens)),Dt(s.promptTokenCount))),cachedTokens:Jt(o.cachedTokens,i),cacheWriteTokens:Jt(o.cacheWriteTokens,Dt(s.cache_creation_input_tokens)),outputTokens:Jt(o.outputTokens,Jt(Jt(Dt(s.output_tokens),Dt(s.completion_tokens)),Dt(s.candidatesTokenCount)))}}return o}function VP(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 Vh(t,e){if(!Kh(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?Jh(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:VP(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 YP(t,e){(async()=>{let r=t.pipeThrough(new TextDecoderStream).pipeThrough(new ln).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"){wu(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);wu(e,f),await s();continue}o=rk(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}wu(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}Vh(e,o)}})()}async function XP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return wu(e,n,r),Vh(e,rk({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:nk(t.headers,"application/json")})}async function ok(t,e){if(!Kh(e.logger)||!t.body)return t;let n=KP(t);if(n.includes("application/json"))try{return await XP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return Vh(e,{cachedExcludedFromPrompt:!1}),t;try{let r=QP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:nk(t.headers,"text/event-stream")})}catch{return t}}function QP(t,e){let n=new TransformStream(void 0,{highWaterMark:1/0},{highWaterMark:1}),r=n.writable.getWriter();YP(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 fa(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function ZP(t){return Array.isArray(t)?t.reduce((e,n)=>e+fa(n),0):0}function e1(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 t1(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=fa(i);else t.system&&typeof t.system=="object"&&(e+=fa(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=fa(i),n+=ZP(i.content),i.role==="assistant"&&(r=e1(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=fa(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 Yh(t,e){if(!Kh(e.logger))return null;let n=t1(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=tk(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=Jh(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var n1=new TextEncoder().encode(`: keepalive
129
129
 
130
- `);function Yh(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(VP)}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 wu(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=YP(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 YP(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 ku(t){return/^data:\s*\[DONE\]\s*$/.test(t)||/^\s*\[DONE\]\s*$/.test(t)}function Su(t){t.push(""),t.push("data: [DONE]"),t.push("")}function Xh(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 wu(h)){if(o)return;if(ku(g)){Su(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 Xh(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(n1)}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 ku(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=r1(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 r1(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 Su(t){return/^data:\s*\[DONE\]\s*$/.test(t)||/^\s*\[DONE\]\s*$/.test(t)}function Au(t){t.push(""),t.push("data: [DONE]"),t.push("")}function Qh(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 ku(h)){if(o)return;if(Su(g)){Au(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 tk(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)}var Po=require("@caeliq/ccr-shared");var nk=[{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"}],XP=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],QP=/^\/preset\/[^/]+/;function ZP(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function e1(t){let e=t.match(QP);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function t1(t){return XP.some(e=>t===e)}function n1(t){for(let e of nk){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 Mn(t,e){if(t.toUpperCase()!=="POST")return null;let n=ZP(e),{suffix:r,presetPrefix:o}=e1(n);if(t1(r))return null;let s=n1(r);return s?{...s,presetPrefix:o}:null}function rk(t,e){return Mn(t,e)!==null}function Au(){let t=[];for(let e of nk){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 ok(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}}var pk=require("crypto");var sk=require("crypto"),ik=/^[a-zA-Z0-9_-]+$/,ak=/[^a-zA-Z0-9_-]+/g,ck=256;function r1(t){return t.length>0&&t.length<=ck&&ik.test(t)}function Qh(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function gr(t){if(typeof t!="string"||t.length===0)return;if(r1(t))return t;let e=Qh(t.replace(ak,"_").slice(0,ck));return e.length?e:void 0}var uk=64,lk=20,o1=uk-lk-1;function s1(t){return t.length>0&&t.length<=uk&&ik.test(t)}function kt(t){if(typeof t!="string"||t.length===0)return;if(s1(t))return t;let e=Qh(t.replace(ak,"_")),n=Qh(e.slice(0,o1))||"call",r=(0,sk.createHash)("sha256").update(t,"utf8").digest("base64url").slice(0,lk);return`${n}_${r}`}function ws(){return{forward:new Map,reverse:new Map}}function Ro(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=kt(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=kt(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=kt(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function Eu(t,e=ws(),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(i1(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)d1(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=p1(t.tools,n),a=h1(t.tool_choice),u=t.reasoning&&typeof t.reasoning=="object"?{...Cs(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 i1(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 a1(t){return t?.content===null||t?.content===void 0||t?.content===""}function dk(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"&&a1(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 c1(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 u1=/^rs_[A-Za-z0-9]+$/;function mr(t){return typeof t=="string"&&u1.test(t)}function ks(t){if(!(typeof t!="string"||!t)&&!mr(t))return t}function Ss(t){let e=typeof t?.signature=="string"?t.signature:"";if(!(!e||mr(e)))return e}function As(t){if(!t||typeof t!="object")return;let e=c1(t),n=ks(t.encrypted_content),r=typeof t.id=="string"&&t.id?t.id:mr(t.encrypted_content)?t.encrypted_content:void 0;if(!(!e&&!n&&!r))return{content:e,...n?{encrypted_content:n}:{},...r?{id:r}:{}}}function vu(t,e,n){typeof e!="string"||!e||typeof n!="string"||!n||t.set(e,(t.get(e)||"")+n)}function Es(t,e){let n=As(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 Un(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=ks(t.thinking?.encrypted_content),i=typeof t.thinking?.id=="string"&&t.thinking.id||(mr(o)?o:void 0)||(mr(t.thinking?.encrypted_content)?t.thinking.encrypted_content:void 0),a=o&&!mr(o)?o:void 0;if(!(!r&&!a&&!s&&!i))return{content:r,...a?{signature:a}:{},...s?{encrypted_content:s}:{},...i?{id:i}:{}}}function vs(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:Un(t),texts:e,images:n,toolCalls:Array.isArray(t?.tool_calls)?t.tool_calls:[]}}function fa(t){return t.texts.some(e=>e.text.length>0)}function Ts(t,e){if(!t||typeof t!="object")return null;let n=typeof t.content=="string"?t.content:"",r=ks(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_${(0,pk.createHash)("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 l1(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 d1(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=As(e);r&&l1(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:Ro(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");dk(t,{id:Ro(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:Ro(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");dk(t,{id:Ro(n,r)??r,type:"function",function:{name:e.name,arguments:JSON.stringify({[Bn]: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:f1(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 f1(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 Bn="input";function fk(t){let e=t.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return e?e[2]:t}function xu(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 hk(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 gk(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 Zh(t,e,n){if(!mk(n)||t!=="exec")return e;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.input=="string")return r.input=gk(t,hk(t,r.input)),JSON.stringify(r)}catch{}return e}function eg(t){if(!t)return"";try{let n=JSON.parse(t)?.[Bn];if(typeof n=="string")return fk(n)}catch{}return fk(t)}function mk(t){return t?.codexIsolateConventions!==!1}function tg(t,e,n){let r=eg(e);return mk(n)&&(r=gk(t,hk(t,r))),xu(r)}function p1(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 sk(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)}var Io=require("@caeliq/ccr-shared");var ik=[{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"}],o1=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],s1=/^\/preset\/[^/]+/;function i1(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function a1(t){let e=t.match(s1);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function c1(t){return o1.some(e=>t===e)}function u1(t){for(let e of ik){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 Mn(t,e){if(t.toUpperCase()!=="POST")return null;let n=i1(e),{suffix:r,presetPrefix:o}=a1(n);if(c1(r))return null;let s=u1(r);return s?{...s,presetPrefix:o}:null}function ak(t,e){return Mn(t,e)!==null}function Eu(){let t=[];for(let e of ik){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 ck(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}}var yk=require("crypto");var uk=require("crypto"),lk=/^[a-zA-Z0-9_-]+$/,dk=/[^a-zA-Z0-9_-]+/g,fk=256;function l1(t){return t.length>0&&t.length<=fk&&lk.test(t)}function Zh(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function gr(t){if(typeof t!="string"||t.length===0)return;if(l1(t))return t;let e=Zh(t.replace(dk,"_").slice(0,fk));return e.length?e:void 0}var pk=64,hk=20,d1=pk-hk-1;function f1(t){return t.length>0&&t.length<=pk&&lk.test(t)}function St(t){if(typeof t!="string"||t.length===0)return;if(f1(t))return t;let e=Zh(t.replace(dk,"_")),n=Zh(e.slice(0,d1))||"call",r=(0,uk.createHash)("sha256").update(t,"utf8").digest("base64url").slice(0,hk);return`${n}_${r}`}function ks(){return{forward:new Map,reverse:new Map}}function Do(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=St(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=St(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=St(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function vu(t,e=ks(),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(p1(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)_1(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=C1(t.tools,n),a=w1(t.tool_choice),u=t.reasoning&&typeof t.reasoning=="object"?{...ws(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 p1(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 h1(t){return t?.content===null||t?.content===void 0||t?.content===""}function gk(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"&&h1(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 g1(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 m1=/^rs_[A-Za-z0-9]+$/;function mr(t){return typeof t=="string"&&m1.test(t)}function Ss(t){if(!(typeof t!="string"||!t)&&!mr(t))return t}function As(t){let e=typeof t?.signature=="string"?t.signature:"";if(!(!e||mr(e)))return e}function Es(t){if(!t||typeof t!="object")return;let e=g1(t),n=Ss(t.encrypted_content),r=typeof t.id=="string"&&t.id?t.id:mr(t.encrypted_content)?t.encrypted_content:void 0;if(!(!e&&!n&&!r))return{content:e,...n?{encrypted_content:n}:{},...r?{id:r}:{}}}function Tu(t,e,n){typeof e!="string"||!e||typeof n!="string"||!n||t.set(e,(t.get(e)||"")+n)}function vs(t,e){let n=Es(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 xu(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 Un(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=Ss(t.thinking?.encrypted_content),a=typeof t.thinking?.id=="string"&&t.thinking.id||(mr(s)?s:void 0)||(mr(t.thinking?.encrypted_content)?t.thinking.encrypted_content:void 0),u=s&&!mr(s)?s:void 0;if(!(!o&&!u&&!i&&!a))return{content:o,...u?{signature:u}:{},...i?{encrypted_content:i}:{},...a?{id:a}:{}}}function Ts(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:Un(t),texts:e,images:n,toolCalls:Array.isArray(t?.tool_calls)?t.tool_calls:[]}}function pa(t){return t.texts.some(e=>e.text.length>0)}function xs(t,e){if(!t||typeof t!="object")return null;let n=typeof t.content=="string"?t.content:"",r=Ss(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_${(0,yk.createHash)("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 y1(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 _1(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=Es(e);r&&y1(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:Do(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");gk(t,{id:Do(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:Do(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");gk(t,{id:Do(n,r)??r,type:"function",function:{name:e.name,arguments:JSON.stringify({[Bn]: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:b1(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 b1(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 Bn="input";function mk(t){let e=t.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return e?e[2]:t}function Ru(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 _k(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 bk(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 eg(t,e,n){if(!Ck(n)||t!=="exec")return e;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.input=="string")return r.input=bk(t,_k(t,r.input)),JSON.stringify(r)}catch{}return e}function tg(t){if(!t)return"";try{let n=JSON.parse(t)?.[Bn];if(typeof n=="string")return mk(n)}catch{}return mk(t)}function Ck(t){return t?.codexIsolateConventions!==!1}function ng(t,e,n){let r=tg(e);return Ck(n)&&(r=bk(t,_k(t,r))),Ru(r)}function C1(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 "${Bn}" 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:{[Bn]:{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:[Bn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function h1(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 yk(t,e){let n=e?.callIdMap??ws(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=Ts(Un(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=Ro(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:tg(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:xu(Zh(f.function.name,h,r)),status:"completed"})}let d=Ak(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 _k(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??ws(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function bk(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function Ck(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:Sk(t,"in_progress")}))}function wk(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 kk(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=Un(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)&&Ck(e,n),s?.content&&(e.thinkingContent+=s.content);let i=ks(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:mr(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&&wk(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=Ro(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=Ro(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),bk(e,n)}function ng(t,e){if(t.finished)return[];t.finished=!0;let n=[];Ck(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};wk(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=tg(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=xu(Zh(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=Sk(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),bk(t,n)}function Sk(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:tg(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:xu(Zh(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=Ts({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:Ak(n)}}function Ak(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 pa(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 Ek(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=ok(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function vk(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 g1(e);if(t==="openai_responses")return Eu(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 g1(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 m1=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"]),y1=["proxy-","x-forwarded-","x-real-ip"];function Tk(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(m1.has(s)||y1.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 xk(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]}var Ok=require("tiktoken");var rg=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())}},Ru=new rg(100);var og=require("fs/promises"),ha=require("fs/promises"),ft=require("path"),xs=require("@caeliq/ccr-shared"),Pk=require("lru-cache");var _1=(0,Ok.get_encoding)("cl100k_base"),yr=t=>_1.encode(t,void 0,[]),Rk="<CCR-SUBAGENT-MODEL>",Dk="</CCR-SUBAGENT-MODEL>",Rs="x-anthropic-billing-header",Ds=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Ik(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 b1(t){let e=`${Rs}:`;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 Du(t,e){let n=t.indexOf(Rk);if(n<0)return;let r=n+Rk.length,o=t.indexOf(Dk,r);if(o<0)return;let s=Ik(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Dk.length)}`),s}function Fk(t,e){if(typeof t=="string")return Du(t,e);if(!(!Ds(t)||typeof t.text!="string"))return Du(t.text,e)}function C1(t){let e=t?.system;if(typeof e=="string")return Du(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=Fk(r,s=>{typeof r=="string"?e[n]=s:Ds(r)&&(r.text=s)});if(o)return o}}function w1(t){if(typeof t.content=="string")return Du(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=Fk(r,s=>{typeof r=="string"?e[n]=s:Ds(r)&&(r.text=s)});if(o)return o}}function k1(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=w1(r);if(o)return o}}function Nk(t){return C1(t)||k1(t)}function Mk(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(Rs)?{present:!0,isSubagent:b1(r)}:{present:!1,isSubagent:!1}}var sg=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=yr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=yr(s.text).length:s.type==="tool_use"?r+=yr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=yr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=yr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=yr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=yr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=yr(o.name+o.description).length),o.input_schema&&(r+=yr(JSON.stringify(o.input_schema)).length)}),r},S1=async(t,e)=>{if(t.sessionId){let n=await ig(t.sessionId);if(n){let r=(0,ft.resolve)(xs.HOME_DIR),o=(0,ft.resolve)(r,(0,ft.basename)(n)),s=(0,ft.relative)(r,o);if(!s||s.startsWith(".."))return;let i=`${(0,ft.basename)(String(t.sessionId))}.json`,a=(0,ft.join)(o,"config.json"),u=(0,ft.join)(o,i);try{let d=JSON.parse(await(0,og.readFile)(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await(0,og.readFile)(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function Bk(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function A1(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function E1(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 v1(t){if(Mt(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 T1=async(t,e,n,r)=>{let o=await S1(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=Bk(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(A1(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=Ik(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 E1(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:v1(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"}},x1=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{}},Ou=async(t,e,n)=>{let{configService:r,event:o}=n,s=Bk(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=x1(i);let a=Ru.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=sg(u,d,f),t.tokenCount=m;let w,C=r.get("CUSTOM_ROUTER_PATH");if(C)try{w=await require(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 T1(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"}},Kr=new Pk.LRUCache({max:1e3}),ig=async(t,e)=>{if(Kr.has(t)){let n=Kr.get(t);return!n||n===""?null:n}try{if(!(await(0,ha.stat)(xs.CLAUDE_PROJECTS_DIR)).isDirectory())return Kr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Kr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Kr.set(t,""),null)}try{let n=await(0,ha.opendir)(xs.CLAUDE_PROJECTS_DIR),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=(0,ft.resolve)(xs.CLAUDE_PROJECTS_DIR),s=`${(0,ft.basename)(String(t))}.jsonl`,i=r.map(async u=>{let d=(0,ft.resolve)(o,(0,ft.basename)(u)),f=(0,ft.relative)(o,d);if(!f||f.startsWith(".."))return null;let p=(0,ft.join)(d,s);try{return(await(0,ha.stat)(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return Kr.set(t,u),u;return Kr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Kr.set(t,""),null}};var Lk=require("fs/promises");var Uk=require("crypto");var R1="59cf53e54c78",ag=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",D1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",jk=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Do="You are Claude Code, Anthropic's official CLI for Claude.";function O1(t){return typeof t=="string"?t:Array.isArray(t)?t.find(n=>n.type==="text")?.text??"":""}function P1(t){let e=t?.find(n=>n.role==="user");return e?O1(e.content):""}function I1(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return(0,Uk.createHash)("sha256").update(R1+n+e).digest("hex").slice(0,3)}function F1(){return"00000"}function N1(t,e=ag,n=D1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=I1(P1(t),e);return`${Rs}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${F1()};`}function Pu(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 Iu(t,e){for(let r=t.length-1;r>=0;r--)t[r].text.startsWith(Rs)&&t.splice(r,1);let n=N1(e);n&&t.unshift({type:"text",text:n})}function Fu(t){let e=t.findIndex(o=>o.text.startsWith(Rs)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Do){if(r?.text.startsWith(Do)&&r.text.length>Do.length){let o={type:"text",text:r.text.slice(Do.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Do},o);return}t.splice(n,0,{type:"text",text:Do})}}function Nu(t,e){let n=t.findIndex(i=>i.text===Do);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 "${Bn}" 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:{[Bn]:{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:[Bn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function w1(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 wk(t,e){let n=e?.callIdMap??ks(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=xs(Un(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=Do(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:ng(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:Ru(eg(f.function.name,h,r)),status:"completed"})}let d=xk(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 kk(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??ks(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function Sk(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function Ak(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:Tk(t,"in_progress")}))}function Ek(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 vk(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=Un(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)&&Ak(e,n),s?.content&&(e.thinkingContent+=s.content);let i=Ss(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:mr(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&&Ek(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=Do(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=Do(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),Sk(e,n)}function rg(t,e){if(t.finished)return[];t.finished=!0;let n=[];Ak(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};Ek(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=ng(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=Ru(eg(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=Tk(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),Sk(t,n)}function Tk(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:ng(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:Ru(eg(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=xs({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:xk(n)}}function xk(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 ha(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 Rk(t,e,n){let r=e&&typeof e=="object"?Kr(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=ck(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function Dk(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 k1(e);if(t==="openai_responses")return vu(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 k1(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 Kr(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var S1=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"]),A1=["proxy-","x-forwarded-","x-real-ip"];function Ok(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(S1.has(s)||A1.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 Pk(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]}var Nk=require("tiktoken");var og=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())}},Du=new og(100);var sg=require("fs/promises"),ga=require("fs/promises"),ft=require("path"),Rs=require("@caeliq/ccr-shared"),Mk=require("lru-cache");var E1=(0,Nk.get_encoding)("cl100k_base"),yr=t=>E1.encode(t,void 0,[]),Ik="<CCR-SUBAGENT-MODEL>",Fk="</CCR-SUBAGENT-MODEL>",Ds="x-anthropic-billing-header",Os=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Bk(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 v1(t){let e=`${Ds}:`;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 Os(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 Ou(t,e){let n=t.indexOf(Ik);if(n<0)return;let r=n+Ik.length,o=t.indexOf(Fk,r);if(o<0)return;let s=Bk(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Fk.length)}`),s}function Uk(t,e){if(typeof t=="string")return Ou(t,e);if(!(!Os(t)||typeof t.text!="string"))return Ou(t.text,e)}function T1(t){let e=t?.system;if(typeof e=="string")return Ou(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=Uk(r,s=>{typeof r=="string"?e[n]=s:Os(r)&&(r.text=s)});if(o)return o}}function x1(t){if(typeof t.content=="string")return Ou(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=Uk(r,s=>{typeof r=="string"?e[n]=s:Os(r)&&(r.text=s)});if(o)return o}}function R1(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(!Os(r)||r.role!=="user")continue;let o=x1(r);if(o)return o}}function jk(t){return T1(t)||R1(t)}function Lk(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:Os(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(Ds)?{present:!0,isSubagent:v1(r)}:{present:!1,isSubagent:!1}}var ig=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=yr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=yr(s.text).length:s.type==="tool_use"?r+=yr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=yr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=yr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=yr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=yr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=yr(o.name+o.description).length),o.input_schema&&(r+=yr(JSON.stringify(o.input_schema)).length)}),r},D1=async(t,e)=>{if(t.sessionId){let n=await ag(t.sessionId);if(n){let r=(0,ft.resolve)(Rs.HOME_DIR),o=(0,ft.resolve)(r,(0,ft.basename)(n)),s=(0,ft.relative)(r,o);if(!s||s.startsWith(".."))return;let i=`${(0,ft.basename)(String(t.sessionId))}.json`,a=(0,ft.join)(o,"config.json"),u=(0,ft.join)(o,i);try{let d=JSON.parse(await(0,sg.readFile)(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await(0,sg.readFile)(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function $k(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function O1(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function P1(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 I1(t){if(kt(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 F1=async(t,e,n,r)=>{let o=await D1(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=$k(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(O1(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=Bk(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 P1(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:I1(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"}},N1=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{}},Pu=async(t,e,n)=>{let{configService:r,event:o}=n,s=$k(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=N1(i);let a=Du.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=ig(u,d,f),t.tokenCount=m;let w,C=r.get("CUSTOM_ROUTER_PATH");if(C)try{w=await require(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 F1(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"}},Vr=new Mk.LRUCache({max:1e3}),ag=async(t,e)=>{if(Vr.has(t)){let n=Vr.get(t);return!n||n===""?null:n}try{if(!(await(0,ga.stat)(Rs.CLAUDE_PROJECTS_DIR)).isDirectory())return Vr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Vr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Vr.set(t,""),null)}try{let n=await(0,ga.opendir)(Rs.CLAUDE_PROJECTS_DIR),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=(0,ft.resolve)(Rs.CLAUDE_PROJECTS_DIR),s=`${(0,ft.basename)(String(t))}.jsonl`,i=r.map(async u=>{let d=(0,ft.resolve)(o,(0,ft.basename)(u)),f=(0,ft.relative)(o,d);if(!f||f.startsWith(".."))return null;let p=(0,ft.join)(d,s);try{return(await(0,ga.stat)(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return Vr.set(t,u),u;return Vr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Vr.set(t,""),null}};var zk=require("fs/promises");var qk=require("crypto");var M1="59cf53e54c78",cg=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",B1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",Hk=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Oo="You are Claude Code, Anthropic's official CLI for Claude.";function U1(t){return typeof t=="string"?t:Array.isArray(t)?t.find(n=>n.type==="text")?.text??"":""}function j1(t){let e=t?.find(n=>n.role==="user");return e?U1(e.content):""}function L1(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return(0,qk.createHash)("sha256").update(M1+n+e).digest("hex").slice(0,3)}function $1(){return"00000"}function q1(t,e=cg,n=B1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=L1(j1(t),e);return`${Ds}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${$1()};`}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 Fu(t,e){for(let r=t.length-1;r>=0;r--)t[r].text.startsWith(Ds)&&t.splice(r,1);let n=q1(e);n&&t.unshift({type:"text",text:n})}function Nu(t){let e=t.findIndex(o=>o.text.startsWith(Ds)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Oo){if(r?.text.startsWith(Oo)&&r.text.length>Oo.length){let o={type:"text",text:r.text.slice(Oo.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Oo},o);return}t.splice(n,0,{type:"text",text:Oo})}}function Mu(t,e){let n=t.findIndex(i=>i.text===Oo);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 M1(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function B1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function Mu(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 Os(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??B1(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 Oo(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 U1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function j1(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 $k(t,e){let n=cg(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 cg(t,e){let n=Oo(t,"user-agent")||"",r=Oo(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(Oo(t,"x-app")||""),cliSession:!!Oo(t,"x-claude-code-session-id"),stainlessPackage:!!Oo(t,"x-stainless-package-version"),billingSystem:U1(e),identitySystem:j1(e)}}function Bu(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 Uu(t){return t==="claude_desktop"||t==="claude_code"}async function ju(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=Pu(t);Iu(r,t.messages),Fu(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(0,Lk.readFile)(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}Nu(r,t.messages);let s=new Map;Mu(t,s),L1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function L1(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 $1={"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:[]}},qk=/\[1m\]$/i;function jn(t){let e=t||"",n=qk.test(e);return{modelId:e.replace(qk,""),requestedOneMillion:n}}function q1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=jn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function Ps(t){let e=q1(t);if(e)return $1[e]}function ug(t,e){return t?.capabilities.includes(e)??!1}function Hk(t){return(t?.capabilities.length??0)>0}var Wk=require("@caeliq/ccr-shared");async function Gk(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||Mn(t.method,s)||Mn("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}=Ek(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=$k(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:cg(t.headers,d)},"classified Anthropic client"),await H1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await vk(i.protocol,d,r,p);h.model=zk(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 Ou(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=zk(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=z1(h.model,i.protocol),A=jn(C.modelName);C.modelName=A.modelId,f.requestedOneMillion=A.requestedOneMillion;let k=n.providerService.getProvider(C.providerName);k||ga(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=Bu(k);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&Uu(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await ju(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 H1(t,e){let n=Mk(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=Nk(t)}function z1(t,e){let n=typeof t=="string"?t.trim():"";n||ga(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||ga(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)&&ga(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function zk(t,e,n){if(typeof t!="string")return t;let r=(0,Wk.decodeClaudeModelAlias)(t);if(!r)return t;let o=jn(r).modelId;return e(o)||ga(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function ga(t,e,n,r,o="api_error"){let s=_s(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function Lu(t,e,n,r){return n?xk(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 ma(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function Io(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function W1(t,e,n,r,o){let s=Aw(t,e),i=s.signal;s.arm();let a;try{a=await Gk(t,e,n,r,o)}catch(d){throw We(d)||i.aborted?typeof d=="string"?Nn(d):Nn(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=Lu(u,r,a.protocolContext,a.modelName)&&!Io(a.protocolContext),f=!Io(a.protocolContext)&&ma(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);Vk(t,n,u,h);let{requestBody:g,config:b,bypass:m}=await Kk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),w=await Yk(g,b,u,n,m,r,{req:t,signal:i,protocolContext:a.protocolContext}),C=await Xk(g,w,u,r,m,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:m});return await Qk(C,e,a.originalBody,i,a.protocolContext.stream,a.protocolContext.protocol)}catch(d){if(We(d))throw typeof d=="string"?Nn(d):d;if(i.aborted)throw Nn(i.reason??d);if(Uh(d)){let f=await G1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw Nn(i.reason??Tt)}throw d}}async function G1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=Ew(a,i);if(!u?.length||s?.aborted||We(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:Fn(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=Mh(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 ys(f,s)}catch(p){if(We(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=Bu(C),k=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:A,anthropicDestinationInScope:A!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&A!=="out_of_scope"&&Uu(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 ju(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=Lu(C,r,k,w)&&!Io(k),q=!Io(k)&&ma(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;Vk(x,n,C,j);let{requestBody:ee,config:z,bypass:te}=await Kk(j,C,r,t.headers,{req:x,provider:C,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:k,skipClientNormalization:!0}),Q=await Yk(ee,z,C,n,te,r,{req:x,signal:s,protocolContext:k}),ye=await Xk(ee,Q,C,r,te,{req:x,signal:s,protocolContext:k});return t.log.info(`Fallback model ${h} succeeded`),await Qk(ye,e,g?.originalBody??t.body,s,k?.stream,k?.protocol)}catch(g){if(We(g))throw g;if(s?.aborted)throw Nn(s.reason??Tt);if(!Uh(g))throw t.log.warn({fallbackModel:h,error:Fn(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:Fn(g)},`Fallback model ${h} failed`),p<u.length-1){let m=Mh(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 ys(m,s)}catch(w){if(We(w)||s?.aborted)return null;throw w}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function Kk(t,e,n,r,o){let s=t,i={},a=Lu(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!Io(o?.protocolContext)),d=Io(o?.protocolContext),f=!d&&ma(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Tk(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:yu(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:yu(i.headers,b.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=mu(s),s=gu(s,e,o)),{requestBody:s,config:i,bypass:u}}function Vk(t,e,n,r){t&&(t._cachePrefixClientDiff=Vh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function Yk(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=Vh(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 ek(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=yu(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=Lw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},m=await tk(w=>bs(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=Ve(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=qh(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=Ve(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?ms(A):void 0,provider:n.name,model:t.model},V}return u(m)}async function Xk(t,e,n,r,o,s){let i=e,a=Io(s?.protocolContext),u=o||!a&&ma(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&ma(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 Qk(t,e,n,r,o,s){t.ok||e.code(t.status);let i=qh(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"?Xh(t.body):t.body,d=Yh(u),f=Jk.Readable.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"||We(m))&&h()}),e.raw.on("close",()=>{e.raw.writableEnded||h()}),f.on("error",m=>{m?.code==="ERR_STREAM_PREMATURE_CLOSE"||m?.code==="ABORT_ERR"||We(m)||e.log?.error?.(Fn(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 lg=async t=>{let e={config:{rateLimit:{...Po.RATE_LIMIT_CONFIG}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=Mn(s.method,i);s.pathname=i,a&&(s.protocolMatch=a,s.clientProtocol=a.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:Iw})),t.get("/health",e,async()=>{let s=Pw();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 Au()){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)=>W1(u,d,t,i,a)))}t.post("/providers",{config:{rateLimit:{...Po.RATE_LIMIT_CONFIG}},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||!J1(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:{...Po.RATE_LIMIT_CONFIG}},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:{...Po.RATE_LIMIT_CONFIG}},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:{...Po.RATE_LIMIT_CONFIG}},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:{...Po.RATE_LIMIT_CONFIG}},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 J1(t){try{return new URL(t),!0}catch{return!1}}var Fo=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 pt=[];for(let t=0;t<256;++t)pt.push((t+256).toString(16).slice(1));function Zk(t,e=0){return(pt[t[e+0]]+pt[t[e+1]]+pt[t[e+2]]+pt[t[e+3]]+"-"+pt[t[e+4]]+pt[t[e+5]]+"-"+pt[t[e+6]]+pt[t[e+7]]+"-"+pt[t[e+8]]+pt[t[e+9]]+"-"+pt[t[e+10]]+pt[t[e+11]]+pt[t[e+12]]+pt[t[e+13]]+pt[t[e+14]]+pt[t[e+15]]).toLowerCase()}var K1=new Uint8Array(16);function dg(){return crypto.getRandomValues(K1)}function V1(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():Y1(t,e,n)}function Y1(t,e,n){t=t||{};let r=t.random??t.rng?.()??dg();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 Zk(r)}var Ln=V1;var eS=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var fg=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function X1(t){if(typeof t!="string")return!1;let e=t.trim();return fg.some(n=>e===n)}function Q1(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 Z1(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function eI(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:Q1(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&X1(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}Z1(o)&&(e.steering="meaningful")}return e}function tI(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 tS(t){return{source:"anthropic",sourceSessionIdentity:tI(t.metadata),turnIntent:eI(t.messages)}}var No=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 H1(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function z1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function Bu(t,e){let n=r=>{let o=H1(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 Ps(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??z1(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 Po(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 W1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function G1(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 Wk(t,e){let n=ug(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 ug(t,e){let n=Po(t,"user-agent")||"",r=Po(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(Po(t,"x-app")||""),cliSession:!!Po(t,"x-claude-code-session-id"),stainlessPackage:!!Po(t,"x-stainless-package-version"),billingSystem:W1(e),identitySystem:G1(e)}}function Uu(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 ju(t){return t==="claude_desktop"||t==="claude_code"}async function Lu(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=Iu(t);Fu(r,t.messages),Nu(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(0,zk.readFile)(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}Mu(r,t.messages);let s=new Map;Bu(t,s),J1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function J1(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:[]}},Gk=/\[1m\]$/i;function jn(t){let e=t||"",n=Gk.test(e);return{modelId:e.replace(Gk,""),requestedOneMillion:n}}function V1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=jn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function Is(t){let e=V1(t);if(e)return K1[e]}function lg(t,e){return t?.capabilities.includes(e)??!1}function Jk(t){return(t?.capabilities.length??0)>0}var Vk=require("@caeliq/ccr-shared");async function Yk(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||Mn(t.method,s)||Mn("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}=Rk(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=Wk(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:ug(t.headers,d)},"classified Anthropic client"),await Y1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await Dk(i.protocol,d,r,p);$w(h,n.configService.get("REASONING_AUTO_SUMMARY")),h.model=Kk(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 Pu(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=Kk(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=X1(h.model,i.protocol),A=jn(C.modelName);C.modelName=A.modelId,f.requestedOneMillion=A.requestedOneMillion;let k=n.providerService.getProvider(C.providerName);k||ma(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=Kr(h),x=Uu(k);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&ju(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await Lu(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 Y1(t,e){let n=Lk(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=jk(t)}function X1(t,e){let n=typeof t=="string"?t.trim():"";n||ma(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||ma(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)&&ma(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function Kk(t,e,n){if(typeof t!="string")return t;let r=(0,Vk.decodeClaudeModelAlias)(t);if(!r)return t;let o=jn(r).modelId;return e(o)||ma(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function ma(t,e,n,r,o="api_error"){let s=bs(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function $u(t,e,n,r){return n?Pk(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 ya(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function Fo(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function Q1(t,e,n,r,o){let s=vw(t,e),i=s.signal;s.arm();let a;try{a=await Yk(t,e,n,r,o)}catch(d){throw We(d)||i.aborted?typeof d=="string"?Nn(d):Nn(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=$u(u,r,a.protocolContext,a.modelName)&&!Fo(a.protocolContext),f=!Fo(a.protocolContext)&&ya(u,r,a.protocolContext),p=a.protocolContext.anthropicNativeWire?a.originalBody:a.clientWireBody??a.originalBody,h=a.protocolContext.anthropicNativeWire||d||f?{...typeof p=="object"&&p?Kr(p):{},model:a.modelName}:Kr(a.unifiedBody);Zk(t,n,u,h);let{requestBody:g,config:b,bypass:m}=await Qk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),w=await eS(g,b,u,n,m,r,{req:t,signal:i,protocolContext:a.protocolContext}),C=await tS(g,w,u,r,m,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:m});return await nS(C,e,a.originalBody,i,a.protocolContext.stream,a.protocolContext.protocol)}catch(d){if(We(d))throw typeof d=="string"?Nn(d):d;if(i.aborted)throw Nn(i.reason??d);if(Uh(d)){let f=await Z1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw Nn(i.reason??xt)}throw d}}async function Z1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=Tw(a,i);if(!u?.length||s?.aborted||We(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:Fn(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=Mh(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 _s(f,s)}catch(p){if(We(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=Uu(C),k=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:A,anthropicDestinationInScope:A!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&A!=="out_of_scope"&&ju(g.protocolContext.anthropicClientKind||"other")),anthropicPolicyApplied:!1,anthropicSystemTransformed:!1,claudeAuthToolNameMap:new Map}:g?.protocolContext,E={...Kr(g?.prePolicyUnifiedBody||g?.unifiedBody||t.unifiedBody||t.body),model:w};k?.anthropicDestinationInScope&&k.anthropicClientKind==="other"&&await Lu(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=$u(C,r,k,w)&&!Fo(k),q=!Fo(k)&&ya(C,r,k),V=k?.anthropicNativeWire?g?.originalBody:g?.clientWireBody??g?.originalBody,j=k?.anthropicNativeWire||O||q?{...typeof V=="object"&&V?Kr(V):{},model:w}:E;Zk(x,n,C,j);let{requestBody:ee,config:z,bypass:te}=await Qk(j,C,r,t.headers,{req:x,provider:C,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:k,skipClientNormalization:!0}),Q=await eS(ee,z,C,n,te,r,{req:x,signal:s,protocolContext:k}),ye=await tS(ee,Q,C,r,te,{req:x,signal:s,protocolContext:k});return t.log.info(`Fallback model ${h} succeeded`),await nS(ye,e,g?.originalBody??t.body,s,k?.stream,k?.protocol)}catch(g){if(We(g))throw g;if(s?.aborted)throw Nn(s.reason??xt);if(!Uh(g))throw t.log.warn({fallbackModel:h,error:Fn(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:Fn(g)},`Fallback model ${h} failed`),p<u.length-1){let m=Mh(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 _s(m,s)}catch(w){if(We(w)||s?.aborted)return null;throw w}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function Qk(t,e,n,r,o){let s=t,i={},a=$u(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!Fo(o?.protocolContext)),d=Fo(o?.protocolContext),f=!d&&ya(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Ok(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:_u(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:_u(i.headers,b.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=yu(s),s=mu(s,e,o)),{requestBody:s,config:i,bypass:u}}function Zk(t,e,n,r){t&&(t._cachePrefixClientDiff=Yh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function eS(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=Yh(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 ok(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=_u(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=zw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},m=await sk(w=>Cs(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=Ve(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=Hh(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=Ve(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?ys(A):void 0,provider:n.name,model:t.model},V}return u(m)}async function tS(t,e,n,r,o,s){let i=e,a=Fo(s?.protocolContext),u=o||!a&&ya(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&ya(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 nS(t,e,n,r,o,s){t.ok||e.code(t.status);let i=Hh(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"?Qh(t.body):t.body,d=Xh(u),f=Xk.Readable.fromWeb(d),p=!1,h=()=>{if(!p){p=!0;try{f.destroyed||f.destroy()}catch{}}},g=()=>{r&&r.removeEventListener("abort",h)};return Rw(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"||We(m))&&h()}),e.raw.on("close",()=>{e.raw.writableEnded||h()}),f.on("error",m=>{m?.code==="ERR_STREAM_PREMATURE_CLOSE"||m?.code==="ABORT_ERR"||We(m)||e.log?.error?.(Fn(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 dg=async t=>{let e={config:{rateLimit:{...Io.RATE_LIMIT_CONFIG}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=Mn(s.method,i);s.pathname=i,a&&(s.protocolMatch=a,s.clientProtocol=a.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:Nw})),t.get("/health",e,async()=>{let s=Fw();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 Eu()){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)=>Q1(u,d,t,i,a)))}t.post("/providers",{config:{rateLimit:{...Io.RATE_LIMIT_CONFIG}},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||!eI(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:{...Io.RATE_LIMIT_CONFIG}},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:{...Io.RATE_LIMIT_CONFIG}},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:{...Io.RATE_LIMIT_CONFIG}},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:{...Io.RATE_LIMIT_CONFIG}},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 eI(t){try{return new URL(t),!0}catch{return!1}}var No=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 pt=[];for(let t=0;t<256;++t)pt.push((t+256).toString(16).slice(1));function rS(t,e=0){return(pt[t[e+0]]+pt[t[e+1]]+pt[t[e+2]]+pt[t[e+3]]+"-"+pt[t[e+4]]+pt[t[e+5]]+"-"+pt[t[e+6]]+pt[t[e+7]]+"-"+pt[t[e+8]]+pt[t[e+9]]+"-"+pt[t[e+10]]+pt[t[e+11]]+pt[t[e+12]]+pt[t[e+13]]+pt[t[e+14]]+pt[t[e+15]]).toLowerCase()}var tI=new Uint8Array(16);function fg(){return crypto.getRandomValues(tI)}function nI(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():rI(t,e,n)}function rI(t,e,n){t=t||{};let r=t.random??t.rng?.()??fg();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 rS(r)}var Ln=nI;var oS=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var pg=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function oI(t){if(typeof t!="string")return!1;let e=t.trim();return pg.some(n=>e===n)}function sI(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 iI(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function aI(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:sI(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&oI(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}iI(o)&&(e.steering="meaningful")}return e}function cI(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 sS(t){return{source:"anthropic",sourceSessionIdentity:cI(t.metadata),turnIntent:aI(t.messages)}}var Mo=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]
144
144
  `:r+=`data: ${JSON.stringify(e.data)}
145
145
  `),r+=`
146
- `,n.enqueue(r)}})}};var pg=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let i=await e(s,r);i!==void 0&&r.enqueue(i)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};function $u(t,e,n,r){let o={...r,...Fn(n)};t?.error?t.error(o,e):console.error(e,o)}function nI(t){if(We(t)||!hr(t))return t;let e=t;if(e&&typeof e=="object"&&e.code==="provider_network_error")return e;let n=String(e?.cause?.message||e?.cause?.code||"").trim(),r=String(e?.message||"Upstream stream failed"),o=new Error(n&&!r.includes(n)?`Upstream stream terminated: ${r} (${n})`:`Upstream stream terminated: ${r}`);return Object.assign(o,{type:"api_error",code:"provider_network_error",cause:e})}function Fe(t,e,n){let r=new TextEncoder,o=!1,s=null,i=!1,a=new ReadableStream({async start(u){if(!t.body){u.close();return}let d={controller:u,encoder:r};try{let f=t.body.pipeThrough(new TextDecoderStream).pipeThrough(new ln).pipeThrough(new No).getReader();for(s=f;!i;){let{done:p,value:h}=await f.read();if(p)break;if(!h)continue;let g=h.split(`
147
- `);for(let b of g)if(b.trim())try{e(b,d)}catch(m){$u(n?.logger,"Error processing line",m,{line:Ve(b)}),u.enqueue(r.encode(b+`
148
- `))}}}catch(f){if(!i){let p=nI(f);$u(n?.logger,"Stream error",p);let h=!1;try{h=n?.onError?.(p,d)===!0}catch(g){$u(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($u(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:{..._u(t.headers),"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function Ee(t,e){return e.encode(`data: ${t}
146
+ `,n.enqueue(r)}})}};var hg=(t,e)=>{let n=t.getReader();return new ReadableStream({async start(r){try{for(;;){let{done:o,value:s}=await n.read();if(o){r.close();break}let i=await e(s,r);i!==void 0&&r.enqueue(i)}}catch(o){r.error(o)}finally{n.releaseLock()}}})};function qu(t,e,n,r){let o={...r,...Fn(n)};t?.error?t.error(o,e):console.error(e,o)}function uI(t){if(We(t)||!hr(t))return t;let e=t;if(e&&typeof e=="object"&&e.code==="provider_network_error")return e;let n=String(e?.cause?.message||e?.cause?.code||"").trim(),r=String(e?.message||"Upstream stream failed"),o=new Error(n&&!r.includes(n)?`Upstream stream terminated: ${r} (${n})`:`Upstream stream terminated: ${r}`);return Object.assign(o,{type:"api_error",code:"provider_network_error",cause:e})}function Fe(t,e,n){let r=new TextEncoder,o=!1,s=null,i=!1,a=new ReadableStream({async start(u){if(!t.body){u.close();return}let d={controller:u,encoder:r};try{let f=t.body.pipeThrough(new TextDecoderStream).pipeThrough(new ln).pipeThrough(new Mo).getReader();for(s=f;!i;){let{done:p,value:h}=await f.read();if(p)break;if(!h)continue;let g=h.split(`
147
+ `);for(let b of g)if(b.trim())try{e(b,d)}catch(m){qu(n?.logger,"Error processing line",m,{line:Ve(b)}),u.enqueue(r.encode(b+`
148
+ `))}}}catch(f){if(!i){let p=uI(f);qu(n?.logger,"Stream error",p);let h=!1;try{h=n?.onError?.(p,d)===!0}catch(g){qu(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(qu(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:{...bu(t.headers),"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function Ee(t,e){return e.encode(`data: ${t}
149
149
 
150
150
  `)}function Oe(t,e){return e.encode(t+`
151
- `)}var qu=ot(hS(),1),CI={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"},hg="\u26A0\uFE0F Upstream ended the turn without a reply";function ya(t){return t?CI[t.toUpperCase()]||t.toLowerCase():null}function gg(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${hg} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var Hu=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:ya(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:ya(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 zu(t,e){return e[t]||t}function Wu(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 Gu(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 Is(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 Ju(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 _a(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof qu.default=="function"?qu.default:qu.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 gS(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 Yr(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 mg(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 mS(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=zu(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}:{}})}),Wu(s.content).forEach(d=>{a.push(Ju(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:Gu(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=Is(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})),fu(r)}function yS(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=mg(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:Yr(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 Fe(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 Hu=ot(_S(),1),TI={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"},gg="\u26A0\uFE0F Upstream ended the turn without a reply";function _a(t){return t?TI[t.toUpperCase()]||t.toLowerCase():null}function mg(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${gg} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var zu=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:_a(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:_a(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 Wu(t,e){return e[t]||t}function Gu(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 Ju(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 Fs(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 Ku(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 ba(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof Hu.default=="function"?Hu.default:Hu.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 bS(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 Xr(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 yg(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 CS(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=Wu(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}:{}})}),Gu(s.content).forEach(d=>{a.push(Ku(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:Ju(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=Fs(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})),pu(r)}function wS(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 Vu(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=yg(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:Xr(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 Fe(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
- `))}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:Yr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
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:Xr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
155
155
 
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:Yr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
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:Xr(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:Yr(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:Xr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(m)}
159
159
 
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:Yr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
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:Xr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
161
161
 
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:Yr(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(w)}
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:Xr(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:mg(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:Yr({...r,...g.usage})};f.enqueue(p.encode(`data: ${JSON.stringify(b)}
164
+ `))}else if(g.type==="message_delta"){let b={choices:[{delta:{},finish_reason:yg(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:Xr({...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:mg(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:Yr(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:yg(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:Xr(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}var Ag=require("crypto");var Rt=require("fs"),Fs=require("path"),yg=require("os"),bS=require("crypto"),wI=(0,Fs.join)((0,yg.homedir)(),".claude-code-router","claude_auth.json"),kI=(0,Fs.join)((0,yg.homedir)(),".claude-code-router","claude_device.json"),SI=/^[0-9a-f]{64}$/;function CS(){return process.env.CCR_CLAUDE_AUTH_FILE||wI}function AI(){return process.env.CCR_CLAUDE_DEVICE_FILE||kI}var _S={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"},Vu=null;function _g(){try{let t=CS();if(!(0,Rt.existsSync)(t))return null;let e=(0,Rt.readFileSync)(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function bg(t){let e=CS(),n=(0,Fs.dirname)(e);(0,Rt.existsSync)(n)||(0,Rt.mkdirSync)(n,{recursive:!0}),(0,Rt.writeFileSync)(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function EI(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function Cg(t){let e=await fetch(_S.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:_S.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 ba(t){let e=_g();if(!e)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(t?.force||EI(e)){if(!e.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");Vu||(Vu=Cg(e.refresh_token).then(n=>(bg(n),n)).finally(()=>{Vu=null})),e=await Vu}return e}function wS(){let t=AI();try{if((0,Rt.existsSync)(t)){let r=JSON.parse((0,Rt.readFileSync)(t,"utf-8"));if(typeof r.device_id=="string"&&SI.test(r.device_id))return r.device_id}}catch{}let e=(0,bS.randomBytes)(32).toString("hex"),n=(0,Fs.dirname)(t);return(0,Rt.existsSync)(n)||(0,Rt.mkdirSync)(n,{recursive:!0}),(0,Rt.writeFileSync)(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}function Ca(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 kS="oauth-2025-04-20";function vI(...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 wg(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 TI(t){return t?.startsWith("claude-cli/")??!1}function kg(t){return t.clientBeta?.trim()?vI(t.clientBeta,kS):kS}function Eg(t,e){let{requestedOneMillion:n}=jn(t),r=Ps(t),o=u=>ug(r,u),i=jn(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"),Hk(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 vg(t,e){if(!t||!e)return t;let n=jn(t).modelId;return Ps(n)?.nativeOneMillion?n:`${n}[1m]`}function Tg(t,e){let n=o=>ug(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 xI="0.94.0";function RI(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function DI(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Sg;function SS(){return Sg||(Sg=(0,Ag.randomUUID)()),Sg}var OI=new Set(["authorization","x-api-key","anthropic-beta","cookie","set-cookie","host","content-length","content-encoding","connection","transfer-encoding","upgrade","te","trailer"]);function PI(){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||OI.has(r.toLowerCase())||(t[r]=o)}return t}function xg(){let t=[jk,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/${ag} (external, ${t})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":SS(),"x-client-request-id":(0,Ag.randomUUID)(),"x-stainless-arch":RI(),"x-stainless-lang":"js","x-stainless-os":DI(),"x-stainless-package-version":xI,"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"}:{},...PI()}}function Rg(){return{user_id:JSON.stringify({device_id:wS(),account_uuid:"",session_id:SS()})}}var Yu=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await ba(),s=r?.req?.headers||{},i=wg(s,"user-agent"),a=r?.protocolContext?.anthropicClientKind||(TI(i)?"claude_code":"other"),u=a==="claude_code",d=!r?.protocolContext||r.protocolContext.anthropicDestinationInScope===!0;if(a==="other"&&d&&!r?.protocolContext?.anthropicPolicyApplied){let g=Pu(e);Iu(g,e.messages),Fu(g),Nu(g,e.messages);let b=new Map;Mu(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?wg(s,"anthropic-beta"):void 0,p=kg(u?{clientBeta:f}:{clientBeta:Eg(vg(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=wg(s,g);b&&(h[g]=b)}else{Object.assign(h,xg());let g=Ps(e.model);r&&(r.claudeAuthPostBuildHook=b=>{Tg(b,g),b.metadata={...b.metadata||{},...Rg()}})}return{body:e,config:{headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async auth(e,n,r){let o=await ba(),s=r?.req?.headers||{},i=Oo(s,"anthropic-beta");return{body:e,config:{url:Ca(n?.baseUrl),headers:{Authorization:`Bearer ${o.access_token}`,"anthropic-beta":kg({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 Os(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 Fe(e,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
171
- `));return}try{let u=JSON.parse(i.slice(6));Os(u,r),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
170
+ `))}}}catch(g){n?.error(`Error parsing ${e} stream chunk`,h,g.message)}}}})}return t}var Eg=require("crypto");var Ot=require("fs"),Ns=require("path"),_g=require("os"),SS=require("crypto"),xI=(0,Ns.join)((0,_g.homedir)(),".claude-code-router","claude_auth.json"),RI=(0,Ns.join)((0,_g.homedir)(),".claude-code-router","claude_device.json"),DI=/^[0-9a-f]{64}$/;function AS(){return process.env.CCR_CLAUDE_AUTH_FILE||xI}function OI(){return process.env.CCR_CLAUDE_DEVICE_FILE||RI}var kS={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"},Yu=null;function bg(){try{let t=AS();if(!(0,Ot.existsSync)(t))return null;let e=(0,Ot.readFileSync)(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function Cg(t){let e=AS(),n=(0,Ns.dirname)(e);(0,Ot.existsSync)(n)||(0,Ot.mkdirSync)(n,{recursive:!0}),(0,Ot.writeFileSync)(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function PI(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function wg(t){let e=await fetch(kS.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:kS.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 Ca(t){let e=bg();if(!e)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(t?.force||PI(e)){if(!e.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");Yu||(Yu=wg(e.refresh_token).then(n=>(Cg(n),n)).finally(()=>{Yu=null})),e=await Yu}return e}function ES(){let t=OI();try{if((0,Ot.existsSync)(t)){let r=JSON.parse((0,Ot.readFileSync)(t,"utf-8"));if(typeof r.device_id=="string"&&DI.test(r.device_id))return r.device_id}}catch{}let e=(0,SS.randomBytes)(32).toString("hex"),n=(0,Ns.dirname)(t);return(0,Ot.existsSync)(n)||(0,Ot.mkdirSync)(n,{recursive:!0}),(0,Ot.writeFileSync)(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}function wa(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 vS="oauth-2025-04-20";function II(...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 kg(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 FI(t){return t?.startsWith("claude-cli/")??!1}function Sg(t){return t.clientBeta?.trim()?II(t.clientBeta,vS):vS}function vg(t,e){let{requestedOneMillion:n}=jn(t),r=Is(t),o=u=>lg(r,u),i=jn(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"),Jk(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 Tg(t,e){if(!t||!e)return t;let n=jn(t).modelId;return Is(n)?.nativeOneMillion?n:`${n}[1m]`}function xg(t,e){let n=o=>lg(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 NI="0.94.0";function MI(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function BI(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Ag;function TS(){return Ag||(Ag=(0,Eg.randomUUID)()),Ag}var UI=new Set(["authorization","x-api-key","anthropic-beta","cookie","set-cookie","host","content-length","content-encoding","connection","transfer-encoding","upgrade","te","trailer"]);function jI(){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||UI.has(r.toLowerCase())||(t[r]=o)}return t}function Rg(){let t=[Hk,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/${cg} (external, ${t})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":TS(),"x-client-request-id":(0,Eg.randomUUID)(),"x-stainless-arch":MI(),"x-stainless-lang":"js","x-stainless-os":BI(),"x-stainless-package-version":NI,"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"}:{},...jI()}}function Dg(){return{user_id:JSON.stringify({device_id:ES(),account_uuid:"",session_id:TS()})}}var Xu=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await Ca(),s=r?.req?.headers||{},i=kg(s,"user-agent"),a=r?.protocolContext?.anthropicClientKind||(FI(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);Fu(g,e.messages),Nu(g),Mu(g,e.messages);let b=new Map;Bu(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?kg(s,"anthropic-beta"):void 0,p=Sg(u?{clientBeta:f}:{clientBeta:vg(Tg(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=kg(s,g);b&&(h[g]=b)}else{Object.assign(h,Rg());let g=Is(e.model);r&&(r.claudeAuthPostBuildHook=b=>{xg(b,g),b.metadata={...b.metadata||{},...Dg()}})}return{body:e,config:{headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async auth(e,n,r){let o=await Ca(),s=r?.req?.headers||{},i=Po(s,"anthropic-beta");return{body:e,config:{url:wa(n?.baseUrl),headers:{Authorization:`Bearer ${o.access_token}`,"anthropic-beta":Sg({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 Ps(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 Fe(e,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
171
+ `));return}try{let u=JSON.parse(i.slice(6));Ps(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=_g();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await Cg(n.refresh_token);return bg(r),{Authorization:`Bearer ${r.access_token}`}}};function Xu(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 II(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 Qu=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:Ca(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,r);o.model=jn(o.model).modelId;let s=r?.protocolContext,a=s?.anthropicDestinationInScope===!0&&s.anthropicClientKind==="other"&&s.anthropicPolicyApplied===!0&&s?.anthropicProviderMode==="api_key";a&&(Tg(o,Ps(o.model)),o.metadata={...o.metadata||{},...Rg()}),r?.claudeAuthPostBuildHook?.(o);let u=Ca(n?.baseUrl),d={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return a&&Object.assign(d,xg(),{"anthropic-beta":Eg(vg(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 Os(i,o),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:r.headers})}return s.includes("text/event-stream")&&r.body?Fe(r,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
175
- `));return}try{let u=JSON.parse(i.slice(6));Os(u,o),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
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=bg();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await wg(n.refresh_token);return Cg(r),{Authorization:`Bearer ${r.access_token}`}}};function Qu(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 LI(t,e){if(!t||typeof t!="object")return;let n=structuredClone(t);if(n.effort!==void 0){let r=e?void 0:qw(n.effort);r?n.effort=r:delete n.effort}return Object.keys(n).length?n:void 0}var Zu=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:wa(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,{...r||{},provider:n});o.model=jn(o.model).modelId;let s=r?.protocolContext,a=s?.anthropicDestinationInScope===!0&&s.anthropicClientKind==="other"&&s.anthropicPolicyApplied===!0&&s?.anthropicProviderMode==="api_key";a&&(xg(o,Is(o.model)),o.metadata={...o.metadata||{},...Dg()}),r?.claudeAuthPostBuildHook?.(o);let u=wa(n?.baseUrl),d={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return a&&Object.assign(d,Rg(),{"anthropic-beta":vg(Tg(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 Vu(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 Ps(i,o),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:r.headers})}return s.includes("text/event-stream")&&r.body?Fe(r,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
175
+ `));return}try{let u=JSON.parse(i.slice(6));Ps(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
- `))}},{logger:this.logger}):r}async transformRequestOut(e,n){n&&(n.unifiedRequest=tS(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
- `)||JSON.stringify(g.content),tool_call_id:gr(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"?eS(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:gr(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=Nt(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={...Cs(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:gr(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=vs(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:gr(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=Mt(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=II(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
178
+ `))}},{logger:this.logger}):r}async transformRequestOut(e,n){n&&(n.unifiedRequest=sS(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
+ `)||JSON.stringify(g.content),tool_call_id:gr(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"?oS(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:gr(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=Rt(e.output_config?.effort??e.effort);if(e.thinking||i){let f=e.thinking?e.thinking.type==="enabled"||e.thinking.type==="adaptive":!0,p=typeof e.thinking?.summary=="string"?e.thinking.summary.trim().toLowerCase():void 0,h=p==="auto"||p==="detailed"||p==="concise"||p==="none"?p:void 0;s.reasoning={...ws(i,f),...typeof e.thinking?.budget_tokens=="number"?{max_tokens:e.thinking.budget_tokens}:{},...h?{summary:h}:{}}}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:gr(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=Ts(w);if(A.thinking){let k=As(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:gr(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=kt(e.reasoning,e.thinking);if(h)f.thinking={type:"disabled"};else if(p?.thinking)f.thinking=p.thinking;else if(e.anthropic_thinking)f.thinking=e.anthropic_thinking;else if(e.reasoning?.enabled||e.reasoning?.effort){let w=Jr(e,r?.provider);f.thinking=w?{type:"adaptive",display:"summarized"}:{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=LI(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
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
@@ -202,7 +202,7 @@ data: ${JSON.stringify(Ce)}
202
202
  `));continue}if(f=Z.model||f,!p&&!A&&!g){p=!0;let Ce={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(Ce)}
204
204
 
205
- `))}let ie=Z.choices?.[0];if(Z.usage&&(d?d.usage=Xu(Z.usage):d={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Xu(Z.usage)}),!ie)continue;let Pe=Un(ie?.delta);if(Pe&&!A&&!g){let Ce=typeof Pe.content=="string"?Pe.content:"",H=Ss(Pe);if(Ce||H){if(x>=0&&!k){let Ae={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
205
+ `))}let ie=Z.choices?.[0];if(Z.usage&&(d?d.usage=Qu(Z.usage):d={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:Qu(Z.usage)}),!ie)continue;let Pe=Un(ie?.delta);if(Pe&&!A&&!g){let Ce=typeof Pe.content=="string"?Pe.content:"",H=As(Pe);if(Ce||H){if(x>=0&&!k){let Ae={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
206
206
  data: ${JSON.stringify(Ae)}
207
207
 
208
208
  `)),x=-1,h=!1}if(!k){let Ae=q(),tt={type:"content_block_start",index:Ae,content_block:{type:"thinking",thinking:""}};V(a.encode(`event: content_block_start
@@ -250,17 +250,17 @@ data: ${JSON.stringify(S)}
250
250
  `))}catch(ae){this.logger?.error(ae)}}}}}if(ie?.finish_reason&&!A&&!g){if(w===0&&C===0&&this.logger?.warn("No content in the stream response!"),x>=0){let Ce={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
251
251
  data: ${JSON.stringify(Ce)}
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"}[ie.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:Xu(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=Un(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_${Ln()}`;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:gr(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:{...Xu(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 FI=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 Xr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Xr(r,e));let n={};for(let r in t){if(e!=="properties"&&!FI.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]=Xr(o[i]);n[r]=s}else r==="items"?n[r]=Xr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>Xr(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 Ns(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ns);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]=Ns(g[m]);e[h]=b}else h==="items"?e[h]=Ns(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(Ns):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 Zu(t){return!t||typeof t!="object"?t:Xr(t)}var wa=["minimal","low","medium","high"];function NI(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function MI(t){let e=NI(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:wa}:{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 BI(t,e){let n=t.toLowerCase(),r=wa.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=wa.indexOf(n);return o<0?r[r.length-1]:r.find(s=>wa.indexOf(s)>=o)??r[r.length-1]}function UI(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function jI(t,e,n){return Math.min(Math.max(t,e),n)}function AS(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=MI(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=wa.filter(f=>r.levels.includes(f));return s?{includeThoughts:!1,thinkingLevel:d[0]}:o?{includeThoughts:!0,thinkingLevel:BI(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?UI(o,r.max):void 0;if(typeof a!="number")return{includeThoughts:!0};let u=jI(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 Mo=new Map,ES=(t,e)=>`${t||"default"}${e}`;function vS(t,e,n){if(!e||!n)return;let r=ES(t,e);for(Mo.delete(r),Mo.set(r,{signature:n,expiresAt:Date.now()+216e5});Mo.size>4096;){let o=Mo.keys().next();if(o.done)break;Mo.delete(o.value)}}function TS(t,e){if(!e)return;let n=ES(t,e),r=Mo.get(n);if(r){if(r.expiresAt<=Date.now()){Mo.delete(n);return}return r.signature}}function LI(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var Ms={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function $I(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(Ms).includes(r)?r:Ms.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(Ms).includes(o)?o:Ms.TYPE_UNSPECIFIED})}}}function ka(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)&&$I(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(Ms).includes(u)?u:Ms.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=ka(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(ka(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=ka(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 qI(t,e){let n=r=>e?.collapseUnions?Ns(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=Xr(r.parameters);r.parameters=n(ka(o))}if(r.response){let o=Xr(r.response);r.response=n(ka(o))}}return t}var RS="skip_thought_signature_validator";function el(t,e){let n=[],r=t.tools||[],o=r.filter(C=>Is(C).name!=="web_search").map(C=>{let{name:A,description:k,parameters:E}=Is(C);return{name:gS(A),description:k,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(qI({functionDeclarations:o},{collapseUnions:LI(t.model)})),r.find(C=>Is(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=zu(C.role,{assistant:"model"}),k=[],E=Un(C),x=Ss(E),O=x?.startsWith("ccr_")?void 0:x,q=j=>A==="model"&&(j==="(no content)"||j.startsWith(hg));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})}}),Wu(C.content).forEach(ee=>{k.push(Ju(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||TS(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?RS: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(ye=>ye.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(ye=>ye.type==="text").map(ye=>ye.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=Gu(i,"parts"),b={},m=AS(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(!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"}[ie.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:Qu(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=Un(r.message);if(s?.content){let u=As(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_${Ln()}`;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:gr(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:{...Qu(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 Qr(t,e){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Qr(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]=Qr(o[i]);n[r]=s}else r==="items"?n[r]=Qr(o,r):["anyOf","allOf","oneOf"].includes(r)&&Array.isArray(o)?n[r]=o.map(s=>Qr(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 Ms(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ms);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]=Ms(g[m]);e[h]=b}else h==="items"?e[h]=Ms(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(Ms):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 el(t){return!t||typeof t!="object"?t:Qr(t)}var ka=["minimal","low","medium","high"];function qI(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function HI(t){let e=qI(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:ka}:{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 zI(t,e){let n=t.toLowerCase(),r=ka.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=ka.indexOf(n);return o<0?r[r.length-1]:r.find(s=>ka.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 GI(t,e,n){return Math.min(Math.max(t,e),n)}function xS(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=HI(t.model);if(r.kind==="none")return;let o=e.effort?.toLowerCase(),s=o==="none"||e.enabled===!1,i=Jr(t),a=e.summary==="none"?!1:i?!0:!s;if(r.kind==="includeOnly")return s?void 0:{includeThoughts:a};if(r.kind==="level"){let p=ka.filter(h=>r.levels.includes(h));return s?{includeThoughts:!1,thinkingLevel:p[0]}:o?{includeThoughts:a,thinkingLevel:zI(o,r.levels)}:{includeThoughts:a}}if(s)return r.min===0?{includeThoughts:!1,thinkingBudget:0}:void 0;let u=e.max_tokens,d=typeof u=="number"?u:o?WI(o,r.max):void 0;if(typeof d!="number")return{includeThoughts:a};let f=GI(d,r.min,r.max);if(t.max_tokens&&f>=t.max_tokens&&(f=t.max_tokens-1),f<r.min){if(r.requireMin)return;f=r.min}return{includeThoughts:a,thinkingBudget:f}}var Bo=new Map,RS=(t,e)=>`${t||"default"}${e}`;function DS(t,e,n){if(!e||!n)return;let r=RS(t,e);for(Bo.delete(r),Bo.set(r,{signature:n,expiresAt:Date.now()+216e5});Bo.size>4096;){let o=Bo.keys().next();if(o.done)break;Bo.delete(o.value)}}function OS(t,e){if(!e)return;let n=RS(t,e),r=Bo.get(n);if(r){if(r.expiresAt<=Date.now()){Bo.delete(n);return}return r.signature}}function JI(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 KI(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 Sa(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)&&KI(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]=Sa(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(Sa(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=Sa(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?Ms(r):r;if(t.functionDeclarations)for(let r of t.functionDeclarations){if(!r.parameters)r.parameters={type:"OBJECT",properties:{}};else{let o=Qr(r.parameters);r.parameters=n(Sa(o))}if(r.response){let o=Qr(r.response);r.response=n(Sa(o))}}return t}var IS="skip_thought_signature_validator";function tl(t,e){let n=[],r=t.tools||[],o=r.filter(C=>Fs(C).name!=="web_search").map(C=>{let{name:A,description:k,parameters:E}=Fs(C);return{name:bS(A),description:k,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(VI({functionDeclarations:o},{collapseUnions:JI(t.model)})),r.find(C=>Fs(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=Wu(C.role,{assistant:"model"}),k=[],E=Un(C),x=As(E),O=x?.startsWith("ccr_")?void 0:x,q=j=>A==="model"&&(j==="(no content)"||j.startsWith(gg));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})}}),Gu(C.content).forEach(ee=>{k.push(Ku(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||OS(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?IS: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(ye=>ye.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(ye=>ye.type==="text").map(ye=>ye.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=Ju(i,"parts"),b={},m=xS(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 tl(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 xS(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===RS||r.startsWith("ccr_")||vS(t,n.id,r)})}async function nl(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+=_a(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),xS(o,f);let p=d?.filter(C=>C.text)?.map(C=>_a(C.text||""))?.join(`
257
- `)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",b=!g&&f.length===0?gg(h):null,m=ya(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 nl(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 PS(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===IS||r.startsWith("ccr_")||DS(t,n.id,r)})}async function rl(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+=ba(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),PS(o,f);let p=d?.filter(C=>C.text)?.map(C=>ba(C.text||""))?.join(`
257
+ `)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",b=!g&&f.length===0?mg(h):null,m=_a(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"?ya(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 Hu({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 Fe(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(_a(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=>_a(z.text||"")).join(`
260
- `),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),xS(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?gg(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,ye={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)},De=h(E);De.length>0&&(ye.choices[0].delta.annotations=De),f(C,ye)}),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}var PS=require("crypto"),HI=15e3,zI=256,_r=new Map,Dg=new Map;function DS(t){return(0,PS.createHash)("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function WI(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function GI(t){return Math.floor(JSON.stringify(t).length/4)}function JI(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 rl(t,e){let n=Date.now();for(let[r,o]of _r)o.expiresAt<=n&&_r.delete(r);for(_r.delete(t),_r.set(t,e);_r.size>zI;){let r=_r.keys().next().value;if(r===void 0)break;_r.delete(r)}}async function ol(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=JI(e);if(Object.keys(s).length===0||GI(s)<WI(n))return e;let i=DS(o),a=[String(r),i,n,DS(s)].join(":"),u=Date.now(),d=_r.get(a);if(d&&d.expiresAt>u)return d.name?OS(e,d.name):e;d&&_r.delete(a);let f=3600,p={model:n,...s,ttl:`${f}s`},h=Dg.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(HI)});if(!b.ok){t.logger?.debug?.({status:b.status},"Gemini cached-content create failed; using implicit cache"),rl(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"),rl(a,{expiresAt:Date.now()+300*1e3});return}return rl(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"),rl(a,{expiresAt:Date.now()+300*1e3});return}finally{Dg.delete(a)}})(),Dg.set(a,h));let g=await h;return g?OS(e,g):e}var sl=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=el(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await ol({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 tl(e)}async transformResponseOut(e,n){return nl(e,this.name,this.logger,n?.provider?.name||this.name)}};async function Kj(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>ot(Md(),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,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"?_a(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 zu({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 Fe(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(ba(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=>ba(z.text||"")).join(`
260
+ `),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),PS(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?mg(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,ye={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)},De=h(E);De.length>0&&(ye.choices[0].delta.annotations=De),f(C,ye)}),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}var MS=require("crypto"),YI=15e3,XI=256,_r=new Map,Og=new Map;function FS(t){return(0,MS.createHash)("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function QI(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function ZI(t){return Math.floor(JSON.stringify(t).length/4)}function eF(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function NS(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function ol(t,e){let n=Date.now();for(let[r,o]of _r)o.expiresAt<=n&&_r.delete(r);for(_r.delete(t),_r.set(t,e);_r.size>XI;){let r=_r.keys().next().value;if(r===void 0)break;_r.delete(r)}}async function sl(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=eF(e);if(Object.keys(s).length===0||ZI(s)<QI(n))return e;let i=FS(o),a=[String(r),i,n,FS(s)].join(":"),u=Date.now(),d=_r.get(a);if(d&&d.expiresAt>u)return d.name?NS(e,d.name):e;d&&_r.delete(a);let f=3600,p={model:n,...s,ttl:`${f}s`},h=Og.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(YI)});if(!b.ok){t.logger?.debug?.({status:b.status},"Gemini cached-content create failed; using implicit cache"),ol(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"),ol(a,{expiresAt:Date.now()+300*1e3});return}return ol(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"),ol(a,{expiresAt:Date.now()+300*1e3});return}finally{Og.delete(a)}})(),Og.set(a,h));let g=await h;return g?NS(e,g):e}var il=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=tl(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await sl({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 nl(e)}async transformResponseOut(e,n){return rl(e,this.name,this.logger,n?.provider?.name||this.name)}};async function tL(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>ot(Bd(),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 Bd=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 Kj(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 ol({body:el(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 tl(e)}async transformResponseOut(e,n){return nl(e,this.name,this.logger,n?.provider?.name||this.name)}};function Ud(){return{content:"",isComplete:!1,hasContent:!1}}function jd(t,e){t.content+=e,t.hasContent=!0}function Ld(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function ao(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function fi(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 co(t){delete t.reasoning_content,delete t.reasoning}var sx=require("node:crypto");var rx=360*60*1e3,Vj=4096,d_="__ccrDeepseekReasoning",f_=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>rx){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>rx&&this.cache.delete(e);for(;this.cache.size>Vj;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},$d=new f_;function p_(t){return Array.isArray(t)?t.map(p_):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=p_(t[n]),e),{}):t}function Xo(t){return JSON.stringify(p_(t))}function qd(t){return(0,sx.createHash)("sha256").update(t).digest("hex")}function ix(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||""):Xo(e)).join(""):Xo(t)}function h_(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Xo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function ax(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function cx(t){let e=h_(t);return qd(Xo({...e,id:void 0}))}function ux(t){return qd(Xo({content:ix(t.content),tool_calls:(t.tool_calls||[]).map(e=>h_(e))}))}function Yj(t){let e={role:t.role,content:ix(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=>h_(n))),e}function ox(t,e){let n=t.filter(r=>r.role!=="system").map(r=>Yj(r));return qd(Xo({namespace:e,messages:n}))}function Xj(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 lx(t,e){if(t.role!=="assistant")return 0;let n=Xj(t);if(!n)return 0;let r=[`scope:${e}:signature:${ux(t)}`];return r.push(...ax(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${cx(o)}`)),r.forEach(o=>$d.put(o,n)),r.length}function Qj(t,e){let n=$d.get(`scope:${e}:signature:${ux(t)}`);if(n)return n;for(let r of ax(t)){let o=$d.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=$d.get(`scope:${e}:tool_call_signature:${cx(r)}`);if(o)return o}}function Zj(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 eL(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||Mt(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 tL(t,e){return qd(Xo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function Hd(t,e,n){if(!eL(t,e))return n?.req&&delete n.req[d_],{restoredFromCache:0,restoredFromThinking:0};let r=tL(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=ox(o,r);if(Zj(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=Qj(a,u);h&&(a.reasoning_content=h,s++)}}lx(a,u)}o.push(a)}return n?.req&&(n.req[d_]={enabled:!0,namespace:r,requestScope:ox(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function dx(t){return t?.req?.[d_]}function zd(t){return dx(t)?.enabled===!0}function pi(t,e){if(!t)return 0;let n=dx(e);return n?lx(t,n.requestScope):0}function Wd(){return{content:"",reasoning:"",toolCalls:new Map}}function hi(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 Gd(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 fx(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 Jd=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Xe(e.messages),e.tools=Qe(e.tools),Hd(e,n,r),e}async transformResponseOut(e,n){let r=zd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return fx(o),r&&pi({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=Ud(),s=r?Wd():null;return Fe(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Oe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Oe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);fx(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(Ee(JSON.stringify(d),a.encoder));return}let p=fi(f);if(p){s&&hi(s,f),jd(o,p);let h=ao(d,{content:p});co(h.choices[0].delta),a.controller.enqueue(Ee(JSON.stringify(h),a.encoder));return}if(s&&hi(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=Ld(o),b=ao(d,{content:h,signature:g});co(b.choices[0].delta),b.choices[0].delta.content=null,a.controller.enqueue(Ee(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(Ee(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Oe(i,a.encoder))}},{onComplete:()=>{s&&pi(Gd(s),n)}})}return e}};var Kd=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 Ud=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 tL(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 sl({body:tl(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 nl(e)}async transformResponseOut(e,n){return rl(e,this.name,this.logger,n?.provider?.name||this.name)}};function jd(){return{content:"",isComplete:!1,hasContent:!1}}function Ld(t,e){t.content+=e,t.hasContent=!0}function $d(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function co(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function pi(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 uo(t){delete t.reasoning_content,delete t.reasoning}var ux=require("node:crypto");var ax=360*60*1e3,nL=4096,f_="__ccrDeepseekReasoning",p_=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>ax){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>ax&&this.cache.delete(e);for(;this.cache.size>nL;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},qd=new p_;function h_(t){return Array.isArray(t)?t.map(h_):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=h_(t[n]),e),{}):t}function Qo(t){return JSON.stringify(h_(t))}function Hd(t){return(0,ux.createHash)("sha256").update(t).digest("hex")}function lx(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||""):Qo(e)).join(""):Qo(t)}function g_(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Qo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function dx(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function fx(t){let e=g_(t);return Hd(Qo({...e,id:void 0}))}function px(t){return Hd(Qo({content:lx(t.content),tool_calls:(t.tool_calls||[]).map(e=>g_(e))}))}function rL(t){let e={role:t.role,content:lx(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=>g_(n))),e}function cx(t,e){let n=t.filter(r=>r.role!=="system").map(r=>rL(r));return Hd(Qo({namespace:e,messages:n}))}function oL(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 hx(t,e){if(t.role!=="assistant")return 0;let n=oL(t);if(!n)return 0;let r=[`scope:${e}:signature:${px(t)}`];return r.push(...dx(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${fx(o)}`)),r.forEach(o=>qd.put(o,n)),r.length}function sL(t,e){let n=qd.get(`scope:${e}:signature:${px(t)}`);if(n)return n;for(let r of dx(t)){let o=qd.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=qd.get(`scope:${e}:tool_call_signature:${fx(r)}`);if(o)return o}}function iL(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 aL(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||kt(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 cL(t,e){return Hd(Qo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function zd(t,e,n){if(!aL(t,e))return n?.req&&delete n.req[f_],{restoredFromCache:0,restoredFromThinking:0};let r=cL(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=cx(o,r);if(iL(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=sL(a,u);h&&(a.reasoning_content=h,s++)}}hx(a,u)}o.push(a)}return n?.req&&(n.req[f_]={enabled:!0,namespace:r,requestScope:cx(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function gx(t){return t?.req?.[f_]}function Wd(t){return gx(t)?.enabled===!0}function hi(t,e){if(!t)return 0;let n=gx(e);return n?hx(t,n.requestScope):0}function Gd(){return{content:"",reasoning:"",toolCalls:new Map}}function gi(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 Jd(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 mx(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 Kd=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Xe(e.messages),e.tools=Qe(e.tools),zd(e,n,r),e}async transformResponseOut(e,n){let r=Wd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return mx(o),r&&hi({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=jd(),s=r?Gd():null;return Fe(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Oe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Oe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);mx(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(Ee(JSON.stringify(d),a.encoder));return}let p=pi(f);if(p){s&&gi(s,f),Ld(o,p);let h=co(d,{content:p});uo(h.choices[0].delta),a.controller.enqueue(Ee(JSON.stringify(h),a.encoder));return}if(s&&gi(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=$d(o),b=co(d,{content:h,signature:g});uo(b.choices[0].delta),b.choices[0].delta.content=null,a.controller.enqueue(Ee(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(Ee(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Oe(i,a.encoder))}},{onComplete:()=>{s&&hi(Jd(s),n)}})}return e}};var Vd=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,17 +270,17 @@ 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 Vd=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=un(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=fu(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=ua(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=To(e):s.includes("gemini")?e=To(e):e={...e,messages:Xe(e.messages),tools:Qe(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=Ud(),r=!1,o=!1;return Fe(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Oe(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Oe(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(Ee(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?fi(d):null;if(f){jd(n,f);let p=ao(u,{content:f});co(p.choices[0].delta),i.controller.enqueue(Ee(JSON.stringify(p),i.encoder));return}if(d?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=Ld(n),g=ao(u,{content:p,signature:h});co(g.choices[0].delta),g.choices[0].delta.content=null,i.controller.enqueue(Ee(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_${Ln()}`}),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(Ee(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Oe(s,i.encoder))}})}return e}};var Yd=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 Xd=class{name="groq";async transformRequestIn(e){return e.messages=Xe(e.messages),e.tools=Qe(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=Zu(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 Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Oe(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_${Ln()}`}),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(Ee(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Oe(r,o.encoder))}})}return e}};var Qd=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 Sx=ot(Ph());var Er=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function px(t){return/^[0-9A-Fa-f]$/.test(t)}function Tr(t){return t>="0"&&t<="9"}function hx(t){return t>=" "}function mi(t){return`,:[]/{}()
274
- +`.includes(t)}function g_(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Zd(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var m_=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,y_=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function __(t){return`,[]/{}
275
- +`.includes(t)}function b_(t){return yi(t)||nL.test(t)}var nL=/^[[{\w-]$/;function C_(t){return t===`
276
- `||t==="\r"||t===" "||t==="\b"||t==="\f"}function vr(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function gx(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function mx(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 yi(t){return w_(t)||ef(t)}function w_(t){return t==='"'||t==="\u201C"||t==="\u201D"}function k_(t){return t==='"'}function ef(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function S_(t){return t==="'"}function _i(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 rn(t,e){let n=t.length;if(!vr(t,n-1))return t+e;for(;vr(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function yx(t,e,n){return t.substring(0,e)+t.substring(e+n)}function _x(t){return/[,\n][ \t\r]*$/.test(t)}var rL={"&quot;":'"',"&amp;":"&","&lt;":"<","&gt;":">","&apos;":"'"},A_=12;function E_(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=rL[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 bx(t){return t!==null&&t.char==='"'}function Cx(t){return t!==null&&t.char==="'"}function gi(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function wx(t,e){switch(e){case")":return gi(t,"(")>gi(t,")");case"]":return gi(t,"[")>gi(t,"]");case"}":return gi(t,"{")>gi(t,"}");default:return!1}}var kx={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},oL={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
277
- `,r:"\r",t:" "};function v_(t){let e=0,n="";d(["```","[```","{```"]),s()||ye(),d(["```","```]","```}"]);let o=p(",");for(o&&i(),b_(t[e])&&_x(n)?(o||(n=rn(n,",")),C()):o&&(n=_i(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,ie=a(ne);do ie=u(),ie&&(ie=a(ne));while(ie);return e>Z}function a(ne){let Z=ne?vr:gx,ie="";for(;;)if(Z(t,e))ie+=t[e],e++;else if(mx(t,e))ie+=" ",e++;else break;return ie.length>0?(n+=ie,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!sL(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(g_(t[e]))for(;e<t.length&&Zd(t[e]);)e++;return i(),!0}return!1}function f(ne){a(!0);for(let Z of ne){let ie=e+Z.length;if(t.slice(e,ie)===Z)return e=ie,!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=rn(n,",")),i()),b(),!(A()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ne||(n=_i(n,",")):De();break}i();let Pe=p(":"),Ce=e>=t.length;Pe||(b_(t[e])||Ce?n=rn(n,":"):ve()),s()||(Pe||Ce?n+="null":ve()),ne=!1}return t[e]==="}"?(n+="}",e++):n=rn(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=rn(n,",")),b(),!s()){ne||(n=_i(n,","));break}ne=!1}return t[e]==="]"?(n+="]",e++):n=rn(n,"]"),!0}return!1}function C(){let ne=!0,Z=!0;for(;Z;)ne?ne=!1:p(",")||(n=rn(n,",")),Z=s();Z||(n=_i(n,",")),n=`[
273
+ `))})}return e}};var Yd=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=un(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=pu(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=la(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=xo(e):s.includes("gemini")?e=xo(e):e={...e,messages:Xe(e.messages),tools:Qe(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=jd(),r=!1,o=!1;return Fe(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Oe(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Oe(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(Ee(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?pi(d):null;if(f){Ld(n,f);let p=co(u,{content:f});uo(p.choices[0].delta),i.controller.enqueue(Ee(JSON.stringify(p),i.encoder));return}if(d?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=$d(n),g=co(u,{content:p,signature:h});uo(g.choices[0].delta),g.choices[0].delta.content=null,i.controller.enqueue(Ee(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_${Ln()}`}),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(Ee(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Oe(s,i.encoder))}})}return e}};var Xd=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 Qd=class{name="groq";async transformRequestIn(e){return e.messages=Xe(e.messages),e.tools=Qe(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=el(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 Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Oe(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_${Ln()}`}),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(Ee(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Oe(r,o.encoder))}})}return e}};var Zd=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 Tx=ot(Ph());var Er=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function yx(t){return/^[0-9A-Fa-f]$/.test(t)}function Tr(t){return t>="0"&&t<="9"}function _x(t){return t>=" "}function yi(t){return`,:[]/{}()
274
+ +`.includes(t)}function m_(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function ef(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var y_=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,__=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function b_(t){return`,[]/{}
275
+ +`.includes(t)}function C_(t){return _i(t)||uL.test(t)}var uL=/^[[{\w-]$/;function w_(t){return t===`
276
+ `||t==="\r"||t===" "||t==="\b"||t==="\f"}function vr(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function bx(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function Cx(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 _i(t){return k_(t)||tf(t)}function k_(t){return t==='"'||t==="\u201C"||t==="\u201D"}function S_(t){return t==='"'}function tf(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function A_(t){return t==="'"}function bi(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 rn(t,e){let n=t.length;if(!vr(t,n-1))return t+e;for(;vr(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function wx(t,e,n){return t.substring(0,e)+t.substring(e+n)}function kx(t){return/[,\n][ \t\r]*$/.test(t)}var lL={"&quot;":'"',"&amp;":"&","&lt;":"<","&gt;":">","&apos;":"'"},E_=12;function v_(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=lL[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 Sx(t){return t!==null&&t.char==='"'}function Ax(t){return t!==null&&t.char==="'"}function mi(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function Ex(t,e){switch(e){case")":return mi(t,"(")>mi(t,")");case"]":return mi(t,"[")>mi(t,"]");case"}":return mi(t,"{")>mi(t,"}");default:return!1}}var vx={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},dL={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
277
+ `,r:"\r",t:" "};function T_(t){let e=0,n="";d(["```","[```","{```"]),s()||ye(),d(["```","```]","```}"]);let o=p(",");for(o&&i(),C_(t[e])&&kx(n)?(o||(n=rn(n,",")),C()):o&&(n=bi(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,ie=a(ne);do ie=u(),ie&&(ie=a(ne));while(ie);return e>Z}function a(ne){let Z=ne?vr:bx,ie="";for(;;)if(Z(t,e))ie+=t[e],e++;else if(Cx(t,e))ie+=" ",e++;else break;return ie.length>0?(n+=ie,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!fL(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(m_(t[e]))for(;e<t.length&&ef(t[e]);)e++;return i(),!0}return!1}function f(ne){a(!0);for(let Z of ne){let ie=e+Z.length;if(t.slice(e,ie)===Z)return e=ie,!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=rn(n,",")),i()),b(),!(A()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ne||(n=bi(n,",")):De();break}i();let Pe=p(":"),Ce=e>=t.length;Pe||(C_(t[e])||Ce?n=rn(n,":"):ve()),s()||(Pe||Ce?n+="null":ve()),ne=!1}return t[e]==="}"?(n+="}",e++):n=rn(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=rn(n,",")),b(),!s()){ne||(n=bi(n,","));break}ne=!1}return t[e]==="]"?(n+="]",e++):n=rn(n,"]"),!0}return!1}function C(){let ne=!0,Z=!0;for(;Z;)ne?ne=!1:p(",")||(n=rn(n,",")),Z=s();Z||(n=bi(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,ie=t[e]==="\\";ie&&(e++,yi(t[e])||Q());let Pe=t[e]==="&"?E_(t.slice(e,e+A_)):null,Ce=bx(Pe)||Cx(Pe);if(yi(t[e])||Ce){let H=k_(t[e])?k_:S_(t[e])?S_:ef(t[e])?ef:w_,Ae=e,tt=n.length,X='"';for(e+=Ce&&Pe?Pe.length:1;;){if(e>=t.length){let S=j(e-1);return!ne&&mi(t.charAt(S))?(e=Ae,n=n.substring(0,tt),A(!0)):(X=rn(X,'"'),n+=X,!0)}if(e===Z)return X=rn(X,'"'),n+=X,!0;let le=Ce&&t[e]==="&"?E_(t.slice(e,e+A_)):null;if(le&&Pe?le.char===Pe.char:H(t[e])){let S=e,T=X.length;if(X+='"',e+=le?le.length:1,n+=X,i(!1),ne||e>=t.length||mi(t[e])&&!wx(X,t[e])||yi(t[e])&&!ee(e)||Tr(t[e]))return k(),!0;t[e]==="\\"&&Q();let R=j(S-1),M=t.charAt(R);if(M===",")return e=Ae,n=n.substring(0,tt),A(!1,R);if(mi(M))return e=Ae,n=n.substring(0,tt),A(!0);n=n.substring(0,tt),e=S+(le?le.length:1),X=`${X.substring(0,T)}\\${X.substring(T)}`}else if(ne&&__(t[e])){if(t[e-1]===":"&&m_.test(t.substring(Ae+1,e+2)))for(;e<t.length&&y_.test(t[e]);)X+=t[e],e++;return X=rn(X,'"'),n+=X,k(),!0}else if(le){let S=le.char;S==='"'?X+='\\"':C_(S)?X+=kx[S]:X+=S,e+=le.length}else if(t[e]==="\\"){let S=t.charAt(e+1);if(oL[S]!==void 0)X+=t.slice(e,e+2),e+=2;else if(S==="u"){let R=2;for(;R<6&&px(t[e+R]);)R++;R===6?(X+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Ye()}else S===`
281
- `?(X+="\\n",e+=2):(X+=S,e+=2)}else{let S=t.charAt(e);S==='"'&&t[e-1]!=="\\"?(X+=`\\${S}`,e++):C_(S)?(X+=kx[S],e++):(hx(S)||te(S),X+=S,e++)}ie&&g()}}return!1}function k(){let ne=!1;for(i();t[e]==="+";){ne=!0,e++,i(),n=_i(n,'"',!0);let Z=n.length;A()?n=yx(n,Z,1):n=rn(n,'"')}return ne}function E(){let ne=e,Z="",ie=!1;for(t[e]==="-"&&(Z+=t[e],e++,!Tr(t[e])&&z()&&(Z+="0")),t[e]==="0"&&Tr(t[e+1])&&(ie=!0);Tr(t[e]);)Z+=t[e],e++;if(t[e]===".")for((Z===""||Z==="-")&&(Z+="0"),Z+=t[e],e++,Tr(t[e])||(Z+="0");Tr(t[e]);)Z+=t[e],e++;if(e>ne){if(t[e]==="e"||t[e]==="E")for(Z==="-"&&(ie=!0),Z+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Z+=t[e],e++),Tr(t[e])||(Z+="0");Tr(t[e]);)Z+=t[e],e++;return z()?(n+=ie?`"${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&&!Zd(t[e+ne.length])?(n+=Z,e+=ne.length,!0):!1}function q(ne){let Z=e;if(g_(t[e])){for(;e<t.length&&Zd(t[e]);)e++;let ie=e;for(;vr(t,ie);)ie++;if(t[ie]==="(")return e=ie+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!__(t[e])&&!yi(t[e])&&(!ne||t[e]!==":");)e++;if(t[e-1]===":"&&m_.test(t.substring(Z,e+2)))for(;e<t.length&&y_.test(t[e]);)e++;if(e>Z){for(;vr(t,e-1)&&e>0;)e--;let ie=t.slice(Z,e);return n+=ie==="undefined"?"null":JSON.stringify(ie),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&&vr(t,Z);)Z--;return Z}function ee(ne){let Z=ne+1;for(;Z<t.length&&vr(t,Z);)Z++;return Z>=t.length||mi(t[Z])}function z(){return e>=t.length||mi(t[e])||vr(t,e)}function te(ne){throw new Er(`Invalid character ${JSON.stringify(ne)}`,e)}function Q(){throw new Er(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ye(){throw new Er("Unexpected end of json string",t.length)}function De(){throw new Er("Object key expected",e)}function ve(){throw new Er("Colon expected",e)}function Ye(){let ne=t.slice(e,e+6);throw new Er(`Invalid unicode character "${ne}"`,e)}}function sL(t,e){return t[e]==="*"&&t[e+1]==="/"}function T_(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=Sx.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=v_(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 tf=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=T_(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(`
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,ie=t[e]==="\\";ie&&(e++,_i(t[e])||Q());let Pe=t[e]==="&"?v_(t.slice(e,e+E_)):null,Ce=Sx(Pe)||Ax(Pe);if(_i(t[e])||Ce){let H=S_(t[e])?S_:A_(t[e])?A_:tf(t[e])?tf:k_,Ae=e,tt=n.length,X='"';for(e+=Ce&&Pe?Pe.length:1;;){if(e>=t.length){let S=j(e-1);return!ne&&yi(t.charAt(S))?(e=Ae,n=n.substring(0,tt),A(!0)):(X=rn(X,'"'),n+=X,!0)}if(e===Z)return X=rn(X,'"'),n+=X,!0;let le=Ce&&t[e]==="&"?v_(t.slice(e,e+E_)):null;if(le&&Pe?le.char===Pe.char:H(t[e])){let S=e,T=X.length;if(X+='"',e+=le?le.length:1,n+=X,i(!1),ne||e>=t.length||yi(t[e])&&!Ex(X,t[e])||_i(t[e])&&!ee(e)||Tr(t[e]))return k(),!0;t[e]==="\\"&&Q();let R=j(S-1),M=t.charAt(R);if(M===",")return e=Ae,n=n.substring(0,tt),A(!1,R);if(yi(M))return e=Ae,n=n.substring(0,tt),A(!0);n=n.substring(0,tt),e=S+(le?le.length:1),X=`${X.substring(0,T)}\\${X.substring(T)}`}else if(ne&&b_(t[e])){if(t[e-1]===":"&&y_.test(t.substring(Ae+1,e+2)))for(;e<t.length&&__.test(t[e]);)X+=t[e],e++;return X=rn(X,'"'),n+=X,k(),!0}else if(le){let S=le.char;S==='"'?X+='\\"':w_(S)?X+=vx[S]:X+=S,e+=le.length}else if(t[e]==="\\"){let S=t.charAt(e+1);if(dL[S]!==void 0)X+=t.slice(e,e+2),e+=2;else if(S==="u"){let R=2;for(;R<6&&yx(t[e+R]);)R++;R===6?(X+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Ye()}else S===`
281
+ `?(X+="\\n",e+=2):(X+=S,e+=2)}else{let S=t.charAt(e);S==='"'&&t[e-1]!=="\\"?(X+=`\\${S}`,e++):w_(S)?(X+=vx[S],e++):(_x(S)||te(S),X+=S,e++)}ie&&g()}}return!1}function k(){let ne=!1;for(i();t[e]==="+";){ne=!0,e++,i(),n=bi(n,'"',!0);let Z=n.length;A()?n=wx(n,Z,1):n=rn(n,'"')}return ne}function E(){let ne=e,Z="",ie=!1;for(t[e]==="-"&&(Z+=t[e],e++,!Tr(t[e])&&z()&&(Z+="0")),t[e]==="0"&&Tr(t[e+1])&&(ie=!0);Tr(t[e]);)Z+=t[e],e++;if(t[e]===".")for((Z===""||Z==="-")&&(Z+="0"),Z+=t[e],e++,Tr(t[e])||(Z+="0");Tr(t[e]);)Z+=t[e],e++;if(e>ne){if(t[e]==="e"||t[e]==="E")for(Z==="-"&&(ie=!0),Z+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Z+=t[e],e++),Tr(t[e])||(Z+="0");Tr(t[e]);)Z+=t[e],e++;return z()?(n+=ie?`"${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&&!ef(t[e+ne.length])?(n+=Z,e+=ne.length,!0):!1}function q(ne){let Z=e;if(m_(t[e])){for(;e<t.length&&ef(t[e]);)e++;let ie=e;for(;vr(t,ie);)ie++;if(t[ie]==="(")return e=ie+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!b_(t[e])&&!_i(t[e])&&(!ne||t[e]!==":");)e++;if(t[e-1]===":"&&y_.test(t.substring(Z,e+2)))for(;e<t.length&&__.test(t[e]);)e++;if(e>Z){for(;vr(t,e-1)&&e>0;)e--;let ie=t.slice(Z,e);return n+=ie==="undefined"?"null":JSON.stringify(ie),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&&vr(t,Z);)Z--;return Z}function ee(ne){let Z=ne+1;for(;Z<t.length&&vr(t,Z);)Z++;return Z>=t.length||yi(t[Z])}function z(){return e>=t.length||yi(t[e])||vr(t,e)}function te(ne){throw new Er(`Invalid character ${JSON.stringify(ne)}`,e)}function Q(){throw new Er(`Unexpected character ${JSON.stringify(t[e])}`,e)}function ye(){throw new Er("Unexpected end of json string",t.length)}function De(){throw new Er("Object key expected",e)}function ve(){throw new Er("Colon expected",e)}function Ye(){let ne=t.slice(e,e+6);throw new Er(`Invalid unicode character "${ne}"`,e)}}function fL(t,e){return t[e]==="*"&&t[e+1]==="/"}function x_(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=Tx.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=T_(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 nf=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=x_(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
282
  `);for(let k of A)k.trim()&&w.enqueue(C.encode(k+`
283
- `))},g=(m,w,C)=>{let A;try{A=T_(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)}
283
+ `))},g=(m,w,C)=>{let A;try{A=x_(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)}
284
284
 
285
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)}
286
286
 
@@ -292,20 +292,20 @@ ${n}
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
293
  `))}continue}let A=u.split(`
294
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+`
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 nf=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?Mt(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),Hd(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=zd(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&&pi({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?Wd():null;return Fe(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
- `));return}if(g.reasoning_content){o+=typeof g.reasoning_content=="string"?g.reasoning_content:JSON.stringify(g.reasoning_content),i&&hi(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)}
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 rf=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?kt(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),zd(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=Wd(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&&hi({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?Gd():null;return Fe(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
+ `));return}if(g.reasoning_content){o+=typeof g.reasoning_content=="string"?g.reasoning_content:JSON.stringify(g.reasoning_content),i&&gi(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
 
298
- `;f.enqueue(p.encode(m));return}if(i&&hi(i,g),(g.content||g.tool_calls)&&o&&!s){s=!0;let b=Date.now().toString(),m={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:o,signature:b}}}]};delete m.choices[0].delta.reasoning_content;let w=`data: ${JSON.stringify(m)}
298
+ `;f.enqueue(p.encode(m));return}if(i&&gi(i,g),(g.content||g.tool_calls)&&o&&!s){s=!0;let b=Date.now().toString(),m={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:o,signature:b}}}]};delete m.choices[0].delta.reasoning_content;let w=`data: ${JSON.stringify(m)}
299
299
 
300
300
  `;f.enqueue(p.encode(w))}if(g.reasoning_content&&delete h.choices[0].delta.reasoning_content,h.choices?.[0]?.delta&&Object.keys(h.choices[0].delta).length>0){s&&h.choices[0].index++;let b=`data: ${JSON.stringify(h)}
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&&pi(Gd(i),n)}})}return e}};var rf=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 of=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 iL(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>ot(Md(),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&&hi(Jd(i),n)}})}return e}};var of=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 sf=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 pL(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>ot(Bd(),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 sf=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 iL(this.logger);return{body:mS(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 yS(e)}async transformResponseOut(e){return Ku(e,this.name,this.logger)}};var Ax=ot(Md(),1);var af=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 Ax.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:Xe(e.messages),tools:Qe(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var cf=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Xe(o.messages),o.tools=Qe(o.tools);let s=un(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 uf=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var lf=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return aL(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),mu(e),e.messages=uL(e.messages),gu(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return dL(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json();return new Response(JSON.stringify(Ex(o)),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function aL(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(lL(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=>cL(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=Nt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...Cs(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function cL(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"&&df(n),n}function df(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 uL(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),df(n),delete n.thinking,n})}function Ex(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0]?.message;e&&df(e);let n=t.choices?.[0]?.delta;return n&&df(n),t}function lL(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 dL(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(Ex(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 wu(w)){if(i)return;if(ku(C)){i=!0,Su(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 af=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 pL(this.logger);return{body:CS(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 wS(e)}async transformResponseOut(e){return Vu(e,this.name,this.logger)}};var xx=ot(Bd(),1);var cf=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 xx.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:Xe(e.messages),tools:Qe(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var uf=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Xe(o.messages),o.tools=Qe(o.tools);let s=un(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 lf=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var df=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return hL(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),yu(e),e.messages=_L(e.messages),mu(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return CL(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json(),s=Dx(structuredClone(o));return new Response(JSON.stringify(s??o),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function hL(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(bL(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=>gL(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=Rt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...ws(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function gL(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"&&R_(n),n}function R_(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 Rx(t){!t||typeof t!="object"||(R_(t),delete t.thinking)}function mL(t){!t||typeof t!="object"||(R_(t),delete t.thinking,delete t.reasoning)}function yL(t){return!t||typeof t!="object"?!0:Object.keys(t).length===0}function _L(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),mL(n),n})}function Dx(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0];return e?(e.message&&Rx(e.message),e.delta&&(Rx(e.delta),yL(e.delta)&&e.finish_reason==null&&t.usage==null)?null:t):t}function bL(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 CL(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=Dx(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 ku(w)){if(i)return;if(Su(C)){i=!0,Au(b);return}let A=u(C);A!=null&&b.push(A)}};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]
@@ -331,26 +331,26 @@ data: [DONE]
331
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+`
332
332
  `))}continue}let C=u.split(`
333
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 hf=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=ws(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),Eu(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||ws(),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=yk(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=_k({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Fe(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=pa("Malformed upstream SSE event",r);s.controller.enqueue(Ee(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 ng(r))s.controller.enqueue(Ee(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(Ee(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=pa(Ve(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(Ee(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=kk(a,r);for(let d of u)s.controller.enqueue(Ee(JSON.stringify(d),s.encoder))}catch{let a=pa("Malformed JSON in upstream SSE event",r);s.controller.enqueue(Ee(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of ng(r))o.controller.enqueue(Ee(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=pa(Ve(i)||"Upstream stream failed",r);s.controller.enqueue(Ee(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=Mt(e.reasoning,e.thinking)?"none":Nt(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=ua(e,n,r);let a=pu(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,...hu(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=Ts(Un(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=kt(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=vs(h);if(g.thinking||g.toolCalls.length||fa(g)||g.images.length){if(d=!1,g.thinking&&p(h),fa(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:kt(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 Fe(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(Ee("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let m=g.response?.error??{},w=Ve(String(m.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(Ee(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(Ee("[DONE]",p.encoder));return}let b=this.convertStreamEvent(g,u,o,s);for(let m of b)p.controller.enqueue(Ee(JSON.stringify(m),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(Ee("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Oe(f,p.encoder))}}else p.controller.enqueue(Oe(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"&&vu(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=Es(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=Es(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:kt(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,...hu(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,...hu(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=As(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:kt(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[Bn]: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}};var Ox=require("crypto"),Px=require("child_process"),xr=require("os"),B_=require("@caeliq/ccr-shared");var He=require("fs"),mf=require("path"),vx=require("os"),fL=(0,mf.join)((0,vx.homedir)(),".claude-code-router","codex_auth.json"),pL=300,hL=11520*60,gL=2*6e4,mL=35e3,Tx={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},gf=null;function O_(){return process.env.CCR_CODEX_AUTH_FILE||fL}function R_(){return`${O_()}.refresh.lock`}function yL(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||Tx.token_endpoint}function P_(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 yf(t){let e=t.account_id?.trim();return e||P_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function _L(t){return P_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function xx(t){let e=P_(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function _f(t){let e=yf(t),n=xx(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function D_(){try{let t=O_();if(!(0,He.existsSync)(t))return null;let e=JSON.parse((0,He.readFileSync)(t,"utf8"));return e.access_token?_f(e):null}catch{return null}}function bL(t){let e=O_();(0,He.mkdirSync)((0,mf.dirname)(e),{recursive:!0});let n=_f(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,He.writeFileSync)(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),(0,He.renameSync)(r,e)}finally{try{(0,He.existsSync)(r)&&(0,He.unlinkSync)(r)}catch{}}}function Rx(t,e=pL){let n=xx(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+hL)}function x_(t,e){let n=yf(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function CL(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 wL(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(yL(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:Tx.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}): ${CL(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 _f({...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 kL(){let t=R_();try{return(0,He.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,He.statSync)(t).mtimeMs>gL&&(0,He.unlinkSync)(t)}catch{}return null}}async function SL(t){let e=Date.now()+mL,n=null;for(;n===null&&(n=kL(),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=(0,He.fstatSync)(n).ino;(0,He.closeSync)(n);try{(0,He.statSync)(R_()).ino===r&&(0,He.unlinkSync)(R_())}catch{}}}async function AL(t,e){return SL(async()=>{let n=D_();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");x_(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!Rx(n))return n;let o=await wL(n);x_(e.expectedAccountId,o);let s=D_();return s&&s.access_token!==n.access_token?(x_(e.expectedAccountId,s),s):(bL(o),o)})}async function Ka(t={}){let e=D_();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!Rx(e)?e:(gf||(gf=AL(e,{...t,expectedAccountId:t.expectedAccountId||yf(e)}).finally(()=>{gf=null})),gf)}function I_(t){let e=_f(t);return{mode:"oauth",token:e.access_token,accountId:yf(e),isFedramp:_L(e)}}var EL=300*1e3,bf=new Map,F_=new Map,Ix="0.145.0",Fx="codex_cli_rs",Nx="x-codex-turn-metadata",vL="x-codex-window-id",TL="x-codex-parent-thread-id",xL="session_id",RL="thread_id",DL="turn_id",OL="window_id";function N_(){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 M_(t){return t.item_id||t.item?.id||t.item?.call_id||""}function PL(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function IL(){switch((0,xr.platform)()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return(0,xr.platform)()||"unknown"}}function FL(){switch((0,xr.arch)()){case"x64":return"x86_64";case"arm64":return"arm64";default:return(0,xr.arch)()||"unknown"}}function NL(){if((0,xr.platform)()==="darwin")try{return(0,Px.execFileSync)("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return(0,xr.release)()||"unknown"}function ML(){return`${Fx}/${Ix} (${IL()} ${NL()}; ${FL()})`}function Dx(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",Ix),e.toString()}function BL(t){return{session_id:t,thread_id:t,turn_id:(0,Ox.randomUUID)(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function UL(t){return{[xL]:t.session_id,[RL]:t.thread_id,[DL]:t.turn_id,[OL]:t.window_id,[Nx]:JSON.stringify(t)}}function jL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function LL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[vL]:t.window_id,[Nx]:JSON.stringify(t),[TL]:t.thread_id}}function $L(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 qL(t,e){return t?.req?.sessionId||$L(e)}function HL(t,e,n){if(!n)return;let r=BL(n);t.client_metadata=jL(t.client_metadata,UL(r)),Object.assign(e,LL(r))}var Cf=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=Mt(e.reasoning,e.thinking)?"none":Nt(e.reasoning?.effort)||Nt(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=$h(e,r);let f=pu(e.messages);e.messages=f;let p=[],h=!1,g=PL(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(`
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 hf=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=ks(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),vu(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||ks(),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=wk(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=kk({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Fe(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=ha("Malformed upstream SSE event",r);s.controller.enqueue(Ee(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 rg(r))s.controller.enqueue(Ee(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(Ee(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=ha(Ve(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(Ee(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=vk(a,r);for(let d of u)s.controller.enqueue(Ee(JSON.stringify(d),s.encoder))}catch{let a=ha("Malformed JSON in upstream SSE event",r);s.controller.enqueue(Ee(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of rg(r))o.controller.enqueue(Ee(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=ha(Ve(i)||"Upstream stream failed",r);s.controller.enqueue(Ee(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=kt(e.reasoning,e.thinking)?"none":Rt(e.reasoning.effort),g=h!=="none"?Jr(e,n):void 0;e.reasoning={...h?{effort:h}:{},...g?{summary:g}:{}}}delete e.stop,delete e.stream_options;let s=xu(e.response_format);s&&(e.text={...e.text,format:s}),delete e.response_format;let i=e.model||"";e=la(e,n,r);let a=hu(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,...gu(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=xs(Un(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=St(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=Ts(h);if(g.thinking||g.toolCalls.length||pa(g)||g.images.length){if(d=!1,g.thinking&&p(h),pa(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:St(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 Fe(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(Ee("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let m=g.response?.error??{},w=Ve(String(m.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(Ee(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(Ee("[DONE]",p.encoder));return}let b=this.convertStreamEvent(g,u,o,s);for(let m of b)p.controller.enqueue(Ee(JSON.stringify(m),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(Ee("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Oe(f,p.encoder))}}else p.controller.enqueue(Oe(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"&&Tu(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=vs(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=vs(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:St(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,...gu(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,...gu(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=Es(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:St(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[Bn]: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}};var Mx=require("crypto"),Bx=require("child_process"),xr=require("os"),j_=require("@caeliq/ccr-shared");var He=require("fs"),mf=require("path"),Ox=require("os"),wL=(0,mf.join)((0,Ox.homedir)(),".claude-code-router","codex_auth.json"),kL=300,SL=11520*60,AL=2*6e4,EL=35e3,Px={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},gf=null;function I_(){return process.env.CCR_CODEX_AUTH_FILE||wL}function O_(){return`${I_()}.refresh.lock`}function vL(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||Px.token_endpoint}function F_(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 yf(t){let e=t.account_id?.trim();return e||F_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function TL(t){return F_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function Ix(t){let e=F_(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function _f(t){let e=yf(t),n=Ix(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function P_(){try{let t=I_();if(!(0,He.existsSync)(t))return null;let e=JSON.parse((0,He.readFileSync)(t,"utf8"));return e.access_token?_f(e):null}catch{return null}}function xL(t){let e=I_();(0,He.mkdirSync)((0,mf.dirname)(e),{recursive:!0});let n=_f(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,He.writeFileSync)(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),(0,He.renameSync)(r,e)}finally{try{(0,He.existsSync)(r)&&(0,He.unlinkSync)(r)}catch{}}}function Fx(t,e=kL){let n=Ix(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+SL)}function D_(t,e){let n=yf(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function RL(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 DL(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(vL(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:Px.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}): ${RL(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 _f({...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 OL(){let t=O_();try{return(0,He.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,He.statSync)(t).mtimeMs>AL&&(0,He.unlinkSync)(t)}catch{}return null}}async function PL(t){let e=Date.now()+EL,n=null;for(;n===null&&(n=OL(),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=(0,He.fstatSync)(n).ino;(0,He.closeSync)(n);try{(0,He.statSync)(O_()).ino===r&&(0,He.unlinkSync)(O_())}catch{}}}async function IL(t,e){return PL(async()=>{let n=P_();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");D_(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!Fx(n))return n;let o=await DL(n);D_(e.expectedAccountId,o);let s=P_();return s&&s.access_token!==n.access_token?(D_(e.expectedAccountId,s),s):(xL(o),o)})}async function Va(t={}){let e=P_();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!Fx(e)?e:(gf||(gf=IL(e,{...t,expectedAccountId:t.expectedAccountId||yf(e)}).finally(()=>{gf=null})),gf)}function N_(t){let e=_f(t);return{mode:"oauth",token:e.access_token,accountId:yf(e),isFedramp:TL(e)}}var FL=300*1e3,bf=new Map,M_=new Map,Ux="0.145.0",jx="codex_cli_rs",Lx="x-codex-turn-metadata",NL="x-codex-window-id",ML="x-codex-parent-thread-id",BL="session_id",UL="thread_id",jL="turn_id",LL="window_id";function B_(){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 U_(t){return t.item_id||t.item?.id||t.item?.call_id||""}function $L(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function qL(){switch((0,xr.platform)()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return(0,xr.platform)()||"unknown"}}function HL(){switch((0,xr.arch)()){case"x64":return"x86_64";case"arm64":return"arm64";default:return(0,xr.arch)()||"unknown"}}function zL(){if((0,xr.platform)()==="darwin")try{return(0,Bx.execFileSync)("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return(0,xr.release)()||"unknown"}function WL(){return`${jx}/${Ux} (${qL()} ${zL()}; ${HL()})`}function Nx(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",Ux),e.toString()}function GL(t){return{session_id:t,thread_id:t,turn_id:(0,Mx.randomUUID)(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function JL(t){return{[BL]:t.session_id,[UL]:t.thread_id,[jL]:t.turn_id,[LL]:t.window_id,[Lx]:JSON.stringify(t)}}function KL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function VL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[NL]:t.window_id,[Lx]:JSON.stringify(t),[ML]:t.thread_id}}function YL(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 XL(t,e){return t?.req?.sessionId||YL(e)}function QL(t,e,n){if(!n)return;let r=GL(n);t.client_metadata=KL(t.client_metadata,JL(r)),Object.assign(e,VL(r))}var Cf=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=kt(e.reasoning,e.thinking)?"none":Rt(e.reasoning?.effort)||Rt(n?.reasoningEffort);if(a){let A={effort:a};if(a!=="none"){let k=Jr(e,n);k&&(A.summary=k)}e.reasoning=A}else delete e.reasoning;let u=["low","medium","high"];n?.verbosity&&u.includes(n.verbosity)&&(e.verbosity=n.verbosity);let d=xu(e.response_format);d&&(e.text={...e.text,format:d}),delete e.response_format,e=$h(e,r);let f=hu(e.messages);e.messages=f;let p=[],h=!1,g=$L(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
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=kt(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=vs(A);if(k.thinking||k.toolCalls.length){h=!1;let E=Ts(k.thinking);E&&p.push(E),(fa(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=kt(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:eg(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);HL(e,w,e.prompt_cache_key||qL(r,e));let C=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:Dx(`${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:Dx(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=(0,B_.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):I_(await Ka())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:Fx,"User-Agent":ML()};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 bf.delete(n.token),null;if((0,B_.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Ka({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),o=I_(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=bf.get(e);if(n&&n.expiresAt>Date.now())return n.value;bf.delete(e);let r=F_.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{F_.delete(e)});return F_.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 bf.set(e,{value:s,expiresAt:Date.now()+EL}),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=N_(),m=x=>(x!==p&&(f++,p=x),f),C=Fe(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(Ee("[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(Ee(JSON.stringify(j),O.encoder))}catch{O.controller.enqueue(Oe(x,O.encoder))}}else O.controller.enqueue(Oe(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=N_(),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)}
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=St(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=Ts(A);if(k.thinking||k.toolCalls.length){h=!1;let E=xs(k.thinking);E&&p.push(E),(pa(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=St(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:tg(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);QL(e,w,e.prompt_cache_key||XL(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=(0,j_.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):N_(await Va())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:jx,"User-Agent":WL()};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 bf.delete(n.token),null;if((0,j_.resolveCodexPat)(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Va({force:!0,previousAccessToken:n.token,expectedAccountId:n.accountId}),o=N_(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=bf.get(e);if(n&&n.expiresAt>Date.now())return n.value;bf.delete(e);let r=M_.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{M_.delete(e)});return M_.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 bf.set(e,{value:s,expiresAt:Date.now()+FL}),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=B_(),m=x=>(x!==p&&(f++,p=x),f),C=Fe(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(Ee("[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(Ee(JSON.stringify(j),O.encoder))}catch{O.controller.enqueue(Oe(x,O.encoder))}}else O.controller.enqueue(Oe(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=B_(),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)}
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:kt(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=M_(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:kt(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=M_(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=M_(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({[Bn]: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=Es(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 vu(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=Es(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(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:St(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=U_(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:St(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=U_(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=U_(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({[Bn]: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=vs(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 Tu(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=vs(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=N_(),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=ks(z.thinking?.encrypted_content);if(te&&(p=te),typeof z.thinking?.id=="string"&&z.thinking.id?h=z.thinking.id:mr(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 ye=Q.index??0,De=b.get(ye)||{index:ye,id:Q.id,type:"function",function:{name:Q.function?.name||"",arguments:""}};Q.id&&(De.id=Q.id),Q.function?.name&&(De.function.name=Q.function.name),typeof Q.function?.arguments=="string"&&(De.function.arguments=(De.function.arguments||"")+Q.function.arguments),b.set(ye,De)}};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 ye=JSON.parse(Q);if(ye.response?.model){let ve=n(ye.response.model);ve&&(i=ve)}let De=this.convertStreamEvent(ye,O,n,k,x,E);V(De)}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=As(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:kt(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[Bn]: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}};var Rr=require("fs"),kf=require("path"),Mx=require("os"),zL=(0,kf.join)((0,Mx.homedir)(),".claude-code-router","qwen_auth.json"),WL="https://qwen.aikit.club",GL=1e4,JL=120,wf=null;function Bx(){return process.env.CCR_QWEN_AUTH_FILE||zL}function KL(){try{let t=Bx();if(!(0,Rr.existsSync)(t))return null;let e=JSON.parse((0,Rr.readFileSync)(t,"utf-8"));return e.token?e:null}catch{return null}}function VL(t){let e=Bx(),n=(0,kf.dirname)(e);(0,Rr.existsSync)(n)||(0,Rr.mkdirSync)(n,{recursive:!0}),(0,Rr.writeFileSync)(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function YL(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 XL(t){try{let e=await fetch(`${WL}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(GL)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function Sf(t){let e=KL();if(!e)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");return(t?.force||e.expiresAt!=null&&Date.now()+JL*1e3>=e.expiresAt)&&(wf||(wf=(async()=>{let r=await XL(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:YL(r),updatedAt:Date.now()};return VL(o),o})().finally(()=>{wf=null})),e=await wf),e}var QL="https://qwen.aikit.club",Ux=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Af=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await Sf();return{url:e?.api_base_url||e?.baseUrl||QL,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:To(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?Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Oe(r,o.encoder));return}let i=s.replace(Ux,"");o.controller.enqueue(Oe(`data: ${i}`,o.encoder));return}o.controller.enqueue(Oe(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(Ux,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var U_=`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,A="",k=new Map,E=new Map,x=B_(),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=Ss(z.thinking?.encrypted_content);if(te&&(p=te),typeof z.thinking?.id=="string"&&z.thinking.id?h=z.thinking.id:mr(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 ye=Q.index??0,De=b.get(ye)||{index:ye,id:Q.id,type:"function",function:{name:Q.function?.name||"",arguments:""}};Q.id&&(De.id=Q.id),Q.function?.name&&(De.function.name=Q.function.name),typeof Q.function?.arguments=="string"&&(De.function.arguments=(De.function.arguments||"")+Q.function.arguments),b.set(ye,De)}};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 ye=JSON.parse(Q);if(ye.response?.model){let ve=n(ye.response.model);ve&&(i=ve)}let De=this.convertStreamEvent(ye,O,n,k,x,E);V(De)}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=Es(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:St(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[Bn]: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}};var Rr=require("fs"),kf=require("path"),$x=require("os"),ZL=(0,kf.join)((0,$x.homedir)(),".claude-code-router","qwen_auth.json"),e2="https://qwen.aikit.club",t2=1e4,n2=120,wf=null;function qx(){return process.env.CCR_QWEN_AUTH_FILE||ZL}function r2(){try{let t=qx();if(!(0,Rr.existsSync)(t))return null;let e=JSON.parse((0,Rr.readFileSync)(t,"utf-8"));return e.token?e:null}catch{return null}}function o2(t){let e=qx(),n=(0,kf.dirname)(e);(0,Rr.existsSync)(n)||(0,Rr.mkdirSync)(n,{recursive:!0}),(0,Rr.writeFileSync)(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function s2(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 i2(t){try{let e=await fetch(`${e2}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(t2)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function Sf(t){let e=r2();if(!e)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");return(t?.force||e.expiresAt!=null&&Date.now()+n2*1e3>=e.expiresAt)&&(wf||(wf=(async()=>{let r=await i2(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:s2(r),updatedAt:Date.now()};return o2(o),o})().finally(()=>{wf=null})),e=await wf),e}var a2="https://qwen.aikit.club",Hx=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Af=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await Sf();return{url:e?.api_base_url||e?.baseUrl||a2,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:xo(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?Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Oe(r,o.encoder));return}let i=s.replace(Hx,"");o.controller.enqueue(Oe(`data: ${i}`,o.encoder));return}o.controller.enqueue(Oe(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(Hx,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var L_=`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.`,ZL=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<ZL)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
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:U_}):r.content=[{type:"text",text:U_},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:U_}]}),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)}
352
+ Your final answer must follow after the closing tag above.`,c2=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<c2)&&(n++,o.content=`<reasoning_content>${o.thinking.content}</reasoning_content>
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:L_}):r.content=[{type:"text",text:L_},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:L_}]}),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
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)}
356
356
 
@@ -374,26 +374,26 @@ ${o.content}`),delete o.thinking)});let r=e.messages[e.messages.length-1];return
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 e2(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 t2(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+=e2(o);return e||n||r}function n2(t){return{type:"thinking",thinking:[{type:"text",text:t}]}}function jx(t){if(!t||typeof t!="object"||!("cache_control"in t))return t;let{cache_control:e,...n}=t;return n}function r2(t){let e={...t},n=t2(e),r=Array.isArray(e.content)?e.content:void 0,o=(r||[]).filter(i=>i?.type==="image_url").map(jx),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(n2(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(jx):e.content=s);return delete e.thinking,delete e.reasoning_content,delete e.cache_control,e}function o2(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 s2(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 $x(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>r2(s))),r.stream===void 0&&(r.stream=!0);let o=un(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=o2(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:Zu(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=s2(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 qx(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?Fe(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Oe(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Oe(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(Oe(o,s.encoder));return}let d=fi(u);if(d){let f=ao(a,{content:d});co(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(Ee(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(Ee(JSON.stringify(a),s.encoder))}catch{s.controller.enqueue(Oe(o,s.encoder))}}):t;return t}var Tf=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:$x(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 qx(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var i2="http://127.0.0.1:3457",xf=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||i2;r?.req?.body&&(r.req.body.stream=!0);let s=un(r,e);return{body:{...e,messages:Xe(e.messages),tools:Qe(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}};var Df=require("crypto");var a2="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",c2="1.18.21",u2=`opencode/${c2}`,j_=3,l2=500,d2=2e3,L_=3e4,f2=.25,Rf=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<j_;h++){let g=this.buildHeaders(n,r,s,i),b;try{b=await bs(a,e,{httpsProxy:u,...n,headers:g,signal:p},o,d)}catch(E){if(h===j_-1||We(E)||!hr(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 ys(O,p);continue}if(b.ok)return b;let m=await b.text(),w=h===j_-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 ys(E,p);continue}let k=Ve(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 u2(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 l2(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+=u2(o);return e||n||r}function d2(t){return{type:"thinking",thinking:[{type:"text",text:t}]}}function zx(t){if(!t||typeof t!="object"||!("cache_control"in t))return t;let{cache_control:e,...n}=t;return n}function f2(t){let e={...t},n=l2(e),r=Array.isArray(e.content)?e.content:void 0,o=(r||[]).filter(i=>i?.type==="image_url").map(zx),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(d2(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(zx):e.content=s);return delete e.thinking,delete e.reasoning_content,delete e.cache_control,e}function p2(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 h2(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="minimal"?"low":e==="low"||e==="medium"||e==="high"?e:"high"}var Wx=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function Gx(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>f2(s))),r.stream===void 0&&(r.stream=!0);let o=un(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=p2(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:el(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-")&&!Wx.has(s)||s.startsWith("mistral-medium-")&&!Wx.has(s))&&(r.reasoning_effort=h2(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 Jx(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?Fe(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Oe(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Oe(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(Oe(o,s.encoder));return}let d=pi(u);if(d){let f=co(a,{content:d});uo(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(Ee(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(Ee(JSON.stringify(a),s.encoder))}catch{s.controller.enqueue(Oe(o,s.encoder))}}):t;return t}var Tf=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:Gx(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 Jx(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var g2="http://127.0.0.1:3457",xf=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||g2;r?.req?.body&&(r.req.body.stream=!0);let s=un(r,e);return{body:{...e,messages:Xe(e.messages),tools:Qe(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}};var Df=require("crypto");var m2="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",y2="1.18.23",_2=`opencode/${y2}`,$_=5,b2=2e3,C2=3e4,q_=2147483647,w2=.25,Rf=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++){let g=this.buildHeaders(n,r,s,i,f,o),b;try{b=await Cs(a,e,{httpsProxy:u,...n,headers:g,signal:p},o,d)}catch(E){if(h===$_-1||We(E)||!hr(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 _s(O,p);continue}if(b.ok)return b;let m=await b.text(),w=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 _s(E,p);continue}let k=Ve(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 Ve(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":u2,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 Bh(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,L_)}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,L_);let i=Date.parse(o);if(Number.isFinite(i))return Math.min(Math.max(0,i-Date.now()),L_)}return this.exponentialRetryDelayMs(n)}exponentialRetryDelayMs(e){let n=l2*2**e*(1+Math.random()*f2);return Math.min(n,d2)}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(0,Df.createHash)("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=(0,Df.randomBytes)(1)[0];i>=248||(s+=a2[i%62])}return`${e}_${o.toString("hex")}${s}`}};var NR=require("@cursor/sdk");var p2=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function Hx(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!p2.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"})}var zx=require("crypto"),Wx=require("os"),Qo=require("path"),$_="cursor-sdk",Of="bridge",h2=(0,Qo.join)((0,Wx.homedir)(),".claude-code-router"),Qn=(0,Qo.join)(h2,"cursor-sdk-workspaces"),Gx=900*1e3,q_=32,Jx=1440*60*1e3,Kx=3600*1e3,g2=/^[0-9a-f]{32}$/;function H_(t,e=Qn){let n=t.replace(/[\\/]+$/,"");return(0,Qo.dirname)(n)!==e.replace(/[\\/]+$/,"")?!1:g2.test((0,Qo.basename)(n))}var Vx=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],Va="custom-user-tools";function Cn(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 bi(t){return(0,zx.createHash)("sha256").update(t.filter(Boolean).join(`
384
- `)).digest("hex").slice(0,32)}function Ci(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 z_(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function Yx(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:Ci(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 Ee(JSON.stringify(s),e)},encodeDone(){return Ee("[DONE]",e)}}}function W_(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+=Ci(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 uo={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},Xx=/<(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*$/,y2=/working director|workspace root|project root|platform|os version|operating system|git repo/i,Qx=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],Zx=[/^additional working director/i,/^additional director/i,/^extra working director/i],eR=[/^platform$/i,/^operating system$/i,/^os$/i],tR=[/^os version$/i,/^system version$/i],_2=[...Qx,...Zx,...eR,...tR],b2=2e5,C2=16,w2=400;function k2(t){let e=[],n=b2,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=Cn(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
385
- `)}function S2(t){let e=[],n=new Set,r=i=>{if(e.length>=C2)return;let a=i.match(m2);if(!a)return;let u=a[1].trim(),d=a[2].trim().slice(0,w2);if(!u||!d)return;let f=u.toLowerCase();n.has(f)||(n.add(f),e.push({key:u,value:d}))},o=!1;Xx.lastIndex=0;let s;for(;s=Xx.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/))y2.test(i)&&r(i);return e}function Pf(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function nR(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function A2(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>nR(e)):[]}function Ya(t){let e=S2(k2(t)),n=Pf(e,Qx),r=n&&nR(n)?n:void 0,o=A2(Pf(e,Zx)).filter(u=>u!==r),s=Pf(e,eR),i=Pf(e,tR),a=!!(r||s||i||e.length);return a?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:a,fingerprint:bi([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:uo}function rR(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)_2.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function Zo(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 E2(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 v2(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 sR(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=rR(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(Zo(e)),n.push(`Host tools are exposed via MCP server "${Va}" 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 T2(t,e,n=Ya(t)){return[...sR(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:",v2(t)].join(`
387
- `)}function x2(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.`,Zo(e)].join(`
388
- `)}function iR(t,e){return["# Agent rules","",...sR(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
389
- `)}function aR(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.",Zo(t)].join(" ")}var R2=[/^(?: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 D2(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:R2.some(o=>o.test(n))}function cR(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&D2(t.assistantText)}function uR(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(Zo(t)),{text:e.join(" ")}}function oR(t){let e=t.trim();return fg.some(n=>e===n)}function O2(t){if(!Array.isArray(t)){let e=Cn(t);return e.trim().length>0&&!oR(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&&!oR(n)}return!0})}function lR(t,e){let n=t.messages||[],r=[],o=e.hostEnv||Ya(t);e.mode==="bridge"?(r.push(T2(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=Cn(f.content);p&&r.push(`[system]
390
- ${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,P2(i,e.turnIntent)+1)):i,u=[];for(let f of a){if(f.role==="assistant"){let p=Cn(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 Ve(i)||"OpenCode provider stream error"}}}buildHeaders(e,n,r,o,s,i){let a=this.getOrCreateSessionId(r),u=this.resolveParentSessionId(i);return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":a,"x-opencode-request":o,"x-opencode-client":"cli",...u?{"x-parent-session-id":u}:{},"user-agent":_2,authorization:void 0}}resolveParentSessionId(e){if(!e)return;let n=e?.req?.headers;if(n&&typeof n=="object"){for(let[o,s]of Object.entries(n))if(o.toLowerCase()==="x-parent-session-id"&&typeof s=="string"&&s)return s}let r=e?.req?.parentSessionId??e?.req?.parentSessionID??e?.parentSessionId??e?.parentSessionID;if(typeof r=="string"&&r)return r}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 Bh(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,q_)}let o=e.headers.get("retry-after");if(o){let s=Number.parseFloat(o);if(Number.isFinite(s)&&s>=0)return Math.min(Math.ceil(s*1e3),q_);let i=Date.parse(o);if(Number.isFinite(i))return Math.min(Math.max(0,Math.ceil(i-Date.now())),q_)}return this.exponentialRetryDelayMs(n)}exponentialRetryDelayMs(e){let n=b2*2**e,r=n+n*w2*Math.random();return Math.min(Math.ceil(r),C2)}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(0,Df.createHash)("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=(0,Df.randomBytes)(1)[0];i>=248||(s+=m2[i%62])}return`${e}_${o.toString("hex")}${s}`}};var LR=require("@cursor/sdk");var k2=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function Kx(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!k2.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"})}var Vx=require("crypto"),Yx=require("os"),Zo=require("path"),H_="cursor-sdk",Of="bridge",S2=(0,Zo.join)((0,Yx.homedir)(),".claude-code-router"),Qn=(0,Zo.join)(S2,"cursor-sdk-workspaces"),Xx=900*1e3,z_=32,Qx=1440*60*1e3,Zx=3600*1e3,A2=/^[0-9a-f]{32}$/;function W_(t,e=Qn){let n=t.replace(/[\\/]+$/,"");return(0,Zo.dirname)(n)!==e.replace(/[\\/]+$/,"")?!1:A2.test((0,Zo.basename)(n))}var eR=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],Ya="custom-user-tools";function Cn(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 Ci(t){return(0,Vx.createHash)("sha256").update(t.filter(Boolean).join(`
384
+ `)).digest("hex").slice(0,32)}function wi(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 G_(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function tR(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:wi(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 Ee(JSON.stringify(s),e)},encodeDone(){return Ee("[DONE]",e)}}}function J_(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+=wi(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 lo={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},nR=/<(env|environment|system-info|system_info)>([\s\S]*?)<\/\1>/gi,E2=/^\s*[-*]?\s*([A-Za-z][A-Za-z0-9 _/'-]{2,48}?)\s*:\s*(\S.*?)\s*$/,v2=/working director|workspace root|project root|platform|os version|operating system|git repo/i,rR=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],oR=[/^additional working director/i,/^additional director/i,/^extra working director/i],sR=[/^platform$/i,/^operating system$/i,/^os$/i],iR=[/^os version$/i,/^system version$/i],T2=[...rR,...oR,...sR,...iR],x2=2e5,R2=16,D2=400;function O2(t){let e=[],n=x2,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=Cn(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
385
+ `)}function P2(t){let e=[],n=new Set,r=i=>{if(e.length>=R2)return;let a=i.match(E2);if(!a)return;let u=a[1].trim(),d=a[2].trim().slice(0,D2);if(!u||!d)return;let f=u.toLowerCase();n.has(f)||(n.add(f),e.push({key:u,value:d}))},o=!1;nR.lastIndex=0;let s;for(;s=nR.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/))v2.test(i)&&r(i);return e}function Pf(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function aR(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function I2(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>aR(e)):[]}function Xa(t){let e=P2(O2(t)),n=Pf(e,rR),r=n&&aR(n)?n:void 0,o=I2(Pf(e,oR)).filter(u=>u!==r),s=Pf(e,sR),i=Pf(e,iR),a=!!(r||s||i||e.length);return a?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:a,fingerprint:Ci([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:lo}function cR(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)T2.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function es(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 F2(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 N2(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 lR(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=cR(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(es(e)),n.push(`Host tools are exposed via MCP server "${Ya}" 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 M2(t,e,n=Xa(t)){return[...lR(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:",N2(t)].join(`
387
+ `)}function B2(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.`,es(e)].join(`
388
+ `)}function dR(t,e){return["# Agent rules","",...lR(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
389
+ `)}function fR(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.",es(t)].join(" ")}var U2=[/^(?: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:U2.some(o=>o.test(n))}function pR(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&j2(t.assistantText)}function hR(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(es(t)),{text:e.join(" ")}}function uR(t){let e=t.trim();return pg.some(n=>e===n)}function L2(t){if(!Array.isArray(t)){let e=Cn(t);return e.trim().length>0&&!uR(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&&!uR(n)}return!0})}function gR(t,e){let n=t.messages||[],r=[],o=e.hostEnv||Xa(t);e.mode==="bridge"?(r.push(M2(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=Cn(f.content);p&&r.push(`[system]
390
+ ${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,$2(i,e.turnIntent)+1)):i,u=[];for(let f of a){if(f.role==="assistant"){let p=Cn(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
- ${Cn(f.content)}`);continue}if(f.role==="user"){let p=Cn(f.content);u=[...u,...E2(f.content)],p&&r.push(`[user]
394
- ${p}`)}}e.mode==="bridge"&&r.push(x2(e.workspaceDir,o));let d=r.join(`
393
+ ${Cn(f.content)}`);continue}if(f.role==="user"){let p=Cn(f.content);u=[...u,...F2(f.content)],p&&r.push(`[user]
394
+ ${p}`)}}e.mode==="bridge"&&r.push(B2(e.workspaceDir,o));let d=r.join(`
395
395
 
396
- `).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function P2(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 dR(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||O2(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:Cn(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}var If=require("crypto"),on=require("fs"),V_=require("path"),J_=require("@cursor/sdk");var lo=require("fs"),wi=require("path");function I2(t){return`#!/usr/bin/env node
396
+ `).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function $2(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 mR(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||L2(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:Cn(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}var If=require("crypto"),on=require("fs"),X_=require("path"),V_=require("@cursor/sdk");var fo=require("fs"),ki=require("path");function q2(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", () => {
@@ -417,7 +417,7 @@ process.stdin.on("end", () => {
417
417
  );
418
418
 
419
419
  // Always allow the SDK synthetic MCP host tools Claude Code bridges through.
420
- if (server.includes(${JSON.stringify(Va)})) {
420
+ if (server.includes(${JSON.stringify(Ya)})) {
421
421
  process.stdout.write(JSON.stringify({ permission: "allow" }));
422
422
  return;
423
423
  }
@@ -432,17 +432,17 @@ process.stdin.on("end", () => {
432
432
  })
433
433
  );
434
434
  });
435
- `}function F2(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${Va}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,aR(t)].join(" ")}function G_(t,e,n){try{if((0,lo.readFileSync)(t,"utf-8")===e)return}catch{}(0,lo.writeFileSync)(t,e,{encoding:"utf-8",mode:n})}function Xa(t,e=uo){let n=(0,wi.join)(t,".cursor"),r=(0,wi.join)(n,"hooks");(0,lo.mkdirSync)(r,{recursive:!0});let o=(0,wi.join)(r,"deny-builtin.cjs");G_(o,I2(F2(e)),448);try{(0,lo.chmodSync)(o,448)}catch{}let s=Vx.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};G_((0,wi.join)(n,"hooks.json"),JSON.stringify(a,null,2),384),G_((0,wi.join)(t,"AGENTS.md"),iR(t,e),384)}var N2=2e3;function M2(t){let e=t;return e?.name==="AbortError"||String(e?.message||t).toLowerCase()==="this operation was aborted"}function ki(t,e){t.poisoned=!0,t.poisonReason=e}async function Y_(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 Nf(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&&ki(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function Nf(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 Mf(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 Qa(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")||(0,on.existsSync)("/.dockerenv")||process.env.container==="docker")}function B2(t,e){(0,on.existsSync)(Qn)||(0,on.mkdirSync)(Qn,{recursive:!0});let n=(0,V_.join)(Qn,t);return(0,on.mkdirSync)(n,{recursive:!0}),Xa(n,e),n}function X_(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 Xa(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function fR(t,e,n=Qn){if(!H_(t,n))return!1;try{return(0,on.rmSync)(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function hR(t){if(t.headerSession)return(0,If.createHash)("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?(0,If.createHash)("sha256").update(e[1]).digest("hex").slice(0,32):(0,If.createHash)("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return bi([t.model||"",t.systemAndFirstUser||""])}function pR(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function Ff(t){t.lastActiveAt=Date.now()}var K_=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&&Ff(n),n}async retireSession(e,n,r){ki(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||uo,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:B2(e.key,o);e.mode==="bridge"&&Xa(s,o);let i=e.mode==="plan"?"plan":"agent",a=Qa(e.sandboxEnabled),u=await J_.Agent.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=Qa(e.sandboxEnabled),r=e.hostEnv||uo;e.mode==="bridge"&&Xa(e.workspaceDir,r);let o=await J_.Agent.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"),Ff(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 Y_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),fR(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(ki(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 Nf(r,N2,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};M2(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>=q_;){let e,n=1/0;for(let[r,o]of this.sessions)pR(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:q_},"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)pR(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=Qn){if(e-this.lastSweepAt<Kx)return 0;this.lastSweepAt=e;let r;try{r=(0,on.readdirSync)(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=(0,V_.join)(n,i);if(!(o.has(a)||!H_(a,n))){try{let u=(0,on.statSync)(a);if(!u.isDirectory()||e-u.mtimeMs<=Jx)continue}catch{continue}fR(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},fo=new K_;var U2="Cursor SDK agent.send timed out";function Q_(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 Z_(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 j2(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 L2(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=j2(r),await Nf(s?Promise.race([o,s.promise]):o,15e3,U2)}catch(i){throw o&&o.then(a=>a.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function e0(t,e,n,r={}){return L2(t,e,n,r.abortSignal)}var _R=require("crypto");var $2=6,q2=512,H2=4;function z2(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function W2(t,e){return t.length<8?!1:t.includes(e)||t.includes(Qn)}function gR(t,e){let n=[],r=0,o=(s,i,a)=>{if(!(n.length>=H2||r>=q2||a>$2)){if(r++,typeof s=="string"){W2(s,e)&&n.push({argPath:i||"(argument)",value:z2(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 mR(t){return t.projectRoot?!t.projectRoot.startsWith(Qn):!0}function yR(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
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.",Zo(r),"Retry the call with a host path."].join(`
437
- `)}var G2=3;function J2(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 t0(){return{scratchViolations:0,scratchCorrections:0}}function bR(t,e,n,r=t0()){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:J2(s.function.parameters),async execute(a,u){let d=gr(u.toolCallId)||(0,_R.randomUUID)(),f=a||{},p=e.hostEnv||uo,h=mR(p)?gR(f,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let g=e.metrics.scratchPathCorrections<G2;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,yR(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:d,name:i,args:f})}})}return o}function wR(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function CR(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function kR(t){let e=[];t.system&&e.push(CR(t.system));for(let n of t.messages||[])e.push(CR(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)),wR(e.join(`
438
- `).length)}function SR(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=wR(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 Bf(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function AR(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=Bf(t.prompt_tokens),s=Bf(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=Bf(e?.prompt_tokens),a=Bf(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 ER(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}}}var vR=require("crypto"),K2=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Zn(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=>Zn(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=Zn(t[n]);r!==void 0&&(e[n]=r)}return e}function r0(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Zn(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 Zn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Zn(n)}).filter(e=>e!==void 0)}function V2(t){if(typeof t!="string")return Zn(t)??null;try{return Zn(JSON.parse(t))??null}catch{return t}}function o0(t){let e=t,n={content:r0(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:V2(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function TR(t){return Array.isArray(t)?t.map(e=>Zn(e)).filter(e=>e!==void 0).sort((e,n)=>n0(e).localeCompare(n0(n))):[]}function n0(t){return JSON.stringify(t)}function s0(t){return(0,vR.createHash)("sha256").update(n0(t)).digest("hex")}function xR(t){return{system:r0(t.system),messages:(t.messages||[]).map(o0)}}function Y2(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(K2.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(o0):r==="system"?o=r0(t.system):r==="tools"?o=TR(t.tools):o=Zn(e[r]),o!==void 0&&(n[r]=o)}return n}function RR(t,e={}){return s0({compatibilityStamp:e.compatibilityStamp||"",request:Y2(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 i0(t){return s0({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Zn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:TR(t.tools),workspaceDir:t.workspaceDir})}function DR(t,e){return s0({messages:e,system:t})}function OR(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=xR(t);return e&&n.messages.push(o0(e)),Object.freeze({transcriptHash:DR(n.system,n.messages),messageCount:n.messages.length})}function PR(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=xR(e);if(!(n.messages.length<=t.messageCount)&&DR(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function X2(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 Dr=t=>({action:"retire-and-replay-full",reason:t});function IR(t){let{session:e,turn:n}=t;if(e.poisoned)return Dr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:Dr("inconsistent-unused-session");if(e.alignment==="unknown")return Dr("unknown-context-alignment");if(e.alignment==="divergent")return Dr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return Dr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return Dr("dead-parked-run");if(n.hasMeaningfulSteering)return Dr("parked-turn-has-steering");let r=X2(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:Dr("parked-tool-results-mismatch")}return n.toolResults.length>0?Dr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function wn(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 a0(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var c0=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 u0(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(wn(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 a0(this.settled,3e3);return}this.phase="aborting";let n=wn(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 a0(o,3e3),this.finishFailed(n)}await a0(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw wn(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(wn(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,wn(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||wn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,wn(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(wn(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"))}},u0=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}}},l0=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 wn(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 wn(e.signal.reason);for(;;){if(e.signal?.aborted)throw wn(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 c0(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()}},FR=new l0;var Q2=900*1e3,Za=null;function d0(t){return bi([t])}async function Z2(t){let e=d0(t);if(Za&&Za.apiKeyFingerprint===e&&Date.now()-Za.fetchedAt<Q2)return Za.models;let n=await NR.Cursor.models.list({apiKey:t})||[];return Za={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function e$(t,e,n){let r;try{r=await Z2(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 t$(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 n$(t){return t.length===1&&t[0]?.role==="user"}function r$(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||Cn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function kn(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 s$(t,e){if(!e||e.type!=="thinking-delta")return;let n=Ci(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function ec(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:fo.retireSession(t,e.reason,()=>Mf(t,async()=>(await Y_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await fo.invalidate(t,e.reason),!0)))}function i$(t,e,n,r){let o=r.cursorMode||Of,s=t.model||"composer-2",i;try{i=Hx(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=hR({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:t$(t)});return{apiKey:i,hostEnv:Ya(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function MR(t,e,n,r={}){let o=i$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=i0({credentialFingerprint:d0(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:z_(t)||""},sandboxEnabled:Qa(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=RR(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await FR.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 a$(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 a$(t,e,n,r,o){kn(r.abortSignal);let s=r.logger||e?.logger;s&&fo.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=z_(t),h=await e$(d,u,p);kn(r.abortSignal);let g=o.hostEnv,b={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};kn(r.abortSignal);let m=await fo.getOrCreate(b);kn(r.abortSignal);let w=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,C=X=>i0({credentialFingerprint:d0(d),guidanceFingerprint:w(X).fingerprint,mode:i,model:h,sandboxEnabled:Qa(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),A=w(m),k=C(m),E=dR(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?PR(m.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?r$(q,E,r.turnIntent):O.kind==="idle"?n$(q):!0,j=!m.hasSentPrompt||!m.transcriptCommit?"unknown":V?"strict":"divergent",ee=IR({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 ec(m,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:m.activeRunToken}),kn(r.abortSignal),m=await fo.getOrCreate(b),kn(r.abortSignal),A=w(m),k=C(m),ee={action:"send-full",reason:"unused-session"}),kn(r.abortSignal),X_(m,A),ee.action==="resume-parked"&&(kn(r.abortSignal),fo.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,ye=(X,le)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ae=>ae.runToken!==le),X.notifySdkMessage()},De=(X,le)=>{let ae=i==="bridge"?bR(t,X,s,ve):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ae?{customTools:ae}:void 0,onDelta:({update:S})=>{let T=s$(X,S);T&&X.enqueueSdkMessage(T,le)}}},ve=t0(),Ye=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,le)=>le.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||Q_(X)||Z_(X)),Z=async(X,le)=>{let ae;if(await Mf(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 ki(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=lR(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:le,hostEnv:A,turnIntent:r.turnIntent});ae=Symbol("cursor-sdk-run"),X.activeRunToken=ae;try{let T=await e0(X,S,De(X,ae),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ae,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,kn(r.abortSignal)}catch(T){throw ae&&X.activeRunToken===ae&&(X.activeRunToken=void 0,ye(X,ae)),(r.abortSignal?.aborted||Z_(T)||Q_(T))&&ki(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}}),!ae)throw new Error("cursor-sdk agent.send did not produce a run token");return ae};if(z)try{Q=await Z(m,te)}catch(X){let le=ne(X,m);if(await ec(m,{reason:"cursor-sdk prompt send failed before streaming"}),!le)throw Ye(X);kn(r.abortSignal),s?.warn?.({err:X,sessionKey:m.key,agentId:m.agentId},"cursor-sdk retrying failed resumed send with fresh session"),m=await fo.getOrCreate(b),kn(r.abortSignal),A=w(m),k=C(m),X_(m,A);try{Q=await Z(m,!1)}catch(ae){throw await ec(m,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ye(ae)}}Q||(Q=Symbol("cursor-sdk-run"),m.activeRunToken=Q);let ie=Yx(u,new TextEncoder),Pe=[],Ce=kR(t),H=0,Ae,tt=new ReadableStream({async start(X){let le=()=>{ve.scratchViolations<=0||s?.warn?.({sessionKey:m.key,model:u,scratchViolations:ve.scratchViolations,scratchCorrections:ve.scratchCorrections,metrics:m.metrics,hostProjectRoot:A.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ae=D=>{Pe.push(D),a&&X.enqueue(ie.encode(D))},S=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=AR(Ae,m.lastSdkUsageRaw,Ce),F=SR(Ce,H,D);return Ae&&(m.lastSdkUsageRaw=Ae),F},R=()=>{if(m.activeRunToken!==Q)return;let F=W_(u,Pe)?.choices?.[0]?.message;!F||F.role!=="assistant"||(m.transcriptCommit=OR(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:Ae,runUsage:m.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ae(ie.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,U,B="",K=0,se=()=>{!P||N||(ae(ie.thinkingSignature()),N=!0,L=!1)};for(;;){let ce=!1;for await(let _e of o$(m,i,Q,r.abortSignal)){if(Ff(m),_e.kind==="host_tool"){if(i!=="bridge")continue;for(se(),L=!1,S(_e.tool.name),S(JSON.stringify(_e.tool.args??{})),ae(ie.toolCall(_e.tool,D)),D+=1;m.pendingEmit.length;){let pe=m.pendingEmit.shift();S(pe.name),S(JSON.stringify(pe.args??{})),ae(ie.toolCall(pe,D)),D+=1}M("tool_calls"),a&&X.enqueue(ie.encodeDone()),X.close();return}if(_e.kind==="end"){if(_e.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(cR({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 pe=Symbol("cursor-sdk-run");Q=pe,m.activeRunToken=pe,await Mf(m,async()=>{if(m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let me=await e0(m,uR(A),De(m,pe),{abortSignal:r.abortSignal,logger:s});if(m.run=me,m.activeRunToken=pe,m.streamIterator=me.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="",ce=!0;break}se(),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(ie.encodeDone()),X.close();return}let ge=_e.message;if(ge){if(ge.type==="assistant")for(let pe of ge.message?.content||[])pe.type==="text"&&pe.text&&(se(),L=!1,F=!0,B+=pe.text,S(pe.text),ae(ie.content(pe.text)));else if(ge.type==="thinking"){if(!L)continue;let pe=_e.source||"stream";if(U&&U!==pe)continue;U=pe;let me=Ci(ge.text);me&&(P=!0,S(me),ae(ie.thinking(me)))}else if(ge.type==="usage")Ae=ER(ge);else if(ge.type==="status"){if(ge.status==="ERROR"||ge.status==="CANCELLED")throw Object.assign(new Error(ge.message||`Cursor run ${ge.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(ge.type==="tool_call"&&i!=="bridge"&&i==="agent"&&ge.name){se(),L=!1;let pe=`
435
+ `}function H2(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${Ya}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,fR(t)].join(" ")}function K_(t,e,n){try{if((0,fo.readFileSync)(t,"utf-8")===e)return}catch{}(0,fo.writeFileSync)(t,e,{encoding:"utf-8",mode:n})}function Qa(t,e=lo){let n=(0,ki.join)(t,".cursor"),r=(0,ki.join)(n,"hooks");(0,fo.mkdirSync)(r,{recursive:!0});let o=(0,ki.join)(r,"deny-builtin.cjs");K_(o,q2(H2(e)),448);try{(0,fo.chmodSync)(o,448)}catch{}let s=eR.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};K_((0,ki.join)(n,"hooks.json"),JSON.stringify(a,null,2),384),K_((0,ki.join)(t,"AGENTS.md"),dR(t,e),384)}var z2=2e3;function W2(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 Q_(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 Nf(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 Nf(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 Mf(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 Za(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")||(0,on.existsSync)("/.dockerenv")||process.env.container==="docker")}function G2(t,e){(0,on.existsSync)(Qn)||(0,on.mkdirSync)(Qn,{recursive:!0});let n=(0,X_.join)(Qn,t);return(0,on.mkdirSync)(n,{recursive:!0}),Qa(n,e),n}function Z_(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 Qa(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function yR(t,e,n=Qn){if(!W_(t,n))return!1;try{return(0,on.rmSync)(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function bR(t){if(t.headerSession)return(0,If.createHash)("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?(0,If.createHash)("sha256").update(e[1]).digest("hex").slice(0,32):(0,If.createHash)("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return Ci([t.model||"",t.systemAndFirstUser||""])}function _R(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function Ff(t){t.lastActiveAt=Date.now()}var Y_=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&&Ff(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||lo,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:G2(e.key,o);e.mode==="bridge"&&Qa(s,o);let i=e.mode==="plan"?"plan":"agent",a=Za(e.sandboxEnabled),u=await V_.Agent.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=Za(e.sandboxEnabled),r=e.hostEnv||lo;e.mode==="bridge"&&Qa(e.workspaceDir,r);let o=await V_.Agent.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"),Ff(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 Q_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),yR(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 Nf(r,z2,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};W2(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>=z_;){let e,n=1/0;for(let[r,o]of this.sessions)_R(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:z_},"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)_R(r)||e-r.lastActiveAt>Xx&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=Qn){if(e-this.lastSweepAt<Zx)return 0;this.lastSweepAt=e;let r;try{r=(0,on.readdirSync)(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=(0,X_.join)(n,i);if(!(o.has(a)||!W_(a,n))){try{let u=(0,on.statSync)(a);if(!u.isDirectory()||e-u.mtimeMs<=Qx)continue}catch{continue}yR(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},po=new Y_;var J2="Cursor SDK agent.send timed out";function e0(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 t0(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 K2(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 V2(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=K2(r),await Nf(s?Promise.race([o,s.promise]):o,15e3,J2)}catch(i){throw o&&o.then(a=>a.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function n0(t,e,n,r={}){return V2(t,e,n,r.abortSignal)}var SR=require("crypto");var Y2=6,X2=512,Q2=4;function Z2(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function e$(t,e){return t.length<8?!1:t.includes(e)||t.includes(Qn)}function CR(t,e){let n=[],r=0,o=(s,i,a)=>{if(!(n.length>=Q2||r>=X2||a>Y2)){if(r++,typeof s=="string"){e$(s,e)&&n.push({argPath:i||"(argument)",value:Z2(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 wR(t){return t.projectRoot?!t.projectRoot.startsWith(Qn):!0}function kR(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
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.",es(r),"Retry the call with a host path."].join(`
437
+ `)}var t$=3;function n$(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 r0(){return{scratchViolations:0,scratchCorrections:0}}function AR(t,e,n,r=r0()){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:n$(s.function.parameters),async execute(a,u){let d=gr(u.toolCallId)||(0,SR.randomUUID)(),f=a||{},p=e.hostEnv||lo,h=wR(p)?CR(f,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let g=e.metrics.scratchPathCorrections<t$;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,kR(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:d,name:i,args:f})}})}return o}function vR(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function ER(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function TR(t){let e=[];t.system&&e.push(ER(t.system));for(let n of t.messages||[])e.push(ER(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)),vR(e.join(`
438
+ `).length)}function xR(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=vR(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 Bf(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function RR(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=Bf(t.prompt_tokens),s=Bf(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=Bf(e?.prompt_tokens),a=Bf(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 DR(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}}}var OR=require("crypto"),r$=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Zn(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=>Zn(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=Zn(t[n]);r!==void 0&&(e[n]=r)}return e}function s0(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Zn(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 Zn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Zn(n)}).filter(e=>e!==void 0)}function o$(t){if(typeof t!="string")return Zn(t)??null;try{return Zn(JSON.parse(t))??null}catch{return t}}function i0(t){let e=t,n={content:s0(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:o$(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function PR(t){return Array.isArray(t)?t.map(e=>Zn(e)).filter(e=>e!==void 0).sort((e,n)=>o0(e).localeCompare(o0(n))):[]}function o0(t){return JSON.stringify(t)}function a0(t){return(0,OR.createHash)("sha256").update(o0(t)).digest("hex")}function IR(t){return{system:s0(t.system),messages:(t.messages||[]).map(i0)}}function s$(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(r$.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(i0):r==="system"?o=s0(t.system):r==="tools"?o=PR(t.tools):o=Zn(e[r]),o!==void 0&&(n[r]=o)}return n}function FR(t,e={}){return a0({compatibilityStamp:e.compatibilityStamp||"",request:s$(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 c0(t){return a0({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Zn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:PR(t.tools),workspaceDir:t.workspaceDir})}function NR(t,e){return a0({messages:e,system:t})}function MR(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=IR(t);return e&&n.messages.push(i0(e)),Object.freeze({transcriptHash:NR(n.system,n.messages),messageCount:n.messages.length})}function BR(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=IR(e);if(!(n.messages.length<=t.messageCount)&&NR(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function i$(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 Dr=t=>({action:"retire-and-replay-full",reason:t});function UR(t){let{session:e,turn:n}=t;if(e.poisoned)return Dr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:Dr("inconsistent-unused-session");if(e.alignment==="unknown")return Dr("unknown-context-alignment");if(e.alignment==="divergent")return Dr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return Dr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return Dr("dead-parked-run");if(n.hasMeaningfulSteering)return Dr("parked-turn-has-steering");let r=i$(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:Dr("parked-tool-results-mismatch")}return n.toolResults.length>0?Dr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function wn(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 u0(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var l0=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 d0(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(wn(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 u0(this.settled,3e3);return}this.phase="aborting";let n=wn(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 u0(o,3e3),this.finishFailed(n)}await u0(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw wn(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(wn(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,wn(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||wn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,wn(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(wn(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"))}},d0=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}}},f0=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 wn(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 wn(e.signal.reason);for(;;){if(e.signal?.aborted)throw wn(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 l0(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()}},jR=new f0;var a$=900*1e3,ec=null;function p0(t){return Ci([t])}async function c$(t){let e=p0(t);if(ec&&ec.apiKeyFingerprint===e&&Date.now()-ec.fetchedAt<a$)return ec.models;let n=await LR.Cursor.models.list({apiKey:t})||[];return ec={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function u$(t,e,n){let r;try{r=await c$(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 l$(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 d$(t){return t.length===1&&t[0]?.role==="user"}function f$(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||Cn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function kn(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*p$(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 h$(t,e){if(!e||e.type!=="thinking-delta")return;let n=wi(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function tc(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:po.retireSession(t,e.reason,()=>Mf(t,async()=>(await Q_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await po.invalidate(t,e.reason),!0)))}function g$(t,e,n,r){let o=r.cursorMode||Of,s=t.model||"composer-2",i;try{i=Kx(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=bR({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:l$(t)});return{apiKey:i,hostEnv:Xa(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function $R(t,e,n,r={}){let o=g$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=c0({credentialFingerprint:p0(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:G_(t)||""},sandboxEnabled:Za(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=FR(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await jR.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 m$(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 m$(t,e,n,r,o){kn(r.abortSignal);let s=r.logger||e?.logger;s&&po.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=G_(t),h=await u$(d,u,p);kn(r.abortSignal);let g=o.hostEnv,b={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};kn(r.abortSignal);let m=await po.getOrCreate(b);kn(r.abortSignal);let w=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,C=X=>c0({credentialFingerprint:p0(d),guidanceFingerprint:w(X).fingerprint,mode:i,model:h,sandboxEnabled:Za(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),A=w(m),k=C(m),E=mR(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?BR(m.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?f$(q,E,r.turnIntent):O.kind==="idle"?d$(q):!0,j=!m.hasSentPrompt||!m.transcriptCommit?"unknown":V?"strict":"divergent",ee=UR({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 tc(m,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:m.activeRunToken}),kn(r.abortSignal),m=await po.getOrCreate(b),kn(r.abortSignal),A=w(m),k=C(m),ee={action:"send-full",reason:"unused-session"}),kn(r.abortSignal),Z_(m,A),ee.action==="resume-parked"&&(kn(r.abortSignal),po.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,ye=(X,le)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ae=>ae.runToken!==le),X.notifySdkMessage()},De=(X,le)=>{let ae=i==="bridge"?AR(t,X,s,ve):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ae?{customTools:ae}:void 0,onDelta:({update:S})=>{let T=h$(X,S);T&&X.enqueueSdkMessage(T,le)}}},ve=r0(),Ye=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,le)=>le.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||e0(X)||t0(X)),Z=async(X,le)=>{let ae;if(await Mf(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=gR(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:le,hostEnv:A,turnIntent:r.turnIntent});ae=Symbol("cursor-sdk-run"),X.activeRunToken=ae;try{let T=await n0(X,S,De(X,ae),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ae,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,kn(r.abortSignal)}catch(T){throw ae&&X.activeRunToken===ae&&(X.activeRunToken=void 0,ye(X,ae)),(r.abortSignal?.aborted||t0(T)||e0(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}}),!ae)throw new Error("cursor-sdk agent.send did not produce a run token");return ae};if(z)try{Q=await Z(m,te)}catch(X){let le=ne(X,m);if(await tc(m,{reason:"cursor-sdk prompt send failed before streaming"}),!le)throw Ye(X);kn(r.abortSignal),s?.warn?.({err:X,sessionKey:m.key,agentId:m.agentId},"cursor-sdk retrying failed resumed send with fresh session"),m=await po.getOrCreate(b),kn(r.abortSignal),A=w(m),k=C(m),Z_(m,A);try{Q=await Z(m,!1)}catch(ae){throw await tc(m,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ye(ae)}}Q||(Q=Symbol("cursor-sdk-run"),m.activeRunToken=Q);let ie=tR(u,new TextEncoder),Pe=[],Ce=TR(t),H=0,Ae,tt=new ReadableStream({async start(X){let le=()=>{ve.scratchViolations<=0||s?.warn?.({sessionKey:m.key,model:u,scratchViolations:ve.scratchViolations,scratchCorrections:ve.scratchCorrections,metrics:m.metrics,hostProjectRoot:A.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ae=D=>{Pe.push(D),a&&X.enqueue(ie.encode(D))},S=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=RR(Ae,m.lastSdkUsageRaw,Ce),F=xR(Ce,H,D);return Ae&&(m.lastSdkUsageRaw=Ae),F},R=()=>{if(m.activeRunToken!==Q)return;let F=J_(u,Pe)?.choices?.[0]?.message;!F||F.role!=="assistant"||(m.transcriptCommit=MR(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:Ae,runUsage:m.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ae(ie.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,U,B="",K=0,se=()=>{!P||N||(ae(ie.thinkingSignature()),N=!0,L=!1)};for(;;){let ce=!1;for await(let _e of p$(m,i,Q,r.abortSignal)){if(Ff(m),_e.kind==="host_tool"){if(i!=="bridge")continue;for(se(),L=!1,S(_e.tool.name),S(JSON.stringify(_e.tool.args??{})),ae(ie.toolCall(_e.tool,D)),D+=1;m.pendingEmit.length;){let pe=m.pendingEmit.shift();S(pe.name),S(JSON.stringify(pe.args??{})),ae(ie.toolCall(pe,D)),D+=1}M("tool_calls"),a&&X.enqueue(ie.encodeDone()),X.close();return}if(_e.kind==="end"){if(_e.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(pR({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 pe=Symbol("cursor-sdk-run");Q=pe,m.activeRunToken=pe,await Mf(m,async()=>{if(m.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let me=await n0(m,hR(A),De(m,pe),{abortSignal:r.abortSignal,logger:s});if(m.run=me,m.activeRunToken=pe,m.streamIterator=me.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="",ce=!0;break}se(),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(ie.encodeDone()),X.close();return}let ge=_e.message;if(ge){if(ge.type==="assistant")for(let pe of ge.message?.content||[])pe.type==="text"&&pe.text&&(se(),L=!1,F=!0,B+=pe.text,S(pe.text),ae(ie.content(pe.text)));else if(ge.type==="thinking"){if(!L)continue;let pe=_e.source||"stream";if(U&&U!==pe)continue;U=pe;let me=wi(ge.text);me&&(P=!0,S(me),ae(ie.thinking(me)))}else if(ge.type==="usage")Ae=DR(ge);else if(ge.type==="status"){if(ge.status==="ERROR"||ge.status==="CANCELLED")throw Object.assign(new Error(ge.message||`Cursor run ${ge.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(ge.type==="tool_call"&&i!=="bridge"&&i==="agent"&&ge.name){se(),L=!1;let pe=`
440
440
  [cursor tool ${ge.status||"running"}: ${ge.name}]
441
- `;S(pe),ae(ie.content(pe))}}}if(!ce)break}!F&&!D&&(se(),M("stop")),a&&X.enqueue(ie.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:m.metrics},"cursor-sdk stream failed"),await ec(m,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{le()}},async cancel(){await ec(m,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=tt.getReader();for(;;){let{done:ae}=await X.read();if(ae)break}let le=W_(u,Pe);return new Response(JSON.stringify(le),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(tt,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function c$(t,e,n){return{cursorMode:t.cursorMode||Of,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var Uf=class{static TransformerName=$_;name=$_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=c$(this.options,r,this.logger),s={...e,messages:Xe(e.messages),tools:Qe(e.tools)},i=await MR(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};var oD=require("crypto");var qt=require("fs"),Lf=require("path"),UR=require("os"),jR=require("crypto"),$f="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",qf="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",p0="http://localhost:51121/oauth-callback",LR=["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"],h0="https://daily-cloudcode-pa.sandbox.googleapis.com",$R="https://autopush-cloudcode-pa.sandbox.googleapis.com",qR="https://cloudcode-pa.googleapis.com",u$=[h0,$R,qR],f0=[qR,h0,$R],l$="1.18.3",d$=(0,Lf.join)((0,UR.homedir)(),".claude-code-router","antigravity_auth.json"),f$=12e4,HR="https://oauth2.googleapis.com/token",p$="https://www.googleapis.com/oauth2/v2/userinfo",jf=null,zR=null;function WR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||d$}function nc(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${l$} 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 tc(){try{let t=WR();if(!(0,qt.existsSync)(t))return null;let e=JSON.parse((0,qt.readFileSync)(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function Hf(t){let e=WR();(0,qt.mkdirSync)((0,Lf.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,qt.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,qt.renameSync)(n,e)}finally{try{(0,qt.existsSync)(n)&&(0,qt.unlinkSync)(n)}catch{}}}function h$(t){return Date.now()+f$>=t.expires_at}async function g$(t){let e=new URLSearchParams({client_id:$f,client_secret:qf,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(HR,{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 Hf(o),o}async function Ai(t){let e=tc();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!h$(e)?e:(jf||(jf=g$(e).finally(()=>{jf=null})),jf)}function Si(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 m$(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 BR(t){await new Promise(e=>setTimeout(e,t))}async function y$(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...nc()};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 BR(2e3);continue}let a=await i.json();if(a?.done===!0)return Si(a?.response)||Si(a)||void 0}catch{}await BR(2e3)}}async function _$(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...nc()},body:JSON.stringify({tierId:e,metadata:GR()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=Si(o?.response)||Si(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?y$(t,n,o.name.trim()):void 0}catch{return}}function b$(t){let e=m$(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function C$(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...nc()},n=JSON.stringify({metadata:GR()}),r;for(let o of f0)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=Si(i);if(a)return a}catch{}for(let o of b$(r))for(let s of f0){let i=await _$(t,o,s);if(i)return i}for(let o of f0)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=Si(await s.json());if(i)return i}catch{}}async function zf(t,e){let n=t?.project_id?.trim();if(n)return n;let r=tc();if(r?.project_id?.trim())return r.project_id.trim();let o=await C$(e);if(o){let s=tc();return s&&Hf({...s,project_id:o}),o}}function rc(){return zR||h0}function JR(t){zR=t}var KR=new Set;function VR(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function YR(t){KR.add(t.replace(/\/$/,""))}function w$(t){return KR.has(t.replace(/\/$/,""))}function XR(t,e){return e?t===404||t===403||t>=500:!1}function QR(t){let e=t?.replace(/\/$/,"")||rc(),n=[...new Set([e,...u$])],r=n.filter(o=>!w$(o));return r.length?r:n}function Wf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function ZR(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:(0,jR.randomUUID)()}}async function eD(t){try{let e=await fetch(p$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function tD(t,e){let n=new URLSearchParams({client_id:$f,client_secret:qf,code:t,grant_type:"authorization_code",redirect_uri:p0,code_verifier:e}),r=await fetch(HR,{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 nD(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 rD(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function k$(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 S$(t){return t?.req?.body?.stream===!0}function A$(t){return QR(t)}var Gf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Ai({force:o?.forceRefresh}),i=await zf(n,s.access_token),a=k$(r,n),u=S$(r),d=ZR({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||(0,oD.randomUUID)(),{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,...nc(),...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||rc(),f=A$(d),p;for(let h=0;h<f.length;h++){let g=f[h],b=Wf(g,r),m=this.buildHeaders(n,r);try{let w=await bs(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 Ai({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=nD(C),k={};throw A!=null&&(k["Retry-After"]=String(Math.ceil(A/1e3))),J(Ve(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&&VR(C)&&(YR(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),XR(w.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${w.status}`,w.status,"provider_error");continue}throw J(Ve(C)||`Antigravity request failed with ${w.status}`,w.status,w.status===403?"permission_error":"provider_error")}return JR(g),w}catch(w){if(w?.statusCode===429||w?.status===429||!hr(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:Wf(rc(),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:Wf(n?.baseUrl||rc(),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?Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(Ee("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=rD(i);o.controller.enqueue(Ee(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Oe(r,o.encoder))}return}o.controller.enqueue(Oe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=rD(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}};var cD=require("@caeliq/ccr-shared");var ze=require("fs"),Kf=require("path"),iD=require("os"),E$=(0,Kf.join)((0,iD.homedir)(),".claude-code-router","xai_auth.json"),v$=2*6e4,T$=35e3,sD={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 S9=300*1e3;var x$=120,Jf=null;function m0(){return process.env.CCR_XAI_AUTH_FILE||E$}function g0(){return`${m0()}.refresh.lock`}function R$(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function D$(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 O$(t){let e=D$(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function oc(){try{let t=m0();if(!(0,ze.existsSync)(t))return null;let e=JSON.parse((0,ze.readFileSync)(t,"utf8"));return e.access_token?e:null}catch{return null}}function P$(t){let e=m0();(0,ze.mkdirSync)((0,Kf.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,ze.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,ze.renameSync)(n,e)}finally{try{(0,ze.existsSync)(n)&&(0,ze.unlinkSync)(n)}catch{}}}function I$(t,e=x$){let n=O$(t);return n?Date.now()/1e3+e>=n:!1}function F$(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 N$(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(sD.token_endpoint,{method:"POST",headers:R$(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:sD.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${F$(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 M$(){let t=g0();try{return(0,ze.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,ze.statSync)(t).mtimeMs>v$&&(0,ze.unlinkSync)(t)}catch{}return null}}async function B$(t){let e=Date.now()+T$,n=null;for(;n===null&&(n=M$(),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=(0,ze.fstatSync)(n).ino;(0,ze.closeSync)(n);try{(0,ze.statSync)(g0()).ino===r&&(0,ze.unlinkSync)(g0())}catch{}}}async function U$(t){return B$(async()=>{let e=oc();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 N$(e),r=oc();return r&&r.access_token!==e.access_token?r:(P$(n),n)})}async function aD(t){return sc({force:!0})}async function sc(t={}){let e=oc();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!I$(e)?e:(Jf||(Jf=U$(e).finally(()=>{Jf=null})),Jf)}var Vf=class{name="xai-auth";logger;async resolveAuth(e){let n=(0,cD.resolveXaiApiKey)(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await sc()).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=oc();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await aD(n.refresh_token)).access_token}`}:null}};var uD={AnthropicTransformer:Qu,GeminiTransformer:sl,VertexGeminiTransformer:Bd,VertexClaudeTransformer:sf,VertexOpenaiTransformer:af,DeepseekTransformer:Jd,TooluseTransformer:Kd,OpenrouterTransformer:Vd,OpenAITransformer:lf,MaxTokenTransformer:Yd,GroqTransformer:Xd,CleancacheTransformer:Qd,EnhanceToolTransformer:tf,ReasoningTransformer:nf,SamplingTransformer:rf,MaxCompletionTokens:of,CerebrasTransformer:cf,StreamOptionsTransformer:uf,CustomParamsTransformer:ff,VercelTransformer:pf,OpenAIResponsesTransformer:hf,CodexTransformer:Cf,QwenAuthTransformer:Af,ForceReasoningTransformer:Ef,ExtraThinkTagTransformer:vf,MistralTransformer:Tf,ChromeOnDeviceTransformer:xf,OpencodeHeadersTransformer:Rf,ClaudeAuthTransformer:Yu,CursorSdkTransformer:Uf,AntigravityAuthTransformer:Gf,XaiAuthTransformer:Vf};var es=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=require(require.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
+ `;S(pe),ae(ie.content(pe))}}}if(!ce)break}!F&&!D&&(se(),M("stop")),a&&X.enqueue(ie.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:m.metrics},"cursor-sdk stream failed"),await tc(m,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{le()}},async cancel(){await tc(m,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=tt.getReader();for(;;){let{done:ae}=await X.read();if(ae)break}let le=J_(u,Pe);return new Response(JSON.stringify(le),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(tt,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function y$(t,e,n){return{cursorMode:t.cursorMode||Of,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var Uf=class{static TransformerName=H_;name=H_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=y$(this.options,r,this.logger),s={...e,messages:Xe(e.messages),tools:Qe(e.tools)},i=await $R(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};var uD=require("crypto");var qt=require("fs"),Lf=require("path"),HR=require("os"),zR=require("crypto"),$f="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",qf="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",g0="http://localhost:51121/oauth-callback",WR=["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"],m0="https://daily-cloudcode-pa.sandbox.googleapis.com",GR="https://autopush-cloudcode-pa.sandbox.googleapis.com",JR="https://cloudcode-pa.googleapis.com",_$=[m0,GR,JR],h0=[JR,m0,GR],b$="1.18.3",C$=(0,Lf.join)((0,HR.homedir)(),".claude-code-router","antigravity_auth.json"),w$=12e4,KR="https://oauth2.googleapis.com/token",k$="https://www.googleapis.com/oauth2/v2/userinfo",jf=null,VR=null;function YR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||C$}function rc(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${b$} 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 nc(){try{let t=YR();if(!(0,qt.existsSync)(t))return null;let e=JSON.parse((0,qt.readFileSync)(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function Hf(t){let e=YR();(0,qt.mkdirSync)((0,Lf.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,qt.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,qt.renameSync)(n,e)}finally{try{(0,qt.existsSync)(n)&&(0,qt.unlinkSync)(n)}catch{}}}function S$(t){return Date.now()+w$>=t.expires_at}async function A$(t){let e=new URLSearchParams({client_id:$f,client_secret:qf,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(KR,{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 Hf(o),o}async function Ei(t){let e=nc();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!S$(e)?e:(jf||(jf=A$(e).finally(()=>{jf=null})),jf)}function Ai(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 E$(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 XR(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function qR(t){await new Promise(e=>setTimeout(e,t))}async function v$(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...rc()};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 qR(2e3);continue}let a=await i.json();if(a?.done===!0)return Ai(a?.response)||Ai(a)||void 0}catch{}await qR(2e3)}}async function T$(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...rc()},body:JSON.stringify({tierId:e,metadata:XR()}),signal:AbortSignal.timeout(3e4)});if(!r.ok)return;let o=await r.json(),s=Ai(o?.response)||Ai(o);return o?.done===!0||s?s:typeof o?.name=="string"&&o.name.trim()?v$(t,n,o.name.trim()):void 0}catch{return}}function x$(t){let e=E$(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function R$(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...rc()},n=JSON.stringify({metadata:XR()}),r;for(let o of h0)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=Ai(i);if(a)return a}catch{}for(let o of x$(r))for(let s of h0){let i=await T$(t,o,s);if(i)return i}for(let o of h0)try{let s=await fetch(`${o}/v1internal:loadCodeAssist`,{method:"POST",headers:e,body:n,signal:AbortSignal.timeout(15e3)});if(!s.ok)continue;let i=Ai(await s.json());if(i)return i}catch{}}async function zf(t,e){let n=t?.project_id?.trim();if(n)return n;let r=nc();if(r?.project_id?.trim())return r.project_id.trim();let o=await R$(e);if(o){let s=nc();return s&&Hf({...s,project_id:o}),o}}function oc(){return VR||m0}function QR(t){VR=t}var ZR=new Set;function eD(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function tD(t){ZR.add(t.replace(/\/$/,""))}function D$(t){return ZR.has(t.replace(/\/$/,""))}function nD(t,e){return e?t===404||t===403||t>=500:!1}function rD(t){let e=t?.replace(/\/$/,"")||oc(),n=[...new Set([e,..._$])],r=n.filter(o=>!D$(o));return r.length?r:n}function Wf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function oD(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:(0,zR.randomUUID)()}}async function sD(t){try{let e=await fetch(k$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function iD(t,e){let n=new URLSearchParams({client_id:$f,client_secret:qf,code:t,grant_type:"authorization_code",redirect_uri:g0,code_verifier:e}),r=await fetch(KR,{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 aD(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 cD(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function O$(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 P$(t){return t?.req?.body?.stream===!0}function I$(t){return rD(t)}var Gf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Ei({force:o?.forceRefresh}),i=await zf(n,s.access_token),a=O$(r,n),u=P$(r),d=oD({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||(0,uD.randomUUID)(),{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,...rc(),...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||oc(),f=I$(d),p;for(let h=0;h<f.length;h++){let g=f[h],b=Wf(g,r),m=this.buildHeaders(n,r);try{let w=await Cs(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 Ei({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=aD(C),k={};throw A!=null&&(k["Retry-After"]=String(Math.ceil(A/1e3))),J(Ve(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&&eD(C)&&(tD(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),nD(w.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${w.status}`,w.status,"provider_error");continue}throw J(Ve(C)||`Antigravity request failed with ${w.status}`,w.status,w.status===403?"permission_error":"provider_error")}return QR(g),w}catch(w){if(w?.statusCode===429||w?.status===429||!hr(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:Wf(oc(),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:Wf(n?.baseUrl||oc(),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?Fe(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Oe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(Ee("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=cD(i);o.controller.enqueue(Ee(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Oe(r,o.encoder))}return}o.controller.enqueue(Oe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=cD(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}};var pD=require("@caeliq/ccr-shared");var ze=require("fs"),Kf=require("path"),dD=require("os"),F$=(0,Kf.join)((0,dD.homedir)(),".claude-code-router","xai_auth.json"),N$=2*6e4,M$=35e3,lD={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 F9=300*1e3;var B$=120,Jf=null;function _0(){return process.env.CCR_XAI_AUTH_FILE||F$}function y0(){return`${_0()}.refresh.lock`}function U$(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function j$(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 L$(t){let e=j$(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function sc(){try{let t=_0();if(!(0,ze.existsSync)(t))return null;let e=JSON.parse((0,ze.readFileSync)(t,"utf8"));return e.access_token?e:null}catch{return null}}function $$(t){let e=_0();(0,ze.mkdirSync)((0,Kf.dirname)(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{(0,ze.writeFileSync)(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),(0,ze.renameSync)(n,e)}finally{try{(0,ze.existsSync)(n)&&(0,ze.unlinkSync)(n)}catch{}}}function q$(t,e=B$){let n=L$(t);return n?Date.now()/1e3+e>=n:!1}function H$(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 z$(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(lD.token_endpoint,{method:"POST",headers:U$(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:lD.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${H$(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 W$(){let t=y0();try{return(0,ze.openSync)(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-(0,ze.statSync)(t).mtimeMs>N$&&(0,ze.unlinkSync)(t)}catch{}return null}}async function G$(t){let e=Date.now()+M$,n=null;for(;n===null&&(n=W$(),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=(0,ze.fstatSync)(n).ino;(0,ze.closeSync)(n);try{(0,ze.statSync)(y0()).ino===r&&(0,ze.unlinkSync)(y0())}catch{}}}async function J$(t){return G$(async()=>{let e=sc();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 z$(e),r=sc();return r&&r.access_token!==e.access_token?r:($$(n),n)})}async function fD(t){return ic({force:!0})}async function ic(t={}){let e=sc();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!q$(e)?e:(Jf||(Jf=J$(e).finally(()=>{Jf=null})),Jf)}var Vf=class{name="xai-auth";logger;async resolveAuth(e){let n=(0,pD.resolveXaiApiKey)(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await ic()).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=sc();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await fD(n.refresh_token)).access_token}`}:null}};var hD={AnthropicTransformer:Zu,GeminiTransformer:il,VertexGeminiTransformer:Ud,VertexClaudeTransformer:af,VertexOpenaiTransformer:cf,DeepseekTransformer:Kd,TooluseTransformer:Vd,OpenrouterTransformer:Yd,OpenAITransformer:df,MaxTokenTransformer:Xd,GroqTransformer:Qd,CleancacheTransformer:Zd,EnhanceToolTransformer:nf,ReasoningTransformer:rf,SamplingTransformer:of,MaxCompletionTokens:sf,CerebrasTransformer:uf,StreamOptionsTransformer:lf,CustomParamsTransformer:ff,VercelTransformer:pf,OpenAIResponsesTransformer:hf,CodexTransformer:Cf,QwenAuthTransformer:Af,ForceReasoningTransformer:Ef,ExtraThinkTagTransformer:vf,MistralTransformer:Tf,ChromeOnDeviceTransformer:xf,OpencodeHeadersTransformer:Rf,ClaudeAuthTransformer:Xu,CursorSdkTransformer:Uf,AntigravityAuthTransformer:Gf,XaiAuthTransformer:Vf};var ts=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=require(require.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(uD).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)}};var lD=require("tiktoken"),ic=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,lD.get_encoding)(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)}};var uc=require("path"),TD=require("os"),Ei=require("fs"),lc=require("fs");var j$=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}},dD=j$,L$=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}},$$=L$,_D=(()=>{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]]))})(),q$=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),H$=q$(_D),fD=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",z$=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|[${fD}])]+`,` ?[^\\s${fD}]+`]]),Yf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",_0=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"),Xf=(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 z$)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=W$(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},W$=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),G$=(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},J$=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,K$=t=>Number.isInteger(t)||typeof t=="bigint",V$=t=>{let e=0;for(let n of t)++e;return e},Y$=t=>bD(t.toLowerCase()),Sn=(...t)=>Array.prototype.concat.apply([],t),b0=t=>new Map(Object.entries(t)),X$=(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},bD=t=>t.replace(new RegExp("\\p{M}","gu"),""),pD=(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},Q$=t=>t.match(/\S+/g)||[],Z$=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},ac=Z$,eq=class extends ac{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Or=eq,tq=class extends Or{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);J$(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}},nq=tq,rq=class extends Or{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}},oq=rq,sq=class extends Or{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>CD(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},iq=sq,aq=class extends Or{normalize(t){let e=Xf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},cq=aq,uq=class extends Or{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Qf=uq,lq=class extends Qf{constructor(){super(...arguments),this.form="NFC"}},dq=lq,fq=class extends Qf{constructor(){super(...arguments),this.form="NFD"}},pq=fq,hq=class extends Qf{constructor(){super(...arguments),this.form="NFKC"}},gq=hq,mq=class extends Qf{constructor(){super(...arguments),this.form="NFKD"}},yq=mq,_q=class extends Or{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}},bq=_q,Cq=class extends Or{normalize(t){return bD(t)}},wq=Cq,kq=class extends Or{normalize(t){return t.toLowerCase()}},Sq=kq,Aq=class extends Or{normalize(t){return t=this.config.prepend+t,t}},Eq=Aq;function vq(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new nq(t);case"Precompiled":return new oq(t);case"Sequence":return new iq(t);case"Replace":return new cq(t);case"NFC":return new dq(t);case"NFD":return new pq(t);case"NFKC":return new gq(t);case"NFKD":return new yq(t);case"Strip":return new bq(t);case"StripAccents":return new wq(t);case"Lowercase":return new Sq(t);case"Prepend":return new Eq(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var CD=vq,Tq=class extends ac{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)}},An=Tq,xq=class extends An{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=_D,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(""))}},Rq=xq,Dq=class extends An{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Oq=Dq,Pq=class extends An{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]}},Iq=Pq,Fq=class extends An{constructor(t){super(),this.config=t,this.pattern=Xf(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):X$(t,this.pattern)}},Nq=Fq,Mq=class extends An{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Yf}]+|[${Yf}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Bq=Mq,Uq=class extends An{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)||[]}},jq=Uq,Lq=class extends An{constructor(){super(),this.pattern=new RegExp(`[^\\s${Yf}]+|[${Yf}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},$q=Lq,qq=class extends An{constructor(t){super(),this.config=t,this.pattern=Xf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Hq=qq,zq=class extends An{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>wD(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},Wq=zq,Gq=class extends An{pre_tokenize_text(t){return Q$(t)}},Jq=Gq,Kq=class extends An{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}},Vq=Kq;function Yq(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new $q;case"Sequence":return new Wq(t);case"Whitespace":return new Oq;case"WhitespaceSplit":return new Jq;case"Metaspace":return new Iq(t);case"ByteLevel":return new Rq(t);case"Split":return new Nq(t);case"Punctuation":return new Bq(t);case"Digits":return new jq(t);case"Replace":return new Hq(t);case"FixedLength":return new Vq(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var wD=Yq,Xq=class extends ac{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=G$(e,this.tokens_to_ids,this.unk_token_id)),e}},Zf=Xq,Qq=class extends Zf{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=b0(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}},hD=Qq,gD=class kD{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new kD(!1,new Map)}},Zq=class{constructor(){this.root=gD.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=gD.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)}}},e4=Zq,y0=class SD{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 SD(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},t4=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 y0(this.bos_token_id??0,0,0,0,0),o=new y0(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 y0(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)}},n4=t4;function r4(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 o4=class extends Zf{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=r4(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new e4,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=V$(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 n4(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}},mD=o4,s4=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}},i4=s4,a4=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()}},c4=a4,u4=class extends Zf{constructor(t){super(t),this.tokens_to_ids=b0(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 c4(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 i4((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}},yD=u4,l4=class extends Zf{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=b0(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}},d4=l4;function f4(t,e){switch(t.type){case"WordPiece":return new hD(t);case"Unigram":return new mD(t,e.eos_token);case"BPE":return new yD(t);default:if(t.vocab)return Array.isArray(t.vocab)?new mD(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new yD(t):new hD(t):new d4(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 p4=f4,h4=class extends ac{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},cc=h4,g4=class extends cc{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=Sn(o,t),s=Sn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=Sn(o,e),s=Sn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},m4=g4,y4=class extends cc{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},_4=y4,b4=class extends cc{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Sn([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=Sn(t,o,e,s),r=Sn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},C4=b4,w4=class extends cc{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Sn([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=Sn(t,o,e,s),r=Sn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},k4=w4,S4=class extends cc{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>AD(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}},A4=S4;function E4(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new m4(t);case"ByteLevel":return new _4(t);case"BertProcessing":return new C4(t);case"RobertaProcessing":return new k4(t);case"Sequence":return new A4(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var AD=E4,v4=class extends ac{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("")}},er=v4,T4=class extends er{constructor(t){super(t),this.byte_decoder=H$,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}},x4=T4,R4=class extends er{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=_0(e)),e})}},D4=R4,O4=class extends er{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}},P4=O4,I4=class extends er{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},F4=I4,N4=class extends er{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=_0(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},M4=N4,B4=class extends er{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>ED(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},U4=B4,j4=class extends er{decode_chain(t){let e=Xf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},L4=j4,$4=class extends er{decode_chain(t){return[t.join("")]}},q4=$4,H4=class extends er{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)})}},z4=H4,W4=class extends er{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}},G4=W4;function J4(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new x4(t);case"WordPiece":return new D4(t);case"Metaspace":return new P4(t);case"BPEDecoder":return new F4(t);case"CTC":return new M4(t);case"Sequence":return new U4(t);case"Replace":return new L4(t);case"Fuse":return new q4(t);case"Strip":return new z4(t);case"ByteFallback":return new G4(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var ED=J4,K4=class{constructor(t,e){let n=pD(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=pD(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=CD(this.tokenizer.normalizer),this.pre_tokenizer=wD(this.tokenizer.pre_tokenizer),this.model=p4(this.tokenizer.model,this.config),this.post_processor=AD(this.tokenizer.post_processor),this.decoder=ED(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 $$(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 dD(o),this.splitter_normalized=new dD(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||!K$(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=_0(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=Y$(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:Sn(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}},vD=K4;var ep=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||(0,uc.join)((0,TD.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,uc.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,uc.join)(e,"tokenizer.json"),tokenizerConfig:(0,uc.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,Ei.existsSync)(e)||(0,Ei.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,Ei.existsSync)(e.tokenizerJson)||!(0,Ei.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([lc.promises.readFile(e.tokenizerJson,"utf-8"),lc.promises.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([lc.promises.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),lc.promises.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 vD(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 tp=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 ts=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 ic("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 ic(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new ep(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new tp(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 C0=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()}},w0=new C0;var OD=ot(hh(),1);k0();S0();E0();RD();var ns=new Map;function x0(t){let e=ns.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function R0(){return Array.from(ns.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var T0=new Map,D0={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,OD.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)Ti.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&&Ti.registerHandlers(s)}n.outputOptions&&Ti.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(T0.has(d))return T0.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 T0.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){ns.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=ns.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 DD(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 ln).getReader();for(C=setInterval(async()=>{ns.get(d)&&await A(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=ns.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:hc(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),ns.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:hc(A))}return w},0):typeof m=="string"&&(g=p.encodeText?p.encodeText(m).length:hc(m));else{let w=Array.isArray(m)?m.map(C=>C.text).join(""):m;g=hc(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 DD(m,r,n.outputOptions,!0,t.log)}return a})})};function hc(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function DD(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 Ti.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function V4(t={}){let e=(0,PD.default)({bodyLimit:52428800,...t});return e.setErrorHandler(xw),e.register(ID.default),e.register(FD.default,{global:!0,...ND.RATE_LIMIT_CONFIG}),e}var O0=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=V4({...r,logger:r.logger??!0}),this.configService=new vo({...e,logger:this.app.log}),this.transformerService=new es(this.configService,this.app.log),this.tokenizerService=new ts(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new Fo(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 lg(a)});return}if(!n)throw new Error("options is required");let r=new vo({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new es(r,this.app.log);await o.initialize();let s=new Fo(r,o,this.app.log),i=new ts(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 lg(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=Mn(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)}}},Y4=O0;0&&(module.exports={ANTIGRAVITY_CLIENT_ID,ANTIGRAVITY_CLIENT_SECRET,ANTIGRAVITY_REDIRECT_URI,ANTIGRAVITY_SCOPES,ConfigService,DEFAULT_LOG_BODY_MAX_BYTES,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,diffHeadersForLog,exchangeAuthorizationCode,fetchUserEmail,getAntigravityAccessToken,getClaudeAccessToken,getCodexAccessToken,getGlobalTokenSpeedStats,getQwenAccessToken,getTokenSpeedStats,getValidAccessToken,getXaiAccessToken,isClientAbortError,isRoutedLlmPost,listClientRouteRegistrations,loadTokens,matchClientProtocol,pluginManager,protocolErrorBody,resolveProjectId,rewriteStream,router,sanitizeBodyForLog,sanitizeHeadersForLog,saveTokens,searchProjectBySession,sessionUsageCache,setHealthReporter,tokenSpeedPlugin});
444
+ Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(hD).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)}};var gD=require("tiktoken"),ac=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=(0,gD.get_encoding)(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)}};var lc=require("path"),PD=require("os"),vi=require("fs"),dc=require("fs");var K$=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}},mD=K$,V$=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}},Y$=V$,SD=(()=>{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]]))})(),X$=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),Q$=X$(SD),yD=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",Z$=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|[${yD}])]+`,` ?[^\\s${yD}]+`]]),Yf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",C0=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"),Xf=(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 Z$)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=eq(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},eq=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),tq=(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},nq=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,rq=t=>Number.isInteger(t)||typeof t=="bigint",oq=t=>{let e=0;for(let n of t)++e;return e},sq=t=>AD(t.toLowerCase()),Sn=(...t)=>Array.prototype.concat.apply([],t),w0=t=>new Map(Object.entries(t)),iq=(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},AD=t=>t.replace(new RegExp("\\p{M}","gu"),""),_D=(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},aq=t=>t.match(/\S+/g)||[],cq=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},cc=cq,uq=class extends cc{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},Or=uq,lq=class extends Or{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);nq(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}},dq=lq,fq=class extends Or{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}},pq=fq,hq=class extends Or{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>ED(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},gq=hq,mq=class extends Or{normalize(t){let e=Xf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},yq=mq,_q=class extends Or{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},Qf=_q,bq=class extends Qf{constructor(){super(...arguments),this.form="NFC"}},Cq=bq,wq=class extends Qf{constructor(){super(...arguments),this.form="NFD"}},kq=wq,Sq=class extends Qf{constructor(){super(...arguments),this.form="NFKC"}},Aq=Sq,Eq=class extends Qf{constructor(){super(...arguments),this.form="NFKD"}},vq=Eq,Tq=class extends Or{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}},xq=Tq,Rq=class extends Or{normalize(t){return AD(t)}},Dq=Rq,Oq=class extends Or{normalize(t){return t.toLowerCase()}},Pq=Oq,Iq=class extends Or{normalize(t){return t=this.config.prepend+t,t}},Fq=Iq;function Nq(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new dq(t);case"Precompiled":return new pq(t);case"Sequence":return new gq(t);case"Replace":return new yq(t);case"NFC":return new Cq(t);case"NFD":return new kq(t);case"NFKC":return new Aq(t);case"NFKD":return new vq(t);case"Strip":return new xq(t);case"StripAccents":return new Dq(t);case"Lowercase":return new Pq(t);case"Prepend":return new Fq(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var ED=Nq,Mq=class extends cc{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)}},An=Mq,Bq=class extends An{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=SD,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(""))}},Uq=Bq,jq=class extends An{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},Lq=jq,$q=class extends An{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]}},qq=$q,Hq=class extends An{constructor(t){super(),this.config=t,this.pattern=Xf(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):iq(t,this.pattern)}},zq=Hq,Wq=class extends An{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Yf}]+|[${Yf}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},Gq=Wq,Jq=class extends An{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)||[]}},Kq=Jq,Vq=class extends An{constructor(){super(),this.pattern=new RegExp(`[^\\s${Yf}]+|[${Yf}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},Yq=Vq,Xq=class extends An{constructor(t){super(),this.config=t,this.pattern=Xf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},Qq=Xq,Zq=class extends An{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>vD(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},e4=Zq,t4=class extends An{pre_tokenize_text(t){return aq(t)}},n4=t4,r4=class extends An{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}},o4=r4;function s4(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new Yq;case"Sequence":return new e4(t);case"Whitespace":return new Lq;case"WhitespaceSplit":return new n4;case"Metaspace":return new qq(t);case"ByteLevel":return new Uq(t);case"Split":return new zq(t);case"Punctuation":return new Gq(t);case"Digits":return new Kq(t);case"Replace":return new Qq(t);case"FixedLength":return new o4(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var vD=s4,i4=class extends cc{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=tq(e,this.tokens_to_ids,this.unk_token_id)),e}},Zf=i4,a4=class extends Zf{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=w0(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}},bD=a4,CD=class TD{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new TD(!1,new Map)}},c4=class{constructor(){this.root=CD.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=CD.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)}}},u4=c4,b0=class xD{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 xD(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},l4=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 b0(this.bos_token_id??0,0,0,0,0),o=new b0(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 b0(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)}},d4=l4;function f4(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 p4=class extends Zf{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=f4(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new u4,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=oq(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 d4(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}},wD=p4,h4=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}},g4=h4,m4=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()}},y4=m4,_4=class extends Zf{constructor(t){super(t),this.tokens_to_ids=w0(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 y4(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 g4((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}},kD=_4,b4=class extends Zf{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=w0(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}},C4=b4;function w4(t,e){switch(t.type){case"WordPiece":return new bD(t);case"Unigram":return new wD(t,e.eos_token);case"BPE":return new kD(t);default:if(t.vocab)return Array.isArray(t.vocab)?new wD(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new kD(t):new bD(t):new C4(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 k4=w4,S4=class extends cc{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},uc=S4,A4=class extends uc{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=Sn(o,t),s=Sn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=Sn(o,e),s=Sn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},E4=A4,v4=class extends uc{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},T4=v4,x4=class extends uc{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=Sn([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=Sn(t,o,e,s),r=Sn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},R4=x4,D4=class extends uc{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=Sn([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=Sn(t,o,e,s),r=Sn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},O4=D4,P4=class extends uc{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>RD(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}},I4=P4;function F4(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new E4(t);case"ByteLevel":return new T4(t);case"BertProcessing":return new R4(t);case"RobertaProcessing":return new O4(t);case"Sequence":return new I4(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var RD=F4,N4=class extends cc{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("")}},er=N4,M4=class extends er{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}},B4=M4,U4=class extends er{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=C0(e)),e})}},j4=U4,L4=class extends er{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}},$4=L4,q4=class extends er{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},H4=q4,z4=class extends er{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=C0(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},W4=z4,G4=class extends er{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>DD(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},J4=G4,K4=class extends er{decode_chain(t){let e=Xf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},V4=K4,Y4=class extends er{decode_chain(t){return[t.join("")]}},X4=Y4,Q4=class extends er{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)})}},Z4=Q4,e6=class extends er{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}},t6=e6;function n6(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new B4(t);case"WordPiece":return new j4(t);case"Metaspace":return new $4(t);case"BPEDecoder":return new H4(t);case"CTC":return new W4(t);case"Sequence":return new J4(t);case"Replace":return new V4(t);case"Fuse":return new X4(t);case"Strip":return new Z4(t);case"ByteFallback":return new t6(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var DD=n6,r6=class{constructor(t,e){let n=_D(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=_D(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=ED(this.tokenizer.normalizer),this.pre_tokenizer=vD(this.tokenizer.pre_tokenizer),this.model=k4(this.tokenizer.model,this.config),this.post_processor=RD(this.tokenizer.post_processor),this.decoder=DD(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 Y$(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 mD(o),this.splitter_normalized=new mD(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||!rq(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=C0(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=sq(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:Sn(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}},OD=r6;var ep=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||(0,lc.join)((0,PD.homedir)(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=(0,lc.join)(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:(0,lc.join)(e,"tokenizer.json"),tokenizerConfig:(0,lc.join)(e,"tokenizer_config.json")}}ensureDir(e){(0,vi.existsSync)(e)||(0,vi.mkdirSync)(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!(0,vi.existsSync)(e.tokenizerJson)||!(0,vi.existsSync)(e.tokenizerConfig))return null;let[n,r]=await Promise.all([dc.promises.readFile(e.tokenizerJson,"utf-8"),dc.promises.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([dc.promises.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),dc.promises.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 OD(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 tp=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 ns=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 ac("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 ac(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new ep(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new tp(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 k0=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()}},S0=new k0;var MD=ot(hh(),1);A0();E0();T0();FD();var rs=new Map;function D0(t){let e=rs.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function O0(){return Array.from(rs.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var R0=new Map,P0={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,MD.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)xi.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&&xi.registerHandlers(s)}n.outputOptions&&xi.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(R0.has(d))return R0.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 R0.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){rs.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=rs.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 ND(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 ln).getReader();for(C=setInterval(async()=>{rs.get(d)&&await A(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=rs.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:gc(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),rs.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:gc(A))}return w},0):typeof m=="string"&&(g=p.encodeText?p.encodeText(m).length:gc(m));else{let w=Array.isArray(m)?m.map(C=>C.text).join(""):m;g=gc(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 ND(m,r,n.outputOptions,!0,t.log)}return a})})};function gc(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function ND(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 xi.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function o6(t={}){let e=(0,BD.default)({bodyLimit:52428800,...t});return e.setErrorHandler(Dw),e.register(UD.default),e.register(jD.default,{global:!0,...LD.RATE_LIMIT_CONFIG}),e}var I0=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=o6({...r,logger:r.logger??!0}),this.configService=new To({...e,logger:this.app.log}),this.transformerService=new ts(this.configService,this.app.log),this.tokenizerService=new ns(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new No(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 dg(a)});return}if(!n)throw new Error("options is required");let r=new To({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ts(r,this.app.log);await o.initialize();let s=new No(r,o,this.app.log),i=new ns(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 dg(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=Mn(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)}}},s6=I0;0&&(module.exports={ANTIGRAVITY_CLIENT_ID,ANTIGRAVITY_CLIENT_SECRET,ANTIGRAVITY_REDIRECT_URI,ANTIGRAVITY_SCOPES,ConfigService,DEFAULT_LOG_BODY_MAX_BYTES,ProviderService,SSEParserTransform,SSESerializerTransform,TokenizerService,TransformerService,calculateTokenCount,diffHeadersForLog,exchangeAuthorizationCode,fetchUserEmail,getAntigravityAccessToken,getClaudeAccessToken,getCodexAccessToken,getGlobalTokenSpeedStats,getQwenAccessToken,getTokenSpeedStats,getValidAccessToken,getXaiAccessToken,isClientAbortError,isRoutedLlmPost,listClientRouteRegistrations,loadTokens,matchClientProtocol,pluginManager,protocolErrorBody,resolveProjectId,rewriteStream,router,sanitizeBodyForLog,sanitizeHeadersForLog,saveTokens,searchProjectBySession,sessionUsageCache,setHealthReporter,tokenSpeedPlugin});
446
446
  /*! Bundled license information:
447
447
 
448
448
  toad-cache/dist/toad-cache.cjs: