@caeliq/llms 1.0.61 → 1.0.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/server.cjs +139 -135
- package/dist/cjs/server.cjs.map +4 -4
- package/dist/esm/server.mjs +137 -133
- package/dist/esm/server.mjs.map +4 -4
- package/dist/server.d.ts +5 -1
- package/dist/tests/oauth-refresh-singleflight.d.ts +1 -0
- package/dist/tests/sse.done-boundary.d.ts +1 -0
- package/dist/utils/claude-auth.d.ts +3 -1
- package/dist/utils/qwen-auth.d.ts +5 -2
- package/dist/utils/sse/done-boundary.d.ts +25 -0
- package/dist/utils/sse/index.d.ts +1 -0
- package/package.json +2 -2
package/dist/esm/server.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var XR=Object.create;var Sp=Object.defineProperty;var QR=Object.getOwnPropertyDescriptor;var ZR=Object.getOwnPropertyNames;var eD=Object.getPrototypeOf,tD=Object.prototype.hasOwnProperty;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Mr=(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}},Gb=(t,e)=>{for(var n in e)Sp(t,n,{get:e[n],enumerable:!0})},nD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ZR(e))!tD.call(t,o)&&o!==n&&Sp(t,o,{get:()=>e[o],enumerable:!(r=QR(e,o))||r.enumerable});return t};var nr=(t,e,n)=>(n=t!=null?XR(eD(t)):{},nD(e||!t||!t.__esModule?Sp(n,"default",{value:t,enumerable:!0}):n,t));var Ii=G(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});yc.AddressError=void 0;var Ap=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};yc.AddressError=Ap});var bc=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.isInSubnet=rD;yn.isHostInSubnet=Jb;yn.isCorrect=oD;yn.prefixLengthFromMask=sD;yn.assertByteArray=iD;yn.numberToPaddedHex=Kb;yn.stringToPaddedHex=aD;yn.testBit=cD;var _c=Ii();function rD(t){return this.subnetMask<t.subnetMask?!1:Jb.call(this,t)}function Jb(t){return this.mask(t.subnetMask)===t.mask()}function oD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function sD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new _c.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new _c.AddressError("Invalid subnet mask.");return r}function iD(t,e,n,r){if(t.length!==e)throw new _c.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 _c.AddressError(`All bytes must be integers between ${r} and 255`)}function Kb(t){return t.toString(16).padStart(2,"0")}function aD(t){return Kb(parseInt(t,10))}function cD(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var Ep=G(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.RE_SUBNET_STRING=_n.RE_ADDRESS=_n.GROUPS=_n.BITS=void 0;_n.BITS=32;_n.GROUPS=4;_n.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;_n.RE_SUBNET_STRING=/\/\d{1,2}$/});var vp=G(Cn=>{"use strict";var uD=Cn&&Cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),lD=Cn&&Cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Vb=Cn&&Cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&uD(e,t,n);return lD(e,t),e};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.Address4=void 0;var bn=Vb(bc()),nt=Vb(Ep()),rr=Ii(),dD=bn.isCorrect(nt.BITS),Lt=class t{constructor(e){this.addressMinusSuffix="",this.groups=nt.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=dD,this.isInSubnet=bn.isInSubnet,this.isHostInSubnet=bn.isHostInSubnet,this.address=e;let n=nt.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>nt.BITS)throw new rr.AddressError("Invalid subnet mask.");e=e.replace(nt.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let n=e.split(".");if(n.some(r=>/^0\d/.test(r)))throw new rr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(nt.RE_ADDRESS))throw new rr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=bn.prefixLengthFromMask(new t(n).bigInt(),nt.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(nt.BITS))-BigInt(1),s=r^o,i=bn.prefixLengthFromMask(s,nt.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==nt.GROUPS)throw new rr.AddressError("Wildcard pattern must have 4 octets");let r=-1;for(let a=0;a<n.length;a++)if(n[a]==="*")r===-1&&(r=a);else if(r!==-1)throw new rr.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let o=r===-1?0:n.length-r,s=n.map(a=>a==="*"?"0":a),i=nt.BITS-o*8;return new t(`${s.join(".")}/${i}`)}static fromHex(e){let n=e.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(n))throw new rr.AddressError("IPv4 hex must be exactly 8 hex digits");let r=[];for(let o=0;o<8;o+=2)r.push(parseInt(n.slice(o,o+2),16));return new t(r.join("."))}static fromInteger(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new rr.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromArpa(e){let r=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(r)}toHex(){return this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<nt.GROUPS;n+=2)e.push(`${bn.stringToPaddedHex(this.parsedAddress[n])}${bn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(nt.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(nt.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(nt.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(nt.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new rr.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromByteArray(e){return bn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new rr.AddressError("IPv4 addresses require exactly 4 bytes");let n=e.join(".");return new t(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}reverseForm(e){e||(e={});let n=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?n:`${n}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(fD)}isPrivate(){return pD.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(hD)}isLinkLocal(){return this.isHostInSubnet(gD)}isUnspecified(){return this.isHostInSubnet(mD)}isBroadcast(){return this.isHostInSubnet(yD)}isCGNAT(){return this.isHostInSubnet(_D)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(nt.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(nt.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};Cn.Address4=Lt;var fD=new Lt("224.0.0.0/4"),pD=[new Lt("10.0.0.0/8"),new Lt("172.16.0.0/12"),new Lt("192.168.0.0/16")],hD=new Lt("127.0.0.0/8"),gD=new Lt("169.254.0.0/16"),mD=new Lt("0.0.0.0/32"),yD=new Lt("255.255.255.255/32"),_D=new Lt("100.64.0.0/10")});var Tp=G(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.RE_URL_WITH_PORT=We.RE_URL=We.RE_ZONE_STRING=We.RE_SUBNET_STRING=We.RE_BAD_ADDRESS=We.RE_BAD_CHARACTERS=We.TYPES=We.SCOPES=We.GROUPS=We.BITS=void 0;We.BITS=128;We.GROUPS=8;We.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};We.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};We.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;We.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;We.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;We.RE_ZONE_STRING=/%.*$/;We.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;We.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var xp=G(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.escapeHtml=Cc;uo.spanAllZeroes=Yb;uo.spanAll=bD;uo.spanLeadingZeroes=CD;uo.simpleGroup=wD;function Cc(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Yb(t){return Cc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function bD(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${Cc(r)} position-${o+e}">${Yb(r)}</span>`).join("")}function Xb(t){return Cc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function CD(t){return t.split(":").map(n=>Xb(n)).join(":")}function wD(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${Xb(r)}</span>`)}});var Qb=G(kt=>{"use strict";var kD=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),SD=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),AD=kt&&kt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&kD(e,t,n);return SD(e,t),e};Object.defineProperty(kt,"__esModule",{value:!0});kt.ADDRESS_BOUNDARY=void 0;kt.groupPossibilities=kc;kt.padGroup=wc;kt.simpleRegularExpression=vD;kt.possibleElisions=TD;var ED=AD(Tp());function kc(t){return`(${t.join("|")})`}function wc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}kt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function vD(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===ED.GROUPS-1?":":"";return kc([wc(o),i])}return wc(o)}).join(":"));return n.push(t.map(wc).join(":")),kc(n)}function TD(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 nC=G(Sn=>{"use strict";var xD=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),RD=Sn&&Sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ec=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&xD(e,t,n);return RD(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.Address6=void 0;var po=Ec(bc()),Rp=Ec(Ep()),xe=Ec(Tp()),lo=Ec(xp()),wn=vp(),fo=Qb(),ct=Ii(),Sc=bc(),DD=po.isCorrect(xe.BITS);function Ac(t){if(!t)throw new Error("Assertion failed.")}function OD(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function PD(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 ID(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 Zb(t){return parseInt(t,16).toString(16).padStart(4,"0")}function eC(t){return t&255}var kn=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=po.isInSubnet,this.isHostInSubnet=po.isHostInSubnet,this.isCorrect=DD,n===void 0?this.groups=xe.GROUPS:this.groups=n,this.address=e;let r=xe.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>xe.BITS)throw new ct.AddressError("Invalid subnet mask.");e=e.replace(xe.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new ct.AddressError("Invalid subnet mask.");let o=xe.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(xe.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){if(e<BigInt(0)||e>(BigInt(1)<<BigInt(xe.BITS))-BigInt(1))throw new ct.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let n=e.toString(16).padStart(32,"0"),r=[];for(let o=0;o<xe.GROUPS;o++)r.push(n.slice(o*4,(o+1)*4));return new t(r.join(":"))}static fromURL(e){var n;let r,o=null,s,i,a=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(a.indexOf("[")!==-1&&a.indexOf("]:")!==-1){if(i="failed to parse address with port",s=xe.RE_URL_WITH_PORT.exec(a),s===null)return{error:i,address:null,port:null};r=s[1],o=s[2]}else{if(i="failed to parse address from URL",s=xe.RE_URL.exec(a),s===null)return{error:i,address:null,port:null};r=(n=s[1])!==null&&n!==void 0?n:s[2]}o?(o=parseInt(o,10),(o<0||o>65535)&&(o=null)):o=null;let u;try{u=new t(r)}catch{return{error:i,address:null,port:null}}return{address:u,port:o}}static fromAddressAndMask(e,n){let r=po.prefixLengthFromMask(new t(n).bigInt(),xe.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(xe.BITS))-BigInt(1),s=r^o,i=po.prefixLengthFromMask(s,xe.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new ct.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new ct.AddressError("Wildcard pattern cannot contain more than one '::'");let r;if(n.length===2){let u=n[0]===""?[]:n[0].split(":"),d=n[1]===""?[]:n[1].split(":"),f=xe.GROUPS-u.length-d.length;if(f<1)throw new ct.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==xe.GROUPS)throw new ct.AddressError("Wildcard pattern must have 8 groups");let o=-1;for(let u=0;u<r.length;u++)if(r[u]==="*")o===-1&&(o=u);else if(o!==-1)throw new ct.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let s=o===-1?0:r.length-o,i=r.map(u=>u==="*"?"0":u),a=xe.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new wn.Address4(e),r=xe.BITS-(Rp.BITS-n.subnetMask);return new t(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(e){let n=e.replace(/(\.ip6\.arpa)?\.$/,""),r=7;if(n.length!==63)throw new ct.AddressError("Invalid 'ip6.arpa' form.");let o=n.split(".").reverse();for(let s=r;s>0;s--){let i=s*4;o.splice(i,0,":")}return n=o.join(""),new t(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let n=xe.BITS-this.subnetMask,r=Math.abs(e-xe.BITS),o=n-r;return o<0?"0":OD((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(xe.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(xe.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(xe.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(xe.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?xe.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":e==="Link-local unicast"||e==="Loopback"?"Link local":e==="Unspecified"?"Unknown":"Global"}getType(){for(let e=0;e<tC.length;e++){let n=tC[e];if(this.isHostInSubnet(n[0]))return n[1]}return"Global unicast"}getBits(e,n){return BigInt(`0b${this.getBitsBase2(e,n)}`)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}getBitsBase16(e,n){let r=n-e;if(r%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,n).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,xe.BITS)}reverseForm(e){e||(e={});let n=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,n).reverse().join(".");return n>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,n=[],r=0,o=[];for(e=0;e<this.parsedAddress.length;e++){let a=parseInt(this.parsedAddress[e],16);a===0&&r++,a!==0&&r>0&&(r>1&&o.push([e-r,e-1]),r=0)}r>1&&o.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);let s=o.map(a=>a[1]-a[0]+1);if(o.length>0){let a=s.indexOf(Math.max(...s));n=ID(this.parsedAddress,o[a])}else n=this.parsedAddress;for(e=0;e<n.length;e++)n[e]!=="compact"&&(n[e]=parseInt(n[e],16).toString(16));let i=n.join(":");return i=i.replace(/^compact$/,"::"),i=i.replace(/(^compact)|(compact$)/,":"),i=i.replace(/compact/,""),i}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(xe.BITS,"0")),this._binaryZeroPad}parse4in6(e){if(e.indexOf(".")===-1)return e;let n=e.split(":"),r=n.slice(-1)[0],o=r.split(".");if(o.length===Rp.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(PD).join("."),a=n.slice(0,-1).map(lo.escapeHtml).join(":"),u=n.length>1?":":"";throw new ct.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(Rp.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new wn.Address4(`${this.parsedAddress4}${i}`),this.v4=!0,n[n.length-1]=this.address4.toGroup6(),e=n.join(":")}return e}parse(e){e=this.parse4in6(e);let n=e.match(xe.RE_BAD_CHARACTERS);if(n)throw new ct.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(xe.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(xe.RE_BAD_ADDRESS);if(r)throw new ct.AddressError(`Address failed regex: ${r.join("")}`,e.replace(xe.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let o=[],s=e.split("::");if(s.length===2){let i=s[0].split(":"),a=s[1].split(":");i.length===1&&i[0]===""&&(i=[]),a.length===1&&a[0]===""&&(a=[]);let u=this.groups-(i.length+a.length);if(!u)throw new ct.AddressError("Error parsing groups");this.elidedGroups=u,this.elisionBegin=i.length,this.elisionEnd=i.length+this.elidedGroups,o=o.concat(i);for(let d=0;d<u;d++)o.push("0");o=o.concat(a)}else if(s.length===1)o=e.split(":"),this.elidedGroups=0;else throw new ct.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new ct.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(Zb).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(Zb).join("")}`)}to4(){let e=this.binaryZeroPad().split(""),n=BigInt(`0b${e.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let r=this.subnetMask-96,o=[];for(let s=0;s<8;s+=2)o.push(parseInt(n.slice(s,s+2),16));return new wn.Address4(`${o.join(".")}/${r}`)}return wn.Address4.fromHex(n)}to4in6(){let e=this.to4(),r=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),o="";return/:$/.test(r)||(o=":"),r+o+e.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),r=(this.getBits(80,96)^BigInt("0xffff")).toString(),o=wn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=wn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Sc.testBit)(a,15),d=(0,Sc.testBit)(a,14),f=(0,Sc.testBit)(a,8),p=(0,Sc.testBit)(a,9),h=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:o.address,client4:i.address,flags:a,coneNat:u,microsoft:{reserved:d,universalLocal:p,groupIndividual:f,nonce:h},udpPort:r}}inspect6to4(){let e=this.getBitsBase16(0,16),n=wn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:n.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}static fromAddress4Nat64(e,n="64:ff9b::/96"){let r=new wn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let i=o.binaryZeroPad(),a=r.binaryZeroPad(),u;if(s===96)u=i.slice(0,96)+a;else{let p=64-s;u=[i.slice(0,s),a.slice(0,p),"00000000",a.slice(p),"0".repeat(56-(32-p))].join("")}let d=BigInt(`0b${u}`).toString(16).padStart(32,"0"),f=[];for(let p=0;p<8;p++)f.push(d.slice(p*4,(p+1)*4));return new t(f.join(":"))}toAddress4Nat64(e="64:ff9b::/96"){let n=new t(e),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(n))return null;let o=this.binaryZeroPad(),s;if(r===96)s=o.slice(96,128);else{let a=64-r;s=o.slice(r,r+a)+o.slice(72,72+(32-a))}let i=[];for(let a=0;a<4;a++)i.push(parseInt(s.slice(a*8,(a+1)*8),2).toString());return new wn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(xe.BITS/4,"0"),n=[];for(let r=0,o=e.length;r<o;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(eC)}static fromByteArray(e){return po.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(eC))}static fromUnsignedByteArray(e){po.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(jD)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(UD)?this.to4():null}isTeredo(){return this.isHostInSubnet(FD)}is6to4(){return this.isHostInSubnet(ND)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(MD)}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(BD)}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=lo.escapeHtml(`${e.prefix}${r}`),s=lo.escapeHtml(r);if(e.className){let i=lo.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return lo.simpleGroup(this.addressMinusSuffix).join(":");Ac(typeof this.elidedGroups=="number"),Ac(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...lo.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(...lo.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Ac(this.address4 instanceof wn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let n=[],r=new t(this.correctForm());if(r.elidedGroups===0)n.push((0,fo.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===xe.GROUPS)n.push((0,fo.possibleElisions)(xe.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,fo.simpleRegularExpression)(o[0].split(":"))),Ac(typeof r.elidedGroups=="number"),n.push((0,fo.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,fo.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",fo.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",fo.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Sn.Address6=kn;var tC=Object.keys(xe.TYPES).map(t=>[new kn(t),xe.TYPES[t]]),FD=new kn("2001::/32"),ND=new kn("2002::/16"),MD=new kn("fc00::/7"),BD=new kn("2001:db8::/32"),jD=new kn("::ffff:0:0/96"),UD=new kn("64:ff9b::/96")});var rC=G(ft=>{"use strict";var LD=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),$D=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),qD=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&LD(e,t,n);return $D(e,t),e};Object.defineProperty(ft,"__esModule",{value:!0});ft.v6=ft.AddressError=ft.Address6=ft.Address4=void 0;var HD=vp();Object.defineProperty(ft,"Address4",{enumerable:!0,get:function(){return HD.Address4}});var zD=nC();Object.defineProperty(ft,"Address6",{enumerable:!0,get:function(){return zD.Address6}});var WD=Ii();Object.defineProperty(ft,"AddressError",{enumerable:!0,get:function(){return WD.AddressError}});var GD=qD(xp());ft.v6={helpers:GD}});var sC=G((Q6,Dp)=>{"use strict";var JD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,KD=/(\w*(\.\w*)*)\..*/;Dp.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,oC(r.stack)}};function oC(t){let e=t.match(JD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(KD)[1]:"anonymous"}Dp.exports.extractPluginName=oC});var aC=G((Z6,iC)=>{"use strict";iC.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var Pp=G((eH,vc)=>{"use strict";var VD=sC(),YD=aC(),XD=0;function Op(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=VD(t)+"-auto-"+XD++),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=YD(e.name);return!n&&!t[r]&&(t[r]=t),t}vc.exports=Op;vc.exports.default=Op;vc.exports.fastifyPlugin=Op});var cC=G(Fp=>{var QD=/^(-?(?:\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?)?)?$/,Tc=1e3,xc=Tc*60,Rc=xc*60,Ni=Rc*24,Ip=Ni*365.25;function ZD(t){var e,n=t.toLowerCase().match(QD);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*Tc:n[4]!=null?e*xc:n[5]!=null?e*Rc:n[6]!=null?e*Ni:n[7]!=null?e*Ni*7:n[8]!=null?e*Ip:e}function Fi(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function eO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<Tc?t+(e?" ms":"ms"):r<xc?Fi(r/Tc,n,"second",e):r<Rc?Fi(r/xc,n,"minute",e):r<Ni?Fi(r/Rc,n,"hour",e):r<Ip?Fi(r/Ni,n,"day",e):Fi(r/Ip,n,"year",e)}Fp.format=eO;Fp.parse=ZD});var lC=G(An=>{"use strict";function Ic(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 Np=class{constructor(e=1e3,n=0){Ic(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}},Dc=class{constructor(e=1e3,n=0){Ic(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 Mp(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var Oc=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:Mp()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=Mp()}getStatistics(){return this.records}},Bp=class{constructor(e=1e3,n=0){Ic(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}},Mi=class{constructor(e=1e3,n=0){Ic(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 uC(t){return`${t.getFullYear()}-${(t.getMonth()+1).toString().padStart(2,"0")}-${t.getDate().toString().padStart(2,"0")}`}var jp=class{constructor(e,n,r){this.cacheId=e,this.statisticTtlInHours=n,this.collectionStart=new Date,this.currentTimeStamp=uC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records=r||new Oc,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=Mp()),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=uC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},Pc=class extends Mi{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new jp(r,s!==void 0?s:24,o)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,n){super.set(e,n),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){let e=this.size>0;super.evict(),e&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,n=!1){let r=this.items[e]!==void 0;super.delete(e),r&&!n&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(n),n.value||(this.hitStatistics.addFalsyHit(),(n.value===void 0||n.value===null||n.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),n.value}this.hitStatistics.addMiss()}};An.Fifo=Dc;An.FifoMap=Np;An.FifoObject=Dc;An.HitStatisticsRecord=Oc;An.Lru=Mi;An.LruHitStatistics=Pc;An.LruMap=Bp;An.LruObject=Mi;An.LruObjectHitStatistics=Pc});var fC=G((rH,dC)=>{"use strict";var{LruMap:tO}=lC();function Bi(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new tO(n)}Bi.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)};Bi.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})};Bi.prototype.child=function(t){return new Bi(t.continueExceeding,t.exponentialBackoff,t.cache)};dC.exports=Bi});var hC=G((oH,pC)=>{"use strict";var nO=`
|
|
1
|
+
var tD=Object.create;var Op=Object.defineProperty;var nD=Object.getOwnPropertyDescriptor;var rD=Object.getOwnPropertyNames;var oD=Object.getPrototypeOf,sD=Object.prototype.hasOwnProperty;var re=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Mr=(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}},Qb=(t,e)=>{for(var n in e)Op(t,n,{get:e[n],enumerable:!0})},iD=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of rD(e))!sD.call(t,o)&&o!==n&&Op(t,o,{get:()=>e[o],enumerable:!(r=nD(e,o))||r.enumerable});return t};var nr=(t,e,n)=>(n=t!=null?tD(oD(t)):{},iD(e||!t||!t.__esModule?Op(n,"default",{value:t,enumerable:!0}):n,t));var Ii=G(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.AddressError=void 0;var Pp=class extends Error{constructor(e,n){super(e),this.name="AddressError",this.parseMessage=n}};_c.AddressError=Pp});var Cc=G(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.isInSubnet=aD;yn.isHostInSubnet=Zb;yn.isCorrect=cD;yn.prefixLengthFromMask=uD;yn.assertByteArray=lD;yn.numberToPaddedHex=eC;yn.stringToPaddedHex=dD;yn.testBit=fD;var bc=Ii();function aD(t){return this.subnetMask<t.subnetMask?!1:Zb.call(this,t)}function Zb(t){return this.mask(t.subnetMask)===t.mask()}function cD(t){return function(){return this.addressMinusSuffix!==this.correctForm()?!1:this.subnetMask===t&&!this.parsedSubnet?!0:this.parsedSubnet===String(this.subnetMask)}}function uD(t,e){let n=t.toString(2).padStart(e,"0");if(n.length>e)throw new bc.AddressError("Invalid subnet mask.");let r=n.indexOf("0");if(r===-1)return e;if(n.slice(r).includes("1"))throw new bc.AddressError("Invalid subnet mask.");return r}function lD(t,e,n,r){if(t.length!==e)throw new bc.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 bc.AddressError(`All bytes must be integers between ${r} and 255`)}function eC(t){return t.toString(16).padStart(2,"0")}function dD(t){return eC(parseInt(t,10))}function fD(t,e){let{length:n}=t;if(e>n)return!1;let r=n-e;return t.substring(r,r+1)==="1"}});var Ip=G(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.RE_SUBNET_STRING=_n.RE_ADDRESS=_n.GROUPS=_n.BITS=void 0;_n.BITS=32;_n.GROUPS=4;_n.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g;_n.RE_SUBNET_STRING=/\/\d{1,2}$/});var Fp=G(Cn=>{"use strict";var pD=Cn&&Cn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hD=Cn&&Cn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),tC=Cn&&Cn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&pD(e,t,n);return hD(e,t),e};Object.defineProperty(Cn,"__esModule",{value:!0});Cn.Address4=void 0;var bn=tC(Cc()),nt=tC(Ip()),rr=Ii(),gD=bn.isCorrect(nt.BITS),Lt=class t{constructor(e){this.addressMinusSuffix="",this.groups=nt.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=gD,this.isInSubnet=bn.isInSubnet,this.isHostInSubnet=bn.isHostInSubnet,this.address=e;let n=nt.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>nt.BITS)throw new rr.AddressError("Invalid subnet mask.");e=e.replace(nt.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new t(e),!0}catch{return!1}}parse(e){let n=e.split(".");if(n.some(r=>/^0\d/.test(r)))throw new rr.AddressError("IPv4 addresses can't have leading zeroes.");if(!e.match(nt.RE_ADDRESS))throw new rr.AddressError("Invalid IPv4 address.");return n}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromAddressAndMask(e,n){let r=bn.prefixLengthFromMask(new t(n).bigInt(),nt.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(nt.BITS))-BigInt(1),s=r^o,i=bn.prefixLengthFromMask(s,nt.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){let n=e.split(".");if(n.length!==nt.GROUPS)throw new rr.AddressError("Wildcard pattern must have 4 octets");let r=-1;for(let a=0;a<n.length;a++)if(n[a]==="*")r===-1&&(r=a);else if(r!==-1)throw new rr.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let o=r===-1?0:n.length-r,s=n.map(a=>a==="*"?"0":a),i=nt.BITS-o*8;return new t(`${s.join(".")}/${i}`)}static fromHex(e){let n=e.replace(/:/g,"");if(!/^[0-9a-fA-F]{8}$/.test(n))throw new rr.AddressError("IPv4 hex must be exactly 8 hex digits");let r=[];for(let o=0;o<8;o+=2)r.push(parseInt(n.slice(o,o+2),16));return new t(r.join("."))}static fromInteger(e){if(!Number.isInteger(e)||e<0||e>4294967295)throw new rr.AddressError("IPv4 integer must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromArpa(e){let r=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new t(r)}toHex(){return this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],n;for(n=0;n<nt.GROUPS;n+=2)e.push(`${bn.stringToPaddedHex(this.parsedAddress[n])}${bn.stringToPaddedHex(this.parsedAddress[n+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>bn.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(nt.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(nt.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(nt.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(nt.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(e){if(e<BigInt(0)||e>BigInt(4294967295))throw new rr.AddressError("IPv4 BigInt must be in the range 0 to 2**32 - 1");return t.fromHex(e.toString(16).padStart(8,"0"))}static fromByteArray(e){return bn.assertByteArray(e,4,"IPv4",0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(e.length!==4)throw new rr.AddressError("IPv4 addresses require exactly 4 bytes");let n=e.join(".");return new t(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}reverseForm(e){e||(e={});let n=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?n:`${n}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(mD)}isPrivate(){return yD.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(_D)}isLinkLocal(){return this.isHostInSubnet(bD)}isUnspecified(){return this.isHostInSubnet(CD)}isBroadcast(){return this.isHostInSubnet(wD)}isCGNAT(){return this.isHostInSubnet(kD)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(nt.BITS,"0")),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(nt.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}};Cn.Address4=Lt;var mD=new Lt("224.0.0.0/4"),yD=[new Lt("10.0.0.0/8"),new Lt("172.16.0.0/12"),new Lt("192.168.0.0/16")],_D=new Lt("127.0.0.0/8"),bD=new Lt("169.254.0.0/16"),CD=new Lt("0.0.0.0/32"),wD=new Lt("255.255.255.255/32"),kD=new Lt("100.64.0.0/10")});var Np=G(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.RE_URL_WITH_PORT=We.RE_URL=We.RE_ZONE_STRING=We.RE_SUBNET_STRING=We.RE_BAD_ADDRESS=We.RE_BAD_CHARACTERS=We.TYPES=We.SCOPES=We.GROUPS=We.BITS=void 0;We.BITS=128;We.GROUPS=8;We.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"};We.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","::ffff:0:0/96":"IPv4-mapped","ff00::/8":"Multicast","fe80::/10":"Link-local unicast","fc00::/7":"Unique local","2002::/16":"6to4","2001:db8::/32":"Documentation","64:ff9b::/96":"NAT64 (well-known)","64:ff9b:1::/48":"NAT64 (local-use)"};We.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi;We.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi;We.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/;We.RE_ZONE_STRING=/%.*$/;We.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i;We.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i});var Mp=G(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.escapeHtml=wc;uo.spanAllZeroes=nC;uo.spanAll=SD;uo.spanLeadingZeroes=AD;uo.simpleGroup=ED;function wc(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function nC(t){return wc(t).replace(/(0+)/g,'<span class="zero">$1</span>')}function SD(t,e=0){return t.split("").map((r,o)=>`<span class="digit value-${wc(r)} position-${o+e}">${nC(r)}</span>`).join("")}function rC(t){return wc(t).replace(/^(0+)/,'<span class="zero">$1</span>')}function AD(t){return t.split(":").map(n=>rC(n)).join(":")}function ED(t,e=0){return t.split(":").map((r,o)=>/group-v4/.test(r)?r:`<span class="hover-group group-${o+e}">${rC(r)}</span>`)}});var oC=G(kt=>{"use strict";var vD=kt&&kt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),TD=kt&&kt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),xD=kt&&kt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&vD(e,t,n);return TD(e,t),e};Object.defineProperty(kt,"__esModule",{value:!0});kt.ADDRESS_BOUNDARY=void 0;kt.groupPossibilities=Sc;kt.padGroup=kc;kt.simpleRegularExpression=DD;kt.possibleElisions=OD;var RD=xD(Np());function Sc(t){return`(${t.join("|")})`}function kc(t){return t.length<4?`0{0,${4-t.length}}${t}`:t}kt.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]";function DD(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===RD.GROUPS-1?":":"";return Sc([kc(o),i])}return kc(o)}).join(":"));return n.push(t.map(kc).join(":")),Sc(n)}function OD(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 Sc(s)}});var cC=G(Sn=>{"use strict";var PD=Sn&&Sn.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),ID=Sn&&Sn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),vc=Sn&&Sn.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&PD(e,t,n);return ID(e,t),e};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.Address6=void 0;var po=vc(Cc()),Bp=vc(Ip()),xe=vc(Np()),lo=vc(Mp()),wn=Fp(),fo=oC(),ct=Ii(),Ac=Cc(),FD=po.isCorrect(xe.BITS);function Ec(t){if(!t)throw new Error("Assertion failed.")}function ND(t){let e=/(\d+)(\d{3})/;for(;e.test(t);)t=t.replace(e,"$1,$2");return t}function MD(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 BD(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 sC(t){return parseInt(t,16).toString(16).padStart(4,"0")}function iC(t){return t&255}var kn=class t{constructor(e,n){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=po.isInSubnet,this.isHostInSubnet=po.isHostInSubnet,this.isCorrect=FD,n===void 0?this.groups=xe.GROUPS:this.groups=n,this.address=e;let r=xe.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>xe.BITS)throw new ct.AddressError("Invalid subnet mask.");e=e.replace(xe.RE_SUBNET_STRING,"")}if(/\//.test(e))throw new ct.AddressError("Invalid subnet mask.");let o=xe.RE_ZONE_STRING.exec(e);o&&(this.zone=o[0],e=e.replace(xe.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromBigInt(e){if(e<BigInt(0)||e>(BigInt(1)<<BigInt(xe.BITS))-BigInt(1))throw new ct.AddressError("IPv6 BigInt must be in the range 0 to 2**128 - 1");let n=e.toString(16).padStart(32,"0"),r=[];for(let o=0;o<xe.GROUPS;o++)r.push(n.slice(o*4,(o+1)*4));return new t(r.join(":"))}static fromURL(e){var n;let r,o=null,s,i,a=e.replace(/^[a-z][a-z0-9+.-]*:\/\//i,"");if(a.indexOf("[")!==-1&&a.indexOf("]:")!==-1){if(i="failed to parse address with port",s=xe.RE_URL_WITH_PORT.exec(a),s===null)return{error:i,address:null,port:null};r=s[1],o=s[2]}else{if(i="failed to parse address from URL",s=xe.RE_URL.exec(a),s===null)return{error:i,address:null,port:null};r=(n=s[1])!==null&&n!==void 0?n:s[2]}o?(o=parseInt(o,10),(o<0||o>65535)&&(o=null)):o=null;let u;try{u=new t(r)}catch{return{error:i,address:null,port:null}}return{address:u,port:o}}static fromAddressAndMask(e,n){let r=po.prefixLengthFromMask(new t(n).bigInt(),xe.BITS);return new t(`${e}/${r}`)}static fromAddressAndWildcardMask(e,n){let r=new t(n).bigInt(),o=(BigInt(1)<<BigInt(xe.BITS))-BigInt(1),s=r^o,i=po.prefixLengthFromMask(s,xe.BITS);return new t(`${e}/${i}`)}static fromWildcard(e){if(e.includes("%")||e.includes("/"))throw new ct.AddressError("Wildcard pattern must not include a zone or CIDR suffix");let n=e.split("::");if(n.length>2)throw new ct.AddressError("Wildcard pattern cannot contain more than one '::'");let r;if(n.length===2){let u=n[0]===""?[]:n[0].split(":"),d=n[1]===""?[]:n[1].split(":"),f=xe.GROUPS-u.length-d.length;if(f<1)throw new ct.AddressError("Wildcard pattern with '::' has too many groups");r=[...u,...new Array(f).fill("0"),...d]}else r=e.split(":");if(r.length!==xe.GROUPS)throw new ct.AddressError("Wildcard pattern must have 8 groups");let o=-1;for(let u=0;u<r.length;u++)if(r[u]==="*")o===-1&&(o=u);else if(o!==-1)throw new ct.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let s=o===-1?0:r.length-o,i=r.map(u=>u==="*"?"0":u),a=xe.BITS-s*16;return new t(`${i.join(":")}/${a}`)}static fromAddress4(e){let n=new wn.Address4(e),r=xe.BITS-(Bp.BITS-n.subnetMask);return new t(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(e){let n=e.replace(/(\.ip6\.arpa)?\.$/,""),r=7;if(n.length!==63)throw new ct.AddressError("Invalid 'ip6.arpa' form.");let o=n.split(".").reverse();for(let s=r;s>0;s--){let i=s*4;o.splice(i,0,":")}return n=o.join(""),new t(n)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let n=xe.BITS-this.subnetMask,r=Math.abs(e-xe.BITS),o=n-r;return o<0?"0":ND((BigInt("2")**BigInt(o)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(xe.BITS-this.subnetMask)}`)}startAddress(){return t.fromBigInt(this._startAddress())}startAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(xe.BITS-this.subnetMask)}`)}endAddress(){return t.fromBigInt(this._endAddress())}endAddressExclusive(){let e=BigInt("1");return t.fromBigInt(this._endAddress()-e)}subnetMaskAddress(){return t.fromBigInt(BigInt(`0b${"1".repeat(this.subnetMask)}${"0".repeat(xe.BITS-this.subnetMask)}`))}wildcardMask(){return t.fromBigInt(BigInt(`0b${"0".repeat(this.subnetMask)}${"1".repeat(xe.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e==="Multicast"||e.startsWith("Multicast ")?xe.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||"Unknown":e==="Link-local unicast"||e==="Loopback"?"Link local":e==="Unspecified"?"Unknown":"Global"}getType(){for(let e=0;e<aC.length;e++){let n=aC[e];if(this.isHostInSubnet(n[0]))return n[1]}return"Global unicast"}getBits(e,n){return BigInt(`0b${this.getBitsBase2(e,n)}`)}getBitsBase2(e,n){return this.binaryZeroPad().slice(e,n)}getBitsBase16(e,n){let r=n-e;if(r%4!==0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,n).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,xe.BITS)}reverseForm(e){e||(e={});let n=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,n).reverse().join(".");return n>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,n=[],r=0,o=[];for(e=0;e<this.parsedAddress.length;e++){let a=parseInt(this.parsedAddress[e],16);a===0&&r++,a!==0&&r>0&&(r>1&&o.push([e-r,e-1]),r=0)}r>1&&o.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);let s=o.map(a=>a[1]-a[0]+1);if(o.length>0){let a=s.indexOf(Math.max(...s));n=BD(this.parsedAddress,o[a])}else n=this.parsedAddress;for(e=0;e<n.length;e++)n[e]!=="compact"&&(n[e]=parseInt(n[e],16).toString(16));let i=n.join(":");return i=i.replace(/^compact$/,"::"),i=i.replace(/(^compact)|(compact$)/,":"),i=i.replace(/compact/,""),i}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(xe.BITS,"0")),this._binaryZeroPad}parse4in6(e){if(e.indexOf(".")===-1)return e;let n=e.split(":"),r=n.slice(-1)[0],o=r.split(".");if(o.length===Bp.GROUPS&&o.every(i=>/^\d{1,3}$/.test(i))&&o.some(i=>/^0\d/.test(i))){let i=o.map(MD).join("."),a=n.slice(0,-1).map(lo.escapeHtml).join(":"),u=n.length>1?":":"";throw new ct.AddressError("IPv4 addresses can't have leading zeroes.",`${a}${u}${i}`)}let s=r.match(Bp.RE_ADDRESS);if(s){this.parsedAddress4=s[0];let i=this.subnetMask>=96?`/${this.subnetMask-96}`:"";this.address4=new wn.Address4(`${this.parsedAddress4}${i}`),this.v4=!0,n[n.length-1]=this.address4.toGroup6(),e=n.join(":")}return e}parse(e){e=this.parse4in6(e);let n=e.match(xe.RE_BAD_CHARACTERS);if(n)throw new ct.AddressError(`Bad character${n.length>1?"s":""} detected in address: ${n.join("")}`,e.replace(xe.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));let r=e.match(xe.RE_BAD_ADDRESS);if(r)throw new ct.AddressError(`Address failed regex: ${r.join("")}`,e.replace(xe.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let o=[],s=e.split("::");if(s.length===2){let i=s[0].split(":"),a=s[1].split(":");i.length===1&&i[0]===""&&(i=[]),a.length===1&&a[0]===""&&(a=[]);let u=this.groups-(i.length+a.length);if(!u)throw new ct.AddressError("Error parsing groups");this.elidedGroups=u,this.elisionBegin=i.length,this.elisionEnd=i.length+this.elidedGroups,o=o.concat(i);for(let d=0;d<u;d++)o.push("0");o=o.concat(a)}else if(s.length===1)o=e.split(":"),this.elidedGroups=0;else throw new ct.AddressError("Too many :: groups found");if(o=o.map(i=>parseInt(i,16).toString(16)),o.length!==this.groups)throw new ct.AddressError("Incorrect number of groups found");return o}canonicalForm(){return this.parsedAddress.map(sC).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(sC).join("")}`)}to4(){let e=this.binaryZeroPad().split(""),n=BigInt(`0b${e.slice(96,128).join("")}`).toString(16).padStart(8,"0");if(this.subnetMask>=96){let r=this.subnetMask-96,o=[];for(let s=0;s<8;s+=2)o.push(parseInt(n.slice(s,s+2),16));return new wn.Address4(`${o.join(".")}/${r}`)}return wn.Address4.fromHex(n)}to4in6(){let e=this.to4(),r=new t(this.parsedAddress.slice(0,6).join(":"),6).correctForm(),o="";return/:$/.test(r)||(o=":"),r+o+e.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),r=(this.getBits(80,96)^BigInt("0xffff")).toString(),o=wn.Address4.fromHex(this.getBitsBase16(32,64)),s=this.getBits(96,128),i=wn.Address4.fromHex((s^BigInt("0xffffffff")).toString(16).padStart(8,"0")),a=this.getBitsBase2(64,80),u=(0,Ac.testBit)(a,15),d=(0,Ac.testBit)(a,14),f=(0,Ac.testBit)(a,8),p=(0,Ac.testBit)(a,9),h=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:o.address,client4:i.address,flags:a,coneNat:u,microsoft:{reserved:d,universalLocal:p,groupIndividual:f,nonce:h},udpPort:r}}inspect6to4(){let e=this.getBitsBase16(0,16),n=wn.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:n.address}}to6to4(){if(!this.is4())return null;let e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new t(e)}static fromAddress4Nat64(e,n="64:ff9b::/96"){let r=new wn.Address4(e),o=new t(n),s=o.subnetMask;if(s!==32&&s!==40&&s!==48&&s!==56&&s!==64&&s!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");let i=o.binaryZeroPad(),a=r.binaryZeroPad(),u;if(s===96)u=i.slice(0,96)+a;else{let p=64-s;u=[i.slice(0,s),a.slice(0,p),"00000000",a.slice(p),"0".repeat(56-(32-p))].join("")}let d=BigInt(`0b${u}`).toString(16).padStart(32,"0"),f=[];for(let p=0;p<8;p++)f.push(d.slice(p*4,(p+1)*4));return new t(f.join(":"))}toAddress4Nat64(e="64:ff9b::/96"){let n=new t(e),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new ct.AddressError("NAT64 prefix length must be 32, 40, 48, 56, 64, or 96");if(!this.isHostInSubnet(n))return null;let o=this.binaryZeroPad(),s;if(r===96)s=o.slice(96,128);else{let a=64-r;s=o.slice(r,r+a)+o.slice(72,72+(32-a))}let i=[];for(let a=0;a<4;a++)i.push(parseInt(s.slice(a*8,(a+1)*8),2).toString());return new wn.Address4(i.join("."))}toByteArray(){let e=this.bigInt().toString(16).padStart(xe.BITS/4,"0"),n=[];for(let r=0,o=e.length;r<o;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}toUnsignedByteArray(){return this.toByteArray().map(iC)}static fromByteArray(e){return po.assertByteArray(e,16,"IPv6",-128),this.fromUnsignedByteArray(e.map(iC))}static fromUnsignedByteArray(e){po.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(qD)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(HD)?this.to4():null}isTeredo(){return this.isHostInSubnet(UD)}is6to4(){return this.isHostInSubnet(jD)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()==="Loopback"}isULA(){return this.isHostInSubnet(LD)}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($D)}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=lo.escapeHtml(`${e.prefix}${r}`),s=lo.escapeHtml(r);if(e.className){let i=lo.escapeHtml(e.className);return`<a href="${o}" class="${i}">${s}</a>`}return`<a href="${o}">${s}</a>`}group(){if(this.elidedGroups===0)return lo.simpleGroup(this.addressMinusSuffix).join(":");Ec(typeof this.elidedGroups=="number"),Ec(typeof this.elisionBegin=="number");let e=[],[n,r]=this.addressMinusSuffix.split("::");n.length?e.push(...lo.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(...lo.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(Ec(this.address4 instanceof wn.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let n=[],r=new t(this.correctForm());if(r.elidedGroups===0)n.push((0,fo.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===xe.GROUPS)n.push((0,fo.possibleElisions)(xe.GROUPS));else{let o=r.address.split("::");o[0].length&&n.push((0,fo.simpleRegularExpression)(o[0].split(":"))),Ec(typeof r.elidedGroups=="number"),n.push((0,fo.possibleElisions)(r.elidedGroups,o[0].length!==0,o[1].length!==0)),o[1].length&&n.push((0,fo.simpleRegularExpression)(o[1].split(":"))),n=[n.join(":")]}return e||(n=["(?=^|",fo.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...n,")(?=[^\\w\\:]|",fo.ADDRESS_BOUNDARY,"|$)"]),n.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}};Sn.Address6=kn;var aC=Object.keys(xe.TYPES).map(t=>[new kn(t),xe.TYPES[t]]),UD=new kn("2001::/32"),jD=new kn("2002::/16"),LD=new kn("fc00::/7"),$D=new kn("2001:db8::/32"),qD=new kn("::ffff:0:0/96"),HD=new kn("64:ff9b::/96")});var uC=G(ft=>{"use strict";var zD=ft&&ft.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WD=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),GD=ft&&ft.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&zD(e,t,n);return WD(e,t),e};Object.defineProperty(ft,"__esModule",{value:!0});ft.v6=ft.AddressError=ft.Address6=ft.Address4=void 0;var JD=Fp();Object.defineProperty(ft,"Address4",{enumerable:!0,get:function(){return JD.Address4}});var KD=cC();Object.defineProperty(ft,"Address6",{enumerable:!0,get:function(){return KD.Address6}});var VD=Ii();Object.defineProperty(ft,"AddressError",{enumerable:!0,get:function(){return VD.AddressError}});var YD=GD(Mp());ft.v6={helpers:YD}});var dC=G((aH,Up)=>{"use strict";var XD=/at\s(?:.*\.)?plugin\s.*\n\s*(.*)/,QD=/(\w*(\.\w*)*)\..*/;Up.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,lC(r.stack)}};function lC(t){let e=t.match(XD);return e?e[1].split(/[/\\]/).slice(-1)[0].match(QD)[1]:"anonymous"}Up.exports.extractPluginName=lC});var pC=G((cH,fC)=>{"use strict";fC.exports=function(e){return e[0]==="@"&&(e=e.slice(1).replace("/","-")),e.replace(/-(.)/g,function(n,r){return r.toUpperCase()})}});var Lp=G((uH,Tc)=>{"use strict";var ZD=dC(),eO=pC(),tO=0;function jp(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=ZD(t)+"-auto-"+tO++),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=eO(e.name);return!n&&!t[r]&&(t[r]=t),t}Tc.exports=jp;Tc.exports.default=jp;Tc.exports.fastifyPlugin=jp});var hC=G(qp=>{var nO=/^(-?(?:\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?)?)?$/,xc=1e3,Rc=xc*60,Dc=Rc*60,Ni=Dc*24,$p=Ni*365.25;function rO(t){var e,n=t.toLowerCase().match(nO);if(n!=null&&(e=parseFloat(n[1])))return n[3]!=null?e*xc:n[4]!=null?e*Rc:n[5]!=null?e*Dc:n[6]!=null?e*Ni:n[7]!=null?e*Ni*7:n[8]!=null?e*$p:e}function Fi(t,e,n,r){var o=(t|0)===t?t:~~(t+.5);return e+o+(r?" "+n+(o!=1?"s":""):n[0])}function oO(t,e){var n=t<0?"-":"",r=t<0?-t:t;return r<xc?t+(e?" ms":"ms"):r<Rc?Fi(r/xc,n,"second",e):r<Dc?Fi(r/Rc,n,"minute",e):r<Ni?Fi(r/Dc,n,"hour",e):r<$p?Fi(r/Ni,n,"day",e):Fi(r/$p,n,"year",e)}qp.format=oO;qp.parse=rO});var mC=G(An=>{"use strict";function Fc(t,e){if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new Error("Invalid max value");if(typeof e!="number"||!Number.isInteger(e)||e<0)throw new Error("Invalid ttl value")}var Hp=class{constructor(e=1e3,n=0){Fc(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}},Oc=class{constructor(e=1e3,n=0){Fc(e,n),this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this.max=e,this.ttl=n}clear(){this.items=Object.create(null),this.first=null,this.last=null,this.size=0}delete(e){let n=this.items[e];n!==void 0&&(delete this.items[e],this.size--,n.prev!==null&&(n.prev.next=n.next),n.next!==null&&(n.next.prev=n.prev),this.first===n&&(this.first=n.next),this.last===n&&(this.last=n.prev))}deleteMany(e){for(var n=0;n<e.length;n++)this.delete(e[n])}evict(){if(this.size>0){let e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}}expiresAt(e){let n=this.items[e];if(n!==void 0)return n.expiry}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e);return}return n.value}}getMany(e){let n=new Array(e.length);for(var r=0;r<e.length;r++)n[r]=this.get(e[r]);return n}keys(){return Object.keys(this.items)}set(e,n){let r=this.items[e];if(r!==void 0){r.value=n,r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl;return}this.max>0&&this.size>=this.max&&this.evict();let o={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:n};this.items[e]=o,++this.size===1?this.first=o:this.last.next=o,this.last=o}};function zp(){return{cacheSize:0,hits:0,falsyHits:0,emptyHits:0,misses:0,expirations:0,evictions:0,invalidateOne:0,invalidateAll:0,sets:0}}var Pc=class{constructor(){this.records={}}initForCache(e,n){this.records[e]={[n]:zp()}}resetForCache(e){if(this.records[e])for(let n of Object.keys(this.records[e]))this.records[e][n]=zp()}getStatistics(){return this.records}},Wp=class{constructor(e=1e3,n=0){Fc(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}},Mi=class{constructor(e=1e3,n=0){Fc(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 Gp=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 Pc,this.records.initForCache(this.cacheId,this.currentTimeStamp)}get currentRecord(){let e=this.records.records[this.cacheId];return e[this.currentTimeStamp]||(e[this.currentTimeStamp]=zp()),e[this.currentTimeStamp]}hoursPassed(){return(Date.now()-this.collectionStart)/1e3/60/60}addHit(){this.archiveIfNeeded(),this.currentRecord.hits++}addFalsyHit(){this.archiveIfNeeded(),this.currentRecord.falsyHits++}addEmptyHit(){this.archiveIfNeeded(),this.currentRecord.emptyHits++}addMiss(){this.archiveIfNeeded(),this.currentRecord.misses++}addEviction(){this.archiveIfNeeded(),this.currentRecord.evictions++}setCacheSize(e){this.archiveIfNeeded(),this.currentRecord.cacheSize=e}addExpiration(){this.archiveIfNeeded(),this.currentRecord.expirations++}addSet(){this.archiveIfNeeded(),this.currentRecord.sets++}addInvalidateOne(){this.archiveIfNeeded(),this.currentRecord.invalidateOne++}addInvalidateAll(){this.archiveIfNeeded(),this.currentRecord.invalidateAll++}getStatistics(){return this.records.getStatistics()}archiveIfNeeded(){Date.now()>=this.archiveAfter&&(this.collectionStart=new Date,this.currentTimeStamp=gC(this.collectionStart),this.archiveAfter=this.collectionStart.getTime()+this.statisticTtlInHours*36e5,this.records.initForCache(this.cacheId,this.currentTimeStamp))}},Ic=class extends Mi{constructor(e,n,r,o,s){if(super(e,n),!r)throw new Error("Cache id is mandatory");this.hitStatistics=new Gp(r,s!==void 0?s:24,o)}getStatistics(){return this.hitStatistics.getStatistics()}set(e,n){super.set(e,n),this.hitStatistics.addSet(),this.hitStatistics.setCacheSize(this.size)}evict(){let e=this.size>0;super.evict(),e&&this.hitStatistics.addEviction(),this.hitStatistics.setCacheSize(this.size)}delete(e,n=!1){let r=this.items[e]!==void 0;super.delete(e),r&&!n&&this.hitStatistics.addInvalidateOne(),this.hitStatistics.setCacheSize(this.size)}clear(){super.clear(),this.hitStatistics.addInvalidateAll(),this.hitStatistics.setCacheSize(this.size)}get(e){let n=this.items[e];if(n!==void 0){if(this.ttl>0&&n.expiry<=Date.now()){this.delete(e,!0),this.hitStatistics.addExpiration();return}return this.bumpLru(n),n.value||(this.hitStatistics.addFalsyHit(),(n.value===void 0||n.value===null||n.value==="")&&this.hitStatistics.addEmptyHit()),this.hitStatistics.addHit(),n.value}this.hitStatistics.addMiss()}};An.Fifo=Oc;An.FifoMap=Hp;An.FifoObject=Oc;An.HitStatisticsRecord=Pc;An.Lru=Mi;An.LruHitStatistics=Ic;An.LruMap=Wp;An.LruObject=Mi;An.LruObjectHitStatistics=Ic});var _C=G((fH,yC)=>{"use strict";var{LruMap:sO}=mC();function Bi(t,e,n=5e3){this.continueExceeding=t,this.exponentialBackoff=e,this.lru=new sO(n)}Bi.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)};Bi.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})};Bi.prototype.child=function(t){return new Bi(t.continueExceeding,t.exponentialBackoff,t.cache)};yC.exports=Bi});var CC=G((pH,bC)=>{"use strict";var iO=`
|
|
2
2
|
-- Key to operate on
|
|
3
3
|
local key = KEYS[1]
|
|
4
4
|
-- Time window for the TTL
|
|
@@ -27,7 +27,7 @@ var XR=Object.create;var Sp=Object.defineProperty;var QR=Object.getOwnPropertyDe
|
|
|
27
27
|
end
|
|
28
28
|
|
|
29
29
|
return {current, timeWindow}
|
|
30
|
-
`,
|
|
30
|
+
`,aO=`
|
|
31
31
|
-- Key to operate on
|
|
32
32
|
local key = KEYS[1]
|
|
33
33
|
|
|
@@ -49,105 +49,107 @@ var XR=Object.create;var Sp=Object.defineProperty;var QR=Object.getOwnPropertyDe
|
|
|
49
49
|
end
|
|
50
50
|
|
|
51
51
|
return {tonumber(current), ttl}
|
|
52
|
-
`;function ji(t,e,n,r="fastify-rate-limit-"){this.continueExceeding=t,this.exponentialBackoff=e,this.redis=n,this.key=r,this.redis.rateLimit||this.redis.defineCommand("rateLimit",{numberOfKeys:1,lua:nO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:rO})}ji.prototype.incr=function(t,e,n,r){this.redis.rateLimit(this.key+t,n,r,this.continueExceeding,this.exponentialBackoff,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};ji.prototype.read=function(t,e,n,r){this.redis.rateLimitRead(this.key+t,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};ji.prototype.child=function(t){return new ji(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};pC.exports=ji});var TC=G((sH,Ui)=>{"use strict";var{isIPv6:oO}=re("node:net"),{Address6:gC}=rC(),sO=Pp(),{parse:_C,format:iO}=cC(),aO=fC(),cO=hC(),bC=1e3,CC=6e4,uO="onRequest",wC=64,lO={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},dO={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},Up=()=>{};function kC(t,e=wC){if(!oO(t))return t.toLowerCase();let n=new gC(t);return n.isMapped4()?n.to4().correctForm():e<128?new gC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function SC(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):wC}var Lp=(t,e)=>kC(t.ip,e),fO=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function $p(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=dO):(n.enableDraftSpec=!1,n.labels=lO),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=bC,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=_C(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=CC,n.hook=e.hook||uO,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:Up,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:Up,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:Up,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=SC(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:Lp,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=fO,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 cO(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new aO(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=mC(r,n,o);return(i,a)=>EC.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=mC(r,n,o);return vC(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=AC(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),yC(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&yC(r,n,o)})}function AC(...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=_C(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=CC),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=bC),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=SC(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function mC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=AC(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function yC(t,e,n){let r=e.hook,o=vC(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function EC(t,e,n,r){let{store:o}=t,s=e.keyGenerator===Lp?Lp(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((C,_)=>{o[h](s,(k,b)=>{k?_(k):C(b)},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 vC(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await EC(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:iO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}Ui.exports=sO($p,{fastify:"5.x",name:"@fastify/rate-limit"});Ui.exports.default=$p;Ui.exports.fastifyRateLimit=$p;Ui.exports.normalizeIP=kC});var xC=G((iH,Fc)=>{Fc.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Fc.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]/;Fc.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 Hp=G((aH,RC)=>{var qp=xC();RC.exports={isSpaceSeparator(t){return typeof t=="string"&&qp.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||qp.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"||qp.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 FC=G((cH,IC)=>{var rt=Hp(),Wp,yt,sr,Mc,Br,Zt,ot,Kp,$i;IC.exports=function(e,n){Wp=String(e),yt="start",sr=[],Mc=0,Br=1,Zt=0,ot=void 0,Kp=void 0,$i=void 0;do ot=pO(),mO[yt]();while(ot.type!=="eof");return typeof n=="function"?Gp({"":$i},"",n):$i};function Gp(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=Gp(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=Gp(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Ae,Ce,Li,or,Re;function pO(){for(Ae="default",Ce="",Li=!1,or=1;;){Re=ir();let t=OC[Ae]();if(t)return t}}function ir(){if(Wp[Mc])return String.fromCodePoint(Wp.codePointAt(Mc))}function Y(){let t=ir();return t===`
|
|
53
|
-
`?(Br++,Zt=0):t?Zt+=t.length:Zt++,t&&(
|
|
54
|
-
`:case"\r":case"\u2028":case"\u2029":Y();return;case"/":Y(),Ae="comment";return;case void 0:return Y(),qe("eof")}if(rt.isSpaceSeparator(Re)){Y();return}return
|
|
55
|
-
`:case"\r":case"\u2028":case"\u2029":Y(),Ae="default";return;case void 0:return Y(),qe("eof")}Y()},value(){switch(Re){case"{":case"[":return qe("punctuator",Y());case"n":return Y(),ho("ull"),qe("null",null);case"t":return Y(),ho("rue"),qe("boolean",!0);case"f":return Y(),ho("alse"),qe("boolean",!1);case"-":case"+":Y()==="-"&&(or=-1),Ae="sign";return;case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),ho("nfinity"),qe("numeric",1/0);case"N":return Y(),ho("aN"),qe("numeric",NaN);case'"':case"'":Li=Y()==='"',Ce="",Ae="string";return}throw He(Y())},identifierNameStartEscape(){if(Re!=="u")throw He(Y());Y();let t=
|
|
56
|
-
`:case"\r":throw He(Y());case"\u2028":case"\u2029":
|
|
57
|
-
`;case"r":return Y(),"\r";case"t":return Y()," ";case"v":return Y(),"\v";case"0":if(Y(),rt.isDigit(ir()))throw He(Y());return"\0";case"x":return Y(),
|
|
52
|
+
`;function Ui(t,e,n,r="fastify-rate-limit-"){this.continueExceeding=t,this.exponentialBackoff=e,this.redis=n,this.key=r,this.redis.rateLimit||this.redis.defineCommand("rateLimit",{numberOfKeys:1,lua:iO}),this.redis.rateLimitRead||this.redis.defineCommand("rateLimitRead",{numberOfKeys:1,lua:aO})}Ui.prototype.incr=function(t,e,n,r){this.redis.rateLimit(this.key+t,n,r,this.continueExceeding,this.exponentialBackoff,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};Ui.prototype.read=function(t,e,n,r){this.redis.rateLimitRead(this.key+t,(o,s)=>{o?e(o,null):e(null,{current:s[0],ttl:s[1]})})};Ui.prototype.child=function(t){return new Ui(t.continueExceeding,t.exponentialBackoff,this.redis,`${this.key}${t.routeInfo.method}${t.routeInfo.url}-`)};bC.exports=Ui});var IC=G((hH,ji)=>{"use strict";var{isIPv6:cO}=re("node:net"),{Address6:wC}=uC(),uO=Lp(),{parse:AC,format:lO}=hC(),dO=_C(),fO=CC(),EC=1e3,vC=6e4,pO="onRequest",TC=64,hO={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},gO={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},Jp=()=>{};function xC(t,e=TC){if(!cO(t))return t.toLowerCase();let n=new wC(t);return n.isMapped4()?n.to4().correctForm():e<128?new wC(`${t}/${e}`).startAddress().correctForm():n.correctForm()}function RC(t){return Number.isFinite(t)&&t>=0&&t<=128?Math.trunc(t):TC}var Kp=(t,e)=>xC(t.ip,e),mO=(t,e)=>{let n=new Error(`Rate limit exceeded, retry in ${e.after}`);return n.statusCode=e.statusCode,n};async function Vp(t,e){let n={global:typeof e.global=="boolean"?e.global:!0};typeof e.enableDraftSpec=="boolean"&&e.enableDraftSpec?(n.enableDraftSpec=!0,n.labels=gO):(n.enableDraftSpec=!1,n.labels=hO),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=EC,Number.isFinite(e.timeWindow)&&e.timeWindow>=0?n.timeWindow=Math.trunc(e.timeWindow):typeof e.timeWindow=="string"?n.timeWindow=AC(e.timeWindow):typeof e.timeWindow=="function"?n.timeWindow=e.timeWindow:n.timeWindow=vC,n.hook=e.hook||pO,n.allowList=e.allowList||null,n.ban=Number.isFinite(e.ban)&&e.ban>=0?Math.trunc(e.ban):-1,n.onBanReach=typeof e.onBanReach=="function"?e.onBanReach:Jp,n.onExceeding=typeof e.onExceeding=="function"?e.onExceeding:Jp,n.onExceeded=typeof e.onExceeded=="function"?e.onExceeded:Jp,n.continueExceeding=typeof e.continueExceeding=="boolean"?e.continueExceeding:!1,n.exponentialBackoff=typeof e.exponentialBackoff=="boolean"?e.exponentialBackoff:!1,n.ipv6Subnet=RC(e.ipv6Subnet),n.keyGenerator=typeof e.keyGenerator=="function"?e.keyGenerator:Kp,typeof e.errorResponseBuilder=="function"?(n.errorResponseBuilder=e.errorResponseBuilder,n.isCustomErrorMessage=!0):(n.errorResponseBuilder=mO,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 fO(n.continueExceeding,n.exponentialBackoff,e.redis,e.nameSpace):r.store=new dO(n.continueExceeding,n.exponentialBackoff,e.cache);t.decorateRequest(r.rateLimitRan,!1),t.hasDecorator("createRateLimit")||t.decorate("createRateLimit",o=>{let s=kC(r,n,o);return(i,a)=>OC.apply(this,s.concat(i,a))}),t.hasDecorator("rateLimit")||t.decorate("rateLimit",o=>{let s=kC(r,n,o);return PC(...s)}),t.addHook("onRoute",o=>{if(o.config?.rateLimit!=null){if(typeof o.config.rateLimit=="object"){let s=Object.create(r),i=DC(n,o.config.rateLimit,{routeInfo:o});s.store=r.store.child(i),SC(s,i,o)}else if(o.config.rateLimit!==!1)throw new Error("Unknown value for route rate-limit configuration")}else n.global&&SC(r,n,o)})}function DC(...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=AC(e.timeWindow):typeof e.timeWindow!="function"&&(e.timeWindow=vC),Number.isFinite(e.max)&&e.max>=0?e.max=Math.trunc(e.max):typeof e.max!="function"&&(e.max=EC),Number.isFinite(e.ban)&&e.ban>=0?e.ban=Math.trunc(e.ban):e.ban=-1,e.ipv6Subnet=RC(e.ipv6Subnet),e.groupId!==void 0&&typeof e.groupId!="string")throw new Error("groupId must be a string");return e}function kC(t,e,n){if(typeof n=="object"){let r=Object.create(t),o=DC(e,n,{routeInfo:{}});return r.store=r.store.child(o),[r,o]}return[t,e]}function SC(t,e,n){let r=e.hook,o=PC(t,e);Array.isArray(n[r])?n[r].push(o):typeof n[r]=="function"?n[r]=[n[r],o]:n[r]=[o]}async function OC(t,e,n,r){let{store:o}=t,s=e.keyGenerator===Kp?Kp(n,e.ipv6Subnet):await e.keyGenerator(n),i=n.routeOptions.config?.rateLimit?.groupId;if(i&&(s+=i),e.allowList){if(typeof e.allowList=="function"){if(await e.allowList(n,s))return{isAllowed:!0,key:s}}else if(e.allowList.indexOf(s)!==-1)return{isAllowed:!0,key:s}}let a=typeof e.max=="number"?e.max:await e.max(n,s),u=typeof e.timeWindow=="number"?e.timeWindow:await e.timeWindow(n,s),d=0,f=0,p=0,h=r?.increment===!1?"read":"incr";if(h==="read"&&typeof o.read!="function")throw new Error("The configured rate-limit store does not implement a `read` method, which is required to use `{ increment: false }`");try{let g=await new Promise((C,y)=>{o[h](s,(k,b)=>{k?y(k):C(b)},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 PC(t,e){let{rateLimitRan:n}=t;return async(r,o)=>{if(r[n])return;r[n]=!0;let s=await OC(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:lO(f*1e3,!0)};throw h&&(g.statusCode=403,g.ban=!0,e.onBanReach(r,i)),e.errorResponseBuilder(r,g)}}ji.exports=uO(Vp,{fastify:"5.x",name:"@fastify/rate-limit"});ji.exports.default=Vp;ji.exports.fastifyRateLimit=Vp;ji.exports.normalizeIP=xC});var FC=G((gH,Nc)=>{Nc.exports.Space_Separator=/[\u1680\u2000-\u200A\u202F\u205F\u3000]/;Nc.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]/;Nc.exports.ID_Continue=/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/});var Xp=G((mH,NC)=>{var Yp=FC();NC.exports={isSpaceSeparator(t){return typeof t=="string"&&Yp.Space_Separator.test(t)},isIdStartChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="$"||t==="_"||Yp.ID_Start.test(t))},isIdContinueChar(t){return typeof t=="string"&&(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="$"||t==="_"||t==="\u200C"||t==="\u200D"||Yp.ID_Continue.test(t))},isDigit(t){return typeof t=="string"&&/[0-9]/.test(t)},isHexDigit(t){return typeof t=="string"&&/[0-9A-Fa-f]/.test(t)}}});var LC=G((yH,jC)=>{var rt=Xp(),Zp,yt,sr,Bc,Br,Zt,ot,nh,$i;jC.exports=function(e,n){Zp=String(e),yt="start",sr=[],Bc=0,Br=1,Zt=0,ot=void 0,nh=void 0,$i=void 0;do ot=yO(),CO[yt]();while(ot.type!=="eof");return typeof n=="function"?eh({"":$i},"",n):$i};function eh(t,e,n){let r=t[e];if(r!=null&&typeof r=="object")if(Array.isArray(r))for(let o=0;o<r.length;o++){let s=String(o),i=eh(r,s,n);i===void 0?delete r[s]:Object.defineProperty(r,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}else for(let o in r){let s=eh(r,o,n);s===void 0?delete r[o]:Object.defineProperty(r,o,{value:s,writable:!0,enumerable:!0,configurable:!0})}return n.call(t,e,r)}var Ae,Ce,Li,or,Re;function yO(){for(Ae="default",Ce="",Li=!1,or=1;;){Re=ir();let t=BC[Ae]();if(t)return t}}function ir(){if(Zp[Bc])return String.fromCodePoint(Zp.codePointAt(Bc))}function Y(){let t=ir();return t===`
|
|
53
|
+
`?(Br++,Zt=0):t?Zt+=t.length:Zt++,t&&(Bc+=t.length),t}var BC={default(){switch(Re){case" ":case"\v":case"\f":case" ":case"\xA0":case"\uFEFF":case`
|
|
54
|
+
`:case"\r":case"\u2028":case"\u2029":Y();return;case"/":Y(),Ae="comment";return;case void 0:return Y(),qe("eof")}if(rt.isSpaceSeparator(Re)){Y();return}return BC[yt]()},comment(){switch(Re){case"*":Y(),Ae="multiLineComment";return;case"/":Y(),Ae="singleLineComment";return}throw He(Y())},multiLineComment(){switch(Re){case"*":Y(),Ae="multiLineCommentAsterisk";return;case void 0:throw He(Y())}Y()},multiLineCommentAsterisk(){switch(Re){case"*":Y();return;case"/":Y(),Ae="default";return;case void 0:throw He(Y())}Y(),Ae="multiLineComment"},singleLineComment(){switch(Re){case`
|
|
55
|
+
`:case"\r":case"\u2028":case"\u2029":Y(),Ae="default";return;case void 0:return Y(),qe("eof")}Y()},value(){switch(Re){case"{":case"[":return qe("punctuator",Y());case"n":return Y(),ho("ull"),qe("null",null);case"t":return Y(),ho("rue"),qe("boolean",!0);case"f":return Y(),ho("alse"),qe("boolean",!1);case"-":case"+":Y()==="-"&&(or=-1),Ae="sign";return;case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),ho("nfinity"),qe("numeric",1/0);case"N":return Y(),ho("aN"),qe("numeric",NaN);case'"':case"'":Li=Y()==='"',Ce="",Ae="string";return}throw He(Y())},identifierNameStartEscape(){if(Re!=="u")throw He(Y());Y();let t=th();switch(t){case"$":case"_":break;default:if(!rt.isIdStartChar(t))throw MC();break}Ce+=t,Ae="identifierName"},identifierName(){switch(Re){case"$":case"_":case"\u200C":case"\u200D":Ce+=Y();return;case"\\":Y(),Ae="identifierNameEscape";return}if(rt.isIdContinueChar(Re)){Ce+=Y();return}return qe("identifier",Ce)},identifierNameEscape(){if(Re!=="u")throw He(Y());Y();let t=th();switch(t){case"$":case"_":case"\u200C":case"\u200D":break;default:if(!rt.isIdContinueChar(t))throw MC();break}Ce+=t,Ae="identifierName"},sign(){switch(Re){case".":Ce=Y(),Ae="decimalPointLeading";return;case"0":Ce=Y(),Ae="zero";return;case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":Ce=Y(),Ae="decimalInteger";return;case"I":return Y(),ho("nfinity"),qe("numeric",or*(1/0));case"N":return Y(),ho("aN"),qe("numeric",NaN)}throw He(Y())},zero(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return;case"x":case"X":Ce+=Y(),Ae="hexadecimal";return}return qe("numeric",or*0)},decimalInteger(){switch(Re){case".":Ce+=Y(),Ae="decimalPoint";return;case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalPointLeading(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}throw He(Y())},decimalPoint(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalFraction";return}return qe("numeric",or*Number(Ce))},decimalFraction(){switch(Re){case"e":case"E":Ce+=Y(),Ae="decimalExponent";return}if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},decimalExponent(){switch(Re){case"+":case"-":Ce+=Y(),Ae="decimalExponentSign";return}if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentSign(){if(rt.isDigit(Re)){Ce+=Y(),Ae="decimalExponentInteger";return}throw He(Y())},decimalExponentInteger(){if(rt.isDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},hexadecimal(){if(rt.isHexDigit(Re)){Ce+=Y(),Ae="hexadecimalInteger";return}throw He(Y())},hexadecimalInteger(){if(rt.isHexDigit(Re)){Ce+=Y();return}return qe("numeric",or*Number(Ce))},string(){switch(Re){case"\\":Y(),Ce+=_O();return;case'"':if(Li)return Y(),qe("string",Ce);Ce+=Y();return;case"'":if(!Li)return Y(),qe("string",Ce);Ce+=Y();return;case`
|
|
56
|
+
`:case"\r":throw He(Y());case"\u2028":case"\u2029":wO(Re);break;case void 0:throw He(Y())}Ce+=Y()},start(){switch(Re){case"{":case"[":return qe("punctuator",Y())}Ae="value"},beforePropertyName(){switch(Re){case"$":case"_":Ce=Y(),Ae="identifierName";return;case"\\":Y(),Ae="identifierNameStartEscape";return;case"}":return qe("punctuator",Y());case'"':case"'":Li=Y()==='"',Ae="string";return}if(rt.isIdStartChar(Re)){Ce+=Y(),Ae="identifierName";return}throw He(Y())},afterPropertyName(){if(Re===":")return qe("punctuator",Y());throw He(Y())},beforePropertyValue(){Ae="value"},afterPropertyValue(){switch(Re){case",":case"}":return qe("punctuator",Y())}throw He(Y())},beforeArrayValue(){if(Re==="]")return qe("punctuator",Y());Ae="value"},afterArrayValue(){switch(Re){case",":case"]":return qe("punctuator",Y())}throw He(Y())},end(){throw He(Y())}};function qe(t,e){return{type:t,value:e,line:Br,column:Zt}}function ho(t){for(let e of t){if(ir()!==e)throw He(Y());Y()}}function _O(){switch(ir()){case"b":return Y(),"\b";case"f":return Y(),"\f";case"n":return Y(),`
|
|
57
|
+
`;case"r":return Y(),"\r";case"t":return Y()," ";case"v":return Y(),"\v";case"0":if(Y(),rt.isDigit(ir()))throw He(Y());return"\0";case"x":return Y(),bO();case"u":return Y(),th();case`
|
|
58
58
|
`:case"\u2028":case"\u2029":return Y(),"";case"\r":return Y(),ir()===`
|
|
59
|
-
`&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw He(Y());case void 0:throw He(Y())}return Y()}function
|
|
59
|
+
`&&Y(),"";case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":throw He(Y());case void 0:throw He(Y())}return Y()}function bO(){let t="",e=ir();if(!rt.isHexDigit(e)||(t+=Y(),e=ir(),!rt.isHexDigit(e)))throw He(Y());return t+=Y(),String.fromCodePoint(parseInt(t,16))}function th(){let t="",e=4;for(;e-- >0;){let n=ir();if(!rt.isHexDigit(n))throw He(Y());t+=Y()}return String.fromCodePoint(parseInt(t,16))}var CO={start(){if(ot.type==="eof")throw go();Qp()},beforePropertyName(){switch(ot.type){case"identifier":case"string":nh=ot.value,yt="afterPropertyName";return;case"punctuator":Mc();return;case"eof":throw go()}},afterPropertyName(){if(ot.type==="eof")throw go();yt="beforePropertyValue"},beforePropertyValue(){if(ot.type==="eof")throw go();Qp()},beforeArrayValue(){if(ot.type==="eof")throw go();if(ot.type==="punctuator"&&ot.value==="]"){Mc();return}Qp()},afterPropertyValue(){if(ot.type==="eof")throw go();switch(ot.value){case",":yt="beforePropertyName";return;case"}":Mc()}},afterArrayValue(){if(ot.type==="eof")throw go();switch(ot.value){case",":yt="beforeArrayValue";return;case"]":Mc()}},end(){}};function Qp(){let t;switch(ot.type){case"punctuator":switch(ot.value){case"{":t={};break;case"[":t=[];break}break;case"null":case"boolean":case"numeric":case"string":t=ot.value;break}if($i===void 0)$i=t;else{let e=sr[sr.length-1];Array.isArray(e)?e.push(t):Object.defineProperty(e,nh,{value:t,writable:!0,enumerable:!0,configurable:!0})}if(t!==null&&typeof t=="object")sr.push(t),Array.isArray(t)?yt="beforeArrayValue":yt="beforePropertyName";else{let e=sr[sr.length-1];e==null?yt="end":Array.isArray(e)?yt="afterArrayValue":yt="afterPropertyValue"}}function Mc(){sr.pop();let t=sr[sr.length-1];t==null?yt="end":Array.isArray(t)?yt="afterArrayValue":yt="afterPropertyValue"}function He(t){return Uc(t===void 0?`JSON5: invalid end of input at ${Br}:${Zt}`:`JSON5: invalid character '${UC(t)}' at ${Br}:${Zt}`)}function go(){return Uc(`JSON5: invalid end of input at ${Br}:${Zt}`)}function MC(){return Zt-=5,Uc(`JSON5: invalid identifier character at ${Br}:${Zt}`)}function wO(t){console.warn(`JSON5: '${UC(t)}' in strings is not valid ECMAScript; consider escaping`)}function UC(t){let e={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"};if(e[t])return e[t];if(t<" "){let n=t.charCodeAt(0).toString(16);return"\\x"+("00"+n).substring(n.length)}return t}function Uc(t){let e=new SyntaxError(t);return e.lineNumber=Br,e.columnNumber=Zt,e}});var qC=G((_H,$C)=>{var rh=Xp();$C.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 y of n){let k;typeof y=="string"?k=y:(typeof y=="number"||y instanceof String||y instanceof Number)&&(k=String(y)),k!==void 0&&i.indexOf(k)<0&&i.push(k)}}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(y,k){let b=k[y];switch(b!=null&&(typeof b.toJSON5=="function"?b=b.toJSON5(y):typeof b.toJSON=="function"&&(b=b.toJSON(y))),a&&(b=a.call(k,y,b)),b instanceof Number?b=Number(b):b instanceof String?b=String(b):b instanceof Boolean&&(b=b.valueOf()),b){case null:return"null";case!0:return"true";case!1:return"false"}if(typeof b=="string")return p(b,!1);if(typeof b=="number")return String(b);if(typeof b=="object")return Array.isArray(b)?C(b):h(b)}function p(y){let k={"'":.1,'"':.2},b={"'":"\\'",'"':'\\"',"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t","\v":"\\v","\0":"\\0","\u2028":"\\u2028","\u2029":"\\u2029"},A="";for(let E=0;E<y.length;E++){let x=y[E];switch(x){case"'":case'"':k[x]++,A+=x;continue;case"\0":if(rh.isDigit(y[E+1])){A+="\\x00";continue}}if(b[x]){A+=b[x];continue}if(x<" "){let O=x.charCodeAt(0).toString(16);A+="\\x"+("00"+O).substring(O.length);continue}A+=x}let w=d||Object.keys(k).reduce((E,x)=>k[E]<k[x]?E:x);return A=A.replace(new RegExp(w,"g"),b[w]),w+A+w}function h(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let k=s;s=s+u;let b=i||Object.keys(y),A=[];for(let E of b){let x=f(E,y);if(x!==void 0){let O=g(E)+":";u!==""&&(O+=" "),O+=x,A.push(O)}}let w;if(A.length===0)w="{}";else{let E;if(u==="")E=A.join(","),w="{"+E+"}";else{let x=`,
|
|
60
60
|
`+s;E=A.join(x),w=`{
|
|
61
61
|
`+s+E+`,
|
|
62
|
-
`+k+"}"}}return o.pop(),s=k,w}function g(
|
|
62
|
+
`+k+"}"}}return o.pop(),s=k,w}function g(y){if(y.length===0)return p(y,!0);let k=String.fromCodePoint(y.codePointAt(0));if(!rh.isIdStartChar(k))return p(y,!0);for(let b=k.length;b<y.length;b++)if(!rh.isIdContinueChar(String.fromCodePoint(y.codePointAt(b))))return p(y,!0);return y}function C(y){if(o.indexOf(y)>=0)throw TypeError("Converting circular structure to JSON5");o.push(y);let k=s;s=s+u;let b=[];for(let w=0;w<y.length;w++){let E=f(String(w),y);b.push(E!==void 0?E:"null")}let A;if(b.length===0)A="[]";else if(u==="")A="["+b.join(",")+"]";else{let w=`,
|
|
63
63
|
`+s,E=b.join(w);A=`[
|
|
64
64
|
`+s+E+`,
|
|
65
|
-
`+k+"]"}return o.pop(),s=k,A}}});var Yp=G((lH,BC)=>{var _O=FC(),bO=MC(),CO={parse:_O,stringify:bO};BC.exports=CO});var hk=G((k3,I1)=>{I1.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 gk=G((S3,F1)=>{F1.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 mk=G((A3,N1)=>{N1.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 yk=G((E3,M1)=>{M1.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 _k=G((v3,B1)=>{B1.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 bk=G((T3,j1)=>{j1.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 Ck=G((x3,U1)=>{U1.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 wk=G((R3,L1)=>{L1.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 kk=G((D3,$1)=>{$1.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 vk=G((O3,Ek)=>{var q1=hk(),H1=gk(),Sk=mk(),z1=yk(),W1=_k(),G1=bk(),J1=Ck(),K1=wk(),V1=kk(),Ak=function(t,e){return t[e]!==void 0?t[e]:e};function Lr(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+=Ak(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=Ak(n,i)}return r}Ek.exports=function(t){return Object.keys(Sk).forEach(function(e){var n=Sk[e];t=t.replace(e,n)}),t=Lr(t,"^",H1),t=Lr(t,"_",q1),t=Lr(t,"\\bb",z1),t=Lr(t,"\\bf",W1),t=Lr(t,"\\it",K1),t=Lr(t,"\\cal",G1),t=Lr(t,"\\frak",J1),t=Lr(t,"\\mono",V1),t}});var Vh=G((D8,rS)=>{"use strict";var Ru=Object.prototype.hasOwnProperty,nS=Object.prototype.toString,Yk=Object.defineProperty,Xk=Object.getOwnPropertyDescriptor,Qk=function(e){return typeof Array.isArray=="function"?Array.isArray(e):nS.call(e)==="[object Array]"},Zk=function(e){if(!e||nS.call(e)!=="[object Object]")return!1;var n=Ru.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Ru.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Ru.call(e,o)},eS=function(e,n){Yk&&n.name==="__proto__"?Yk(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},tS=function(e,n){if(n==="__proto__")if(Ru.call(e,n)){if(Xk)return Xk(e,n).value}else return;return e[n]};rS.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=tS(a,n),o=tS(e,n),a!==o&&(f&&o&&(Zk(o)||(s=Qk(o)))?(s?(s=!1,i=r&&Qk(r)?r:[]):i=r&&Zk(r)?r:{},eS(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&eS(a,{name:n,newValue:o}));return a}});var oS=G((O8,vI)=>{vI.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 iS=G((P8,sS)=>{"use strict";var TI=oS();sS.exports={pkg:TI}});var Qh=G(qt=>{"use strict";var cS=qt&&qt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qt,"__esModule",{value:!0});qt.GaxiosError=qt.GAXIOS_ERROR_SYMBOL=void 0;qt.defaultErrorRedactor=uS;var aS=cS(Vh()),xI=cS(iS()),Yh=xI.default.pkg;qt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Yh.name}-gaxios-error`);var Xh=class t extends Error{config;response;code;status;error;[qt.GAXIOS_ERROR_SYMBOL]=Yh.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&qt.GAXIOS_ERROR_SYMBOL in e&&e[qt.GAXIOS_ERROR_SYMBOL]===Yh.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,aS.default)(!0,{},n),this.response&&(this.response.config=(0,aS.default)(!0,{},this.response.config)),this.response){try{this.response.data=RI(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let a of e.data.error.errors)typeof a=="object"&&"message"in a&&typeof a.message=="string"&&i.push(a.message);return Object.assign({message:i.join(`
|
|
66
|
-
`)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};qt.GaxiosError=Xh;function RI(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 uS(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&&(uS({config:t.response.config}),n(t.response.headers),t.response.bodyUsed&&(r(t.response,"data"),o(t.response.data))),t}});var dS=G(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});Zh.getRetryConfig=DI;async function DI(t){let e=lS(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||OI)(t))return{shouldRetry:!1,config:t.config};let o=PI(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 OI(t){let e=lS(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 lS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function PI(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 tg=G(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.GaxiosInterceptorManager=void 0;var eg=class extends Set{};Du.GaxiosInterceptorManager=eg});var pS=G((M8,fS)=>{var bs=1e3,Cs=bs*60,ws=Cs*60,Ao=ws*24,II=Ao*7,FI=Ao*365.25;fS.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return NI(t);if(n==="number"&&isFinite(t))return e.long?BI(t):MI(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function NI(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*FI;case"weeks":case"week":case"w":return n*II;case"days":case"day":case"d":return n*Ao;case"hours":case"hour":case"hrs":case"hr":case"h":return n*ws;case"minutes":case"minute":case"mins":case"min":case"m":return n*Cs;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 MI(t){var e=Math.abs(t);return e>=Ao?Math.round(t/Ao)+"d":e>=ws?Math.round(t/ws)+"h":e>=Cs?Math.round(t/Cs)+"m":e>=bs?Math.round(t/bs)+"s":t+"ms"}function BI(t){var e=Math.abs(t);return e>=Ao?Ou(t,e,Ao,"day"):e>=ws?Ou(t,e,ws,"hour"):e>=Cs?Ou(t,e,Cs,"minute"):e>=bs?Ou(t,e,bs,"second"):t+" ms"}function Ou(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var ng=G((B8,hS)=>{function jI(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=pS(),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,C;function _(...k){if(!_.enabled)return;let b=_,A=Number(new Date),w=A-(p||A);b.diff=w,b.prev=p,b.curr=A,p=A,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";E++;let V=n.formatters[q];if(typeof V=="function"){let U=k[E];O=V.call(b,U),k.splice(E,1),E--}return O}),n.formatArgs.call(b,k),(b.log||n.log).apply(b,k)}return _.namespace=f,_.useColors=n.useColors(),_.color=n.selectColor(f),_.extend=r,_.destroy=n.destroy,Object.defineProperty(_,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==n.namespaces&&(g=n.namespaces,C=n.enabled(f)),C),set:k=>{h=k}}),typeof n.init=="function"&&n.init(_),_}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,C=-1,_=0;for(;h<f.length;)if(g<p.length&&(p[g]===f[h]||p[g]==="*"))p[g]==="*"?(C=g,_=h,g++):(h++,g++);else if(C!==-1)g=C+1,_++,h=_;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}hS.exports=jI});var gS=G((Et,Pu)=>{Et.formatArgs=LI;Et.save=$I;Et.load=qI;Et.useColors=UI;Et.storage=HI();Et.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Et.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function UI(){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 LI(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Pu.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}Et.log=console.debug||console.log||(()=>{});function $I(t){try{t?Et.storage.setItem("debug",t):Et.storage.removeItem("debug")}catch{}}function qI(){let t;try{t=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function HI(){try{return localStorage}catch{}}Pu.exports=ng()(Et);var{formatters:zI}=Pu.exports;zI.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var yS=G((j8,mS)=>{"use strict";mS.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 CS=G((U8,bS)=>{"use strict";var WI=re("os"),_S=re("tty"),Ht=yS(),{env:st}=process,Iu;Ht("no-color")||Ht("no-colors")||Ht("color=false")||Ht("color=never")?Iu=0:(Ht("color")||Ht("colors")||Ht("color=true")||Ht("color=always"))&&(Iu=1);function GI(){if("FORCE_COLOR"in st)return st.FORCE_COLOR==="true"?1:st.FORCE_COLOR==="false"?0:st.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(st.FORCE_COLOR,10),3)}function JI(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function KI(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=GI();r!==void 0&&(Iu=r);let o=n?Iu:r;if(o===0)return 0;if(n){if(Ht("color=16m")||Ht("color=full")||Ht("color=truecolor"))return 3;if(Ht("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(st.TERM==="dumb")return s;if(process.platform==="win32"){let i=WI.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in st)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in st)||st.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in st)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(st.TEAMCITY_VERSION)?1:0;if(st.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in st){let i=Number.parseInt((st.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(st.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(st.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(st.TERM)||"COLORTERM"in st?1:s}function rg(t,e={}){let n=KI(t,{streamIsTTY:t&&t.isTTY,...e});return JI(n)}bS.exports={supportsColor:rg,stdout:rg({isTTY:_S.isatty(1)}),stderr:rg({isTTY:_S.isatty(2)})}});var kS=G((it,Nu)=>{var VI=re("tty"),Fu=re("util");it.init=nF;it.log=ZI;it.formatArgs=XI;it.save=eF;it.load=tF;it.useColors=YI;it.destroy=Fu.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");it.colors=[6,2,3,4,5,1];try{let t=CS();t&&(t.stderr||t).level>=2&&(it.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}it.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function YI(){return"colors"in it.inspectOpts?!!it.inspectOpts.colors:VI.isatty(process.stderr.fd)}function XI(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
|
+
`+k+"]"}return o.pop(),s=k,A}}});var oh=G((bH,HC)=>{var kO=LC(),SO=qC(),AO={parse:kO,stringify:SO};HC.exports=AO});var Ck=G((F3,U1)=>{U1.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 wk=G((N3,j1)=>{j1.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 kk=G((M3,L1)=>{L1.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 Sk=G((B3,$1)=>{$1.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 Ak=G((U3,q1)=>{q1.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 Ek=G((j3,H1)=>{H1.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 vk=G((L3,z1)=>{z1.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 Tk=G(($3,W1)=>{W1.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 xk=G((q3,G1)=>{G1.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 Pk=G((H3,Ok)=>{var J1=Ck(),K1=wk(),Rk=kk(),V1=Sk(),Y1=Ak(),X1=Ek(),Q1=vk(),Z1=Tk(),eI=xk(),Dk=function(t,e){return t[e]!==void 0?t[e]:e};function Lr(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+=Dk(n,i),o="normal";continue}else if(o==="long"&&i==="}"){o="normal";continue}o==="normal"?r+=i:r+=Dk(n,i)}return r}Ok.exports=function(t){return Object.keys(Rk).forEach(function(e){var n=Rk[e];t=t.replace(e,n)}),t=Lr(t,"^",K1),t=Lr(t,"_",J1),t=Lr(t,"\\bb",V1),t=Lr(t,"\\bf",Y1),t=Lr(t,"\\it",Z1),t=Lr(t,"\\cal",X1),t=Lr(t,"\\frak",Q1),t=Lr(t,"\\mono",eI),t}});var rg=G((q8,uS)=>{"use strict";var Nu=Object.prototype.hasOwnProperty,cS=Object.prototype.toString,nS=Object.defineProperty,rS=Object.getOwnPropertyDescriptor,oS=function(e){return typeof Array.isArray=="function"?Array.isArray(e):cS.call(e)==="[object Array]"},sS=function(e){if(!e||cS.call(e)!=="[object Object]")return!1;var n=Nu.call(e,"constructor"),r=e.constructor&&e.constructor.prototype&&Nu.call(e.constructor.prototype,"isPrototypeOf");if(e.constructor&&!n&&!r)return!1;var o;for(o in e);return typeof o>"u"||Nu.call(e,o)},iS=function(e,n){nS&&n.name==="__proto__"?nS(e,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):e[n.name]=n.newValue},aS=function(e,n){if(n==="__proto__")if(Nu.call(e,n)){if(rS)return rS(e,n).value}else return;return e[n]};uS.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=aS(a,n),o=aS(e,n),a!==o&&(f&&o&&(sS(o)||(s=oS(o)))?(s?(s=!1,i=r&&oS(r)?r:[]):i=r&&sS(r)?r:{},iS(a,{name:n,newValue:t(f,i,o)})):typeof o<"u"&&iS(a,{name:n,newValue:o}));return a}});var lS=G((H8,OI)=>{OI.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 fS=G((z8,dS)=>{"use strict";var PI=lS();dS.exports={pkg:PI}});var ig=G(qt=>{"use strict";var hS=qt&&qt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(qt,"__esModule",{value:!0});qt.GaxiosError=qt.GAXIOS_ERROR_SYMBOL=void 0;qt.defaultErrorRedactor=gS;var pS=hS(rg()),II=hS(fS()),og=II.default.pkg;qt.GAXIOS_ERROR_SYMBOL=Symbol.for(`${og.name}-gaxios-error`);var sg=class t extends Error{config;response;code;status;error;[qt.GAXIOS_ERROR_SYMBOL]=og.version;static[Symbol.hasInstance](e){return e&&typeof e=="object"&&qt.GAXIOS_ERROR_SYMBOL in e&&e[qt.GAXIOS_ERROR_SYMBOL]===og.version?!0:Function.prototype[Symbol.hasInstance].call(t,e)}constructor(e,n,r,o){if(super(e,{cause:o}),this.config=n,this.response=r,this.error=o instanceof Error?o:void 0,this.config=(0,pS.default)(!0,{},n),this.response&&(this.response.config=(0,pS.default)(!0,{},this.response.config)),this.response){try{this.response.data=FI(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}o instanceof DOMException?this.code=o.name:o&&typeof o=="object"&&"code"in o&&(typeof o.code=="string"||typeof o.code=="number")&&(this.code=o.code)}static extractAPIErrorFromResponse(e,n="The request failed"){let r=n;if(typeof e.data=="string"&&(r=e.data),e.data&&typeof e.data=="object"&&"error"in e.data&&e.data.error&&!e.ok){if(typeof e.data.error=="string")return{message:e.data.error,code:e.status,status:e.statusText};if(typeof e.data.error=="object"){r="message"in e.data.error&&typeof e.data.error.message=="string"?e.data.error.message:r;let o="status"in e.data.error&&typeof e.data.error.status=="string"?e.data.error.status:e.statusText,s="code"in e.data.error&&typeof e.data.error.code=="number"?e.data.error.code:e.status;if("errors"in e.data.error&&Array.isArray(e.data.error.errors)){let i=[];for(let a of e.data.error.errors)typeof a=="object"&&"message"in a&&typeof a.message=="string"&&i.push(a.message);return Object.assign({message:i.join(`
|
|
66
|
+
`)||r,code:s,status:o},e.data.error)}return Object.assign({message:r,code:s,status:o},e.data.error)}}return{message:r,code:e.status,status:e.statusText}}};qt.GaxiosError=sg;function FI(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 yS=G(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});ag.getRetryConfig=NI;async function NI(t){let e=mS(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||MI)(t))return{shouldRetry:!1,config:t.config};let o=BI(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 MI(t){let e=mS(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 mS(t){if(t&&t.config&&t.config.retryConfig)return t.config.retryConfig}function BI(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(Mu=>{"use strict";Object.defineProperty(Mu,"__esModule",{value:!0});Mu.GaxiosInterceptorManager=void 0;var cg=class extends Set{};Mu.GaxiosInterceptorManager=cg});var bS=G((K8,_S)=>{var bs=1e3,Cs=bs*60,ws=Cs*60,Ao=ws*24,UI=Ao*7,jI=Ao*365.25;_S.exports=function(t,e){e=e||{};var n=typeof t;if(n==="string"&&t.length>0)return LI(t);if(n==="number"&&isFinite(t))return e.long?qI(t):$I(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function LI(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*jI;case"weeks":case"week":case"w":return n*UI;case"days":case"day":case"d":return n*Ao;case"hours":case"hour":case"hrs":case"hr":case"h":return n*ws;case"minutes":case"minute":case"mins":case"min":case"m":return n*Cs;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 $I(t){var e=Math.abs(t);return e>=Ao?Math.round(t/Ao)+"d":e>=ws?Math.round(t/ws)+"h":e>=Cs?Math.round(t/Cs)+"m":e>=bs?Math.round(t/bs)+"s":t+"ms"}function qI(t){var e=Math.abs(t);return e>=Ao?Bu(t,e,Ao,"day"):e>=ws?Bu(t,e,ws,"hour"):e>=Cs?Bu(t,e,Cs,"minute"):e>=bs?Bu(t,e,bs,"second"):t+" ms"}function Bu(t,e,n,r){var o=e>=n*1.5;return Math.round(t/n)+" "+r+(o?"s":"")}});var lg=G((V8,CS)=>{function HI(t){n.debug=n,n.default=n,n.coerce=u,n.disable=i,n.enable=o,n.enabled=a,n.humanize=bS(),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,C;function y(...k){if(!y.enabled)return;let b=y,A=Number(new Date),w=A-(p||A);b.diff=w,b.prev=p,b.curr=A,p=A,k[0]=n.coerce(k[0]),typeof k[0]!="string"&&k.unshift("%O");let E=0;k[0]=k[0].replace(/%([a-zA-Z%])/g,(O,q)=>{if(O==="%%")return"%";E++;let V=n.formatters[q];if(typeof V=="function"){let j=k[E];O=V.call(b,j),k.splice(E,1),E--}return O}),n.formatArgs.call(b,k),(b.log||n.log).apply(b,k)}return y.namespace=f,y.useColors=n.useColors(),y.color=n.selectColor(f),y.extend=r,y.destroy=n.destroy,Object.defineProperty(y,"enabled",{enumerable:!0,configurable:!1,get:()=>h!==null?h:(g!==n.namespaces&&(g=n.namespaces,C=n.enabled(f)),C),set:k=>{h=k}}),typeof n.init=="function"&&n.init(y),y}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,C=-1,y=0;for(;h<f.length;)if(g<p.length&&(p[g]===f[h]||p[g]==="*"))p[g]==="*"?(C=g,y=h,g++):(h++,g++);else if(C!==-1)g=C+1,y++,h=y;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}CS.exports=HI});var wS=G((Et,Uu)=>{Et.formatArgs=WI;Et.save=GI;Et.load=JI;Et.useColors=zI;Et.storage=KI();Et.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Et.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function zI(){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 WI(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Uu.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let n=0,r=0;t[0].replace(/%[a-zA-Z%]/g,o=>{o!=="%%"&&(n++,o==="%c"&&(r=n))}),t.splice(r,0,e)}Et.log=console.debug||console.log||(()=>{});function GI(t){try{t?Et.storage.setItem("debug",t):Et.storage.removeItem("debug")}catch{}}function JI(){let t;try{t=Et.storage.getItem("debug")||Et.storage.getItem("DEBUG")}catch{}return!t&&typeof process<"u"&&"env"in process&&(t=process.env.DEBUG),t}function KI(){try{return localStorage}catch{}}Uu.exports=lg()(Et);var{formatters:VI}=Uu.exports;VI.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var SS=G((Y8,kS)=>{"use strict";kS.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 vS=G((X8,ES)=>{"use strict";var YI=re("os"),AS=re("tty"),Ht=SS(),{env:st}=process,ju;Ht("no-color")||Ht("no-colors")||Ht("color=false")||Ht("color=never")?ju=0:(Ht("color")||Ht("colors")||Ht("color=true")||Ht("color=always"))&&(ju=1);function XI(){if("FORCE_COLOR"in st)return st.FORCE_COLOR==="true"?1:st.FORCE_COLOR==="false"?0:st.FORCE_COLOR.length===0?1:Math.min(Number.parseInt(st.FORCE_COLOR,10),3)}function QI(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function ZI(t,{streamIsTTY:e,sniffFlags:n=!0}={}){let r=XI();r!==void 0&&(ju=r);let o=n?ju:r;if(o===0)return 0;if(n){if(Ht("color=16m")||Ht("color=full")||Ht("color=truecolor"))return 3;if(Ht("color=256"))return 2}if(t&&!e&&o===void 0)return 0;let s=o||0;if(st.TERM==="dumb")return s;if(process.platform==="win32"){let i=YI.release().split(".");return Number(i[0])>=10&&Number(i[2])>=10586?Number(i[2])>=14931?3:2:1}if("CI"in st)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE","DRONE"].some(i=>i in st)||st.CI_NAME==="codeship"?1:s;if("TEAMCITY_VERSION"in st)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(st.TEAMCITY_VERSION)?1:0;if(st.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in st){let i=Number.parseInt((st.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(st.TERM_PROGRAM){case"iTerm.app":return i>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(st.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(st.TERM)||"COLORTERM"in st?1:s}function dg(t,e={}){let n=ZI(t,{streamIsTTY:t&&t.isTTY,...e});return QI(n)}ES.exports={supportsColor:dg,stdout:dg({isTTY:AS.isatty(1)}),stderr:dg({isTTY:AS.isatty(2)})}});var xS=G((it,$u)=>{var eF=re("tty"),Lu=re("util");it.init=aF;it.log=oF;it.formatArgs=nF;it.save=sF;it.load=iF;it.useColors=tF;it.destroy=Lu.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");it.colors=[6,2,3,4,5,1];try{let t=vS();t&&(t.stderr||t).level>=2&&(it.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}it.inspectOpts=Object.keys(process.env).filter(t=>/^debug_/i.test(t)).reduce((t,e)=>{let n=e.substring(6).toLowerCase().replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),t[n]=r,t},{});function tF(){return"colors"in it.inspectOpts?!!it.inspectOpts.colors:eF.isatty(process.stderr.fd)}function nF(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+"
|
|
69
|
-
`)}function
|
|
70
|
-
`).map(e=>e.trim()).join(" ")};
|
|
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
|
|
68
|
+
`+s),t.push(o+"m+"+$u.exports.humanize(this.diff)+"\x1B[0m")}else t[0]=rF()+e+" "+t[0]}function rF(){return it.inspectOpts.hideDate?"":new Date().toISOString()+" "}function oF(...t){return process.stderr.write(Lu.formatWithOptions(it.inspectOpts,...t)+`
|
|
69
|
+
`)}function sF(t){t?process.env.DEBUG=t:delete process.env.DEBUG}function iF(){return process.env.DEBUG}function aF(t){t.inspectOpts={};let e=Object.keys(it.inspectOpts);for(let n=0;n<e.length;n++)t.inspectOpts[e[n]]=it.inspectOpts[e[n]]}$u.exports=lg()(it);var{formatters:TS}=$u.exports;TS.o=function(t){return this.inspectOpts.colors=this.useColors,Lu.inspect(t,this.inspectOpts).split(`
|
|
70
|
+
`).map(e=>e.trim()).join(" ")};TS.O=function(t){return this.inspectOpts.colors=this.useColors,Lu.inspect(t,this.inspectOpts)}});var pg=G((Q8,fg)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?fg.exports=wS():fg.exports=xS()});var OS=G(vt=>{"use strict";var cF=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]})),uF=vt&&vt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),RS=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)&&cF(e,t,n);return uF(e,t),e};Object.defineProperty(vt,"__esModule",{value:!0});vt.req=vt.json=vt.toBuffer=void 0;var lF=RS(re("http")),dF=RS(re("https"));async function DS(t){let e=0,n=[];for await(let r of t)e+=r.length,n.push(r);return Buffer.concat(n,e)}vt.toBuffer=DS;async function fF(t){let n=(await DS(t)).toString("utf8");try{return JSON.parse(n)}catch(r){let o=r;throw o.message+=` (input: ${n})`,o}}vt.json=fF;function pF(t,e={}){let r=((typeof t=="string"?t:t.href).startsWith("https:")?dF:lF).request(t,e),o=new Promise((s,i)=>{r.once("response",s).once("error",i).end()});return r.then=o.then.bind(o),r}vt.req=pF});var NS=G(Pt=>{"use strict";var IS=Pt&&Pt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),hF=Pt&&Pt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),FS=Pt&&Pt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&IS(e,t,n);return hF(e,t),e},gF=Pt&&Pt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&IS(e,t,n)};Object.defineProperty(Pt,"__esModule",{value:!0});Pt.Agent=void 0;var mF=FS(re("net")),PS=FS(re("http")),yF=re("https");gF(OS(),Pt);var Pn=Symbol("AgentBaseInternalState"),hg=class extends PS.Agent{constructor(e){super(e),this[Pn]={}}isSecureEndpoint(e){if(e){if(typeof e.secureEndpoint=="boolean")return e.secureEndpoint;if(typeof e.protocol=="string")return e.protocol==="https:"}let{stack:n}=new Error;return typeof n!="string"?!1:n.split(`
|
|
71
|
+
`).some(r=>r.indexOf("(https.js:")!==-1||r.indexOf("node:https:")!==-1)}incrementSockets(e){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;this.sockets[e]||(this.sockets[e]=[]);let n=new mF.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)?yF.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 PS.Agent)try{return a.addRequest(e,o)}catch(u){return r(u)}this[Pn].currentSocket=a,super.createSocket(e,n,r)},a=>{this.decrementSockets(s,i),r(a)})}createConnection(){let e=this[Pn].currentSocket;if(this[Pn].currentSocket=void 0,!e)throw new Error("No socket was returned in the `connect()` function");return e}get defaultPort(){return this[Pn].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(e){this[Pn]&&(this[Pn].defaultPort=e)}get protocol(){return this[Pn].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(e){this[Pn]&&(this[Pn].protocol=e)}};Pt.Agent=hg});var MS=G(ks=>{"use strict";var _F=ks&&ks.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ks,"__esModule",{value:!0});ks.parseProxyResponse=void 0;var bF=_F(pg()),qu=(0,bF.default)("https-proxy-agent:parse-proxy-response");function CF(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(),qu("onend"),n(new Error("Proxy connection ended before receiving CONNECT response"))}function u(f){i(),qu("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){
|
|
74
|
-
`),C=g.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let
|
|
73
|
+
`);if(h===-1){qu("have not received end of HTTP headers yet..."),s();return}let g=p.slice(0,h).toString("ascii").split(`\r
|
|
74
|
+
`),C=g.shift();if(!C)return t.destroy(),n(new Error("No header received from proxy CONNECT response"));let y=C.split(" "),k=+y[1],b=y.slice(2).join(" "),A={};for(let w of g){if(!w)continue;let E=w.indexOf(":");if(E===-1)return t.destroy(),n(new Error(`Invalid header from proxy CONNECT response: "${w}"`));let x=w.slice(0,E).toLowerCase(),O=w.slice(E+1).trimStart(),q=A[x];typeof q=="string"?A[x]=[q,O]:Array.isArray(q)?q.push(O):A[x]=O}qu("got proxy server response: %o %o",C,A),i(),e({connect:{statusCode:k,statusText:b,headers:A},buffered:p})}t.on("error",u),t.on("end",a),s()})}ks.parseProxyResponse=CF});var qS=G(zt=>{"use strict";var wF=zt&&zt.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),kF=zt&&zt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),LS=zt&&zt.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)n!=="default"&&Object.prototype.hasOwnProperty.call(t,n)&&wF(e,t,n);return kF(e,t),e},$S=zt&&zt.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(zt,"__esModule",{value:!0});zt.HttpsProxyAgent=void 0;var Hu=LS(re("net")),BS=LS(re("tls")),SF=$S(re("assert")),AF=$S(pg()),EF=NS(),vF=re("url"),TF=MS(),ta=(0,AF.default)("https-proxy-agent"),US=t=>t.servername===void 0&&t.host&&!Hu.isIP(t.host)?{...t,servername:t.host}:t,zu=class extends EF.Agent{constructor(e,n){super(n),this.options={path:void 0},this.proxy=typeof e=="string"?new vF.URL(e):e,this.proxyHeaders=n?.headers??{},ta("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?jS(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:"?(ta("Creating `tls.Socket`: %o",this.connectOpts),o=BS.connect(US(this.connectOpts))):(ta("Creating `net.Socket`: %o",this.connectOpts),o=Hu.connect(this.connectOpts));let s=typeof this.proxyHeaders=="function"?this.proxyHeaders():{...this.proxyHeaders},i=Hu.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,
|
|
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",
|
|
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,C,_,k=It(E=>{this[E+"Mark"]=n},"mark"),b=It(E=>{delete this[E+"Mark"]},"clear"),A=It((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),w=It((E,x)=>{let O=E+"Mark";O in this&&(x?(A(E,this[O],n,e),delete this[O]):(A(E,this[O],e.length,e),this[O]=0))},"dataCallback");for(n=0;n<r;n++)switch(C=e[n],d){case Ue.START_BOUNDARY:if(u===i.length-2){if(C===na)f|=Hr.LAST_BOUNDARY;else if(C!==$u)return;u++;break}else if(u-1===i.length-2){if(f&Hr.LAST_BOUNDARY&&C===na)d=Ue.END,f=0;else if(!(f&Hr.LAST_BOUNDARY)&&C===Lu)u=0,A("onPartBegin"),d=Ue.HEADER_FIELD_START;else return;break}C!==i[u+2]&&(u=-2),C===i[u+2]&&u++;break;case Ue.HEADER_FIELD_START:d=Ue.HEADER_FIELD,k("onHeaderField"),u=0;case Ue.HEADER_FIELD:if(C===$u){b("onHeaderField"),d=Ue.HEADERS_ALMOST_DONE;break}if(u++,C===na)break;if(C===xF){if(u===1)return;w("onHeaderField",!0),d=Ue.HEADER_VALUE_START;break}if(_=OF(C),_<RF||_>DF)return;break;case Ue.HEADER_VALUE_START:if(C===TF)break;k("onHeaderValue"),d=Ue.HEADER_VALUE;case Ue.HEADER_VALUE:C===$u&&(w("onHeaderValue",!0),A("onHeaderEnd"),d=Ue.HEADER_VALUE_ALMOST_DONE);break;case Ue.HEADER_VALUE_ALMOST_DONE:if(C!==Lu)return;d=Ue.HEADER_FIELD_START;break;case Ue.HEADERS_ALMOST_DONE:if(C!==Lu)return;A("onHeadersEnd"),d=Ue.PART_DATA_START;break;case Ue.PART_DATA_START:d=Ue.PART_DATA,k("onPartData");case Ue.PART_DATA:if(o=u,u===0){for(n+=h;n<g&&!(e[n]in a);)n+=p;n-=h,C=e[n]}if(u<i.length)i[u]===C?(u===0&&w("onPartData",!0),u++):u=0;else if(u===i.length)u++,C===$u?f|=Hr.PART_BOUNDARY:C===na?f|=Hr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&Hr.PART_BOUNDARY){if(u=0,C===Lu){f&=~Hr.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),d=Ue.HEADER_FIELD_START;break}}else f&Hr.LAST_BOUNDARY&&C===na?(A("onPartEnd"),d=Ue.END,f=0):u=0;if(u>0)s[u-1]=C;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);A("onPartData",0,o,E),o=0,k("onPartData"),n--}break;case Ue.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=u,this.state=d,this.flags=f}end(){if(this.state===Ue.HEADER_FIELD_START&&this.index===0||this.state===Ue.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==Ue.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};It(jS,"MultipartParser");PF=jS;It(US,"_fileName");It(LS,"toFormData")});import ua from"node:http";import FF from"node:https";import Es from"node:zlib";import Mn,{PassThrough as Xu,pipeline as vs}from"node:stream";import{Buffer as pt}from"node:buffer";import{types as Qu,deprecate as Zu,promisify as NF}from"node:util";import{format as MF}from"node:url";import{isIP as BF}from"node:net";import{promises as jF,statSync as tA,createReadStream as UF}from"node:fs";import{basename as LF}from"node:path";function nA(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 rA(){return zS||(zS=1,(function(t,e){(function(n,r){r(e)})($F,function(n){function r(){}m(r,"noop");function o(c){return typeof c=="object"&&c!==null||typeof c=="function"}m(o,"typeIsObject");let s=r;function i(c,l){try{Object.defineProperty(c,"name",{value:l,configurable:!0})}catch{}}m(i,"setFunctionName");let a=Promise,u=Promise.prototype.then,d=Promise.reject.bind(a);function f(c){return new a(c)}m(f,"newPromise");function p(c){return f(l=>l(c))}m(p,"promiseResolvedWith");function h(c){return d(c)}m(h,"promiseRejectedWith");function g(c,l,y){return u.call(c,l,y)}m(g,"PerformPromiseThen");function C(c,l,y){g(g(c,l,y),void 0,s)}m(C,"uponPromise");function _(c,l){C(c,l)}m(_,"uponFulfillment");function k(c,l){C(c,void 0,l)}m(k,"uponRejection");function b(c,l,y){return g(c,l,y)}m(b,"transformPromiseWith");function A(c){g(c,void 0,s)}m(A,"setPromiseIsHandledToTrue");let w=m(c=>{if(typeof queueMicrotask=="function")w=queueMicrotask;else{let l=p(void 0);w=m(y=>g(l,y),"_queueMicrotask")}return w(c)},"_queueMicrotask");function E(c,l,y){if(typeof c!="function")throw new TypeError("Argument is not a function");return Function.prototype.apply.call(c,l,y)}m(E,"reflectCall");function x(c,l,y){try{return p(E(c,l,y))}catch(v){return h(v)}}m(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 y=this._back,v=y;y._elements.length===O-1&&(v={_elements:[],_next:void 0}),y._elements.push(l),v!==y&&(this._back=v,y._next=v),++this._size}shift(){let l=this._front,y=l,v=this._cursor,I=v+1,$=l._elements,W=$[v];return I===O&&(y=l._next,I=0),--this._size,this._cursor=I,l!==y&&(this._front=y),$[v]=void 0,W}forEach(l){let y=this._cursor,v=this._front,I=v._elements;for(;(y!==I.length||v._next!==void 0)&&!(y===I.length&&(v=v._next,I=v._elements,y=0,I.length===0));)l(I[y]),++y}peek(){let l=this._front,y=this._cursor;return l._elements[y]}};m(q,"SimpleQueue");let V=q,U=Symbol("[[AbortSteps]]"),ee=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),te=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function _e(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ae(c):Z(c,l._storedError)}m(_e,"ReadableStreamReaderGenericInitialize");function Oe(c,l){let y=c._ownerReadableStream;return jt(y,l)}m(Oe,"ReadableStreamReaderGenericCancel");function Te(c){let l=c._ownerReadableStream;l._state==="readable"?Ie(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):we(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._readableStreamController[Q](),l._reader=void 0,c._ownerReadableStream=void 0}m(Te,"ReadableStreamReaderGenericRelease");function Ge(c){return new TypeError("Cannot "+c+" a stream using a released reader")}m(Ge,"readerLockException");function ne(c){c._closedPromise=f((l,y)=>{c._closedPromise_resolve=l,c._closedPromise_reject=y})}m(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Ie(c,l)}m(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ae(c){ne(c),H(c)}m(ae,"defaultReaderClosedPromiseInitializeAsResolved");function Ie(c,l){c._closedPromise_reject!==void 0&&(A(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}m(Ie,"defaultReaderClosedPromiseReject");function we(c,l){Z(c,l)}m(we,"defaultReaderClosedPromiseResetToRejected");function H(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}m(H,"defaultReaderClosedPromiseResolve");let Ee=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},Ze=Math.trunc||function(c){return c<0?Math.ceil(c):Math.floor(c)};function X(c){return typeof c=="object"||typeof c=="function"}m(X,"isDictionary");function de(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}m(de,"assertDictionary");function ce(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}m(ce,"assertFunction");function S(c){return typeof c=="object"&&c!==null||typeof c=="function"}m(S,"isObject");function T(c,l){if(!S(c))throw new TypeError(`${l} is not an object.`)}m(T,"assertObject");function R(c,l,y){if(c===void 0)throw new TypeError(`Parameter ${l} is required in '${y}'.`)}m(R,"assertRequiredArgument");function M(c,l,y){if(c===void 0)throw new TypeError(`${l} is required in '${y}'.`)}m(M,"assertRequiredField");function D(c){return Number(c)}m(D,"convertUnrestrictedDouble");function F(c){return c===0?0:c}m(F,"censorNegativeZero");function L(c){return F(Ze(c))}m(L,"integerPart");function P(c,l){let y=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ee(v))throw new TypeError(`${l} is not a finite number`);if(v=L(v),v<0||v>y)throw new TypeError(`${l} is outside the accepted range of 0 to ${y}, inclusive`);return!Ee(v)||v===0?0:v}m(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!Qn(c))throw new TypeError(`${l} is not a ReadableStream.`)}m(N,"assertReadableStream");function j(c){return new me(c)}m(j,"AcquireReadableStreamDefaultReader");function B(c,l){c._reader._readRequests.push(l)}m(B,"ReadableStreamAddReadRequest");function K(c,l,y){let v=c._reader._readRequests.shift();y?v._closeSteps():v._chunkSteps(l)}m(K,"ReadableStreamFulfillReadRequest");function ie(c){return c._reader._readRequests.length}m(ie,"ReadableStreamGetNumReadRequests");function ue(c){let l=c._reader;return!(l===void 0||!he(l))}m(ue,"ReadableStreamHasDefaultReader");let be=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");_e(this,l),this._readRequests=new V}get closed(){return he(this)?this._closedPromise:h(mn("closed"))}cancel(l=void 0){return he(this)?this._ownerReadableStream===void 0?h(Ge("cancel")):Oe(this,l):h(mn("cancel"))}read(){if(!he(this))return h(mn("read"));if(this._ownerReadableStream===void 0)return h(Ge("read from"));let l,y,v=f((I,$)=>{l=I,y=$});return ye(this,{_chunkSteps:m(I=>l({value:I,done:!1}),"_chunkSteps"),_closeSteps:m(()=>l({value:void 0,done:!0}),"_closeSteps"),_errorSteps:m(I=>y(I),"_errorSteps")}),v}releaseLock(){if(!he(this))throw mn("releaseLock");this._ownerReadableStream!==void 0&&Fe(this)}};m(be,"ReadableStreamDefaultReader");let me=be;Object.defineProperties(me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(me.prototype.cancel,"cancel"),i(me.prototype.read,"read"),i(me.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(me.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function he(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof me}m(he,"IsReadableStreamDefaultReader");function ye(c,l){let y=c._ownerReadableStream;y._disturbed=!0,y._state==="closed"?l._closeSteps():y._state==="errored"?l._errorSteps(y._storedError):y._readableStreamController[te](l)}m(ye,"ReadableStreamDefaultReaderRead");function Fe(c){Te(c);let l=new TypeError("Reader was released");Ye(c,l)}m(Fe,"ReadableStreamDefaultReaderRelease");function Ye(c,l){let y=c._readRequests;c._readRequests=new V,y.forEach(v=>{v._errorSteps(l)})}m(Ye,"ReadableStreamDefaultReaderErrorReadRequests");function mn(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}m(mn,"defaultReaderBrandCheckException");let ui=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),Uo=class{constructor(l,y){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=y}next(){let l=m(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?b(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let y=m(()=>this._returnSteps(l),"returnSteps");return this._ongoingPromise?b(this._ongoingPromise,y,y):y()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,y,v,I=f(($,W)=>{y=$,v=W});return ye(l,{_chunkSteps:m($=>{this._ongoingPromise=void 0,w(()=>y({value:$,done:!1}))},"_chunkSteps"),_closeSteps:m(()=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),y({value:void 0,done:!0})},"_closeSteps"),_errorSteps:m($=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),v($)},"_errorSteps")}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let y=this._reader;if(!this._preventCancel){let v=Oe(y,l);return Te(y),b(v,()=>({value:l,done:!0}))}return Te(y),p({value:l,done:!0})}};m(Uo,"ReadableStreamAsyncIteratorImpl");let xt=Uo,Sr={next(){return et(this)?this._asyncIteratorImpl.next():h(je("next"))},return(c){return et(this)?this._asyncIteratorImpl.return(c):h(je("return"))}};Object.setPrototypeOf(Sr,ui);function ht(c,l){let y=j(c),v=new xt(y,l),I=Object.create(Sr);return I._asyncIteratorImpl=v,I}m(ht,"AcquireReadableStreamAsyncIterator");function et(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof xt}catch{return!1}}m(et,"IsReadableStreamAsyncIterator");function je(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}m(je,"streamAsyncIteratorBrandCheckException");let X_=Number.isNaN||function(c){return c!==c};var Cf,wf,kf;function Lo(c){return c.slice()}m(Lo,"CreateArrayFromList");function Sf(c,l,y,v,I){new Uint8Array(c).set(new Uint8Array(y,v,I),l)}m(Sf,"CopyDataBlockBytes");let Jn=m(c=>(typeof c.transfer=="function"?Jn=m(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Jn=m(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):Jn=m(l=>l,"TransferArrayBuffer"),Jn(c)),"TransferArrayBuffer"),Ar=m(c=>(typeof c.detached=="boolean"?Ar=m(l=>l.detached,"IsDetachedBuffer"):Ar=m(l=>l.byteLength===0,"IsDetachedBuffer"),Ar(c)),"IsDetachedBuffer");function Af(c,l,y){if(c.slice)return c.slice(l,y);let v=y-l,I=new ArrayBuffer(v);return Sf(I,0,c,l,v),I}m(Af,"ArrayBufferSlice");function li(c,l){let y=c[l];if(y!=null){if(typeof y!="function")throw new TypeError(`${String(l)} is not a function`);return y}}m(li,"GetMethod");function Q_(c){let l={[Symbol.iterator]:()=>c.iterator},y=(async function*(){return yield*l})(),v=y.next;return{iterator:y,nextMethod:v,done:!1}}m(Q_,"CreateAsyncFromSyncIterator");let Ef=(kf=(Cf=Symbol.asyncIterator)!==null&&Cf!==void 0?Cf:(wf=Symbol.for)===null||wf===void 0?void 0:wf.call(Symbol,"Symbol.asyncIterator"))!==null&&kf!==void 0?kf:"@@asyncIterator";function vf(c,l="sync",y){if(y===void 0)if(l==="async"){if(y=li(c,Ef),y===void 0){let $=li(c,Symbol.iterator),W=vf(c,"sync",$);return Q_(W)}}else y=li(c,Symbol.iterator);if(y===void 0)throw new TypeError("The object is not iterable");let v=E(y,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}}m(vf,"GetIterator");function Z_(c){let l=E(c.nextMethod,c.iterator,[]);if(!o(l))throw new TypeError("The iterator.next() method must return an object");return l}m(Z_,"IteratorNext");function e0(c){return!!c.done}m(e0,"IteratorComplete");function t0(c){return c.value}m(t0,"IteratorValue");function n0(c){return!(typeof c!="number"||X_(c)||c<0)}m(n0,"IsNonNegativeNumber");function Tf(c){let l=Af(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}m(Tf,"CloneAsUint8Array");function za(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}m(za,"DequeueValue");function Wa(c,l,y){if(!n0(y)||y===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:y}),c._queueTotalSize+=y}m(Wa,"EnqueueValueWithSize");function r0(c){return c._queue.peek().value}m(r0,"PeekQueueValue");function Kn(c){c._queue=new V,c._queueTotalSize=0}m(Kn,"ResetQueue");function xf(c){return c===DataView}m(xf,"isDataViewConstructor");function o0(c){return xf(c.constructor)}m(o0,"isDataView");function s0(c){return xf(c)?1:c.BYTES_PER_ELEMENT}m(s0,"arrayBufferViewElementSize");let i0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ga(this))throw Xa("view");return this._view}respond(l){if(!Ga(this))throw Xa("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(Ar(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");hi(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!Ga(this))throw Xa("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(Ar(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");gi(this._associatedReadableByteStreamController,l)}};m(i0,"ReadableStreamBYOBRequest");let no=i0;Object.defineProperties(no.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(no.prototype.respond,"respond"),i(no.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(no.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let a0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Er(this))throw qo("byobRequest");return Ya(this)}get desiredSize(){if(!Er(this))throw qo("desiredSize");return jf(this)}close(){if(!Er(this))throw qo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw new TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);$o(this)}enqueue(l){if(!Er(this))throw qo("enqueue");if(R(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let y=this._controlledReadableByteStream._state;if(y!=="readable")throw new TypeError(`The stream (in ${y} state) is not in the readable state and cannot be enqueued to`);pi(this,l)}error(l=void 0){if(!Er(this))throw qo("error");Rt(this,l)}[z](l){Rf(this),Kn(this);let y=this._cancelAlgorithm(l);return fi(this),y}[te](l){let y=this._controlledReadableByteStream;if(this._queueTotalSize>0){Bf(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(y,l),vr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};m(a0,"ReadableByteStreamController");let Vn=a0;Object.defineProperties(Vn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Vn.prototype.close,"close"),i(Vn.prototype.enqueue,"enqueue"),i(Vn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Vn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Er(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof Vn}m(Er,"IsReadableByteStreamController");function Ga(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof no}m(Ga,"IsReadableStreamBYOBRequest");function vr(c){if(!f0(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();C(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,vr(c)),null),y=>(Rt(c,y),null))}m(vr,"ReadableByteStreamControllerCallPullIfNeeded");function Rf(c){Ka(c),c._pendingPullIntos=new V}m(Rf,"ReadableByteStreamControllerClearPendingPullIntos");function Ja(c,l){let y=!1;c._state==="closed"&&(y=!0);let v=Df(l);l.readerType==="default"?K(c,v,y):_0(c,v,y)}m(Ja,"ReadableByteStreamControllerCommitPullIntoDescriptor");function Df(c){let l=c.bytesFilled,y=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/y)}m(Df,"ReadableByteStreamControllerConvertPullIntoDescriptor");function di(c,l,y,v){c._queue.push({buffer:l,byteOffset:y,byteLength:v}),c._queueTotalSize+=v}m(di,"ReadableByteStreamControllerEnqueueChunkToQueue");function Of(c,l,y,v){let I;try{I=Af(l,y,y+v)}catch($){throw Rt(c,$),$}di(c,I,0,v)}m(Of,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function Pf(c,l){l.bytesFilled>0&&Of(c,l.buffer,l.byteOffset,l.bytesFilled),ro(c)}m(Pf,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function If(c,l){let y=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+y,I=y,$=!1,W=v%l.elementSize,se=v-W;se>=l.minimumFill&&(I=se-l.bytesFilled,$=!0);let le=c._queue;for(;I>0;){let ge=le.peek(),ke=Math.min(I,ge.byteLength),Se=l.byteOffset+l.bytesFilled;Sf(l.buffer,Se,ge.buffer,ge.byteOffset,ke),ge.byteLength===ke?le.shift():(ge.byteOffset+=ke,ge.byteLength-=ke),c._queueTotalSize-=ke,Ff(c,ke,l),I-=ke}return $}m(If,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function Ff(c,l,y){y.bytesFilled+=l}m(Ff,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function Nf(c){c._queueTotalSize===0&&c._closeRequested?(fi(c),Vo(c._controlledReadableByteStream)):vr(c)}m(Nf,"ReadableByteStreamControllerHandleQueueDrain");function Ka(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}m(Ka,"ReadableByteStreamControllerInvalidateBYOBRequest");function Va(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();If(c,l)&&(ro(c),Ja(c._controlledReadableByteStream,l))}}m(Va,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function c0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let y=l._readRequests.shift();Bf(c,y)}}m(c0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function u0(c,l,y,v){let I=c._controlledReadableByteStream,$=l.constructor,W=s0($),{byteOffset:se,byteLength:le}=l,ge=y*W,ke;try{ke=Jn(l.buffer)}catch(Be){v._errorSteps(Be);return}let Se={buffer:ke,bufferByteLength:ke.byteLength,byteOffset:se,byteLength:le,bytesFilled:0,minimumFill:ge,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(Se),$f(I,v);return}if(I._state==="closed"){let Be=new $(Se.buffer,Se.byteOffset,0);v._closeSteps(Be);return}if(c._queueTotalSize>0){if(If(c,Se)){let Be=Df(Se);Nf(c),v._chunkSteps(Be);return}if(c._closeRequested){let Be=new TypeError("Insufficient bytes to fill elements in the given buffer");Rt(c,Be),v._errorSteps(Be);return}}c._pendingPullIntos.push(Se),$f(I,v),vr(c)}m(u0,"ReadableByteStreamControllerPullInto");function l0(c,l){l.readerType==="none"&&ro(c);let y=c._controlledReadableByteStream;if(Qa(y))for(;qf(y)>0;){let v=ro(c);Ja(y,v)}}m(l0,"ReadableByteStreamControllerRespondInClosedState");function d0(c,l,y){if(Ff(c,l,y),y.readerType==="none"){Pf(c,y),Va(c);return}if(y.bytesFilled<y.minimumFill)return;ro(c);let v=y.bytesFilled%y.elementSize;if(v>0){let I=y.byteOffset+y.bytesFilled;Of(c,y.buffer,I-v,v)}y.bytesFilled-=v,Ja(c._controlledReadableByteStream,y),Va(c)}m(d0,"ReadableByteStreamControllerRespondInReadableState");function Mf(c,l){let y=c._pendingPullIntos.peek();Ka(c),c._controlledReadableByteStream._state==="closed"?l0(c,y):d0(c,l,y),vr(c)}m(Mf,"ReadableByteStreamControllerRespondInternal");function ro(c){return c._pendingPullIntos.shift()}m(ro,"ReadableByteStreamControllerShiftPendingPullInto");function f0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ue(l)&&ie(l)>0||Qa(l)&&qf(l)>0||jf(c)>0)}m(f0,"ReadableByteStreamControllerShouldCallPull");function fi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}m(fi,"ReadableByteStreamControllerClearAlgorithms");function $o(c){let l=c._controlledReadableByteStream;if(!(c._closeRequested||l._state!=="readable")){if(c._queueTotalSize>0){c._closeRequested=!0;return}if(c._pendingPullIntos.length>0){let y=c._pendingPullIntos.peek();if(y.bytesFilled%y.elementSize!==0){let v=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Rt(c,v),v}}fi(c),Vo(l)}}m($o,"ReadableByteStreamControllerClose");function pi(c,l){let y=c._controlledReadableByteStream;if(c._closeRequested||y._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Ar(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=Jn(v);if(c._pendingPullIntos.length>0){let se=c._pendingPullIntos.peek();if(Ar(se.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Ka(c),se.buffer=Jn(se.buffer),se.readerType==="none"&&Pf(c,se)}if(ue(y))if(c0(c),ie(y)===0)di(c,W,I,$);else{c._pendingPullIntos.length>0&&ro(c);let se=new Uint8Array(W,I,$);K(y,se,!1)}else Qa(y)?(di(c,W,I,$),Va(c)):di(c,W,I,$);vr(c)}m(pi,"ReadableByteStreamControllerEnqueue");function Rt(c,l){let y=c._controlledReadableByteStream;y._state==="readable"&&(Rf(c),Kn(c),fi(c),dp(y,l))}m(Rt,"ReadableByteStreamControllerError");function Bf(c,l){let y=c._queue.shift();c._queueTotalSize-=y.byteLength,Nf(c);let v=new Uint8Array(y.buffer,y.byteOffset,y.byteLength);l._chunkSteps(v)}m(Bf,"ReadableByteStreamControllerFillReadRequestFromQueue");function Ya(c){if(c._byobRequest===null&&c._pendingPullIntos.length>0){let l=c._pendingPullIntos.peek(),y=new Uint8Array(l.buffer,l.byteOffset+l.bytesFilled,l.byteLength-l.bytesFilled),v=Object.create(no.prototype);h0(v,c,y),c._byobRequest=v}return c._byobRequest}m(Ya,"ReadableByteStreamControllerGetBYOBRequest");function jf(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}m(jf,"ReadableByteStreamControllerGetDesiredSize");function hi(c,l){let y=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(y.bytesFilled+l>y.byteLength)throw new RangeError("bytesWritten out of range")}y.buffer=Jn(y.buffer),Mf(c,l)}m(hi,"ReadableByteStreamControllerRespond");function gi(c,l){let y=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(y.byteOffset+y.bytesFilled!==l.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(y.bufferByteLength!==l.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(y.bytesFilled+l.byteLength>y.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let v=l.byteLength;y.buffer=Jn(l.buffer),Mf(c,v)}m(gi,"ReadableByteStreamControllerRespondWithNewView");function Uf(c,l,y,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,Kn(l),l._closeRequested=!1,l._started=!1,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,l._autoAllocateChunkSize=W,l._pendingPullIntos=new V,c._readableStreamController=l;let se=y();C(p(se),()=>(l._started=!0,vr(l),null),le=>(Rt(l,le),null))}m(Uf,"SetUpReadableByteStreamController");function p0(c,l,y){let v=Object.create(Vn.prototype),I,$,W;l.start!==void 0?I=m(()=>l.start(v),"startAlgorithm"):I=m(()=>{},"startAlgorithm"),l.pull!==void 0?$=m(()=>l.pull(v),"pullAlgorithm"):$=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?W=m(le=>l.cancel(le),"cancelAlgorithm"):W=m(()=>p(void 0),"cancelAlgorithm");let se=l.autoAllocateChunkSize;if(se===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Uf(c,v,I,$,W,y,se)}m(p0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function h0(c,l,y){c._associatedReadableByteStreamController=l,c._view=y}m(h0,"SetUpReadableStreamBYOBRequest");function Xa(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}m(Xa,"byobRequestBrandCheckException");function qo(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}m(qo,"byteStreamControllerBrandCheckException");function g0(c,l){de(c,l);let y=c?.mode;return{mode:y===void 0?void 0:m0(y,`${l} has member 'mode' that`)}}m(g0,"convertReaderOptions");function m0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}m(m0,"convertReadableStreamReaderMode");function y0(c,l){var y;de(c,l);let v=(y=c?.min)!==null&&y!==void 0?y:1;return{min:P(v,`${l} has member 'min' that`)}}m(y0,"convertByobReadOptions");function Lf(c){return new Tr(c)}m(Lf,"AcquireReadableStreamBYOBReader");function $f(c,l){c._reader._readIntoRequests.push(l)}m($f,"ReadableStreamAddReadIntoRequest");function _0(c,l,y){let v=c._reader._readIntoRequests.shift();y?v._closeSteps(l):v._chunkSteps(l)}m(_0,"ReadableStreamFulfillReadIntoRequest");function qf(c){return c._reader._readIntoRequests.length}m(qf,"ReadableStreamGetNumReadIntoRequests");function Qa(c){let l=c._reader;return!(l===void 0||!xr(l))}m(Qa,"ReadableStreamHasBYOBReader");let b0=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Er(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");_e(this,l),this._readIntoRequests=new V}get closed(){return xr(this)?this._closedPromise:h(mi("closed"))}cancel(l=void 0){return xr(this)?this._ownerReadableStream===void 0?h(Ge("cancel")):Oe(this,l):h(mi("cancel"))}read(l,y={}){if(!xr(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(Ar(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=y0(y,"options")}catch(le){return h(le)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(o0(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(Ge("read from"));let $,W,se=f((le,ge)=>{$=le,W=ge});return Hf(this,l,I,{_chunkSteps:m(le=>$({value:le,done:!1}),"_chunkSteps"),_closeSteps:m(le=>$({value:le,done:!0}),"_closeSteps"),_errorSteps:m(le=>W(le),"_errorSteps")}),se}releaseLock(){if(!xr(this))throw mi("releaseLock");this._ownerReadableStream!==void 0&&C0(this)}};m(b0,"ReadableStreamBYOBReader");let Tr=b0;Object.defineProperties(Tr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(Tr.prototype.cancel,"cancel"),i(Tr.prototype.read,"read"),i(Tr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function xr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof Tr}m(xr,"IsReadableStreamBYOBReader");function Hf(c,l,y,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):u0(I._readableStreamController,l,y,v)}m(Hf,"ReadableStreamBYOBReaderRead");function C0(c){Te(c);let l=new TypeError("Reader was released");zf(c,l)}m(C0,"ReadableStreamBYOBReaderRelease");function zf(c,l){let y=c._readIntoRequests;c._readIntoRequests=new V,y.forEach(v=>{v._errorSteps(l)})}m(zf,"ReadableStreamBYOBReaderErrorReadIntoRequests");function mi(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}m(mi,"byobReaderBrandCheckException");function Ho(c,l){let{highWaterMark:y}=c;if(y===void 0)return l;if(X_(y)||y<0)throw new RangeError("Invalid highWaterMark");return y}m(Ho,"ExtractHighWaterMark");function yi(c){let{size:l}=c;return l||(()=>1)}m(yi,"ExtractSizeAlgorithm");function _i(c,l){de(c,l);let y=c?.highWaterMark,v=c?.size;return{highWaterMark:y===void 0?void 0:D(y),size:v===void 0?void 0:w0(v,`${l} has member 'size' that`)}}m(_i,"convertQueuingStrategy");function w0(c,l){return ce(c,l),y=>D(c(y))}m(w0,"convertQueuingStrategySize");function k0(c,l){de(c,l);let y=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:y===void 0?void 0:S0(y,c,`${l} has member 'abort' that`),close:v===void 0?void 0:A0(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:E0(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:v0(W,c,`${l} has member 'write' that`),type:$}}m(k0,"convertUnderlyingSink");function S0(c,l,y){return ce(c,y),v=>x(c,l,[v])}m(S0,"convertUnderlyingSinkAbortCallback");function A0(c,l,y){return ce(c,y),()=>x(c,l,[])}m(A0,"convertUnderlyingSinkCloseCallback");function E0(c,l,y){return ce(c,y),v=>E(c,l,[v])}m(E0,"convertUnderlyingSinkStartCallback");function v0(c,l,y){return ce(c,y),(v,I)=>x(c,l,[v,I])}m(v0,"convertUnderlyingSinkWriteCallback");function Wf(c,l){if(!oo(c))throw new TypeError(`${l} is not a WritableStream.`)}m(Wf,"assertWritableStream");function T0(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}m(T0,"isAbortSignal");let KR=typeof AbortController=="function";function x0(){if(KR)return new AbortController}m(x0,"createAbortController");let R0=class{constructor(l={},y={}){l===void 0?l=null:T(l,"First parameter");let v=_i(y,"Second parameter"),I=k0(l,"First parameter");if(Jf(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=yi(v),W=Ho(v,1);G0(this,I,W,$)}get locked(){if(!oo(this))throw Si("locked");return so(this)}abort(l=void 0){return oo(this)?so(this)?h(new TypeError("Cannot abort a stream that already has a writer")):bi(this,l):h(Si("abort"))}close(){return oo(this)?so(this)?h(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?h(new TypeError("Cannot close an already-closing stream")):Kf(this):h(Si("close"))}getWriter(){if(!oo(this))throw Si("getWriter");return Gf(this)}};m(R0,"WritableStream");let Rr=R0;Object.defineProperties(Rr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Rr.prototype.abort,"abort"),i(Rr.prototype.close,"close"),i(Rr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Rr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function Gf(c){return new Yn(c)}m(Gf,"AcquireWritableStreamDefaultWriter");function D0(c,l,y,v,I=1,$=()=>1){let W=Object.create(Rr.prototype);Jf(W);let se=Object.create(zo.prototype);return Zf(W,se,c,l,y,v,I,$),W}m(D0,"CreateWritableStream");function Jf(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}m(Jf,"InitializeWritableStream");function oo(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Rr}m(oo,"IsWritableStream");function so(c){return c._writer!==void 0}m(so,"IsWritableStreamLocked");function bi(c,l){var y;if(c._state==="closed"||c._state==="errored")return p(void 0);c._writableStreamController._abortReason=l,(y=c._writableStreamController._abortController)===null||y===void 0||y.abort(l);let v=c._state;if(v==="closed"||v==="errored")return p(void 0);if(c._pendingAbortRequest!==void 0)return c._pendingAbortRequest._promise;let I=!1;v==="erroring"&&(I=!0,l=void 0);let $=f((W,se)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:se,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||ec(c,l),$}m(bi,"WritableStreamAbort");function Kf(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 y=f((I,$)=>{let W={_resolve:I,_reject:$};c._closeRequest=W}),v=c._writer;return v!==void 0&&c._backpressure&&l==="writable"&&cc(v),J0(c._writableStreamController),y}m(Kf,"WritableStreamClose");function O0(c){return f((l,y)=>{let v={_resolve:l,_reject:y};c._writeRequests.push(v)})}m(O0,"WritableStreamAddWriteRequest");function Za(c,l){if(c._state==="writable"){ec(c,l);return}tc(c)}m(Za,"WritableStreamDealWithRejection");function ec(c,l){let y=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&Yf(v,l),!M0(c)&&y._started&&tc(c)}m(ec,"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){Ci(c);return}let y=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,y._wasAlreadyErroring){y._reject(l),Ci(c);return}let v=c._writableStreamController[U](y._reason);C(v,()=>(y._resolve(),Ci(c),null),I=>(y._reject(I),Ci(c),null))}m(tc,"WritableStreamFinishErroring");function P0(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}m(P0,"WritableStreamFinishInFlightWrite");function I0(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,Za(c,l)}m(I0,"WritableStreamFinishInFlightWriteWithError");function F0(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&&rp(l)}m(F0,"WritableStreamFinishInFlightClose");function N0(c,l){c._inFlightCloseRequest._reject(l),c._inFlightCloseRequest=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._reject(l),c._pendingAbortRequest=void 0),Za(c,l)}m(N0,"WritableStreamFinishInFlightCloseWithError");function Xt(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}m(Xt,"WritableStreamCloseQueuedOrInFlight");function M0(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}m(M0,"WritableStreamHasOperationMarkedInFlight");function B0(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}m(B0,"WritableStreamMarkCloseRequestInFlight");function j0(c){c._inFlightWriteRequest=c._writeRequests.shift()}m(j0,"WritableStreamMarkFirstWriteRequestInFlight");function Ci(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&ic(l,c._storedError)}m(Ci,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function nc(c,l){let y=c._writer;y!==void 0&&l!==c._backpressure&&(l?eb(y):cc(y)),c._backpressure=l}m(nc,"WritableStreamUpdateBackpressure");let U0=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Wf(l,"First parameter"),so(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let y=l._state;if(y==="writable")!Xt(l)&&l._backpressure?Ei(this):op(this),Ai(this);else if(y==="erroring")ac(this,l._storedError),Ai(this);else if(y==="closed")op(this),Q0(this);else{let v=l._storedError;ac(this,v),np(this,v)}}get closed(){return Dr(this)?this._closedPromise:h(Or("closed"))}get desiredSize(){if(!Dr(this))throw Or("desiredSize");if(this._ownerWritableStream===void 0)throw Go("desiredSize");return H0(this)}get ready(){return Dr(this)?this._readyPromise:h(Or("ready"))}abort(l=void 0){return Dr(this)?this._ownerWritableStream===void 0?h(Go("abort")):L0(this,l):h(Or("abort"))}close(){if(!Dr(this))return h(Or("close"));let l=this._ownerWritableStream;return l===void 0?h(Go("close")):Xt(l)?h(new TypeError("Cannot close an already-closing stream")):Vf(this)}releaseLock(){if(!Dr(this))throw Or("releaseLock");this._ownerWritableStream!==void 0&&Xf(this)}write(l=void 0){return Dr(this)?this._ownerWritableStream===void 0?h(Go("write to")):Qf(this,l):h(Or("write"))}};m(U0,"WritableStreamDefaultWriter");let Yn=U0;Object.defineProperties(Yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(Yn.prototype.abort,"abort"),i(Yn.prototype.close,"close"),i(Yn.prototype.releaseLock,"releaseLock"),i(Yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Dr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof Yn}m(Dr,"IsWritableStreamDefaultWriter");function L0(c,l){let y=c._ownerWritableStream;return bi(y,l)}m(L0,"WritableStreamDefaultWriterAbort");function Vf(c){let l=c._ownerWritableStream;return Kf(l)}m(Vf,"WritableStreamDefaultWriterClose");function $0(c){let l=c._ownerWritableStream,y=l._state;return Xt(l)||y==="closed"?p(void 0):y==="errored"?h(l._storedError):Vf(c)}m($0,"WritableStreamDefaultWriterCloseWithErrorPropagation");function q0(c,l){c._closedPromiseState==="pending"?ic(c,l):Z0(c,l)}m(q0,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function Yf(c,l){c._readyPromiseState==="pending"?sp(c,l):tb(c,l)}m(Yf,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function H0(c){let l=c._ownerWritableStream,y=l._state;return y==="errored"||y==="erroring"?null:y==="closed"?0:ep(l._writableStreamController)}m(H0,"WritableStreamDefaultWriterGetDesiredSize");function Xf(c){let l=c._ownerWritableStream,y=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Yf(c,y),q0(c,y),l._writer=void 0,c._ownerWritableStream=void 0}m(Xf,"WritableStreamDefaultWriterRelease");function Qf(c,l){let y=c._ownerWritableStream,v=y._writableStreamController,I=K0(v,l);if(y!==c._ownerWritableStream)return h(Go("write to"));let $=y._state;if($==="errored")return h(y._storedError);if(Xt(y)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(y._storedError);let W=O0(y);return V0(v,l,I),W}m(Qf,"WritableStreamDefaultWriterWrite");let z0={},W0=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!rc(this))throw sc("abortReason");return this._abortReason}get signal(){if(!rc(this))throw sc("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 sc("error");this._controlledWritableStream._state==="writable"&&tp(this,l)}[U](l){let y=this._abortAlgorithm(l);return wi(this),y}[ee](){Kn(this)}};m(W0,"WritableStreamDefaultController");let zo=W0;Object.defineProperties(zo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function rc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof zo}m(rc,"IsWritableStreamDefaultController");function Zf(c,l,y,v,I,$,W,se){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._abortReason=void 0,l._abortController=x0(),l._started=!1,l._strategySizeAlgorithm=se,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let le=oc(l);nc(c,le);let ge=y(),ke=p(ge);C(ke,()=>(l._started=!0,ki(l),null),Se=>(l._started=!0,Za(c,Se),null))}m(Zf,"SetUpWritableStreamDefaultController");function G0(c,l,y,v){let I=Object.create(zo.prototype),$,W,se,le;l.start!==void 0?$=m(()=>l.start(I),"startAlgorithm"):$=m(()=>{},"startAlgorithm"),l.write!==void 0?W=m(ge=>l.write(ge,I),"writeAlgorithm"):W=m(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?se=m(()=>l.close(),"closeAlgorithm"):se=m(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?le=m(ge=>l.abort(ge),"abortAlgorithm"):le=m(()=>p(void 0),"abortAlgorithm"),Zf(c,I,$,W,se,le,y,v)}m(G0,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function wi(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}m(wi,"WritableStreamDefaultControllerClearAlgorithms");function J0(c){Wa(c,z0,0),ki(c)}m(J0,"WritableStreamDefaultControllerClose");function K0(c,l){try{return c._strategySizeAlgorithm(l)}catch(y){return Wo(c,y),1}}m(K0,"WritableStreamDefaultControllerGetChunkSize");function ep(c){return c._strategyHWM-c._queueTotalSize}m(ep,"WritableStreamDefaultControllerGetDesiredSize");function V0(c,l,y){try{Wa(c,l,y)}catch(I){Wo(c,I);return}let v=c._controlledWritableStream;if(!Xt(v)&&v._state==="writable"){let I=oc(c);nc(v,I)}ki(c)}m(V0,"WritableStreamDefaultControllerWrite");function ki(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 y=r0(c);y===z0?Y0(c):X0(c,y)}m(ki,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function Wo(c,l){c._controlledWritableStream._state==="writable"&&tp(c,l)}m(Wo,"WritableStreamDefaultControllerErrorIfNeeded");function Y0(c){let l=c._controlledWritableStream;B0(l),za(c);let y=c._closeAlgorithm();wi(c),C(y,()=>(F0(l),null),v=>(N0(l,v),null))}m(Y0,"WritableStreamDefaultControllerProcessClose");function X0(c,l){let y=c._controlledWritableStream;j0(y);let v=c._writeAlgorithm(l);C(v,()=>{P0(y);let I=y._state;if(za(c),!Xt(y)&&I==="writable"){let $=oc(c);nc(y,$)}return ki(c),null},I=>(y._state==="writable"&&wi(c),I0(y,I),null))}m(X0,"WritableStreamDefaultControllerProcessWrite");function oc(c){return ep(c)<=0}m(oc,"WritableStreamDefaultControllerGetBackpressure");function tp(c,l){let y=c._controlledWritableStream;wi(c),ec(y,l)}m(tp,"WritableStreamDefaultControllerError");function Si(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}m(Si,"streamBrandCheckException$2");function sc(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}m(sc,"defaultControllerBrandCheckException$2");function Or(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}m(Or,"defaultWriterBrandCheckException");function Go(c){return new TypeError("Cannot "+c+" a stream using a released writer")}m(Go,"defaultWriterLockException");function Ai(c){c._closedPromise=f((l,y)=>{c._closedPromise_resolve=l,c._closedPromise_reject=y,c._closedPromiseState="pending"})}m(Ai,"defaultWriterClosedPromiseInitialize");function np(c,l){Ai(c),ic(c,l)}m(np,"defaultWriterClosedPromiseInitializeAsRejected");function Q0(c){Ai(c),rp(c)}m(Q0,"defaultWriterClosedPromiseInitializeAsResolved");function ic(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")}m(ic,"defaultWriterClosedPromiseReject");function Z0(c,l){np(c,l)}m(Z0,"defaultWriterClosedPromiseResetToRejected");function rp(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="resolved")}m(rp,"defaultWriterClosedPromiseResolve");function Ei(c){c._readyPromise=f((l,y)=>{c._readyPromise_resolve=l,c._readyPromise_reject=y}),c._readyPromiseState="pending"}m(Ei,"defaultWriterReadyPromiseInitialize");function ac(c,l){Ei(c),sp(c,l)}m(ac,"defaultWriterReadyPromiseInitializeAsRejected");function op(c){Ei(c),cc(c)}m(op,"defaultWriterReadyPromiseInitializeAsResolved");function sp(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")}m(sp,"defaultWriterReadyPromiseReject");function eb(c){Ei(c)}m(eb,"defaultWriterReadyPromiseReset");function tb(c,l){ac(c,l)}m(tb,"defaultWriterReadyPromiseResetToRejected");function cc(c){c._readyPromise_resolve!==void 0&&(c._readyPromise_resolve(void 0),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="fulfilled")}m(cc,"defaultWriterReadyPromiseResolve");function nb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof ag<"u")return ag}m(nb,"getGlobals");let VR=nb();function rb(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}m(rb,"isDOMExceptionConstructor");function ob(){let c=VR?.DOMException;return rb(c)?c:void 0}m(ob,"getFromGlobal");function sb(){let c=m(function(l,y){this.message=l||"",this.name=y||"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}m(sb,"createPolyfill");let YR=ob()||sb();function ip(c,l,y,v,I,$){let W=j(c),se=Gf(l);c._disturbed=!0;let le=!1,ge=p(void 0);return f((ke,Se)=>{let Be;if($!==void 0){if(Be=m(()=>{let fe=$.reason!==void 0?$.reason:new YR("Aborted","AbortError"),De=[];v||De.push(()=>l._state==="writable"?bi(l,fe):p(void 0)),I||De.push(()=>c._state==="readable"?jt(c,fe):p(void 0)),gt(()=>Promise.all(De.map(Me=>Me())),!0,fe)},"abortAlgorithm"),$.aborted){Be();return}$.addEventListener("abort",Be)}function Ct(){return f((fe,De)=>{function Me(mt){mt?fe():g(er(),Me,De)}m(Me,"next"),Me(!1)})}m(Ct,"pipeLoop");function er(){return le?p(!0):g(se._readyPromise,()=>f((fe,De)=>{ye(W,{_chunkSteps:m(Me=>{ge=g(Qf(se,Me),void 0,r),fe(!1)},"_chunkSteps"),_closeSteps:m(()=>fe(!0),"_closeSteps"),_errorSteps:De})}))}if(m(er,"pipeStep"),Ut(c,W._closedPromise,fe=>(v?wt(!0,fe):gt(()=>bi(l,fe),!0,fe),null)),Ut(l,se._closedPromise,fe=>(I?wt(!0,fe):gt(()=>jt(c,fe),!0,fe),null)),tt(c,W._closedPromise,()=>(y?wt():gt(()=>$0(se)),null)),Xt(l)||l._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");I?wt(!0,fe):gt(()=>jt(c,fe),!0,fe)}A(Ct());function Qt(){let fe=ge;return g(ge,()=>fe!==ge?Qt():void 0)}m(Qt,"waitForWritesToFinish");function Ut(fe,De,Me){fe._state==="errored"?Me(fe._storedError):k(De,Me)}m(Ut,"isOrBecomesErrored");function tt(fe,De,Me){fe._state==="closed"?Me():_(De,Me)}m(tt,"isOrBecomesClosed");function gt(fe,De,Me){if(le)return;le=!0,l._state==="writable"&&!Xt(l)?_(Qt(),mt):mt();function mt(){return C(fe(),()=>tr(De,Me),Nr=>tr(!0,Nr)),null}m(mt,"doTheRest")}m(gt,"shutdownWithAction");function wt(fe,De){le||(le=!0,l._state==="writable"&&!Xt(l)?_(Qt(),()=>tr(fe,De)):tr(fe,De))}m(wt,"shutdown");function tr(fe,De){return Xf(se),Te(W),$!==void 0&&$.removeEventListener("abort",Be),fe?Se(De):ke(void 0),null}m(tr,"finalize")})}m(ip,"ReadableStreamPipeTo");let ib=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!vi(this))throw xi("desiredSize");return uc(this)}close(){if(!vi(this))throw xi("close");if(!ao(this))throw new TypeError("The stream is not in a state that permits close");Pr(this)}enqueue(l=void 0){if(!vi(this))throw xi("enqueue");if(!ao(this))throw new TypeError("The stream is not in a state that permits enqueue");return io(this,l)}error(l=void 0){if(!vi(this))throw xi("error");Bt(this,l)}[z](l){Kn(this);let y=this._cancelAlgorithm(l);return Ti(this),y}[te](l){let y=this._controlledReadableStream;if(this._queue.length>0){let v=za(this);this._closeRequested&&this._queue.length===0?(Ti(this),Vo(y)):Jo(this),l._chunkSteps(v)}else B(y,l),Jo(this)}[Q](){}};m(ib,"ReadableStreamDefaultController");let Xn=ib;Object.defineProperties(Xn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Xn.prototype.close,"close"),i(Xn.prototype.enqueue,"enqueue"),i(Xn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function vi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof Xn}m(vi,"IsReadableStreamDefaultController");function Jo(c){if(!ap(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();C(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Jo(c)),null),y=>(Bt(c,y),null))}m(Jo,"ReadableStreamDefaultControllerCallPullIfNeeded");function ap(c){let l=c._controlledReadableStream;return!ao(c)||!c._started?!1:!!(Zn(l)&&ie(l)>0||uc(c)>0)}m(ap,"ReadableStreamDefaultControllerShouldCallPull");function Ti(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}m(Ti,"ReadableStreamDefaultControllerClearAlgorithms");function Pr(c){if(!ao(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(Ti(c),Vo(l))}m(Pr,"ReadableStreamDefaultControllerClose");function io(c,l){if(!ao(c))return;let y=c._controlledReadableStream;if(Zn(y)&&ie(y)>0)K(y,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Bt(c,I),I}try{Wa(c,l,v)}catch(I){throw Bt(c,I),I}}Jo(c)}m(io,"ReadableStreamDefaultControllerEnqueue");function Bt(c,l){let y=c._controlledReadableStream;y._state==="readable"&&(Kn(c),Ti(c),dp(y,l))}m(Bt,"ReadableStreamDefaultControllerError");function uc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}m(uc,"ReadableStreamDefaultControllerGetDesiredSize");function ab(c){return!ap(c)}m(ab,"ReadableStreamDefaultControllerHasBackpressure");function ao(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}m(ao,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function cp(c,l,y,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._started=!1,l._closeRequested=!1,l._pullAgain=!1,l._pulling=!1,l._strategySizeAlgorithm=W,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,c._readableStreamController=l;let se=y();C(p(se),()=>(l._started=!0,Jo(l),null),le=>(Bt(l,le),null))}m(cp,"SetUpReadableStreamDefaultController");function cb(c,l,y,v){let I=Object.create(Xn.prototype),$,W,se;l.start!==void 0?$=m(()=>l.start(I),"startAlgorithm"):$=m(()=>{},"startAlgorithm"),l.pull!==void 0?W=m(()=>l.pull(I),"pullAlgorithm"):W=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?se=m(le=>l.cancel(le),"cancelAlgorithm"):se=m(()=>p(void 0),"cancelAlgorithm"),cp(c,I,$,W,se,y,v)}m(cb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function xi(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}m(xi,"defaultControllerBrandCheckException$1");function ub(c,l){return Er(c._readableStreamController)?db(c):lb(c)}m(ub,"ReadableStreamTee");function lb(c,l){let y=j(c),v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(tt=>{Se=tt});function Ct(){return v?(I=!0,p(void 0)):(v=!0,ye(y,{_chunkSteps:m(tt=>{w(()=>{I=!1;let gt=tt,wt=tt;$||io(ge._readableStreamController,gt),W||io(ke._readableStreamController,wt),v=!1,I&&Ct()})},"_chunkSteps"),_closeSteps:m(()=>{v=!1,$||Pr(ge._readableStreamController),W||Pr(ke._readableStreamController),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{v=!1},"_errorSteps")}),p(void 0))}m(Ct,"pullAlgorithm");function er(tt){if($=!0,se=tt,W){let gt=Lo([se,le]),wt=jt(c,gt);Se(wt)}return Be}m(er,"cancel1Algorithm");function Qt(tt){if(W=!0,le=tt,$){let gt=Lo([se,le]),wt=jt(c,gt);Se(wt)}return Be}m(Qt,"cancel2Algorithm");function Ut(){}return m(Ut,"startAlgorithm"),ge=Ko(Ut,Ct,er),ke=Ko(Ut,Ct,Qt),k(y._closedPromise,tt=>(Bt(ge._readableStreamController,tt),Bt(ke._readableStreamController,tt),(!$||!W)&&Se(void 0),null)),[ge,ke]}m(lb,"ReadableStreamDefaultTee");function db(c){let l=j(c),y=!1,v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(fe=>{Se=fe});function Ct(fe){k(fe._closedPromise,De=>(fe!==l||(Rt(ge._readableStreamController,De),Rt(ke._readableStreamController,De),(!$||!W)&&Se(void 0)),null))}m(Ct,"forwardReaderError");function er(){xr(l)&&(Te(l),l=j(c),Ct(l)),ye(l,{_chunkSteps:m(fe=>{w(()=>{v=!1,I=!1;let De=fe,Me=fe;if(!$&&!W)try{Me=Tf(fe)}catch(mt){Rt(ge._readableStreamController,mt),Rt(ke._readableStreamController,mt),Se(jt(c,mt));return}$||pi(ge._readableStreamController,De),W||pi(ke._readableStreamController,Me),y=!1,v?Ut():I&&tt()})},"_chunkSteps"),_closeSteps:m(()=>{y=!1,$||$o(ge._readableStreamController),W||$o(ke._readableStreamController),ge._readableStreamController._pendingPullIntos.length>0&&hi(ge._readableStreamController,0),ke._readableStreamController._pendingPullIntos.length>0&&hi(ke._readableStreamController,0),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{y=!1},"_errorSteps")})}m(er,"pullWithDefaultReader");function Qt(fe,De){he(l)&&(Te(l),l=Lf(c),Ct(l));let Me=De?ke:ge,mt=De?ge:ke;Hf(l,fe,1,{_chunkSteps:m(Nr=>{w(()=>{v=!1,I=!1;let Yo=De?W:$;if(De?$:W)Yo||gi(Me._readableStreamController,Nr);else{let Xo;try{Xo=Tf(Nr)}catch(kp){Rt(Me._readableStreamController,kp),Rt(mt._readableStreamController,kp),Se(jt(c,kp));return}Yo||gi(Me._readableStreamController,Nr),pi(mt._readableStreamController,Xo)}y=!1,v?Ut():I&&tt()})},"_chunkSteps"),_closeSteps:m(Nr=>{y=!1;let Yo=De?W:$,Xo=De?$:W;Yo||$o(Me._readableStreamController),Xo||$o(mt._readableStreamController),Nr!==void 0&&(Yo||gi(Me._readableStreamController,Nr),!Xo&&mt._readableStreamController._pendingPullIntos.length>0&&hi(mt._readableStreamController,0)),(!Yo||!Xo)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{y=!1},"_errorSteps")})}m(Qt,"pullWithBYOBReader");function Ut(){if(y)return v=!0,p(void 0);y=!0;let fe=Ya(ge._readableStreamController);return fe===null?er():Qt(fe._view,!1),p(void 0)}m(Ut,"pull1Algorithm");function tt(){if(y)return I=!0,p(void 0);y=!0;let fe=Ya(ke._readableStreamController);return fe===null?er():Qt(fe._view,!0),p(void 0)}m(tt,"pull2Algorithm");function gt(fe){if($=!0,se=fe,W){let De=Lo([se,le]),Me=jt(c,De);Se(Me)}return Be}m(gt,"cancel1Algorithm");function wt(fe){if(W=!0,le=fe,$){let De=Lo([se,le]),Me=jt(c,De);Se(Me)}return Be}m(wt,"cancel2Algorithm");function tr(){}return m(tr,"startAlgorithm"),ge=lp(tr,Ut,gt),ke=lp(tr,tt,wt),Ct(l),[ge,ke]}m(db,"ReadableByteStreamTee");function fb(c){return o(c)&&typeof c.getReader<"u"}m(fb,"isReadableStreamLike");function pb(c){return fb(c)?gb(c.getReader()):hb(c)}m(pb,"ReadableStreamFrom");function hb(c){let l,y=vf(c,"async"),v=r;function I(){let W;try{W=Z_(y)}catch(le){return h(le)}let se=p(W);return b(se,le=>{if(!o(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(e0(le))Pr(l._readableStreamController);else{let ge=t0(le);io(l._readableStreamController,ge)}})}m(I,"pullAlgorithm");function $(W){let se=y.iterator,le;try{le=li(se,"return")}catch(Se){return h(Se)}if(le===void 0)return p(void 0);let ge;try{ge=E(le,se,[W])}catch(Se){return h(Se)}let ke=p(ge);return b(ke,Se=>{if(!o(Se))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return m($,"cancelAlgorithm"),l=Ko(v,I,$,0),l}m(hb,"ReadableStreamFromIterable");function gb(c){let l,y=r;function v(){let $;try{$=c.read()}catch(W){return h(W)}return b($,W=>{if(!o(W))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Pr(l._readableStreamController);else{let se=W.value;io(l._readableStreamController,se)}})}m(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return m(I,"cancelAlgorithm"),l=Ko(y,v,I,0),l}m(gb,"ReadableStreamFromDefaultReader");function mb(c,l){de(c,l);let y=c,v=y?.autoAllocateChunkSize,I=y?.cancel,$=y?.pull,W=y?.start,se=y?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:yb(I,y,`${l} has member 'cancel' that`),pull:$===void 0?void 0:_b($,y,`${l} has member 'pull' that`),start:W===void 0?void 0:bb(W,y,`${l} has member 'start' that`),type:se===void 0?void 0:Cb(se,`${l} has member 'type' that`)}}m(mb,"convertUnderlyingDefaultOrByteSource");function yb(c,l,y){return ce(c,y),v=>x(c,l,[v])}m(yb,"convertUnderlyingSourceCancelCallback");function _b(c,l,y){return ce(c,y),v=>x(c,l,[v])}m(_b,"convertUnderlyingSourcePullCallback");function bb(c,l,y){return ce(c,y),v=>E(c,l,[v])}m(bb,"convertUnderlyingSourceStartCallback");function Cb(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}m(Cb,"convertReadableStreamType");function wb(c,l){return de(c,l),{preventCancel:!!c?.preventCancel}}m(wb,"convertIteratorOptions");function up(c,l){de(c,l);let y=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&kb($,`${l} has member 'signal' that`),{preventAbort:!!y,preventCancel:!!v,preventClose:!!I,signal:$}}m(up,"convertPipeOptions");function kb(c,l){if(!T0(c))throw new TypeError(`${l} is not an AbortSignal.`)}m(kb,"assertAbortSignal");function Sb(c,l){de(c,l);let y=c?.readable;M(y,"readable","ReadableWritablePair"),N(y,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),Wf(v,`${l} has member 'writable' that`),{readable:y,writable:v}}m(Sb,"convertReadableWritablePair");let Ab=class{constructor(l={},y={}){l===void 0?l=null:T(l,"First parameter");let v=_i(y,"Second parameter"),I=mb(l,"First parameter");if(lc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=Ho(v,0);p0(this,I,$)}else{let $=yi(v),W=Ho(v,1);cb(this,I,W,$)}}get locked(){if(!Qn(this))throw Ir("locked");return Zn(this)}cancel(l=void 0){return Qn(this)?Zn(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):jt(this,l):h(Ir("cancel"))}getReader(l=void 0){if(!Qn(this))throw Ir("getReader");return g0(l,"First parameter").mode===void 0?j(this):Lf(this)}pipeThrough(l,y={}){if(!Qn(this))throw Ir("pipeThrough");R(l,1,"pipeThrough");let v=Sb(l,"First parameter"),I=up(y,"Second parameter");if(Zn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(so(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=ip(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return A($),v.readable}pipeTo(l,y={}){if(!Qn(this))return h(Ir("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!oo(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=up(y,"Second parameter")}catch(I){return h(I)}return Zn(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):so(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):ip(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!Qn(this))throw Ir("tee");let l=ub(this);return Lo(l)}values(l=void 0){if(!Qn(this))throw Ir("values");let y=wb(l,"First parameter");return ht(this,y.preventCancel)}[Ef](l){return this.values(l)}static from(l){return pb(l)}};m(Ab,"ReadableStream");let dt=Ab;Object.defineProperties(dt,{from:{enumerable:!0}}),Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(dt.from,"from"),i(dt.prototype.cancel,"cancel"),i(dt.prototype.getReader,"getReader"),i(dt.prototype.pipeThrough,"pipeThrough"),i(dt.prototype.pipeTo,"pipeTo"),i(dt.prototype.tee,"tee"),i(dt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(dt.prototype,Ef,{value:dt.prototype.values,writable:!0,configurable:!0});function Ko(c,l,y,v=1,I=()=>1){let $=Object.create(dt.prototype);lc($);let W=Object.create(Xn.prototype);return cp($,W,c,l,y,v,I),$}m(Ko,"CreateReadableStream");function lp(c,l,y){let v=Object.create(dt.prototype);lc(v);let I=Object.create(Vn.prototype);return Uf(v,I,c,l,y,0,void 0),v}m(lp,"CreateReadableByteStream");function lc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}m(lc,"InitializeReadableStream");function Qn(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof dt}m(Qn,"IsReadableStream");function Zn(c){return c._reader!==void 0}m(Zn,"IsReadableStreamLocked");function jt(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);Vo(c);let y=c._reader;if(y!==void 0&&xr(y)){let I=y._readIntoRequests;y._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return b(v,r)}m(jt,"ReadableStreamCancel");function Vo(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),he(l))){let y=l._readRequests;l._readRequests=new V,y.forEach(v=>{v._closeSteps()})}}m(Vo,"ReadableStreamClose");function dp(c,l){c._state="errored",c._storedError=l;let y=c._reader;y!==void 0&&(Ie(y,l),he(y)?Ye(y,l):zf(y,l))}m(dp,"ReadableStreamError");function Ir(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}m(Ir,"streamBrandCheckException$1");function fp(c,l){de(c,l);let y=c?.highWaterMark;return M(y,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(y)}}m(fp,"convertQueuingStrategyInit");let Eb=m(c=>c.byteLength,"byteLengthSizeFunction");i(Eb,"size");let vb=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=fp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!hp(this))throw pp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!hp(this))throw pp("size");return Eb}};m(vb,"ByteLengthQueuingStrategy");let dc=vb;Object.defineProperties(dc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function pp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}m(pp,"byteLengthBrandCheckException");function hp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof dc}m(hp,"IsByteLengthQueuingStrategy");let Tb=m(()=>1,"countSizeFunction");i(Tb,"size");let xb=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=fp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!mp(this))throw gp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!mp(this))throw gp("size");return Tb}};m(xb,"CountQueuingStrategy");let fc=xb;Object.defineProperties(fc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function gp(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}m(gp,"countBrandCheckException");function mp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof fc}m(mp,"IsCountQueuingStrategy");function Rb(c,l){de(c,l);let y=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,se=c?.writableType;return{cancel:y===void 0?void 0:Ib(y,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:Db(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:Ob($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:Pb(W,c,`${l} has member 'transform' that`),writableType:se}}m(Rb,"convertTransformer");function Db(c,l,y){return ce(c,y),v=>x(c,l,[v])}m(Db,"convertTransformerFlushCallback");function Ob(c,l,y){return ce(c,y),v=>E(c,l,[v])}m(Ob,"convertTransformerStartCallback");function Pb(c,l,y){return ce(c,y),(v,I)=>x(c,l,[v,I])}m(Pb,"convertTransformerTransformCallback");function Ib(c,l,y){return ce(c,y),v=>x(c,l,[v])}m(Ib,"convertTransformerCancelCallback");let Fb=class{constructor(l={},y={},v={}){l===void 0&&(l=null);let I=_i(y,"Second parameter"),$=_i(v,"Third parameter"),W=Rb(l,"First parameter");if(W.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(W.writableType!==void 0)throw new RangeError("Invalid writableType specified");let se=Ho($,0),le=yi($),ge=Ho(I,1),ke=yi(I),Se,Be=f(Ct=>{Se=Ct});Nb(this,Be,ge,ke,se,le),jb(this,W),W.start!==void 0?Se(W.start(this._transformStreamController)):Se(void 0)}get readable(){if(!yp(this))throw wp("readable");return this._readable}get writable(){if(!yp(this))throw wp("writable");return this._writable}};m(Fb,"TransformStream");let pc=Fb;Object.defineProperties(pc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function Nb(c,l,y,v,I,$){function W(){return l}m(W,"startAlgorithm");function se(Be){return $b(c,Be)}m(se,"writeAlgorithm");function le(Be){return qb(c,Be)}m(le,"abortAlgorithm");function ge(){return Hb(c)}m(ge,"closeAlgorithm"),c._writable=D0(W,se,ge,le,y,v);function ke(){return zb(c)}m(ke,"pullAlgorithm");function Se(Be){return Wb(c,Be)}m(Se,"cancelAlgorithm"),c._readable=Ko(W,ke,Se,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Ri(c,!0),c._transformStreamController=void 0}m(Nb,"InitializeTransformStream");function yp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof pc}m(yp,"IsTransformStream");function _p(c,l){Bt(c._readable._readableStreamController,l),hc(c,l)}m(_p,"TransformStreamError");function hc(c,l){Oi(c._transformStreamController),Wo(c._writable._writableStreamController,l),gc(c)}m(hc,"TransformStreamErrorWritableAndUnblockWrite");function gc(c){c._backpressure&&Ri(c,!1)}m(gc,"TransformStreamUnblockWrite");function Ri(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(y=>{c._backpressureChangePromise_resolve=y}),c._backpressure=l}m(Ri,"TransformStreamSetBackpressure");let Mb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Di(this))throw Pi("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return uc(l)}enqueue(l=void 0){if(!Di(this))throw Pi("enqueue");bp(this,l)}error(l=void 0){if(!Di(this))throw Pi("error");Ub(this,l)}terminate(){if(!Di(this))throw Pi("terminate");Lb(this)}};m(Mb,"TransformStreamDefaultController");let Fr=Mb;Object.defineProperties(Fr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Fr.prototype.enqueue,"enqueue"),i(Fr.prototype.error,"error"),i(Fr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Di(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Fr}m(Di,"IsTransformStreamDefaultController");function Bb(c,l,y,v,I){l._controlledTransformStream=c,c._transformStreamController=l,l._transformAlgorithm=y,l._flushAlgorithm=v,l._cancelAlgorithm=I,l._finishPromise=void 0,l._finishPromise_resolve=void 0,l._finishPromise_reject=void 0}m(Bb,"SetUpTransformStreamDefaultController");function jb(c,l){let y=Object.create(Fr.prototype),v,I,$;l.transform!==void 0?v=m(W=>l.transform(W,y),"transformAlgorithm"):v=m(W=>{try{return bp(y,W),p(void 0)}catch(se){return h(se)}},"transformAlgorithm"),l.flush!==void 0?I=m(()=>l.flush(y),"flushAlgorithm"):I=m(()=>p(void 0),"flushAlgorithm"),l.cancel!==void 0?$=m(W=>l.cancel(W),"cancelAlgorithm"):$=m(()=>p(void 0),"cancelAlgorithm"),Bb(c,y,v,I,$)}m(jb,"SetUpTransformStreamDefaultControllerFromTransformer");function Oi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}m(Oi,"TransformStreamDefaultControllerClearAlgorithms");function bp(c,l){let y=c._controlledTransformStream,v=y._readable._readableStreamController;if(!ao(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{io(v,l)}catch(I){throw hc(y,I),y._readable._storedError}ab(v)!==y._backpressure&&Ri(y,!0)}m(bp,"TransformStreamDefaultControllerEnqueue");function Ub(c,l){_p(c._controlledTransformStream,l)}m(Ub,"TransformStreamDefaultControllerError");function Cp(c,l){let y=c._transformAlgorithm(l);return b(y,void 0,v=>{throw _p(c._controlledTransformStream,v),v})}m(Cp,"TransformStreamDefaultControllerPerformTransform");function Lb(c){let l=c._controlledTransformStream,y=l._readable._readableStreamController;Pr(y);let v=new TypeError("TransformStream terminated");hc(l,v)}m(Lb,"TransformStreamDefaultControllerTerminate");function $b(c,l){let y=c._transformStreamController;if(c._backpressure){let v=c._backpressureChangePromise;return b(v,()=>{let I=c._writable;if(I._state==="erroring")throw I._storedError;return Cp(y,l)})}return Cp(y,l)}m($b,"TransformStreamDefaultSinkWriteAlgorithm");function qb(c,l){let y=c._transformStreamController;if(y._finishPromise!==void 0)return y._finishPromise;let v=c._readable;y._finishPromise=f(($,W)=>{y._finishPromise_resolve=$,y._finishPromise_reject=W});let I=y._cancelAlgorithm(l);return Oi(y),C(I,()=>(v._state==="errored"?co(y,v._storedError):(Bt(v._readableStreamController,l),mc(y)),null),$=>(Bt(v._readableStreamController,$),co(y,$),null)),y._finishPromise}m(qb,"TransformStreamDefaultSinkAbortAlgorithm");function Hb(c){let l=c._transformStreamController;if(l._finishPromise!==void 0)return l._finishPromise;let y=c._readable;l._finishPromise=f((I,$)=>{l._finishPromise_resolve=I,l._finishPromise_reject=$});let v=l._flushAlgorithm();return Oi(l),C(v,()=>(y._state==="errored"?co(l,y._storedError):(Pr(y._readableStreamController),mc(l)),null),I=>(Bt(y._readableStreamController,I),co(l,I),null)),l._finishPromise}m(Hb,"TransformStreamDefaultSinkCloseAlgorithm");function zb(c){return Ri(c,!1),c._backpressureChangePromise}m(zb,"TransformStreamDefaultSourcePullAlgorithm");function Wb(c,l){let y=c._transformStreamController;if(y._finishPromise!==void 0)return y._finishPromise;let v=c._writable;y._finishPromise=f(($,W)=>{y._finishPromise_resolve=$,y._finishPromise_reject=W});let I=y._cancelAlgorithm(l);return Oi(y),C(I,()=>(v._state==="errored"?co(y,v._storedError):(Wo(v._writableStreamController,l),gc(c),mc(y)),null),$=>(Wo(v._writableStreamController,$),gc(c),co(y,$),null)),y._finishPromise}m(Wb,"TransformStreamDefaultSourceCancelAlgorithm");function Pi(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}m(Pi,"defaultControllerBrandCheckException");function mc(c){c._finishPromise_resolve!==void 0&&(c._finishPromise_resolve(),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}m(mc,"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)}m(co,"defaultControllerFinishPromiseReject");function wp(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}m(wp,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=dc,n.CountQueuingStrategy=fc,n.ReadableByteStreamController=Vn,n.ReadableStream=dt,n.ReadableStreamBYOBReader=Tr,n.ReadableStreamBYOBRequest=no,n.ReadableStreamDefaultController=Xn,n.ReadableStreamDefaultReader=me,n.TransformStream=pc,n.TransformStreamDefaultController=Fr,n.WritableStream=Rr,n.WritableStreamDefaultController=zo,n.WritableStreamDefaultWriter=Yn})})(Gu,Gu.exports)),Gu.exports}function GS(){if(WS)return HS;WS=1;let t=65536;if(!globalThis.ReadableStream)try{let e=re("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,re("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,rA())}try{let{Blob:e}=re("buffer");e&&!e.prototype.stream&&(e.prototype.stream=m(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 HS}async function*Ju(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,JS),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+JS)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function sA(t,e=Do){var n=`${KS()}${KS()}`.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+
|
|
76
|
+
`;let u=(0,TF.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",xF),n.secureEndpoint?(ta("Upgrading socket connection to TLS"),BS.connect({...jS(US(n),"host","path","port"),socket:o})):o;o.destroy();let p=new Hu.Socket({writable:!1});return p.readable=!0,e.once("socket",h=>{ta("Replaying proxy buffer for failed request"),(0,SF.default)(h.listenerCount("data")>0),h.push(f),h.push(null)}),p}};zu.protocols=["http","https"];zt.HttpsProxyAgent=zu;function xF(t){t.resume()}function jS(t,...e){let n={},r;for(r in t)e.includes(r)||(n[r]=t[r]);return n}});function mg(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var RF,DF,gg,Wu=Mr(()=>{RF=Object.defineProperty,DF=(t,e)=>RF(t,"name",{value:e,configurable:!0}),gg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};DF(mg,"getDefaultExportFromCjs")});var JS={};Qb(JS,{toFormData:()=>GS});function WS(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 GS(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 BF(n[1]||n[2]),o,s,i,a,u,d,f=[],p=new vo,h=It(b=>{i+=k.decode(b,{stream:!0})},"onPartData"),g=It(b=>{f.push(b)},"appendToFile"),C=It(()=>{let b=new Ss(f,d,{type:u});p.append(a,b)},"appendFileToFormData"),y=It(()=>{p.append(a,i)},"appendEntryToFormData"),k=new TextDecoder("utf-8");k.decode(),r.onPartBegin=function(){r.onPartData=h,r.onPartEnd=y,o="",s="",i="",a="",u="",d=null,f.length=0},r.onHeaderField=function(b){o+=k.decode(b,{stream:!0})},r.onHeaderValue=function(b){s+=k.decode(b,{stream:!0})},r.onHeaderEnd=function(){if(s+=k.decode(),o=o.toLowerCase(),o==="content-disposition"){let b=s.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i);b&&(a=b[2]||b[3]||""),d=WS(s),d&&(r.onPartData=g,r.onPartEnd=C)}else o==="content-type"&&(u=s);s="",o=""};for await(let b of t)r.write(b);return r.end(),p}var OF,It,In,je,HS,Hr,Gu,Ju,PF,na,IF,FF,NF,MF,Eo,zS,BF,KS=Mr(()=>{Ku();Wu();OF=Object.defineProperty,It=(t,e)=>OF(t,"name",{value:e,configurable:!0}),In=0,je={START_BOUNDARY:In++,HEADER_FIELD_START:In++,HEADER_FIELD:In++,HEADER_VALUE_START:In++,HEADER_VALUE:In++,HEADER_VALUE_ALMOST_DONE:In++,HEADERS_ALMOST_DONE:In++,PART_DATA_START:In++,PART_DATA:In++,END:In++},HS=1,Hr={PART_BOUNDARY:HS,LAST_BOUNDARY:HS*=2},Gu=10,Ju=13,PF=32,na=45,IF=58,FF=97,NF=122,MF=It(t=>t|32,"lower"),Eo=It(()=>{},"noop"),zS=class{constructor(e){this.index=0,this.flags=0,this.onHeaderEnd=Eo,this.onHeaderField=Eo,this.onHeadersEnd=Eo,this.onHeaderValue=Eo,this.onPartBegin=Eo,this.onPartData=Eo,this.onPartEnd=Eo,this.boundaryChars={},e=`\r
|
|
78
|
+
--`+e;let n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r),this.boundaryChars[n[r]]=!0;this.boundary=n,this.lookbehind=new Uint8Array(this.boundary.length+8),this.state=je.START_BOUNDARY}write(e){let n=0,r=e.length,o=this.index,{lookbehind:s,boundary:i,boundaryChars:a,index:u,state:d,flags:f}=this,p=this.boundary.length,h=p-1,g=e.length,C,y,k=It(E=>{this[E+"Mark"]=n},"mark"),b=It(E=>{delete this[E+"Mark"]},"clear"),A=It((E,x,O,q)=>{(x===void 0||x!==O)&&this[E](q&&q.subarray(x,O))},"callback"),w=It((E,x)=>{let O=E+"Mark";O in this&&(x?(A(E,this[O],n,e),delete this[O]):(A(E,this[O],e.length,e),this[O]=0))},"dataCallback");for(n=0;n<r;n++)switch(C=e[n],d){case je.START_BOUNDARY:if(u===i.length-2){if(C===na)f|=Hr.LAST_BOUNDARY;else if(C!==Ju)return;u++;break}else if(u-1===i.length-2){if(f&Hr.LAST_BOUNDARY&&C===na)d=je.END,f=0;else if(!(f&Hr.LAST_BOUNDARY)&&C===Gu)u=0,A("onPartBegin"),d=je.HEADER_FIELD_START;else return;break}C!==i[u+2]&&(u=-2),C===i[u+2]&&u++;break;case je.HEADER_FIELD_START:d=je.HEADER_FIELD,k("onHeaderField"),u=0;case je.HEADER_FIELD:if(C===Ju){b("onHeaderField"),d=je.HEADERS_ALMOST_DONE;break}if(u++,C===na)break;if(C===IF){if(u===1)return;w("onHeaderField",!0),d=je.HEADER_VALUE_START;break}if(y=MF(C),y<FF||y>NF)return;break;case je.HEADER_VALUE_START:if(C===PF)break;k("onHeaderValue"),d=je.HEADER_VALUE;case je.HEADER_VALUE:C===Ju&&(w("onHeaderValue",!0),A("onHeaderEnd"),d=je.HEADER_VALUE_ALMOST_DONE);break;case je.HEADER_VALUE_ALMOST_DONE:if(C!==Gu)return;d=je.HEADER_FIELD_START;break;case je.HEADERS_ALMOST_DONE:if(C!==Gu)return;A("onHeadersEnd"),d=je.PART_DATA_START;break;case je.PART_DATA_START:d=je.PART_DATA,k("onPartData");case je.PART_DATA:if(o=u,u===0){for(n+=h;n<g&&!(e[n]in a);)n+=p;n-=h,C=e[n]}if(u<i.length)i[u]===C?(u===0&&w("onPartData",!0),u++):u=0;else if(u===i.length)u++,C===Ju?f|=Hr.PART_BOUNDARY:C===na?f|=Hr.LAST_BOUNDARY:u=0;else if(u-1===i.length)if(f&Hr.PART_BOUNDARY){if(u=0,C===Gu){f&=~Hr.PART_BOUNDARY,A("onPartEnd"),A("onPartBegin"),d=je.HEADER_FIELD_START;break}}else f&Hr.LAST_BOUNDARY&&C===na?(A("onPartEnd"),d=je.END,f=0):u=0;if(u>0)s[u-1]=C;else if(o>0){let E=new Uint8Array(s.buffer,s.byteOffset,s.byteLength);A("onPartData",0,o,E),o=0,k("onPartData"),n--}break;case je.END:break;default:throw new Error(`Unexpected state entered: ${d}`)}w("onHeaderField"),w("onHeaderValue"),w("onPartData"),this.index=u,this.state=d,this.flags=f}end(){if(this.state===je.HEADER_FIELD_START&&this.index===0||this.state===je.PART_DATA&&this.index===this.boundary.length)this.onPartEnd();else if(this.state!==je.END)throw new Error("MultipartParser.end(): stream ended unexpectedly")}};It(zS,"MultipartParser");BF=zS;It(WS,"_fileName");It(GS,"toFormData")});import ua from"node:http";import jF from"node:https";import Es from"node:zlib";import Mn,{PassThrough as rl,pipeline as vs}from"node:stream";import{Buffer as pt}from"node:buffer";import{types as ol,deprecate as sl,promisify as LF}from"node:util";import{format as $F}from"node:url";import{isIP as qF}from"node:net";import{promises as HF,statSync as aA,createReadStream as zF}from"node:fs";import{basename as WF}from"node:path";function cA(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 uA(){return YS||(YS=1,(function(t,e){(function(n,r){r(e)})(GF,function(n){function r(){}m(r,"noop");function o(c){return typeof c=="object"&&c!==null||typeof c=="function"}m(o,"typeIsObject");let s=r;function i(c,l){try{Object.defineProperty(c,"name",{value:l,configurable:!0})}catch{}}m(i,"setFunctionName");let a=Promise,u=Promise.prototype.then,d=Promise.reject.bind(a);function f(c){return new a(c)}m(f,"newPromise");function p(c){return f(l=>l(c))}m(p,"promiseResolvedWith");function h(c){return d(c)}m(h,"promiseRejectedWith");function g(c,l,_){return u.call(c,l,_)}m(g,"PerformPromiseThen");function C(c,l,_){g(g(c,l,_),void 0,s)}m(C,"uponPromise");function y(c,l){C(c,l)}m(y,"uponFulfillment");function k(c,l){C(c,void 0,l)}m(k,"uponRejection");function b(c,l,_){return g(c,l,_)}m(b,"transformPromiseWith");function A(c){g(c,void 0,s)}m(A,"setPromiseIsHandledToTrue");let w=m(c=>{if(typeof queueMicrotask=="function")w=queueMicrotask;else{let l=p(void 0);w=m(_=>g(l,_),"_queueMicrotask")}return w(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,_)}m(E,"reflectCall");function x(c,l,_){try{return p(E(c,l,_))}catch(v){return h(v)}}m(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[_]}};m(q,"SimpleQueue");let V=q,j=Symbol("[[AbortSteps]]"),ee=Symbol("[[ErrorSteps]]"),z=Symbol("[[CancelSteps]]"),te=Symbol("[[PullSteps]]"),Q=Symbol("[[ReleaseSteps]]");function _e(c,l){c._ownerReadableStream=l,l._reader=c,l._state==="readable"?ne(c):l._state==="closed"?ae(c):Z(c,l._storedError)}m(_e,"ReadableStreamReaderGenericInitialize");function Oe(c,l){let _=c._ownerReadableStream;return Ut(_,l)}m(Oe,"ReadableStreamReaderGenericCancel");function Te(c){let l=c._ownerReadableStream;l._state==="readable"?Ie(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):we(c,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),l._readableStreamController[Q](),l._reader=void 0,c._ownerReadableStream=void 0}m(Te,"ReadableStreamReaderGenericRelease");function Ge(c){return new TypeError("Cannot "+c+" a stream using a released reader")}m(Ge,"readerLockException");function ne(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_})}m(ne,"defaultReaderClosedPromiseInitialize");function Z(c,l){ne(c),Ie(c,l)}m(Z,"defaultReaderClosedPromiseInitializeAsRejected");function ae(c){ne(c),H(c)}m(ae,"defaultReaderClosedPromiseInitializeAsResolved");function Ie(c,l){c._closedPromise_reject!==void 0&&(A(c._closedPromise),c._closedPromise_reject(l),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}m(Ie,"defaultReaderClosedPromiseReject");function we(c,l){Z(c,l)}m(we,"defaultReaderClosedPromiseResetToRejected");function H(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0)}m(H,"defaultReaderClosedPromiseResolve");let Ee=Number.isFinite||function(c){return typeof c=="number"&&isFinite(c)},Ze=Math.trunc||function(c){return c<0?Math.ceil(c):Math.floor(c)};function X(c){return typeof c=="object"||typeof c=="function"}m(X,"isDictionary");function de(c,l){if(c!==void 0&&!X(c))throw new TypeError(`${l} is not an object.`)}m(de,"assertDictionary");function ce(c,l){if(typeof c!="function")throw new TypeError(`${l} is not a function.`)}m(ce,"assertFunction");function S(c){return typeof c=="object"&&c!==null||typeof c=="function"}m(S,"isObject");function T(c,l){if(!S(c))throw new TypeError(`${l} is not an object.`)}m(T,"assertObject");function R(c,l,_){if(c===void 0)throw new TypeError(`Parameter ${l} is required in '${_}'.`)}m(R,"assertRequiredArgument");function M(c,l,_){if(c===void 0)throw new TypeError(`${l} is required in '${_}'.`)}m(M,"assertRequiredField");function D(c){return Number(c)}m(D,"convertUnrestrictedDouble");function F(c){return c===0?0:c}m(F,"censorNegativeZero");function L(c){return F(Ze(c))}m(L,"integerPart");function P(c,l){let _=Number.MAX_SAFE_INTEGER,v=Number(c);if(v=F(v),!Ee(v))throw new TypeError(`${l} is not a finite number`);if(v=L(v),v<0||v>_)throw new TypeError(`${l} is outside the accepted range of 0 to ${_}, inclusive`);return!Ee(v)||v===0?0:v}m(P,"convertUnsignedLongLongWithEnforceRange");function N(c,l){if(!Qn(c))throw new TypeError(`${l} is not a ReadableStream.`)}m(N,"assertReadableStream");function U(c){return new me(c)}m(U,"AcquireReadableStreamDefaultReader");function B(c,l){c._reader._readRequests.push(l)}m(B,"ReadableStreamAddReadRequest");function K(c,l,_){let v=c._reader._readRequests.shift();_?v._closeSteps():v._chunkSteps(l)}m(K,"ReadableStreamFulfillReadRequest");function ie(c){return c._reader._readRequests.length}m(ie,"ReadableStreamGetNumReadRequests");function ue(c){let l=c._reader;return!(l===void 0||!he(l))}m(ue,"ReadableStreamHasDefaultReader");let be=class{constructor(l){if(R(l,1,"ReadableStreamDefaultReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");_e(this,l),this._readRequests=new V}get closed(){return he(this)?this._closedPromise:h(mn("closed"))}cancel(l=void 0){return he(this)?this._ownerReadableStream===void 0?h(Ge("cancel")):Oe(this,l):h(mn("cancel"))}read(){if(!he(this))return h(mn("read"));if(this._ownerReadableStream===void 0)return h(Ge("read from"));let l,_,v=f((I,$)=>{l=I,_=$});return ye(this,{_chunkSteps:m(I=>l({value:I,done:!1}),"_chunkSteps"),_closeSteps:m(()=>l({value:void 0,done:!0}),"_closeSteps"),_errorSteps:m(I=>_(I),"_errorSteps")}),v}releaseLock(){if(!he(this))throw mn("releaseLock");this._ownerReadableStream!==void 0&&Fe(this)}};m(be,"ReadableStreamDefaultReader");let me=be;Object.defineProperties(me.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(me.prototype.cancel,"cancel"),i(me.prototype.read,"read"),i(me.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(me.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});function he(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readRequests")?!1:c instanceof me}m(he,"IsReadableStreamDefaultReader");function ye(c,l){let _=c._ownerReadableStream;_._disturbed=!0,_._state==="closed"?l._closeSteps():_._state==="errored"?l._errorSteps(_._storedError):_._readableStreamController[te](l)}m(ye,"ReadableStreamDefaultReaderRead");function Fe(c){Te(c);let l=new TypeError("Reader was released");Ye(c,l)}m(Fe,"ReadableStreamDefaultReaderRelease");function Ye(c,l){let _=c._readRequests;c._readRequests=new V,_.forEach(v=>{v._errorSteps(l)})}m(Ye,"ReadableStreamDefaultReaderErrorReadRequests");function mn(c){return new TypeError(`ReadableStreamDefaultReader.prototype.${c} can only be used on a ReadableStreamDefaultReader`)}m(mn,"defaultReaderBrandCheckException");let ui=Object.getPrototypeOf(Object.getPrototypeOf(async function*(){}).prototype),jo=class{constructor(l,_){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=l,this._preventCancel=_}next(){let l=m(()=>this._nextSteps(),"nextSteps");return this._ongoingPromise=this._ongoingPromise?b(this._ongoingPromise,l,l):l(),this._ongoingPromise}return(l){let _=m(()=>this._returnSteps(l),"returnSteps");return this._ongoingPromise?b(this._ongoingPromise,_,_):_()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});let l=this._reader,_,v,I=f(($,W)=>{_=$,v=W});return ye(l,{_chunkSteps:m($=>{this._ongoingPromise=void 0,w(()=>_({value:$,done:!1}))},"_chunkSteps"),_closeSteps:m(()=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),_({value:void 0,done:!0})},"_closeSteps"),_errorSteps:m($=>{this._ongoingPromise=void 0,this._isFinished=!0,Te(l),v($)},"_errorSteps")}),I}_returnSteps(l){if(this._isFinished)return Promise.resolve({value:l,done:!0});this._isFinished=!0;let _=this._reader;if(!this._preventCancel){let v=Oe(_,l);return Te(_),b(v,()=>({value:l,done:!0}))}return Te(_),p({value:l,done:!0})}};m(jo,"ReadableStreamAsyncIteratorImpl");let xt=jo,Sr={next(){return et(this)?this._asyncIteratorImpl.next():h(Ue("next"))},return(c){return et(this)?this._asyncIteratorImpl.return(c):h(Ue("return"))}};Object.setPrototypeOf(Sr,ui);function ht(c,l){let _=U(c),v=new xt(_,l),I=Object.create(Sr);return I._asyncIteratorImpl=v,I}m(ht,"AcquireReadableStreamAsyncIterator");function et(c){if(!o(c)||!Object.prototype.hasOwnProperty.call(c,"_asyncIteratorImpl"))return!1;try{return c._asyncIteratorImpl instanceof xt}catch{return!1}}m(et,"IsReadableStreamAsyncIterator");function Ue(c){return new TypeError(`ReadableStreamAsyncIterator.${c} can only be used on a ReadableSteamAsyncIterator`)}m(Ue,"streamAsyncIteratorBrandCheckException");let r0=Number.isNaN||function(c){return c!==c};var xf,Rf,Df;function Lo(c){return c.slice()}m(Lo,"CreateArrayFromList");function Of(c,l,_,v,I){new Uint8Array(c).set(new Uint8Array(_,v,I),l)}m(Of,"CopyDataBlockBytes");let Jn=m(c=>(typeof c.transfer=="function"?Jn=m(l=>l.transfer(),"TransferArrayBuffer"):typeof structuredClone=="function"?Jn=m(l=>structuredClone(l,{transfer:[l]}),"TransferArrayBuffer"):Jn=m(l=>l,"TransferArrayBuffer"),Jn(c)),"TransferArrayBuffer"),Ar=m(c=>(typeof c.detached=="boolean"?Ar=m(l=>l.detached,"IsDetachedBuffer"):Ar=m(l=>l.byteLength===0,"IsDetachedBuffer"),Ar(c)),"IsDetachedBuffer");function Pf(c,l,_){if(c.slice)return c.slice(l,_);let v=_-l,I=new ArrayBuffer(v);return Of(I,0,c,l,v),I}m(Pf,"ArrayBufferSlice");function li(c,l){let _=c[l];if(_!=null){if(typeof _!="function")throw new TypeError(`${String(l)} is not a function`);return _}}m(li,"GetMethod");function o0(c){let l={[Symbol.iterator]:()=>c.iterator},_=(async function*(){return yield*l})(),v=_.next;return{iterator:_,nextMethod:v,done:!1}}m(o0,"CreateAsyncFromSyncIterator");let If=(Df=(xf=Symbol.asyncIterator)!==null&&xf!==void 0?xf:(Rf=Symbol.for)===null||Rf===void 0?void 0:Rf.call(Symbol,"Symbol.asyncIterator"))!==null&&Df!==void 0?Df:"@@asyncIterator";function Ff(c,l="sync",_){if(_===void 0)if(l==="async"){if(_=li(c,If),_===void 0){let $=li(c,Symbol.iterator),W=Ff(c,"sync",$);return o0(W)}}else _=li(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}}m(Ff,"GetIterator");function s0(c){let l=E(c.nextMethod,c.iterator,[]);if(!o(l))throw new TypeError("The iterator.next() method must return an object");return l}m(s0,"IteratorNext");function i0(c){return!!c.done}m(i0,"IteratorComplete");function a0(c){return c.value}m(a0,"IteratorValue");function c0(c){return!(typeof c!="number"||r0(c)||c<0)}m(c0,"IsNonNegativeNumber");function Nf(c){let l=Pf(c.buffer,c.byteOffset,c.byteOffset+c.byteLength);return new Uint8Array(l)}m(Nf,"CloneAsUint8Array");function Wa(c){let l=c._queue.shift();return c._queueTotalSize-=l.size,c._queueTotalSize<0&&(c._queueTotalSize=0),l.value}m(Wa,"DequeueValue");function Ga(c,l,_){if(!c0(_)||_===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");c._queue.push({value:l,size:_}),c._queueTotalSize+=_}m(Ga,"EnqueueValueWithSize");function u0(c){return c._queue.peek().value}m(u0,"PeekQueueValue");function Kn(c){c._queue=new V,c._queueTotalSize=0}m(Kn,"ResetQueue");function Mf(c){return c===DataView}m(Mf,"isDataViewConstructor");function l0(c){return Mf(c.constructor)}m(l0,"isDataView");function d0(c){return Mf(c)?1:c.BYTES_PER_ELEMENT}m(d0,"arrayBufferViewElementSize");let f0=class{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ja(this))throw Qa("view");return this._view}respond(l){if(!Ja(this))throw Qa("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(Ar(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");hi(this._associatedReadableByteStreamController,l)}respondWithNewView(l){if(!Ja(this))throw Qa("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(Ar(l.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");gi(this._associatedReadableByteStreamController,l)}};m(f0,"ReadableStreamBYOBRequest");let no=f0;Object.defineProperties(no.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),i(no.prototype.respond,"respond"),i(no.prototype.respondWithNewView,"respondWithNewView"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(no.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});let p0=class{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Er(this))throw qo("byobRequest");return Xa(this)}get desiredSize(){if(!Er(this))throw qo("desiredSize");return Gf(this)}close(){if(!Er(this))throw qo("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");let l=this._controlledReadableByteStream._state;if(l!=="readable")throw new TypeError(`The stream (in ${l} state) is not in the readable state and cannot be closed`);$o(this)}enqueue(l){if(!Er(this))throw qo("enqueue");if(R(l,1,"enqueue"),!ArrayBuffer.isView(l))throw new TypeError("chunk must be an array buffer view");if(l.byteLength===0)throw new TypeError("chunk must have non-zero byteLength");if(l.buffer.byteLength===0)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");let _=this._controlledReadableByteStream._state;if(_!=="readable")throw new TypeError(`The stream (in ${_} state) is not in the readable state and cannot be enqueued to`);pi(this,l)}error(l=void 0){if(!Er(this))throw qo("error");Rt(this,l)}[z](l){Bf(this),Kn(this);let _=this._cancelAlgorithm(l);return fi(this),_}[te](l){let _=this._controlledReadableByteStream;if(this._queueTotalSize>0){Wf(this,l);return}let v=this._autoAllocateChunkSize;if(v!==void 0){let I;try{I=new ArrayBuffer(v)}catch(W){l._errorSteps(W);return}let $={buffer:I,bufferByteLength:v,byteOffset:0,byteLength:v,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push($)}B(_,l),vr(this)}[Q](){if(this._pendingPullIntos.length>0){let l=this._pendingPullIntos.peek();l.readerType="none",this._pendingPullIntos=new V,this._pendingPullIntos.push(l)}}};m(p0,"ReadableByteStreamController");let Vn=p0;Object.defineProperties(Vn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Vn.prototype.close,"close"),i(Vn.prototype.enqueue,"enqueue"),i(Vn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Vn.prototype,Symbol.toStringTag,{value:"ReadableByteStreamController",configurable:!0});function Er(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableByteStream")?!1:c instanceof Vn}m(Er,"IsReadableByteStreamController");function Ja(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_associatedReadableByteStreamController")?!1:c instanceof no}m(Ja,"IsReadableStreamBYOBRequest");function vr(c){if(!_0(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();C(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,vr(c)),null),_=>(Rt(c,_),null))}m(vr,"ReadableByteStreamControllerCallPullIfNeeded");function Bf(c){Va(c),c._pendingPullIntos=new V}m(Bf,"ReadableByteStreamControllerClearPendingPullIntos");function Ka(c,l){let _=!1;c._state==="closed"&&(_=!0);let v=Uf(l);l.readerType==="default"?K(c,v,_):A0(c,v,_)}m(Ka,"ReadableByteStreamControllerCommitPullIntoDescriptor");function Uf(c){let l=c.bytesFilled,_=c.elementSize;return new c.viewConstructor(c.buffer,c.byteOffset,l/_)}m(Uf,"ReadableByteStreamControllerConvertPullIntoDescriptor");function di(c,l,_,v){c._queue.push({buffer:l,byteOffset:_,byteLength:v}),c._queueTotalSize+=v}m(di,"ReadableByteStreamControllerEnqueueChunkToQueue");function jf(c,l,_,v){let I;try{I=Pf(l,_,_+v)}catch($){throw Rt(c,$),$}di(c,I,0,v)}m(jf,"ReadableByteStreamControllerEnqueueClonedChunkToQueue");function Lf(c,l){l.bytesFilled>0&&jf(c,l.buffer,l.byteOffset,l.bytesFilled),ro(c)}m(Lf,"ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue");function $f(c,l){let _=Math.min(c._queueTotalSize,l.byteLength-l.bytesFilled),v=l.bytesFilled+_,I=_,$=!1,W=v%l.elementSize,se=v-W;se>=l.minimumFill&&(I=se-l.bytesFilled,$=!0);let le=c._queue;for(;I>0;){let ge=le.peek(),ke=Math.min(I,ge.byteLength),Se=l.byteOffset+l.bytesFilled;Of(l.buffer,Se,ge.buffer,ge.byteOffset,ke),ge.byteLength===ke?le.shift():(ge.byteOffset+=ke,ge.byteLength-=ke),c._queueTotalSize-=ke,qf(c,ke,l),I-=ke}return $}m($f,"ReadableByteStreamControllerFillPullIntoDescriptorFromQueue");function qf(c,l,_){_.bytesFilled+=l}m(qf,"ReadableByteStreamControllerFillHeadPullIntoDescriptor");function Hf(c){c._queueTotalSize===0&&c._closeRequested?(fi(c),Vo(c._controlledReadableByteStream)):vr(c)}m(Hf,"ReadableByteStreamControllerHandleQueueDrain");function Va(c){c._byobRequest!==null&&(c._byobRequest._associatedReadableByteStreamController=void 0,c._byobRequest._view=null,c._byobRequest=null)}m(Va,"ReadableByteStreamControllerInvalidateBYOBRequest");function Ya(c){for(;c._pendingPullIntos.length>0;){if(c._queueTotalSize===0)return;let l=c._pendingPullIntos.peek();$f(c,l)&&(ro(c),Ka(c._controlledReadableByteStream,l))}}m(Ya,"ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue");function h0(c){let l=c._controlledReadableByteStream._reader;for(;l._readRequests.length>0;){if(c._queueTotalSize===0)return;let _=l._readRequests.shift();Wf(c,_)}}m(h0,"ReadableByteStreamControllerProcessReadRequestsUsingQueue");function g0(c,l,_,v){let I=c._controlledReadableByteStream,$=l.constructor,W=d0($),{byteOffset:se,byteLength:le}=l,ge=_*W,ke;try{ke=Jn(l.buffer)}catch(Be){v._errorSteps(Be);return}let Se={buffer:ke,bufferByteLength:ke.byteLength,byteOffset:se,byteLength:le,bytesFilled:0,minimumFill:ge,elementSize:W,viewConstructor:$,readerType:"byob"};if(c._pendingPullIntos.length>0){c._pendingPullIntos.push(Se),Vf(I,v);return}if(I._state==="closed"){let Be=new $(Se.buffer,Se.byteOffset,0);v._closeSteps(Be);return}if(c._queueTotalSize>0){if($f(c,Se)){let Be=Uf(Se);Hf(c),v._chunkSteps(Be);return}if(c._closeRequested){let Be=new TypeError("Insufficient bytes to fill elements in the given buffer");Rt(c,Be),v._errorSteps(Be);return}}c._pendingPullIntos.push(Se),Vf(I,v),vr(c)}m(g0,"ReadableByteStreamControllerPullInto");function m0(c,l){l.readerType==="none"&&ro(c);let _=c._controlledReadableByteStream;if(Za(_))for(;Yf(_)>0;){let v=ro(c);Ka(_,v)}}m(m0,"ReadableByteStreamControllerRespondInClosedState");function y0(c,l,_){if(qf(c,l,_),_.readerType==="none"){Lf(c,_),Ya(c);return}if(_.bytesFilled<_.minimumFill)return;ro(c);let v=_.bytesFilled%_.elementSize;if(v>0){let I=_.byteOffset+_.bytesFilled;jf(c,_.buffer,I-v,v)}_.bytesFilled-=v,Ka(c._controlledReadableByteStream,_),Ya(c)}m(y0,"ReadableByteStreamControllerRespondInReadableState");function zf(c,l){let _=c._pendingPullIntos.peek();Va(c),c._controlledReadableByteStream._state==="closed"?m0(c,_):y0(c,l,_),vr(c)}m(zf,"ReadableByteStreamControllerRespondInternal");function ro(c){return c._pendingPullIntos.shift()}m(ro,"ReadableByteStreamControllerShiftPendingPullInto");function _0(c){let l=c._controlledReadableByteStream;return l._state!=="readable"||c._closeRequested||!c._started?!1:!!(ue(l)&&ie(l)>0||Za(l)&&Yf(l)>0||Gf(c)>0)}m(_0,"ReadableByteStreamControllerShouldCallPull");function fi(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0}m(fi,"ReadableByteStreamControllerClearAlgorithms");function $o(c){let l=c._controlledReadableByteStream;if(!(c._closeRequested||l._state!=="readable")){if(c._queueTotalSize>0){c._closeRequested=!0;return}if(c._pendingPullIntos.length>0){let _=c._pendingPullIntos.peek();if(_.bytesFilled%_.elementSize!==0){let v=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Rt(c,v),v}}fi(c),Vo(l)}}m($o,"ReadableByteStreamControllerClose");function pi(c,l){let _=c._controlledReadableByteStream;if(c._closeRequested||_._state!=="readable")return;let{buffer:v,byteOffset:I,byteLength:$}=l;if(Ar(v))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");let W=Jn(v);if(c._pendingPullIntos.length>0){let se=c._pendingPullIntos.peek();if(Ar(se.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Va(c),se.buffer=Jn(se.buffer),se.readerType==="none"&&Lf(c,se)}if(ue(_))if(h0(c),ie(_)===0)di(c,W,I,$);else{c._pendingPullIntos.length>0&&ro(c);let se=new Uint8Array(W,I,$);K(_,se,!1)}else Za(_)?(di(c,W,I,$),Ya(c)):di(c,W,I,$);vr(c)}m(pi,"ReadableByteStreamControllerEnqueue");function Rt(c,l){let _=c._controlledReadableByteStream;_._state==="readable"&&(Bf(c),Kn(c),fi(c),bp(_,l))}m(Rt,"ReadableByteStreamControllerError");function Wf(c,l){let _=c._queue.shift();c._queueTotalSize-=_.byteLength,Hf(c);let v=new Uint8Array(_.buffer,_.byteOffset,_.byteLength);l._chunkSteps(v)}m(Wf,"ReadableByteStreamControllerFillReadRequestFromQueue");function Xa(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(no.prototype);C0(v,c,_),c._byobRequest=v}return c._byobRequest}m(Xa,"ReadableByteStreamControllerGetBYOBRequest");function Gf(c){let l=c._controlledReadableByteStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}m(Gf,"ReadableByteStreamControllerGetDesiredSize");function hi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l!==0)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(l===0)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(_.bytesFilled+l>_.byteLength)throw new RangeError("bytesWritten out of range")}_.buffer=Jn(_.buffer),zf(c,l)}m(hi,"ReadableByteStreamControllerRespond");function gi(c,l){let _=c._pendingPullIntos.peek();if(c._controlledReadableByteStream._state==="closed"){if(l.byteLength!==0)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(l.byteLength===0)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(_.byteOffset+_.bytesFilled!==l.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(_.bufferByteLength!==l.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(_.bytesFilled+l.byteLength>_.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");let v=l.byteLength;_.buffer=Jn(l.buffer),zf(c,v)}m(gi,"ReadableByteStreamControllerRespondWithNewView");function Jf(c,l,_,v,I,$,W){l._controlledReadableByteStream=c,l._pullAgain=!1,l._pulling=!1,l._byobRequest=null,l._queue=l._queueTotalSize=void 0,Kn(l),l._closeRequested=!1,l._started=!1,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,l._autoAllocateChunkSize=W,l._pendingPullIntos=new V,c._readableStreamController=l;let se=_();C(p(se),()=>(l._started=!0,vr(l),null),le=>(Rt(l,le),null))}m(Jf,"SetUpReadableByteStreamController");function b0(c,l,_){let v=Object.create(Vn.prototype),I,$,W;l.start!==void 0?I=m(()=>l.start(v),"startAlgorithm"):I=m(()=>{},"startAlgorithm"),l.pull!==void 0?$=m(()=>l.pull(v),"pullAlgorithm"):$=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?W=m(le=>l.cancel(le),"cancelAlgorithm"):W=m(()=>p(void 0),"cancelAlgorithm");let se=l.autoAllocateChunkSize;if(se===0)throw new TypeError("autoAllocateChunkSize must be greater than 0");Jf(c,v,I,$,W,_,se)}m(b0,"SetUpReadableByteStreamControllerFromUnderlyingSource");function C0(c,l,_){c._associatedReadableByteStreamController=l,c._view=_}m(C0,"SetUpReadableStreamBYOBRequest");function Qa(c){return new TypeError(`ReadableStreamBYOBRequest.prototype.${c} can only be used on a ReadableStreamBYOBRequest`)}m(Qa,"byobRequestBrandCheckException");function qo(c){return new TypeError(`ReadableByteStreamController.prototype.${c} can only be used on a ReadableByteStreamController`)}m(qo,"byteStreamControllerBrandCheckException");function w0(c,l){de(c,l);let _=c?.mode;return{mode:_===void 0?void 0:k0(_,`${l} has member 'mode' that`)}}m(w0,"convertReaderOptions");function k0(c,l){if(c=`${c}`,c!=="byob")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamReaderMode`);return c}m(k0,"convertReadableStreamReaderMode");function S0(c,l){var _;de(c,l);let v=(_=c?.min)!==null&&_!==void 0?_:1;return{min:P(v,`${l} has member 'min' that`)}}m(S0,"convertByobReadOptions");function Kf(c){return new Tr(c)}m(Kf,"AcquireReadableStreamBYOBReader");function Vf(c,l){c._reader._readIntoRequests.push(l)}m(Vf,"ReadableStreamAddReadIntoRequest");function A0(c,l,_){let v=c._reader._readIntoRequests.shift();_?v._closeSteps(l):v._chunkSteps(l)}m(A0,"ReadableStreamFulfillReadIntoRequest");function Yf(c){return c._reader._readIntoRequests.length}m(Yf,"ReadableStreamGetNumReadIntoRequests");function Za(c){let l=c._reader;return!(l===void 0||!xr(l))}m(Za,"ReadableStreamHasBYOBReader");let E0=class{constructor(l){if(R(l,1,"ReadableStreamBYOBReader"),N(l,"First parameter"),Zn(l))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Er(l._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");_e(this,l),this._readIntoRequests=new V}get closed(){return xr(this)?this._closedPromise:h(mi("closed"))}cancel(l=void 0){return xr(this)?this._ownerReadableStream===void 0?h(Ge("cancel")):Oe(this,l):h(mi("cancel"))}read(l,_={}){if(!xr(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(Ar(l.buffer))return h(new TypeError("view's buffer has been detached"));let v;try{v=S0(_,"options")}catch(le){return h(le)}let I=v.min;if(I===0)return h(new TypeError("options.min must be greater than 0"));if(l0(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(Ge("read from"));let $,W,se=f((le,ge)=>{$=le,W=ge});return Xf(this,l,I,{_chunkSteps:m(le=>$({value:le,done:!1}),"_chunkSteps"),_closeSteps:m(le=>$({value:le,done:!0}),"_closeSteps"),_errorSteps:m(le=>W(le),"_errorSteps")}),se}releaseLock(){if(!xr(this))throw mi("releaseLock");this._ownerReadableStream!==void 0&&v0(this)}};m(E0,"ReadableStreamBYOBReader");let Tr=E0;Object.defineProperties(Tr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),i(Tr.prototype.cancel,"cancel"),i(Tr.prototype.read,"read"),i(Tr.prototype.releaseLock,"releaseLock"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Tr.prototype,Symbol.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});function xr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readIntoRequests")?!1:c instanceof Tr}m(xr,"IsReadableStreamBYOBReader");function Xf(c,l,_,v){let I=c._ownerReadableStream;I._disturbed=!0,I._state==="errored"?v._errorSteps(I._storedError):g0(I._readableStreamController,l,_,v)}m(Xf,"ReadableStreamBYOBReaderRead");function v0(c){Te(c);let l=new TypeError("Reader was released");Qf(c,l)}m(v0,"ReadableStreamBYOBReaderRelease");function Qf(c,l){let _=c._readIntoRequests;c._readIntoRequests=new V,_.forEach(v=>{v._errorSteps(l)})}m(Qf,"ReadableStreamBYOBReaderErrorReadIntoRequests");function mi(c){return new TypeError(`ReadableStreamBYOBReader.prototype.${c} can only be used on a ReadableStreamBYOBReader`)}m(mi,"byobReaderBrandCheckException");function Ho(c,l){let{highWaterMark:_}=c;if(_===void 0)return l;if(r0(_)||_<0)throw new RangeError("Invalid highWaterMark");return _}m(Ho,"ExtractHighWaterMark");function yi(c){let{size:l}=c;return l||(()=>1)}m(yi,"ExtractSizeAlgorithm");function _i(c,l){de(c,l);let _=c?.highWaterMark,v=c?.size;return{highWaterMark:_===void 0?void 0:D(_),size:v===void 0?void 0:T0(v,`${l} has member 'size' that`)}}m(_i,"convertQueuingStrategy");function T0(c,l){return ce(c,l),_=>D(c(_))}m(T0,"convertQueuingStrategySize");function x0(c,l){de(c,l);let _=c?.abort,v=c?.close,I=c?.start,$=c?.type,W=c?.write;return{abort:_===void 0?void 0:R0(_,c,`${l} has member 'abort' that`),close:v===void 0?void 0:D0(v,c,`${l} has member 'close' that`),start:I===void 0?void 0:O0(I,c,`${l} has member 'start' that`),write:W===void 0?void 0:P0(W,c,`${l} has member 'write' that`),type:$}}m(x0,"convertUnderlyingSink");function R0(c,l,_){return ce(c,_),v=>x(c,l,[v])}m(R0,"convertUnderlyingSinkAbortCallback");function D0(c,l,_){return ce(c,_),()=>x(c,l,[])}m(D0,"convertUnderlyingSinkCloseCallback");function O0(c,l,_){return ce(c,_),v=>E(c,l,[v])}m(O0,"convertUnderlyingSinkStartCallback");function P0(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}m(P0,"convertUnderlyingSinkWriteCallback");function Zf(c,l){if(!oo(c))throw new TypeError(`${l} is not a WritableStream.`)}m(Zf,"assertWritableStream");function I0(c){if(typeof c!="object"||c===null)return!1;try{return typeof c.aborted=="boolean"}catch{return!1}}m(I0,"isAbortSignal");let QR=typeof AbortController=="function";function F0(){if(QR)return new AbortController}m(F0,"createAbortController");let N0=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=_i(_,"Second parameter"),I=x0(l,"First parameter");if(tp(this),I.type!==void 0)throw new RangeError("Invalid type is specified");let $=yi(v),W=Ho(v,1);Q0(this,I,W,$)}get locked(){if(!oo(this))throw Si("locked");return so(this)}abort(l=void 0){return oo(this)?so(this)?h(new TypeError("Cannot abort a stream that already has a writer")):bi(this,l):h(Si("abort"))}close(){return oo(this)?so(this)?h(new TypeError("Cannot close a stream that already has a writer")):Xt(this)?h(new TypeError("Cannot close an already-closing stream")):np(this):h(Si("close"))}getWriter(){if(!oo(this))throw Si("getWriter");return ep(this)}};m(N0,"WritableStream");let Rr=N0;Object.defineProperties(Rr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),i(Rr.prototype.abort,"abort"),i(Rr.prototype.close,"close"),i(Rr.prototype.getWriter,"getWriter"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Rr.prototype,Symbol.toStringTag,{value:"WritableStream",configurable:!0});function ep(c){return new Yn(c)}m(ep,"AcquireWritableStreamDefaultWriter");function M0(c,l,_,v,I=1,$=()=>1){let W=Object.create(Rr.prototype);tp(W);let se=Object.create(zo.prototype);return ap(W,se,c,l,_,v,I,$),W}m(M0,"CreateWritableStream");function tp(c){c._state="writable",c._storedError=void 0,c._writer=void 0,c._writableStreamController=void 0,c._writeRequests=new V,c._inFlightWriteRequest=void 0,c._closeRequest=void 0,c._inFlightCloseRequest=void 0,c._pendingAbortRequest=void 0,c._backpressure=!1}m(tp,"InitializeWritableStream");function oo(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_writableStreamController")?!1:c instanceof Rr}m(oo,"IsWritableStream");function so(c){return c._writer!==void 0}m(so,"IsWritableStreamLocked");function bi(c,l){var _;if(c._state==="closed"||c._state==="errored")return p(void 0);c._writableStreamController._abortReason=l,(_=c._writableStreamController._abortController)===null||_===void 0||_.abort(l);let v=c._state;if(v==="closed"||v==="errored")return p(void 0);if(c._pendingAbortRequest!==void 0)return c._pendingAbortRequest._promise;let I=!1;v==="erroring"&&(I=!0,l=void 0);let $=f((W,se)=>{c._pendingAbortRequest={_promise:void 0,_resolve:W,_reject:se,_reason:l,_wasAlreadyErroring:I}});return c._pendingAbortRequest._promise=$,I||tc(c,l),$}m(bi,"WritableStreamAbort");function np(c){let l=c._state;if(l==="closed"||l==="errored")return h(new TypeError(`The stream (in ${l} state) is not in the writable state and cannot be closed`));let _=f((I,$)=>{let W={_resolve:I,_reject:$};c._closeRequest=W}),v=c._writer;return v!==void 0&&c._backpressure&&l==="writable"&&uc(v),Z0(c._writableStreamController),_}m(np,"WritableStreamClose");function B0(c){return f((l,_)=>{let v={_resolve:l,_reject:_};c._writeRequests.push(v)})}m(B0,"WritableStreamAddWriteRequest");function ec(c,l){if(c._state==="writable"){tc(c,l);return}nc(c)}m(ec,"WritableStreamDealWithRejection");function tc(c,l){let _=c._writableStreamController;c._state="erroring",c._storedError=l;let v=c._writer;v!==void 0&&op(v,l),!q0(c)&&_._started&&nc(c)}m(tc,"WritableStreamStartErroring");function nc(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){Ci(c);return}let _=c._pendingAbortRequest;if(c._pendingAbortRequest=void 0,_._wasAlreadyErroring){_._reject(l),Ci(c);return}let v=c._writableStreamController[j](_._reason);C(v,()=>(_._resolve(),Ci(c),null),I=>(_._reject(I),Ci(c),null))}m(nc,"WritableStreamFinishErroring");function U0(c){c._inFlightWriteRequest._resolve(void 0),c._inFlightWriteRequest=void 0}m(U0,"WritableStreamFinishInFlightWrite");function j0(c,l){c._inFlightWriteRequest._reject(l),c._inFlightWriteRequest=void 0,ec(c,l)}m(j0,"WritableStreamFinishInFlightWriteWithError");function L0(c){c._inFlightCloseRequest._resolve(void 0),c._inFlightCloseRequest=void 0,c._state==="erroring"&&(c._storedError=void 0,c._pendingAbortRequest!==void 0&&(c._pendingAbortRequest._resolve(),c._pendingAbortRequest=void 0)),c._state="closed";let l=c._writer;l!==void 0&&dp(l)}m(L0,"WritableStreamFinishInFlightClose");function $0(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)}m($0,"WritableStreamFinishInFlightCloseWithError");function Xt(c){return!(c._closeRequest===void 0&&c._inFlightCloseRequest===void 0)}m(Xt,"WritableStreamCloseQueuedOrInFlight");function q0(c){return!(c._inFlightWriteRequest===void 0&&c._inFlightCloseRequest===void 0)}m(q0,"WritableStreamHasOperationMarkedInFlight");function H0(c){c._inFlightCloseRequest=c._closeRequest,c._closeRequest=void 0}m(H0,"WritableStreamMarkCloseRequestInFlight");function z0(c){c._inFlightWriteRequest=c._writeRequests.shift()}m(z0,"WritableStreamMarkFirstWriteRequestInFlight");function Ci(c){c._closeRequest!==void 0&&(c._closeRequest._reject(c._storedError),c._closeRequest=void 0);let l=c._writer;l!==void 0&&ac(l,c._storedError)}m(Ci,"WritableStreamRejectCloseAndClosedPromiseIfNeeded");function rc(c,l){let _=c._writer;_!==void 0&&l!==c._backpressure&&(l?ib(_):uc(_)),c._backpressure=l}m(rc,"WritableStreamUpdateBackpressure");let W0=class{constructor(l){if(R(l,1,"WritableStreamDefaultWriter"),Zf(l,"First parameter"),so(l))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=l,l._writer=this;let _=l._state;if(_==="writable")!Xt(l)&&l._backpressure?Ei(this):fp(this),Ai(this);else if(_==="erroring")cc(this,l._storedError),Ai(this);else if(_==="closed")fp(this),ob(this);else{let v=l._storedError;cc(this,v),lp(this,v)}}get closed(){return Dr(this)?this._closedPromise:h(Or("closed"))}get desiredSize(){if(!Dr(this))throw Or("desiredSize");if(this._ownerWritableStream===void 0)throw Go("desiredSize");return V0(this)}get ready(){return Dr(this)?this._readyPromise:h(Or("ready"))}abort(l=void 0){return Dr(this)?this._ownerWritableStream===void 0?h(Go("abort")):G0(this,l):h(Or("abort"))}close(){if(!Dr(this))return h(Or("close"));let l=this._ownerWritableStream;return l===void 0?h(Go("close")):Xt(l)?h(new TypeError("Cannot close an already-closing stream")):rp(this)}releaseLock(){if(!Dr(this))throw Or("releaseLock");this._ownerWritableStream!==void 0&&sp(this)}write(l=void 0){return Dr(this)?this._ownerWritableStream===void 0?h(Go("write to")):ip(this,l):h(Or("write"))}};m(W0,"WritableStreamDefaultWriter");let Yn=W0;Object.defineProperties(Yn.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),i(Yn.prototype.abort,"abort"),i(Yn.prototype.close,"close"),i(Yn.prototype.releaseLock,"releaseLock"),i(Yn.prototype.write,"write"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Yn.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});function Dr(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_ownerWritableStream")?!1:c instanceof Yn}m(Dr,"IsWritableStreamDefaultWriter");function G0(c,l){let _=c._ownerWritableStream;return bi(_,l)}m(G0,"WritableStreamDefaultWriterAbort");function rp(c){let l=c._ownerWritableStream;return np(l)}m(rp,"WritableStreamDefaultWriterClose");function J0(c){let l=c._ownerWritableStream,_=l._state;return Xt(l)||_==="closed"?p(void 0):_==="errored"?h(l._storedError):rp(c)}m(J0,"WritableStreamDefaultWriterCloseWithErrorPropagation");function K0(c,l){c._closedPromiseState==="pending"?ac(c,l):sb(c,l)}m(K0,"WritableStreamDefaultWriterEnsureClosedPromiseRejected");function op(c,l){c._readyPromiseState==="pending"?pp(c,l):ab(c,l)}m(op,"WritableStreamDefaultWriterEnsureReadyPromiseRejected");function V0(c){let l=c._ownerWritableStream,_=l._state;return _==="errored"||_==="erroring"?null:_==="closed"?0:cp(l._writableStreamController)}m(V0,"WritableStreamDefaultWriterGetDesiredSize");function sp(c){let l=c._ownerWritableStream,_=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");op(c,_),K0(c,_),l._writer=void 0,c._ownerWritableStream=void 0}m(sp,"WritableStreamDefaultWriterRelease");function ip(c,l){let _=c._ownerWritableStream,v=_._writableStreamController,I=eb(v,l);if(_!==c._ownerWritableStream)return h(Go("write to"));let $=_._state;if($==="errored")return h(_._storedError);if(Xt(_)||$==="closed")return h(new TypeError("The stream is closing or closed and cannot be written to"));if($==="erroring")return h(_._storedError);let W=B0(_);return tb(v,l,I),W}m(ip,"WritableStreamDefaultWriterWrite");let Y0={},X0=class{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!oc(this))throw ic("abortReason");return this._abortReason}get signal(){if(!oc(this))throw ic("signal");if(this._abortController===void 0)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(l=void 0){if(!oc(this))throw ic("error");this._controlledWritableStream._state==="writable"&&up(this,l)}[j](l){let _=this._abortAlgorithm(l);return wi(this),_}[ee](){Kn(this)}};m(X0,"WritableStreamDefaultController");let zo=X0;Object.defineProperties(zo.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(zo.prototype,Symbol.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});function oc(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledWritableStream")?!1:c instanceof zo}m(oc,"IsWritableStreamDefaultController");function ap(c,l,_,v,I,$,W,se){l._controlledWritableStream=c,c._writableStreamController=l,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._abortReason=void 0,l._abortController=F0(),l._started=!1,l._strategySizeAlgorithm=se,l._strategyHWM=W,l._writeAlgorithm=v,l._closeAlgorithm=I,l._abortAlgorithm=$;let le=sc(l);rc(c,le);let ge=_(),ke=p(ge);C(ke,()=>(l._started=!0,ki(l),null),Se=>(l._started=!0,ec(c,Se),null))}m(ap,"SetUpWritableStreamDefaultController");function Q0(c,l,_,v){let I=Object.create(zo.prototype),$,W,se,le;l.start!==void 0?$=m(()=>l.start(I),"startAlgorithm"):$=m(()=>{},"startAlgorithm"),l.write!==void 0?W=m(ge=>l.write(ge,I),"writeAlgorithm"):W=m(()=>p(void 0),"writeAlgorithm"),l.close!==void 0?se=m(()=>l.close(),"closeAlgorithm"):se=m(()=>p(void 0),"closeAlgorithm"),l.abort!==void 0?le=m(ge=>l.abort(ge),"abortAlgorithm"):le=m(()=>p(void 0),"abortAlgorithm"),ap(c,I,$,W,se,le,_,v)}m(Q0,"SetUpWritableStreamDefaultControllerFromUnderlyingSink");function wi(c){c._writeAlgorithm=void 0,c._closeAlgorithm=void 0,c._abortAlgorithm=void 0,c._strategySizeAlgorithm=void 0}m(wi,"WritableStreamDefaultControllerClearAlgorithms");function Z0(c){Ga(c,Y0,0),ki(c)}m(Z0,"WritableStreamDefaultControllerClose");function eb(c,l){try{return c._strategySizeAlgorithm(l)}catch(_){return Wo(c,_),1}}m(eb,"WritableStreamDefaultControllerGetChunkSize");function cp(c){return c._strategyHWM-c._queueTotalSize}m(cp,"WritableStreamDefaultControllerGetDesiredSize");function tb(c,l,_){try{Ga(c,l,_)}catch(I){Wo(c,I);return}let v=c._controlledWritableStream;if(!Xt(v)&&v._state==="writable"){let I=sc(c);rc(v,I)}ki(c)}m(tb,"WritableStreamDefaultControllerWrite");function ki(c){let l=c._controlledWritableStream;if(!c._started||l._inFlightWriteRequest!==void 0)return;if(l._state==="erroring"){nc(l);return}if(c._queue.length===0)return;let _=u0(c);_===Y0?nb(c):rb(c,_)}m(ki,"WritableStreamDefaultControllerAdvanceQueueIfNeeded");function Wo(c,l){c._controlledWritableStream._state==="writable"&&up(c,l)}m(Wo,"WritableStreamDefaultControllerErrorIfNeeded");function nb(c){let l=c._controlledWritableStream;H0(l),Wa(c);let _=c._closeAlgorithm();wi(c),C(_,()=>(L0(l),null),v=>($0(l,v),null))}m(nb,"WritableStreamDefaultControllerProcessClose");function rb(c,l){let _=c._controlledWritableStream;z0(_);let v=c._writeAlgorithm(l);C(v,()=>{U0(_);let I=_._state;if(Wa(c),!Xt(_)&&I==="writable"){let $=sc(c);rc(_,$)}return ki(c),null},I=>(_._state==="writable"&&wi(c),j0(_,I),null))}m(rb,"WritableStreamDefaultControllerProcessWrite");function sc(c){return cp(c)<=0}m(sc,"WritableStreamDefaultControllerGetBackpressure");function up(c,l){let _=c._controlledWritableStream;wi(c),tc(_,l)}m(up,"WritableStreamDefaultControllerError");function Si(c){return new TypeError(`WritableStream.prototype.${c} can only be used on a WritableStream`)}m(Si,"streamBrandCheckException$2");function ic(c){return new TypeError(`WritableStreamDefaultController.prototype.${c} can only be used on a WritableStreamDefaultController`)}m(ic,"defaultControllerBrandCheckException$2");function Or(c){return new TypeError(`WritableStreamDefaultWriter.prototype.${c} can only be used on a WritableStreamDefaultWriter`)}m(Or,"defaultWriterBrandCheckException");function Go(c){return new TypeError("Cannot "+c+" a stream using a released writer")}m(Go,"defaultWriterLockException");function Ai(c){c._closedPromise=f((l,_)=>{c._closedPromise_resolve=l,c._closedPromise_reject=_,c._closedPromiseState="pending"})}m(Ai,"defaultWriterClosedPromiseInitialize");function lp(c,l){Ai(c),ac(c,l)}m(lp,"defaultWriterClosedPromiseInitializeAsRejected");function ob(c){Ai(c),dp(c)}m(ob,"defaultWriterClosedPromiseInitializeAsResolved");function ac(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")}m(ac,"defaultWriterClosedPromiseReject");function sb(c,l){lp(c,l)}m(sb,"defaultWriterClosedPromiseResetToRejected");function dp(c){c._closedPromise_resolve!==void 0&&(c._closedPromise_resolve(void 0),c._closedPromise_resolve=void 0,c._closedPromise_reject=void 0,c._closedPromiseState="resolved")}m(dp,"defaultWriterClosedPromiseResolve");function Ei(c){c._readyPromise=f((l,_)=>{c._readyPromise_resolve=l,c._readyPromise_reject=_}),c._readyPromiseState="pending"}m(Ei,"defaultWriterReadyPromiseInitialize");function cc(c,l){Ei(c),pp(c,l)}m(cc,"defaultWriterReadyPromiseInitializeAsRejected");function fp(c){Ei(c),uc(c)}m(fp,"defaultWriterReadyPromiseInitializeAsResolved");function pp(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")}m(pp,"defaultWriterReadyPromiseReject");function ib(c){Ei(c)}m(ib,"defaultWriterReadyPromiseReset");function ab(c,l){cc(c,l)}m(ab,"defaultWriterReadyPromiseResetToRejected");function uc(c){c._readyPromise_resolve!==void 0&&(c._readyPromise_resolve(void 0),c._readyPromise_resolve=void 0,c._readyPromise_reject=void 0,c._readyPromiseState="fulfilled")}m(uc,"defaultWriterReadyPromiseResolve");function cb(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof gg<"u")return gg}m(cb,"getGlobals");let ZR=cb();function ub(c){if(!(typeof c=="function"||typeof c=="object")||c.name!=="DOMException")return!1;try{return new c,!0}catch{return!1}}m(ub,"isDOMExceptionConstructor");function lb(){let c=ZR?.DOMException;return ub(c)?c:void 0}m(lb,"getFromGlobal");function db(){let c=m(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}m(db,"createPolyfill");let eD=lb()||db();function hp(c,l,_,v,I,$){let W=U(c),se=ep(l);c._disturbed=!0;let le=!1,ge=p(void 0);return f((ke,Se)=>{let Be;if($!==void 0){if(Be=m(()=>{let fe=$.reason!==void 0?$.reason:new eD("Aborted","AbortError"),De=[];v||De.push(()=>l._state==="writable"?bi(l,fe):p(void 0)),I||De.push(()=>c._state==="readable"?Ut(c,fe):p(void 0)),gt(()=>Promise.all(De.map(Me=>Me())),!0,fe)},"abortAlgorithm"),$.aborted){Be();return}$.addEventListener("abort",Be)}function Ct(){return f((fe,De)=>{function Me(mt){mt?fe():g(er(),Me,De)}m(Me,"next"),Me(!1)})}m(Ct,"pipeLoop");function er(){return le?p(!0):g(se._readyPromise,()=>f((fe,De)=>{ye(W,{_chunkSteps:m(Me=>{ge=g(ip(se,Me),void 0,r),fe(!1)},"_chunkSteps"),_closeSteps:m(()=>fe(!0),"_closeSteps"),_errorSteps:De})}))}if(m(er,"pipeStep"),jt(c,W._closedPromise,fe=>(v?wt(!0,fe):gt(()=>bi(l,fe),!0,fe),null)),jt(l,se._closedPromise,fe=>(I?wt(!0,fe):gt(()=>Ut(c,fe),!0,fe),null)),tt(c,W._closedPromise,()=>(_?wt():gt(()=>J0(se)),null)),Xt(l)||l._state==="closed"){let fe=new TypeError("the destination writable stream closed before all data could be piped to it");I?wt(!0,fe):gt(()=>Ut(c,fe),!0,fe)}A(Ct());function Qt(){let fe=ge;return g(ge,()=>fe!==ge?Qt():void 0)}m(Qt,"waitForWritesToFinish");function jt(fe,De,Me){fe._state==="errored"?Me(fe._storedError):k(De,Me)}m(jt,"isOrBecomesErrored");function tt(fe,De,Me){fe._state==="closed"?Me():y(De,Me)}m(tt,"isOrBecomesClosed");function gt(fe,De,Me){if(le)return;le=!0,l._state==="writable"&&!Xt(l)?y(Qt(),mt):mt();function mt(){return C(fe(),()=>tr(De,Me),Nr=>tr(!0,Nr)),null}m(mt,"doTheRest")}m(gt,"shutdownWithAction");function wt(fe,De){le||(le=!0,l._state==="writable"&&!Xt(l)?y(Qt(),()=>tr(fe,De)):tr(fe,De))}m(wt,"shutdown");function tr(fe,De){return sp(se),Te(W),$!==void 0&&$.removeEventListener("abort",Be),fe?Se(De):ke(void 0),null}m(tr,"finalize")})}m(hp,"ReadableStreamPipeTo");let fb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!vi(this))throw xi("desiredSize");return lc(this)}close(){if(!vi(this))throw xi("close");if(!ao(this))throw new TypeError("The stream is not in a state that permits close");Pr(this)}enqueue(l=void 0){if(!vi(this))throw xi("enqueue");if(!ao(this))throw new TypeError("The stream is not in a state that permits enqueue");return io(this,l)}error(l=void 0){if(!vi(this))throw xi("error");Bt(this,l)}[z](l){Kn(this);let _=this._cancelAlgorithm(l);return Ti(this),_}[te](l){let _=this._controlledReadableStream;if(this._queue.length>0){let v=Wa(this);this._closeRequested&&this._queue.length===0?(Ti(this),Vo(_)):Jo(this),l._chunkSteps(v)}else B(_,l),Jo(this)}[Q](){}};m(fb,"ReadableStreamDefaultController");let Xn=fb;Object.defineProperties(Xn.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Xn.prototype.close,"close"),i(Xn.prototype.enqueue,"enqueue"),i(Xn.prototype.error,"error"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Xn.prototype,Symbol.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});function vi(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledReadableStream")?!1:c instanceof Xn}m(vi,"IsReadableStreamDefaultController");function Jo(c){if(!gp(c))return;if(c._pulling){c._pullAgain=!0;return}c._pulling=!0;let l=c._pullAlgorithm();C(l,()=>(c._pulling=!1,c._pullAgain&&(c._pullAgain=!1,Jo(c)),null),_=>(Bt(c,_),null))}m(Jo,"ReadableStreamDefaultControllerCallPullIfNeeded");function gp(c){let l=c._controlledReadableStream;return!ao(c)||!c._started?!1:!!(Zn(l)&&ie(l)>0||lc(c)>0)}m(gp,"ReadableStreamDefaultControllerShouldCallPull");function Ti(c){c._pullAlgorithm=void 0,c._cancelAlgorithm=void 0,c._strategySizeAlgorithm=void 0}m(Ti,"ReadableStreamDefaultControllerClearAlgorithms");function Pr(c){if(!ao(c))return;let l=c._controlledReadableStream;c._closeRequested=!0,c._queue.length===0&&(Ti(c),Vo(l))}m(Pr,"ReadableStreamDefaultControllerClose");function io(c,l){if(!ao(c))return;let _=c._controlledReadableStream;if(Zn(_)&&ie(_)>0)K(_,l,!1);else{let v;try{v=c._strategySizeAlgorithm(l)}catch(I){throw Bt(c,I),I}try{Ga(c,l,v)}catch(I){throw Bt(c,I),I}}Jo(c)}m(io,"ReadableStreamDefaultControllerEnqueue");function Bt(c,l){let _=c._controlledReadableStream;_._state==="readable"&&(Kn(c),Ti(c),bp(_,l))}m(Bt,"ReadableStreamDefaultControllerError");function lc(c){let l=c._controlledReadableStream._state;return l==="errored"?null:l==="closed"?0:c._strategyHWM-c._queueTotalSize}m(lc,"ReadableStreamDefaultControllerGetDesiredSize");function pb(c){return!gp(c)}m(pb,"ReadableStreamDefaultControllerHasBackpressure");function ao(c){let l=c._controlledReadableStream._state;return!c._closeRequested&&l==="readable"}m(ao,"ReadableStreamDefaultControllerCanCloseOrEnqueue");function mp(c,l,_,v,I,$,W){l._controlledReadableStream=c,l._queue=void 0,l._queueTotalSize=void 0,Kn(l),l._started=!1,l._closeRequested=!1,l._pullAgain=!1,l._pulling=!1,l._strategySizeAlgorithm=W,l._strategyHWM=$,l._pullAlgorithm=v,l._cancelAlgorithm=I,c._readableStreamController=l;let se=_();C(p(se),()=>(l._started=!0,Jo(l),null),le=>(Bt(l,le),null))}m(mp,"SetUpReadableStreamDefaultController");function hb(c,l,_,v){let I=Object.create(Xn.prototype),$,W,se;l.start!==void 0?$=m(()=>l.start(I),"startAlgorithm"):$=m(()=>{},"startAlgorithm"),l.pull!==void 0?W=m(()=>l.pull(I),"pullAlgorithm"):W=m(()=>p(void 0),"pullAlgorithm"),l.cancel!==void 0?se=m(le=>l.cancel(le),"cancelAlgorithm"):se=m(()=>p(void 0),"cancelAlgorithm"),mp(c,I,$,W,se,_,v)}m(hb,"SetUpReadableStreamDefaultControllerFromUnderlyingSource");function xi(c){return new TypeError(`ReadableStreamDefaultController.prototype.${c} can only be used on a ReadableStreamDefaultController`)}m(xi,"defaultControllerBrandCheckException$1");function gb(c,l){return Er(c._readableStreamController)?yb(c):mb(c)}m(gb,"ReadableStreamTee");function mb(c,l){let _=U(c),v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(tt=>{Se=tt});function Ct(){return v?(I=!0,p(void 0)):(v=!0,ye(_,{_chunkSteps:m(tt=>{w(()=>{I=!1;let gt=tt,wt=tt;$||io(ge._readableStreamController,gt),W||io(ke._readableStreamController,wt),v=!1,I&&Ct()})},"_chunkSteps"),_closeSteps:m(()=>{v=!1,$||Pr(ge._readableStreamController),W||Pr(ke._readableStreamController),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{v=!1},"_errorSteps")}),p(void 0))}m(Ct,"pullAlgorithm");function er(tt){if($=!0,se=tt,W){let gt=Lo([se,le]),wt=Ut(c,gt);Se(wt)}return Be}m(er,"cancel1Algorithm");function Qt(tt){if(W=!0,le=tt,$){let gt=Lo([se,le]),wt=Ut(c,gt);Se(wt)}return Be}m(Qt,"cancel2Algorithm");function jt(){}return m(jt,"startAlgorithm"),ge=Ko(jt,Ct,er),ke=Ko(jt,Ct,Qt),k(_._closedPromise,tt=>(Bt(ge._readableStreamController,tt),Bt(ke._readableStreamController,tt),(!$||!W)&&Se(void 0),null)),[ge,ke]}m(mb,"ReadableStreamDefaultTee");function yb(c){let l=U(c),_=!1,v=!1,I=!1,$=!1,W=!1,se,le,ge,ke,Se,Be=f(fe=>{Se=fe});function Ct(fe){k(fe._closedPromise,De=>(fe!==l||(Rt(ge._readableStreamController,De),Rt(ke._readableStreamController,De),(!$||!W)&&Se(void 0)),null))}m(Ct,"forwardReaderError");function er(){xr(l)&&(Te(l),l=U(c),Ct(l)),ye(l,{_chunkSteps:m(fe=>{w(()=>{v=!1,I=!1;let De=fe,Me=fe;if(!$&&!W)try{Me=Nf(fe)}catch(mt){Rt(ge._readableStreamController,mt),Rt(ke._readableStreamController,mt),Se(Ut(c,mt));return}$||pi(ge._readableStreamController,De),W||pi(ke._readableStreamController,Me),_=!1,v?jt():I&&tt()})},"_chunkSteps"),_closeSteps:m(()=>{_=!1,$||$o(ge._readableStreamController),W||$o(ke._readableStreamController),ge._readableStreamController._pendingPullIntos.length>0&&hi(ge._readableStreamController,0),ke._readableStreamController._pendingPullIntos.length>0&&hi(ke._readableStreamController,0),(!$||!W)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{_=!1},"_errorSteps")})}m(er,"pullWithDefaultReader");function Qt(fe,De){he(l)&&(Te(l),l=Kf(c),Ct(l));let Me=De?ke:ge,mt=De?ge:ke;Xf(l,fe,1,{_chunkSteps:m(Nr=>{w(()=>{v=!1,I=!1;let Yo=De?W:$;if(De?$:W)Yo||gi(Me._readableStreamController,Nr);else{let Xo;try{Xo=Nf(Nr)}catch(Dp){Rt(Me._readableStreamController,Dp),Rt(mt._readableStreamController,Dp),Se(Ut(c,Dp));return}Yo||gi(Me._readableStreamController,Nr),pi(mt._readableStreamController,Xo)}_=!1,v?jt():I&&tt()})},"_chunkSteps"),_closeSteps:m(Nr=>{_=!1;let Yo=De?W:$,Xo=De?$:W;Yo||$o(Me._readableStreamController),Xo||$o(mt._readableStreamController),Nr!==void 0&&(Yo||gi(Me._readableStreamController,Nr),!Xo&&mt._readableStreamController._pendingPullIntos.length>0&&hi(mt._readableStreamController,0)),(!Yo||!Xo)&&Se(void 0)},"_closeSteps"),_errorSteps:m(()=>{_=!1},"_errorSteps")})}m(Qt,"pullWithBYOBReader");function jt(){if(_)return v=!0,p(void 0);_=!0;let fe=Xa(ge._readableStreamController);return fe===null?er():Qt(fe._view,!1),p(void 0)}m(jt,"pull1Algorithm");function tt(){if(_)return I=!0,p(void 0);_=!0;let fe=Xa(ke._readableStreamController);return fe===null?er():Qt(fe._view,!0),p(void 0)}m(tt,"pull2Algorithm");function gt(fe){if($=!0,se=fe,W){let De=Lo([se,le]),Me=Ut(c,De);Se(Me)}return Be}m(gt,"cancel1Algorithm");function wt(fe){if(W=!0,le=fe,$){let De=Lo([se,le]),Me=Ut(c,De);Se(Me)}return Be}m(wt,"cancel2Algorithm");function tr(){}return m(tr,"startAlgorithm"),ge=_p(tr,jt,gt),ke=_p(tr,tt,wt),Ct(l),[ge,ke]}m(yb,"ReadableByteStreamTee");function _b(c){return o(c)&&typeof c.getReader<"u"}m(_b,"isReadableStreamLike");function bb(c){return _b(c)?wb(c.getReader()):Cb(c)}m(bb,"ReadableStreamFrom");function Cb(c){let l,_=Ff(c,"async"),v=r;function I(){let W;try{W=s0(_)}catch(le){return h(le)}let se=p(W);return b(se,le=>{if(!o(le))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");if(i0(le))Pr(l._readableStreamController);else{let ge=a0(le);io(l._readableStreamController,ge)}})}m(I,"pullAlgorithm");function $(W){let se=_.iterator,le;try{le=li(se,"return")}catch(Se){return h(Se)}if(le===void 0)return p(void 0);let ge;try{ge=E(le,se,[W])}catch(Se){return h(Se)}let ke=p(ge);return b(ke,Se=>{if(!o(Se))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")})}return m($,"cancelAlgorithm"),l=Ko(v,I,$,0),l}m(Cb,"ReadableStreamFromIterable");function wb(c){let l,_=r;function v(){let $;try{$=c.read()}catch(W){return h(W)}return b($,W=>{if(!o(W))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(W.done)Pr(l._readableStreamController);else{let se=W.value;io(l._readableStreamController,se)}})}m(v,"pullAlgorithm");function I($){try{return p(c.cancel($))}catch(W){return h(W)}}return m(I,"cancelAlgorithm"),l=Ko(_,v,I,0),l}m(wb,"ReadableStreamFromDefaultReader");function kb(c,l){de(c,l);let _=c,v=_?.autoAllocateChunkSize,I=_?.cancel,$=_?.pull,W=_?.start,se=_?.type;return{autoAllocateChunkSize:v===void 0?void 0:P(v,`${l} has member 'autoAllocateChunkSize' that`),cancel:I===void 0?void 0:Sb(I,_,`${l} has member 'cancel' that`),pull:$===void 0?void 0:Ab($,_,`${l} has member 'pull' that`),start:W===void 0?void 0:Eb(W,_,`${l} has member 'start' that`),type:se===void 0?void 0:vb(se,`${l} has member 'type' that`)}}m(kb,"convertUnderlyingDefaultOrByteSource");function Sb(c,l,_){return ce(c,_),v=>x(c,l,[v])}m(Sb,"convertUnderlyingSourceCancelCallback");function Ab(c,l,_){return ce(c,_),v=>x(c,l,[v])}m(Ab,"convertUnderlyingSourcePullCallback");function Eb(c,l,_){return ce(c,_),v=>E(c,l,[v])}m(Eb,"convertUnderlyingSourceStartCallback");function vb(c,l){if(c=`${c}`,c!=="bytes")throw new TypeError(`${l} '${c}' is not a valid enumeration value for ReadableStreamType`);return c}m(vb,"convertReadableStreamType");function Tb(c,l){return de(c,l),{preventCancel:!!c?.preventCancel}}m(Tb,"convertIteratorOptions");function yp(c,l){de(c,l);let _=c?.preventAbort,v=c?.preventCancel,I=c?.preventClose,$=c?.signal;return $!==void 0&&xb($,`${l} has member 'signal' that`),{preventAbort:!!_,preventCancel:!!v,preventClose:!!I,signal:$}}m(yp,"convertPipeOptions");function xb(c,l){if(!I0(c))throw new TypeError(`${l} is not an AbortSignal.`)}m(xb,"assertAbortSignal");function Rb(c,l){de(c,l);let _=c?.readable;M(_,"readable","ReadableWritablePair"),N(_,`${l} has member 'readable' that`);let v=c?.writable;return M(v,"writable","ReadableWritablePair"),Zf(v,`${l} has member 'writable' that`),{readable:_,writable:v}}m(Rb,"convertReadableWritablePair");let Db=class{constructor(l={},_={}){l===void 0?l=null:T(l,"First parameter");let v=_i(_,"Second parameter"),I=kb(l,"First parameter");if(dc(this),I.type==="bytes"){if(v.size!==void 0)throw new RangeError("The strategy for a byte stream cannot have a size function");let $=Ho(v,0);b0(this,I,$)}else{let $=yi(v),W=Ho(v,1);hb(this,I,W,$)}}get locked(){if(!Qn(this))throw Ir("locked");return Zn(this)}cancel(l=void 0){return Qn(this)?Zn(this)?h(new TypeError("Cannot cancel a stream that already has a reader")):Ut(this,l):h(Ir("cancel"))}getReader(l=void 0){if(!Qn(this))throw Ir("getReader");return w0(l,"First parameter").mode===void 0?U(this):Kf(this)}pipeThrough(l,_={}){if(!Qn(this))throw Ir("pipeThrough");R(l,1,"pipeThrough");let v=Rb(l,"First parameter"),I=yp(_,"Second parameter");if(Zn(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(so(v.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");let $=hp(this,v.writable,I.preventClose,I.preventAbort,I.preventCancel,I.signal);return A($),v.readable}pipeTo(l,_={}){if(!Qn(this))return h(Ir("pipeTo"));if(l===void 0)return h("Parameter 1 is required in 'pipeTo'.");if(!oo(l))return h(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let v;try{v=yp(_,"Second parameter")}catch(I){return h(I)}return Zn(this)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):so(l)?h(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):hp(this,l,v.preventClose,v.preventAbort,v.preventCancel,v.signal)}tee(){if(!Qn(this))throw Ir("tee");let l=gb(this);return Lo(l)}values(l=void 0){if(!Qn(this))throw Ir("values");let _=Tb(l,"First parameter");return ht(this,_.preventCancel)}[If](l){return this.values(l)}static from(l){return bb(l)}};m(Db,"ReadableStream");let dt=Db;Object.defineProperties(dt,{from:{enumerable:!0}}),Object.defineProperties(dt.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),i(dt.from,"from"),i(dt.prototype.cancel,"cancel"),i(dt.prototype.getReader,"getReader"),i(dt.prototype.pipeThrough,"pipeThrough"),i(dt.prototype.pipeTo,"pipeTo"),i(dt.prototype.tee,"tee"),i(dt.prototype.values,"values"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(dt.prototype,Symbol.toStringTag,{value:"ReadableStream",configurable:!0}),Object.defineProperty(dt.prototype,If,{value:dt.prototype.values,writable:!0,configurable:!0});function Ko(c,l,_,v=1,I=()=>1){let $=Object.create(dt.prototype);dc($);let W=Object.create(Xn.prototype);return mp($,W,c,l,_,v,I),$}m(Ko,"CreateReadableStream");function _p(c,l,_){let v=Object.create(dt.prototype);dc(v);let I=Object.create(Vn.prototype);return Jf(v,I,c,l,_,0,void 0),v}m(_p,"CreateReadableByteStream");function dc(c){c._state="readable",c._reader=void 0,c._storedError=void 0,c._disturbed=!1}m(dc,"InitializeReadableStream");function Qn(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_readableStreamController")?!1:c instanceof dt}m(Qn,"IsReadableStream");function Zn(c){return c._reader!==void 0}m(Zn,"IsReadableStreamLocked");function Ut(c,l){if(c._disturbed=!0,c._state==="closed")return p(void 0);if(c._state==="errored")return h(c._storedError);Vo(c);let _=c._reader;if(_!==void 0&&xr(_)){let I=_._readIntoRequests;_._readIntoRequests=new V,I.forEach($=>{$._closeSteps(void 0)})}let v=c._readableStreamController[z](l);return b(v,r)}m(Ut,"ReadableStreamCancel");function Vo(c){c._state="closed";let l=c._reader;if(l!==void 0&&(H(l),he(l))){let _=l._readRequests;l._readRequests=new V,_.forEach(v=>{v._closeSteps()})}}m(Vo,"ReadableStreamClose");function bp(c,l){c._state="errored",c._storedError=l;let _=c._reader;_!==void 0&&(Ie(_,l),he(_)?Ye(_,l):Qf(_,l))}m(bp,"ReadableStreamError");function Ir(c){return new TypeError(`ReadableStream.prototype.${c} can only be used on a ReadableStream`)}m(Ir,"streamBrandCheckException$1");function Cp(c,l){de(c,l);let _=c?.highWaterMark;return M(_,"highWaterMark","QueuingStrategyInit"),{highWaterMark:D(_)}}m(Cp,"convertQueuingStrategyInit");let Ob=m(c=>c.byteLength,"byteLengthSizeFunction");i(Ob,"size");let Pb=class{constructor(l){R(l,1,"ByteLengthQueuingStrategy"),l=Cp(l,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!kp(this))throw wp("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!kp(this))throw wp("size");return Ob}};m(Pb,"ByteLengthQueuingStrategy");let fc=Pb;Object.defineProperties(fc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(fc.prototype,Symbol.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});function wp(c){return new TypeError(`ByteLengthQueuingStrategy.prototype.${c} can only be used on a ByteLengthQueuingStrategy`)}m(wp,"byteLengthBrandCheckException");function kp(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_byteLengthQueuingStrategyHighWaterMark")?!1:c instanceof fc}m(kp,"IsByteLengthQueuingStrategy");let Ib=m(()=>1,"countSizeFunction");i(Ib,"size");let Fb=class{constructor(l){R(l,1,"CountQueuingStrategy"),l=Cp(l,"First parameter"),this._countQueuingStrategyHighWaterMark=l.highWaterMark}get highWaterMark(){if(!Ap(this))throw Sp("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Ap(this))throw Sp("size");return Ib}};m(Fb,"CountQueuingStrategy");let pc=Fb;Object.defineProperties(pc.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(pc.prototype,Symbol.toStringTag,{value:"CountQueuingStrategy",configurable:!0});function Sp(c){return new TypeError(`CountQueuingStrategy.prototype.${c} can only be used on a CountQueuingStrategy`)}m(Sp,"countBrandCheckException");function Ap(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_countQueuingStrategyHighWaterMark")?!1:c instanceof pc}m(Ap,"IsCountQueuingStrategy");function Nb(c,l){de(c,l);let _=c?.cancel,v=c?.flush,I=c?.readableType,$=c?.start,W=c?.transform,se=c?.writableType;return{cancel:_===void 0?void 0:jb(_,c,`${l} has member 'cancel' that`),flush:v===void 0?void 0:Mb(v,c,`${l} has member 'flush' that`),readableType:I,start:$===void 0?void 0:Bb($,c,`${l} has member 'start' that`),transform:W===void 0?void 0:Ub(W,c,`${l} has member 'transform' that`),writableType:se}}m(Nb,"convertTransformer");function Mb(c,l,_){return ce(c,_),v=>x(c,l,[v])}m(Mb,"convertTransformerFlushCallback");function Bb(c,l,_){return ce(c,_),v=>E(c,l,[v])}m(Bb,"convertTransformerStartCallback");function Ub(c,l,_){return ce(c,_),(v,I)=>x(c,l,[v,I])}m(Ub,"convertTransformerTransformCallback");function jb(c,l,_){return ce(c,_),v=>x(c,l,[v])}m(jb,"convertTransformerCancelCallback");let Lb=class{constructor(l={},_={},v={}){l===void 0&&(l=null);let I=_i(_,"Second parameter"),$=_i(v,"Third parameter"),W=Nb(l,"First parameter");if(W.readableType!==void 0)throw new RangeError("Invalid readableType specified");if(W.writableType!==void 0)throw new RangeError("Invalid writableType specified");let se=Ho($,0),le=yi($),ge=Ho(I,1),ke=yi(I),Se,Be=f(Ct=>{Se=Ct});$b(this,Be,ge,ke,se,le),zb(this,W),W.start!==void 0?Se(W.start(this._transformStreamController)):Se(void 0)}get readable(){if(!Ep(this))throw Rp("readable");return this._readable}get writable(){if(!Ep(this))throw Rp("writable");return this._writable}};m(Lb,"TransformStream");let hc=Lb;Object.defineProperties(hc.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(hc.prototype,Symbol.toStringTag,{value:"TransformStream",configurable:!0});function $b(c,l,_,v,I,$){function W(){return l}m(W,"startAlgorithm");function se(Be){return Jb(c,Be)}m(se,"writeAlgorithm");function le(Be){return Kb(c,Be)}m(le,"abortAlgorithm");function ge(){return Vb(c)}m(ge,"closeAlgorithm"),c._writable=M0(W,se,ge,le,_,v);function ke(){return Yb(c)}m(ke,"pullAlgorithm");function Se(Be){return Xb(c,Be)}m(Se,"cancelAlgorithm"),c._readable=Ko(W,ke,Se,I,$),c._backpressure=void 0,c._backpressureChangePromise=void 0,c._backpressureChangePromise_resolve=void 0,Ri(c,!0),c._transformStreamController=void 0}m($b,"InitializeTransformStream");function Ep(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_transformStreamController")?!1:c instanceof hc}m(Ep,"IsTransformStream");function vp(c,l){Bt(c._readable._readableStreamController,l),gc(c,l)}m(vp,"TransformStreamError");function gc(c,l){Oi(c._transformStreamController),Wo(c._writable._writableStreamController,l),mc(c)}m(gc,"TransformStreamErrorWritableAndUnblockWrite");function mc(c){c._backpressure&&Ri(c,!1)}m(mc,"TransformStreamUnblockWrite");function Ri(c,l){c._backpressureChangePromise!==void 0&&c._backpressureChangePromise_resolve(),c._backpressureChangePromise=f(_=>{c._backpressureChangePromise_resolve=_}),c._backpressure=l}m(Ri,"TransformStreamSetBackpressure");let qb=class{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Di(this))throw Pi("desiredSize");let l=this._controlledTransformStream._readable._readableStreamController;return lc(l)}enqueue(l=void 0){if(!Di(this))throw Pi("enqueue");Tp(this,l)}error(l=void 0){if(!Di(this))throw Pi("error");Wb(this,l)}terminate(){if(!Di(this))throw Pi("terminate");Gb(this)}};m(qb,"TransformStreamDefaultController");let Fr=qb;Object.defineProperties(Fr.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),i(Fr.prototype.enqueue,"enqueue"),i(Fr.prototype.error,"error"),i(Fr.prototype.terminate,"terminate"),typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(Fr.prototype,Symbol.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});function Di(c){return!o(c)||!Object.prototype.hasOwnProperty.call(c,"_controlledTransformStream")?!1:c instanceof Fr}m(Di,"IsTransformStreamDefaultController");function Hb(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}m(Hb,"SetUpTransformStreamDefaultController");function zb(c,l){let _=Object.create(Fr.prototype),v,I,$;l.transform!==void 0?v=m(W=>l.transform(W,_),"transformAlgorithm"):v=m(W=>{try{return Tp(_,W),p(void 0)}catch(se){return h(se)}},"transformAlgorithm"),l.flush!==void 0?I=m(()=>l.flush(_),"flushAlgorithm"):I=m(()=>p(void 0),"flushAlgorithm"),l.cancel!==void 0?$=m(W=>l.cancel(W),"cancelAlgorithm"):$=m(()=>p(void 0),"cancelAlgorithm"),Hb(c,_,v,I,$)}m(zb,"SetUpTransformStreamDefaultControllerFromTransformer");function Oi(c){c._transformAlgorithm=void 0,c._flushAlgorithm=void 0,c._cancelAlgorithm=void 0}m(Oi,"TransformStreamDefaultControllerClearAlgorithms");function Tp(c,l){let _=c._controlledTransformStream,v=_._readable._readableStreamController;if(!ao(v))throw new TypeError("Readable side is not in a state that permits enqueue");try{io(v,l)}catch(I){throw gc(_,I),_._readable._storedError}pb(v)!==_._backpressure&&Ri(_,!0)}m(Tp,"TransformStreamDefaultControllerEnqueue");function Wb(c,l){vp(c._controlledTransformStream,l)}m(Wb,"TransformStreamDefaultControllerError");function xp(c,l){let _=c._transformAlgorithm(l);return b(_,void 0,v=>{throw vp(c._controlledTransformStream,v),v})}m(xp,"TransformStreamDefaultControllerPerformTransform");function Gb(c){let l=c._controlledTransformStream,_=l._readable._readableStreamController;Pr(_);let v=new TypeError("TransformStream terminated");gc(l,v)}m(Gb,"TransformStreamDefaultControllerTerminate");function Jb(c,l){let _=c._transformStreamController;if(c._backpressure){let v=c._backpressureChangePromise;return b(v,()=>{let I=c._writable;if(I._state==="erroring")throw I._storedError;return xp(_,l)})}return xp(_,l)}m(Jb,"TransformStreamDefaultSinkWriteAlgorithm");function Kb(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 Oi(_),C(I,()=>(v._state==="errored"?co(_,v._storedError):(Bt(v._readableStreamController,l),yc(_)),null),$=>(Bt(v._readableStreamController,$),co(_,$),null)),_._finishPromise}m(Kb,"TransformStreamDefaultSinkAbortAlgorithm");function Vb(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 Oi(l),C(v,()=>(_._state==="errored"?co(l,_._storedError):(Pr(_._readableStreamController),yc(l)),null),I=>(Bt(_._readableStreamController,I),co(l,I),null)),l._finishPromise}m(Vb,"TransformStreamDefaultSinkCloseAlgorithm");function Yb(c){return Ri(c,!1),c._backpressureChangePromise}m(Yb,"TransformStreamDefaultSourcePullAlgorithm");function Xb(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 Oi(_),C(I,()=>(v._state==="errored"?co(_,v._storedError):(Wo(v._writableStreamController,l),mc(c),yc(_)),null),$=>(Wo(v._writableStreamController,$),mc(c),co(_,$),null)),_._finishPromise}m(Xb,"TransformStreamDefaultSourceCancelAlgorithm");function Pi(c){return new TypeError(`TransformStreamDefaultController.prototype.${c} can only be used on a TransformStreamDefaultController`)}m(Pi,"defaultControllerBrandCheckException");function yc(c){c._finishPromise_resolve!==void 0&&(c._finishPromise_resolve(),c._finishPromise_resolve=void 0,c._finishPromise_reject=void 0)}m(yc,"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)}m(co,"defaultControllerFinishPromiseReject");function Rp(c){return new TypeError(`TransformStream.prototype.${c} can only be used on a TransformStream`)}m(Rp,"streamBrandCheckException"),n.ByteLengthQueuingStrategy=fc,n.CountQueuingStrategy=pc,n.ReadableByteStreamController=Vn,n.ReadableStream=dt,n.ReadableStreamBYOBReader=Tr,n.ReadableStreamBYOBRequest=no,n.ReadableStreamDefaultController=Xn,n.ReadableStreamDefaultReader=me,n.TransformStream=hc,n.TransformStreamDefaultController=Fr,n.WritableStream=Rr,n.WritableStreamDefaultController=zo,n.WritableStreamDefaultWriter=Yn})})(Qu,Qu.exports)),Qu.exports}function QS(){if(XS)return VS;XS=1;let t=65536;if(!globalThis.ReadableStream)try{let e=re("node:process"),{emitWarning:n}=e;try{e.emitWarning=()=>{},Object.assign(globalThis,re("node:stream/web")),e.emitWarning=n}catch(r){throw e.emitWarning=n,r}}catch{Object.assign(globalThis,uA())}try{let{Blob:e}=re("buffer");e&&!e.prototype.stream&&(e.prototype.stream=m(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 VS}async function*Zu(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,ZS),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+ZS)).arrayBuffer();r+=s.byteLength,yield new Uint8Array(s)}}}function dA(t,e=Do){var n=`${eA()}${eA()}`.replace(/\./g,"").slice(-28).padStart(32,"-"),r=[],o=`--${n}\r
|
|
79
|
+
Content-Disposition: form-data; name="`;return t.forEach((s,i)=>typeof s=="string"?r.push(o+wg(i)+`"\r
|
|
80
80
|
\r
|
|
81
81
|
${s.replace(/\r(?!\n)|(?<!\r)\n/g,`\r
|
|
82
82
|
`)}\r
|
|
83
|
-
`):r.push(o+
|
|
83
|
+
`):r.push(o+wg(i)+`"; filename="${wg(s.name,1)}"\r
|
|
84
84
|
Content-Type: ${s.type||"application/octet-stream"}\r
|
|
85
85
|
\r
|
|
86
86
|
`,s,`\r
|
|
87
|
-
`)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function
|
|
87
|
+
`)),r.push(`--${n}--`),new e(r,{type:"multipart/form-data; boundary="+n})}async function el(t){if(t[Tt].disturbed)throw new TypeError(`body used already for: ${t.url}`);if(t[Tt].disturbed=!0,t[Tt].error)throw t[Tt].error;let{body:e}=t;if(e===null)return pt.alloc(0);if(!(e instanceof Mn))return pt.alloc(0);let n=[],r=0;try{for await(let o of e){if(t.size>0&&r+o.length>t.size){let s=new Wt(`content size at ${t.url} over limit: ${t.size}`,"max-size");throw e.destroy(s),s}r+=o.length,n.push(o)}}catch(o){throw o instanceof dl?o:new Wt(`Invalid response body while trying to fetch ${t.url}: ${o.message}`,"system",o)}if(e.readableEnded===!0||e._readableState.ended===!0)try{return n.every(o=>typeof o=="string")?pt.from(n.join("")):pt.concat(n,r)}catch(o){throw new Wt(`Could not create Buffer from response body for ${t.url}: ${o.message}`,"system",o)}else throw new Wt(`Premature close of server response while trying to fetch ${t.url}`)}function bA(t=[]){return new pr(t.reduce((e,n,r,o)=>(r%2===0&&e.push(o.slice(r,r+2)),e),[]).filter(([e,n])=>{try{return tl(e),Sg(e,String(n)),!0}catch{return!1}}))}function Ag(t,e=!1){return t==null||(t=new URL(t),/^(about|blob|data):$/.test(t.protocol))?"no-referrer":(t.username="",t.password="",t.hash="",e&&(t.pathname="",t.search=""),t)}function kA(t){if(!wA.has(t))throw new TypeError(`Invalid referrerPolicy: ${t}`);return t}function SA(t){if(/^(http|ws)s:$/.test(t.protocol))return!0;let e=t.host.replace(/(^\[)|(]$)/g,""),n=qF(e);return n===4&&/^127\./.test(e)||n===6&&/^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(e)?!0:t.host==="localhost"||t.host.endsWith(".localhost")?!1:t.protocol==="file:"}function xo(t){return/^about:(blank|srcdoc)$/.test(t)||t.protocol==="data:"||/^(blob|filesystem):$/.test(t.protocol)?!0:SA(t)}function AA(t,{referrerURLCallback:e,referrerOriginCallback:n}={}){if(t.referrer==="no-referrer"||t.referrerPolicy==="")return null;let r=t.referrerPolicy;if(t.referrer==="about:client")return"no-referrer";let o=t.referrer,s=Ag(o),i=Ag(o,!0);s.toString().length>4096&&(s=i),e&&(s=e(s)),n&&(i=n(i));let a=new URL(t.url);switch(r){case"no-referrer":return"no-referrer";case"origin":return i;case"unsafe-url":return s;case"strict-origin":return xo(s)&&!xo(a)?"no-referrer":i.toString();case"strict-origin-when-cross-origin":return s.origin===a.origin?s:xo(s)&&!xo(a)?"no-referrer":i;case"same-origin":return s.origin===a.origin?s:"no-referrer";case"origin-when-cross-origin":return s.origin===a.origin?s:i;case"no-referrer-when-downgrade":return xo(s)&&!xo(a)?"no-referrer":s;default:throw new TypeError(`Invalid referrerPolicy: ${r}`)}}function EA(t){let e=(t.get("referrer-policy")||"").split(/[,\s]+/),n="";for(let r of e)r&&wA.has(r)&&(n=r);return n}function RA(){if(nA)return kg;if(nA=1,!globalThis.DOMException)try{let{MessageChannel:t}=re("worker_threads"),e=new t().port1,n=new ArrayBuffer;e.postMessage(n,[n,n])}catch(t){t.constructor.name==="DOMException"&&(globalThis.DOMException=t.constructor)}return kg=globalThis.DOMException,kg}async function Fg(t,e){return new Promise((n,r)=>{let o=new la(t,e),{parsedURL:s,options:i}=cN(o);if(!dN.has(s.protocol))throw new TypeError(`node-fetch cannot load ${t}. URL scheme "${s.protocol.replace(/:$/,"")}" is not supported.`);if(s.protocol==="data:"){let C=cA(o.url),y=new Fn(C,{headers:{"Content-Type":C.typeFull}});n(y);return}let a=(s.protocol==="https:"?jF:ua).request,{signal:u}=o,d=null,f=m(()=>{let C=new Pg("The operation was aborted.");r(C),o.body&&o.body instanceof Mn.Readable&&o.body.destroy(C),!(!d||!d.body)&&d.body.emit("error",C)},"abort");if(u&&u.aborted){f();return}let p=m(()=>{f(),g()},"abortAndFinalize"),h=a(s.toString(),i);u&&u.addEventListener("abort",p);let g=m(()=>{h.abort(),u&&u.removeEventListener("abort",p)},"finalize");h.on("error",C=>{r(new Wt(`request to ${o.url} failed, reason: ${C.message}`,"system",C)),g()}),jA(h,C=>{d&&d.body&&d.body.destroy(C)}),process.version<"v14"&&h.on("socket",C=>{let y;C.prependListener("end",()=>{y=C._eventsCount}),C.prependListener("close",k=>{if(d&&y<C._eventsCount&&!k){let b=new Error("Premature close");b.code="ERR_STREAM_PREMATURE_CLOSE",d.body.emit("error",b)}})}),h.on("response",C=>{h.setTimeout(0);let y=bA(C.rawHeaders);if(fl(C.statusCode)){let E=y.get("Location"),x=null;try{x=E===null?null:new URL(E,o.url)}catch{if(o.redirect!=="manual"){r(new Wt(`uri requested responds with an invalid redirect URL: ${E}`,"invalid-redirect")),g();return}}switch(o.redirect){case"error":r(new Wt(`uri requested responds with a redirect, redirect mode is set to error: ${o.url}`,"no-redirect")),g();return;case"manual":break;case"follow":{if(x===null)break;if(o.counter>=o.follow){r(new Wt(`maximum redirect reached at: ${o.url}`,"max-redirect")),g();return}let O={headers:new pr(o.headers),follow:o.follow,counter:o.counter+1,agent:o.agent,compress:o.compress,method:o.method,body:Og(o),signal:o.signal,size:o.size,referrer:o.referrer,referrerPolicy:o.referrerPolicy};if(!QF(o.url,x)||!ZF(o.url,x))for(let V of["authorization","www-authenticate","cookie","cookie2"])O.headers.delete(V);if(C.statusCode!==303&&o.body&&e.body instanceof Mn.Readable){r(new Wt("Cannot follow redirect with body being a readable stream","unsupported-redirect")),g();return}(C.statusCode===303||(C.statusCode===301||C.statusCode===302)&&o.method==="POST")&&(O.method="GET",O.body=void 0,O.headers.delete("content-length"));let q=EA(y);q&&(O.referrerPolicy=q),n(Fg(new la(x,O))),g();return}default:return r(new TypeError(`Redirect option '${o.redirect}' is not a valid value of RequestRedirect`))}}u&&C.once("end",()=>{u.removeEventListener("abort",p)});let k=vs(C,new rl,E=>{E&&r(E)});process.version<"v12.10"&&C.on("aborted",p);let b={url:o.url,status:C.statusCode,statusText:C.statusMessage,headers:y,size:o.size,counter:o.counter,highWaterMark:o.highWaterMark},A=y.get("Content-Encoding");if(!o.compress||o.method==="HEAD"||A===null||C.statusCode===204||C.statusCode===304){d=new Fn(k,b),n(d);return}let w={flush:Es.Z_SYNC_FLUSH,finishFlush:Es.Z_SYNC_FLUSH};if(A==="gzip"||A==="x-gzip"){k=vs(k,Es.createGunzip(w),E=>{E&&r(E)}),d=new Fn(k,b),n(d);return}if(A==="deflate"||A==="x-deflate"){let E=vs(C,new rl,x=>{x&&r(x)});E.once("data",x=>{(x[0]&15)===8?k=vs(k,Es.createInflate(),O=>{O&&r(O)}):k=vs(k,Es.createInflateRaw(),O=>{O&&r(O)}),d=new Fn(k,b),n(d)}),E.once("end",()=>{d||(d=new Fn(k,b),n(d))});return}if(A==="br"){k=vs(k,Es.createBrotliDecompress(),E=>{E&&r(E)}),d=new Fn(k,b),n(d);return}d=new Fn(k,b),n(d)}),rN(h,o).catch(r)})}function jA(t,e){let n=pt.from(`0\r
|
|
88
88
|
\r
|
|
89
|
-
`),r=!1,o=!1,s;t.on("response",i=>{let{headers:a}=i;r=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),t.on("socket",i=>{let a=m(()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},"onSocketClose"),u=m(d=>{o=pt.compare(d.slice(-5),n)===0,!o&&s&&(o=pt.compare(s.slice(-3),n.slice(0,3))===0&&pt.compare(d.slice(-2),n.slice(3))===0),s=d},"onData");i.prependListener("close",a),i.on("data",u),t.on("close",()=>{i.removeListener("close",a),i.removeListener("data",u)})})}function Le(t){let e=
|
|
90
|
-
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),To=m((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),vo=(dg=class{constructor(...t){if(fr(this,tn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ia](){return"FormData"}[HF](){return this.entries()}static[zF](t){return t&&typeof t=="object"&&t[ia]==="FormData"&&!WF.some(e=>typeof t[e]!="function")}append(...t){To("append",arguments,2),ze(this,tn).push(VS(...t))}delete(t){To("delete",arguments,1),t+="",rn(this,tn,ze(this,tn).filter(([e])=>e!==t))}get(t){To("get",arguments,1),t+="";for(var e=ze(this,tn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return To("getAll",arguments,1),e=[],t+="",ze(this,tn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return To("has",arguments,1),t+="",ze(this,tn).some(e=>e[0]===t)}forEach(t,e){To("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){To("set",arguments,2);var e=[],n=!0;t=VS(...t),ze(this,tn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),rn(this,tn,e)}*entries(){yield*ze(this,tn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},tn=new WeakMap,m(dg,"FormData"),dg);m(sA,"formDataToBlob");iA=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}};m(iA,"FetchBaseError");sl=iA,aA=class extends sl{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};m(aA,"FetchError");Wt=aA,el=Symbol.toStringTag,cA=m(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[el]==="URLSearchParams","isURLSearchParameters"),tl=m(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[el]),"isBlob"),GF=m(t=>typeof t=="object"&&(t[el]==="AbortSignal"||t[el]==="EventTarget"),"isAbortSignal"),JF=m((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),KF=m((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),VF=NF(Mn.pipeline),Tt=Symbol("Body internals"),uA=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:cA(e)?e=pt.from(e.toString()):tl(e)||pt.isBuffer(e)||(Qu.isAnyArrayBuffer(e)?e=pt.from(e):ArrayBuffer.isView(e)?e=pt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mn||(e instanceof vo?(e=sA(e),r=e.type.split("=")[1]):e=pt.from(String(e))));let o=e;pt.isBuffer(e)?o=Mn.Readable.from(e):tl(e)&&(o=Mn.Readable.from(e.stream())),this[Tt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Mn&&e.on("error",s=>{let i=s instanceof sl?s:new Wt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Tt].error=i})}get body(){return this[Tt].stream}get bodyUsed(){return this[Tt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await Ku(this);return e.slice(n,n+r)}async formData(){let e=this.headers.get("content-type");if(e.startsWith("application/x-www-form-urlencoded")){let r=new vo,o=new URLSearchParams(await this.text());for(let[s,i]of o)r.append(s,i);return r}let{toFormData:n}=await Promise.resolve().then(()=>(qS(),$S));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Tt].body&&this[Tt].body.type||"",n=await this.arrayBuffer();return new Do([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await Ku(this);return new TextDecoder().decode(e)}buffer(){return Ku(this)}};m(uA,"Body");aa=uA;aa.prototype.buffer=Zu(aa.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(aa.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:Zu(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});m(Ku,"consumeBody");Sg=m((t,e)=>{let n,r,{body:o}=t[Tt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Mn&&typeof o.getBoundary!="function"&&(n=new Xu({highWaterMark:e}),r=new Xu({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Tt].stream=n,o=r),o},"clone"),YF=Zu(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"),lA=m((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":cA(t)?"application/x-www-form-urlencoded;charset=UTF-8":tl(t)?t.type||null:pt.isBuffer(t)||Qu.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof vo?`multipart/form-data; boundary=${e[Tt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${YF(t)}`:t instanceof Mn?null:"text/plain;charset=UTF-8","extractContentType"),XF=m(t=>{let{body:e}=t[Tt];return e===null?0:tl(e)?e.size:pt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),QF=m(async(t,{body:e})=>{e===null?t.end():await VF(e,t)},"writeToStream"),Vu=typeof ua.validateHeaderName=="function"?ua.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}},gg=typeof ua.validateHeaderValue=="function"?ua.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}},dA=class fA extends URLSearchParams{constructor(e){let n=[];if(e instanceof fA){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"&&!Qu.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"||Qu.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])=>(Vu(r),gg(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)=>(Vu(i),gg(i,String(a)),URLSearchParams.prototype[o].call(r,String(i).toLowerCase(),String(a)));case"delete":case"has":case"getAll":return i=>(Vu(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},{})}};m(dA,"Headers");pr=dA;Object.defineProperties(pr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));m(pA,"fromRawHeaders");ZF=new Set([301,302,303,307,308]),il=m(t=>ZF.has(t),"isRedirect"),nn=Symbol("Response internals"),hA=class sa extends aa{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new pr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=lA(e,this);s&&o.append("Content-Type",s)}this[nn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||""}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new sa(Sg(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(!il(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new sa(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new sa(null,{status:0,statusText:""});return e[nn].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new pr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new sa(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};m(hA,"Response");Fn=hA;Object.defineProperties(Fn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});eN=m(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");m(mg,"stripURLForUseAsAReferrer");gA=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),tN="strict-origin-when-cross-origin";m(mA,"validateReferrerPolicy");m(yA,"isOriginPotentiallyTrustworthy");m(xo,"isUrlPotentiallyTrustworthy");m(_A,"determineRequestsReferrer");m(bA,"parseReferrerPolicyFromHeader");at=Symbol("Request internals"),oa=m(t=>typeof t=="object"&&typeof t[at]=="object","isRequest"),nN=Zu(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),CA=class wA extends aa{constructor(e,n={}){let r;if(oa(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()),!oa(n)&&"data"in n&&nN(),(n.body!=null||oa(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:oa(e)&&e.body!==null?Sg(e):null;super(s,{size:n.size||e.size||0});let i=new pr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=lA(s,this);d&&i.set("Content-Type",d)}let a=oa(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!GF(a))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=n.referrer==null?e.referrer:n.referrer;if(u==="")u="no-referrer";else if(u){let d=new URL(u);u=/^about:(\/\/)?client$/.test(d)?"client":d}else u=void 0;this[at]={method:o,redirect:n.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:a,referrer:u},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[at].method}get url(){return MF(this[at].parsedURL)}get headers(){return this[at].headers}get redirect(){return this[at].redirect}get signal(){return this[at].signal}get referrer(){if(this[at].referrer==="no-referrer")return"";if(this[at].referrer==="client")return"about:client";if(this[at].referrer)return this[at].referrer.toString()}get referrerPolicy(){return this[at].referrerPolicy}set referrerPolicy(e){this[at].referrerPolicy=mA(e)}clone(){return new wA(this)}get[Symbol.toStringTag](){return"Request"}};m(CA,"Request");la=CA;Object.defineProperties(la.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}});rN=m(t=>{let{parsedURL:e}=t[at],n=new pr(t[at].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let a=XF(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=tN),t.referrer&&t.referrer!=="no-referrer"?t[at].referrer=_A(t):t[at].referrer="no-referrer",t[at].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=eN(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"),kA=class extends sl{constructor(e,n="aborted"){super(e,n)}};m(kA,"AbortError");Ag=kA;m(SA,"requireNodeDomexception");oN=SA(),sN=cg(oN),{stat:Eg}=jF,AA=m((t,e)=>xA(tA(t),t,e),"blobFromSync"),EA=m((t,e)=>Eg(t).then(n=>xA(n,t,e)),"blobFrom"),vA=m((t,e)=>Eg(t).then(n=>RA(n,t,e)),"fileFrom"),TA=m((t,e)=>RA(tA(t),t,e),"fileFromSync"),xA=m((t,e,n="")=>new Do([new PA({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),RA=m((t,e,n="")=>new Ss([new PA({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],LF(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),DA=class OA{constructor(e){fr(this,Ts),fr(this,xs),rn(this,Ts,e.path),rn(this,xs,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new OA({path:ze(this,Ts),lastModified:this.lastModified,size:n-e,start:ze(this,xs)+e})}async*stream(){let{mtimeMs:e}=await Eg(ze(this,Ts));if(e>this.lastModified)throw new sN("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*UF(ze(this,Ts),{start:ze(this,xs),end:ze(this,xs)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};Ts=new WeakMap,xs=new WeakMap,m(DA,"BlobDataItem");PA=DA,iN=new Set(["data:","http:","https:"]);m(vg,"fetch$1");m(IA,"fixResponseChunkedTransferBadEnding");FA=new WeakMap,yg=new WeakMap;m(Le,"pd");m(_g,"setCancelFlag");m(Ro,"Event"),Ro.prototype={get type(){return Le(this).event.type},get target(){return Le(this).eventTarget},get currentTarget(){return Le(this).currentTarget},composedPath(){let t=Le(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Le(this).eventPhase},stopPropagation(){let t=Le(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Le(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Le(this).event.bubbles},get cancelable(){return!!Le(this).event.cancelable},preventDefault(){_g(Le(this))},get defaultPrevented(){return Le(this).canceled},get composed(){return!!Le(this).event.composed},get timeStamp(){return Le(this).timeStamp},get srcElement(){return Le(this).eventTarget},get cancelBubble(){return Le(this).stopped},set cancelBubble(t){if(!t)return;let e=Le(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Le(this).canceled},set returnValue(t){t||_g(Le(this))},initEvent(){}},Object.defineProperty(Ro.prototype,"constructor",{value:Ro,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Ro.prototype,window.Event.prototype),yg.set(window.Event.prototype,Ro));m(Tg,"defineRedirectDescriptor");m(NA,"defineCallDescriptor");m(MA,"defineWrapper");m(xg,"getWrapper");m(BA,"wrapEvent");m(jA,"isStopped");m(UA,"setEventPhase");m(LA,"setCurrentTarget");m(bg,"setPassiveListener");$A=new WeakMap,XS=1,QS=2,Yu=3;m(ca,"isObject");m(Rs,"getListeners");m(qA,"defineEventAttributeDescriptor");m(Rg,"defineEventAttribute");m(Cg,"defineCustomEventTarget");m(Nn,"EventTarget"),Nn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!ca(e))throw new TypeError("'listener' should be a function or an object.");let r=Rs(this),o=ca(n),s=(o?n.capture:n)?XS:QS,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=Rs(this),o=(ca(n)?n.capture:n)?XS:QS,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=Rs(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=BA(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,bg(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!==Yu&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(jA(o))break;r=r.next}return bg(o,null),UA(o,0),LA(o,null),!o.defaultPrevented}},Object.defineProperty(Nn.prototype,"constructor",{value:Nn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(Nn.prototype,window.EventTarget.prototype);HA=class extends Nn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=rl.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}};m(HA,"AbortSignal");nl=HA;Rg(nl.prototype,"abort");m(zA,"createAbortSignal");m(WA,"abortSignal");rl=new WeakMap;Object.defineProperties(nl.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(nl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});ol=(fg=class{constructor(){GA.set(this,zA())}get signal(){return wg(this)}abort(){WA(wg(this))}},m(fg,"AbortController"),fg),GA=new WeakMap;m(wg,"getSignal"),Object.defineProperties(ol.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ol.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});aN=Object.defineProperty,cN=m((t,e)=>aN(t,"name",{value:e,configurable:!0}),"e"),JA=vg;kg();m(kg,"s"),cN(kg,"checkNodeEnvironment")});var KA={};Gb(KA,{AbortController:()=>mN,AbortError:()=>Ag,Blob:()=>lN,FetchError:()=>Wt,File:()=>dN,FormData:()=>fN,Headers:()=>pN,Request:()=>hN,Response:()=>gN,blobFrom:()=>EA,blobFromSync:()=>AA,default:()=>uN,fetch:()=>uN,fileFrom:()=>vA,fileFromSync:()=>TA,isRedirect:()=>il});var Wr,uN,lN,dN,fN,pN,hN,gN,mN,VA=Mr(()=>{qu();qu();Uu();Wr=!!globalThis.process?.env?.FORCE_NODE_FETCH,uN=!Wr&&globalThis.fetch||JA,lN=!Wr&&globalThis.Blob||Do,dN=!Wr&&globalThis.File||Ss,fN=!Wr&&globalThis.FormData||vo,pN=!Wr&&globalThis.Headers||pr,hN=!Wr&&globalThis.Request||la,gN=!Wr&&globalThis.Response||Fn,mN=!Wr&&globalThis.AbortController||ol});var QA=G(Os=>{"use strict";var yN=Os&&Os.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Ds;Object.defineProperty(Os,"__esModule",{value:!0});Os.Gaxios=void 0;var _N=yN(Vh()),bN=re("https"),Oo=Qh(),CN=dS(),YA=re("stream"),XA=tg(),wN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),kN=204,al=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new XA.GaxiosInterceptorManager,response:new XA.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&&Ds.mergeHeaders(s,n.headers),r&&Ds.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 Ds.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=Buffer.concat(o.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=Oo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Oo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Oo.GaxiosError?r=n:n instanceof Error?r=new Oo.GaxiosError(n.message,e,void 0,n):r=new Oo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,CN.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===kN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Oo.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of s)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(r.toString()))return!1}else if(i instanceof URL){if(i.origin===r.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let a=i.replace(/^\*\./,".");if(r.hostname.endsWith(a))return!1}else if(i===r.origin||i===r.hostname||i===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Ds.mergeHeaders(n,e.headers);let r=(0,_N.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 YA.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 wN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=YA.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 Ds.#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 bN.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Oo.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
|
|
89
|
+
`),r=!1,o=!1,s;t.on("response",i=>{let{headers:a}=i;r=a["transfer-encoding"]==="chunked"&&!a["content-length"]}),t.on("socket",i=>{let a=m(()=>{if(r&&!o){let d=new Error("Premature close");d.code="ERR_STREAM_PREMATURE_CLOSE",e(d)}},"onSocketClose"),u=m(d=>{o=pt.compare(d.slice(-5),n)===0,!o&&s&&(o=pt.compare(s.slice(-3),n.slice(0,3))===0&&pt.compare(d.slice(-2),n.slice(3))===0),s=d},"onData");i.prependListener("close",a),i.on("data",u),t.on("close",()=>{i.removeListener("close",a),i.removeListener("data",u)})})}function Le(t){let e=LA.get(t);return console.assert(e!=null,"'this' is expected an Event object, but got",t),e}function vg(t){if(t.passiveListener!=null){typeof console<"u"&&typeof console.error=="function"&&console.error("Unable to preventDefault inside passive event listener invocation.",t.passiveListener);return}t.event.cancelable&&(t.canceled=!0,typeof t.event.preventDefault=="function"&&t.event.preventDefault())}function Ro(t,e){LA.set(this,{eventTarget:t,event:e,eventPhase:2,currentTarget:t,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:e.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});let n=Object.keys(e);for(let r=0;r<n.length;++r){let o=n[r];o in this||Object.defineProperty(this,o,Ng(o))}}function Ng(t){return{get(){return Le(this).event[t]},set(e){Le(this).event[t]=e},configurable:!0,enumerable:!0}}function $A(t){return{value(){let e=Le(this).event;return e[t].apply(e,arguments)},configurable:!0,enumerable:!0}}function qA(t,e){let n=Object.keys(e);if(n.length===0)return t;function r(o,s){t.call(this,o,s)}m(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?$A(s):Ng(s))}}return r}function Mg(t){if(t==null||t===Object.prototype)return Ro;let e=Eg.get(t);return e==null&&(e=qA(Mg(Object.getPrototypeOf(t)),t),Eg.set(t,e)),e}function HA(t,e){let n=Mg(Object.getPrototypeOf(e));return new n(t,e)}function zA(t){return Le(t).immediateStopped}function WA(t,e){Le(t).eventPhase=e}function GA(t,e){Le(t).currentTarget=e}function Tg(t,e){Le(t).passiveListener=e}function ca(t){return t!==null&&typeof t=="object"}function Rs(t){let e=JA.get(t);if(e==null)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return e}function KA(t){return{get(){let e=Rs(this).get(t);for(;e!=null;){if(e.listenerType===nl)return e.listener;e=e.next}return null},set(e){typeof e!="function"&&!ca(e)&&(e=null);let n=Rs(this),r=null,o=n.get(t);for(;o!=null;)o.listenerType===nl?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:nl,passive:!1,once:!1,next:null};r===null?n.set(t,s):r.next=s}},configurable:!0,enumerable:!0}}function Bg(t,e){Object.defineProperty(t,`on${e}`,KA(e))}function xg(t){function e(){Nn.call(this)}m(e,"CustomEventTarget"),e.prototype=Object.create(Nn.prototype,{constructor:{value:e,configurable:!0,writable:!0}});for(let n=0;n<t.length;++n)Bg(e.prototype,t[n]);return e}function Nn(){if(this instanceof Nn){JA.set(this,new Map);return}if(arguments.length===1&&Array.isArray(arguments[0]))return xg(arguments[0]);if(arguments.length>0){let t=new Array(arguments.length);for(let e=0;e<arguments.length;++e)t[e]=arguments[e];return xg(t)}throw new TypeError("Cannot call a class as a function")}function YA(){let t=Object.create(cl.prototype);return Nn.call(t),ul.set(t,!1),t}function XA(t){ul.get(t)===!1&&(ul.set(t,!0),t.dispatchEvent({type:"abort"}))}function Rg(t){let e=QA.get(t);if(e==null)throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${t===null?"null":typeof t}`);return e}function Dg(){!globalThis.process?.versions?.node&&!globalThis.process?.env?.DISABLE_NODE_FETCH_NATIVE_WARN&&console.warn("[node-fetch-native] Node.js compatible build of `node-fetch-native` is being used in a non-Node.js environment. Please make sure you are using proper export conditions or report this issue to https://github.com/unjs/node-fetch-native. You can set `process.env.DISABLE_NODE_FETCH_NATIVE_WARN` to disable this warning.")}var UF,sA,m,iA,ze,fr,rn,zr,Vu,As,yg,ra,Yu,Xu,_g,tn,bg,Ts,xs,Cg,VS,Qu,GF,YS,XS,ZS,lA,Do,JF,Ss,ia,KF,VF,eA,YF,tA,wg,To,vo,fA,dl,pA,Wt,il,hA,al,XF,QF,ZF,eN,Tt,gA,aa,Og,tN,mA,nN,rN,tl,Sg,yA,pr,oN,fl,nn,CA,Fn,sN,wA,iN,at,oa,aN,vA,la,cN,xA,Pg,kg,nA,uN,lN,Ig,DA,OA,PA,IA,FA,NA,MA,UA,dN,LA,Eg,JA,rA,oA,nl,VA,cl,ul,ll,QA,fN,pN,ZA,Ku=Mr(()=>{Wu();UF=Object.defineProperty,sA=t=>{throw TypeError(t)},m=(t,e)=>UF(t,"name",{value:e,configurable:!0}),iA=(t,e,n)=>e.has(t)||sA("Cannot "+n),ze=(t,e,n)=>(iA(t,e,"read from private field"),n?n.call(t):e.get(t)),fr=(t,e,n)=>e.has(t)?sA("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),rn=(t,e,n,r)=>(iA(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n);m(cA,"dataUriToBuffer");VS={},Qu={exports:{}};GF=Qu.exports;m(uA,"requirePonyfill_es2018");m(QS,"requireStreams"),QS();ZS=65536;m(Zu,"toIterator");lA=(ra=class{constructor(t=[],e={}){if(fr(this,zr,[]),fr(this,Vu,""),fr(this,As,0),fr(this,yg,"transparent"),typeof t!="object"||t===null)throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");if(typeof t[Symbol.iterator]!="function")throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");if(typeof e!="object"&&typeof e!="function")throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");e===null&&(e={});let n=new TextEncoder;for(let o of t){let s;ArrayBuffer.isView(o)?s=new Uint8Array(o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)):o instanceof ArrayBuffer?s=new Uint8Array(o.slice(0)):o instanceof ra?s=o:s=n.encode(`${o}`),rn(this,As,ze(this,As)+(ArrayBuffer.isView(s)?s.byteLength:s.size)),ze(this,zr).push(s)}rn(this,yg,`${e.endings===void 0?"transparent":e.endings}`);let r=e.type===void 0?"":String(e.type);rn(this,Vu,/^[\x20-\x7E]*$/.test(r)?r:"")}get size(){return ze(this,As)}get type(){return ze(this,Vu)}async text(){let t=new TextDecoder,e="";for await(let n of Zu(ze(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 Zu(ze(this,zr),!1))t.set(n,e),e+=n.length;return t.buffer}stream(){let t=Zu(ze(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=ze(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 ra([],{type:String(n).toLowerCase()});return rn(f,As,i),rn(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,Vu=new WeakMap,As=new WeakMap,yg=new WeakMap,m(ra,"Blob"),ra);Object.defineProperties(lA.prototype,{size:{enumerable:!0},type:{enumerable:!0},slice:{enumerable:!0}});Do=lA,JF=(_g=class extends Do{constructor(t,e,n={}){if(arguments.length<2)throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);super(t,n),fr(this,Yu,0),fr(this,Xu,""),n===null&&(n={});let r=n.lastModified===void 0?Date.now():Number(n.lastModified);Number.isNaN(r)||rn(this,Yu,r),rn(this,Xu,String(e))}get name(){return ze(this,Xu)}get lastModified(){return ze(this,Yu)}get[Symbol.toStringTag](){return"File"}static[Symbol.hasInstance](t){return!!t&&t instanceof Do&&/^(File)$/.test(t[Symbol.toStringTag])}},Yu=new WeakMap,Xu=new WeakMap,m(_g,"File"),_g),Ss=JF;({toStringTag:ia,iterator:KF,hasInstance:VF}=Symbol),eA=Math.random,YF="append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","),tA=m((t,e,n)=>(t+="",/^(Blob|File)$/.test(e&&e[ia])?[(n=n!==void 0?n+"":e[ia]=="File"?e.name:"blob",t),e.name!==n||e[ia]=="blob"?new Ss([e],n,e):e]:[t,e+""]),"f"),wg=m((t,e)=>(e?t:t.replace(/\r?\n|\r/g,`\r
|
|
90
|
+
`)).replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22"),"e$1"),To=m((t,e,n)=>{if(e.length<n)throw new TypeError(`Failed to execute '${t}' on 'FormData': ${n} arguments required, but only ${e.length} present.`)},"x"),vo=(bg=class{constructor(...t){if(fr(this,tn,[]),t.length)throw new TypeError("Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.")}get[ia](){return"FormData"}[KF](){return this.entries()}static[VF](t){return t&&typeof t=="object"&&t[ia]==="FormData"&&!YF.some(e=>typeof t[e]!="function")}append(...t){To("append",arguments,2),ze(this,tn).push(tA(...t))}delete(t){To("delete",arguments,1),t+="",rn(this,tn,ze(this,tn).filter(([e])=>e!==t))}get(t){To("get",arguments,1),t+="";for(var e=ze(this,tn),n=e.length,r=0;r<n;r++)if(e[r][0]===t)return e[r][1];return null}getAll(t,e){return To("getAll",arguments,1),e=[],t+="",ze(this,tn).forEach(n=>n[0]===t&&e.push(n[1])),e}has(t){return To("has",arguments,1),t+="",ze(this,tn).some(e=>e[0]===t)}forEach(t,e){To("forEach",arguments,1);for(var[n,r]of this)t.call(e,r,n,this)}set(...t){To("set",arguments,2);var e=[],n=!0;t=tA(...t),ze(this,tn).forEach(r=>{r[0]===t[0]?n&&(n=!e.push(t)):e.push(r)}),n&&e.push(t),rn(this,tn,e)}*entries(){yield*ze(this,tn)}*keys(){for(var[t]of this)yield t}*values(){for(var[,t]of this)yield t}},tn=new WeakMap,m(bg,"FormData"),bg);m(dA,"formDataToBlob");fA=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}};m(fA,"FetchBaseError");dl=fA,pA=class extends dl{constructor(e,n,r){super(e,n),r&&(this.code=this.errno=r.code,this.erroredSysCall=r.syscall)}};m(pA,"FetchError");Wt=pA,il=Symbol.toStringTag,hA=m(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[il]==="URLSearchParams","isURLSearchParameters"),al=m(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[il]),"isBlob"),XF=m(t=>typeof t=="object"&&(t[il]==="AbortSignal"||t[il]==="EventTarget"),"isAbortSignal"),QF=m((t,e)=>{let n=new URL(e).hostname,r=new URL(t).hostname;return n===r||n.endsWith(`.${r}`)},"isDomainOrSubdomain"),ZF=m((t,e)=>{let n=new URL(e).protocol,r=new URL(t).protocol;return n===r},"isSameProtocol"),eN=LF(Mn.pipeline),Tt=Symbol("Body internals"),gA=class{constructor(e,{size:n=0}={}){let r=null;e===null?e=null:hA(e)?e=pt.from(e.toString()):al(e)||pt.isBuffer(e)||(ol.isAnyArrayBuffer(e)?e=pt.from(e):ArrayBuffer.isView(e)?e=pt.from(e.buffer,e.byteOffset,e.byteLength):e instanceof Mn||(e instanceof vo?(e=dA(e),r=e.type.split("=")[1]):e=pt.from(String(e))));let o=e;pt.isBuffer(e)?o=Mn.Readable.from(e):al(e)&&(o=Mn.Readable.from(e.stream())),this[Tt]={body:e,stream:o,boundary:r,disturbed:!1,error:null},this.size=n,e instanceof Mn&&e.on("error",s=>{let i=s instanceof dl?s:new Wt(`Invalid response body while trying to fetch ${this.url}: ${s.message}`,"system",s);this[Tt].error=i})}get body(){return this[Tt].stream}get bodyUsed(){return this[Tt].disturbed}async arrayBuffer(){let{buffer:e,byteOffset:n,byteLength:r}=await 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 vo,o=new URLSearchParams(await this.text());for(let[s,i]of o)r.append(s,i);return r}let{toFormData:n}=await Promise.resolve().then(()=>(KS(),JS));return n(this.body,e)}async blob(){let e=this.headers&&this.headers.get("content-type")||this[Tt].body&&this[Tt].body.type||"",n=await this.arrayBuffer();return new Do([n],{type:e})}async json(){let e=await this.text();return JSON.parse(e)}async text(){let e=await el(this);return new TextDecoder().decode(e)}buffer(){return el(this)}};m(gA,"Body");aa=gA;aa.prototype.buffer=sl(aa.prototype.buffer,"Please use 'response.arrayBuffer()' instead of 'response.buffer()'","node-fetch#buffer"),Object.defineProperties(aa.prototype,{body:{enumerable:!0},bodyUsed:{enumerable:!0},arrayBuffer:{enumerable:!0},blob:{enumerable:!0},json:{enumerable:!0},text:{enumerable:!0},data:{get:sl(()=>{},"data doesn't exist, use json(), text(), arrayBuffer(), or body instead","https://github.com/node-fetch/node-fetch/issues/1000 (response)")}});m(el,"consumeBody");Og=m((t,e)=>{let n,r,{body:o}=t[Tt];if(t.bodyUsed)throw new Error("cannot clone body after it is used");return o instanceof Mn&&typeof o.getBoundary!="function"&&(n=new rl({highWaterMark:e}),r=new rl({highWaterMark:e}),o.pipe(n),o.pipe(r),t[Tt].stream=n,o=r),o},"clone"),tN=sl(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"),mA=m((t,e)=>t===null?null:typeof t=="string"?"text/plain;charset=UTF-8":hA(t)?"application/x-www-form-urlencoded;charset=UTF-8":al(t)?t.type||null:pt.isBuffer(t)||ol.isAnyArrayBuffer(t)||ArrayBuffer.isView(t)?null:t instanceof vo?`multipart/form-data; boundary=${e[Tt].boundary}`:t&&typeof t.getBoundary=="function"?`multipart/form-data;boundary=${tN(t)}`:t instanceof Mn?null:"text/plain;charset=UTF-8","extractContentType"),nN=m(t=>{let{body:e}=t[Tt];return e===null?0:al(e)?e.size:pt.isBuffer(e)?e.length:e&&typeof e.getLengthSync=="function"&&e.hasKnownLength&&e.hasKnownLength()?e.getLengthSync():null},"getTotalBytes"),rN=m(async(t,{body:e})=>{e===null?t.end():await eN(e,t)},"writeToStream"),tl=typeof ua.validateHeaderName=="function"?ua.validateHeaderName:t=>{if(!/^[\^`\-\w!#$%&'*+.|~]+$/.test(t)){let e=new TypeError(`Header name must be a valid HTTP token [${t}]`);throw Object.defineProperty(e,"code",{value:"ERR_INVALID_HTTP_TOKEN"}),e}},Sg=typeof ua.validateHeaderValue=="function"?ua.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}},yA=class _A extends URLSearchParams{constructor(e){let n=[];if(e instanceof _A){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"&&!ol.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"||ol.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),Sg(r,String(o)),[String(r).toLowerCase(),String(o)])):void 0,super(n),new Proxy(this,{get(r,o,s){switch(o){case"append":case"set":return(i,a)=>(tl(i),Sg(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},{})}};m(yA,"Headers");pr=yA;Object.defineProperties(pr.prototype,["get","entries","forEach","values"].reduce((t,e)=>(t[e]={enumerable:!0},t),{}));m(bA,"fromRawHeaders");oN=new Set([301,302,303,307,308]),fl=m(t=>oN.has(t),"isRedirect"),nn=Symbol("Response internals"),CA=class sa extends aa{constructor(e=null,n={}){super(e,n);let r=n.status!=null?n.status:200,o=new pr(n.headers);if(e!==null&&!o.has("Content-Type")){let s=mA(e,this);s&&o.append("Content-Type",s)}this[nn]={type:"default",url:n.url,status:r,statusText:n.statusText||"",headers:o,counter:n.counter,highWaterMark:n.highWaterMark}}get type(){return this[nn].type}get url(){return this[nn].url||""}get status(){return this[nn].status}get ok(){return this[nn].status>=200&&this[nn].status<300}get redirected(){return this[nn].counter>0}get statusText(){return this[nn].statusText}get headers(){return this[nn].headers}get highWaterMark(){return this[nn].highWaterMark}clone(){return new sa(Og(this,this.highWaterMark),{type:this.type,url:this.url,status:this.status,statusText:this.statusText,headers:this.headers,ok:this.ok,redirected:this.redirected,size:this.size,highWaterMark:this.highWaterMark})}static redirect(e,n=302){if(!fl(n))throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');return new sa(null,{headers:{location:new URL(e).toString()},status:n})}static error(){let e=new sa(null,{status:0,statusText:""});return e[nn].type="error",e}static json(e=void 0,n={}){let r=JSON.stringify(e);if(r===void 0)throw new TypeError("data is not JSON serializable");let o=new pr(n&&n.headers);return o.has("content-type")||o.set("content-type","application/json"),new sa(r,{...n,headers:o})}get[Symbol.toStringTag](){return"Response"}};m(CA,"Response");Fn=CA;Object.defineProperties(Fn.prototype,{type:{enumerable:!0},url:{enumerable:!0},status:{enumerable:!0},ok:{enumerable:!0},redirected:{enumerable:!0},statusText:{enumerable:!0},headers:{enumerable:!0},clone:{enumerable:!0}});sN=m(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");m(Ag,"stripURLForUseAsAReferrer");wA=new Set(["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"]),iN="strict-origin-when-cross-origin";m(kA,"validateReferrerPolicy");m(SA,"isOriginPotentiallyTrustworthy");m(xo,"isUrlPotentiallyTrustworthy");m(AA,"determineRequestsReferrer");m(EA,"parseReferrerPolicyFromHeader");at=Symbol("Request internals"),oa=m(t=>typeof t=="object"&&typeof t[at]=="object","isRequest"),aN=sl(()=>{},".data is not a valid RequestInit property, use .body instead","https://github.com/node-fetch/node-fetch/issues/1000 (request)"),vA=class TA extends aa{constructor(e,n={}){let r;if(oa(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()),!oa(n)&&"data"in n&&aN(),(n.body!=null||oa(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:oa(e)&&e.body!==null?Og(e):null;super(s,{size:n.size||e.size||0});let i=new pr(n.headers||e.headers||{});if(s!==null&&!i.has("Content-Type")){let d=mA(s,this);d&&i.set("Content-Type",d)}let a=oa(e)?e.signal:null;if("signal"in n&&(a=n.signal),a!=null&&!XF(a))throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");let u=n.referrer==null?e.referrer:n.referrer;if(u==="")u="no-referrer";else if(u){let d=new URL(u);u=/^about:(\/\/)?client$/.test(d)?"client":d}else u=void 0;this[at]={method:o,redirect:n.redirect||e.redirect||"follow",headers:i,parsedURL:r,signal:a,referrer:u},this.follow=n.follow===void 0?e.follow===void 0?20:e.follow:n.follow,this.compress=n.compress===void 0?e.compress===void 0?!0:e.compress:n.compress,this.counter=n.counter||e.counter||0,this.agent=n.agent||e.agent,this.highWaterMark=n.highWaterMark||e.highWaterMark||16384,this.insecureHTTPParser=n.insecureHTTPParser||e.insecureHTTPParser||!1,this.referrerPolicy=n.referrerPolicy||e.referrerPolicy||""}get method(){return this[at].method}get url(){return $F(this[at].parsedURL)}get headers(){return this[at].headers}get redirect(){return this[at].redirect}get signal(){return this[at].signal}get referrer(){if(this[at].referrer==="no-referrer")return"";if(this[at].referrer==="client")return"about:client";if(this[at].referrer)return this[at].referrer.toString()}get referrerPolicy(){return this[at].referrerPolicy}set referrerPolicy(e){this[at].referrerPolicy=kA(e)}clone(){return new TA(this)}get[Symbol.toStringTag](){return"Request"}};m(vA,"Request");la=vA;Object.defineProperties(la.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}});cN=m(t=>{let{parsedURL:e}=t[at],n=new pr(t[at].headers);n.has("Accept")||n.set("Accept","*/*");let r=null;if(t.body===null&&/^(post|put)$/i.test(t.method)&&(r="0"),t.body!==null){let a=nN(t);typeof a=="number"&&!Number.isNaN(a)&&(r=String(a))}r&&n.set("Content-Length",r),t.referrerPolicy===""&&(t.referrerPolicy=iN),t.referrer&&t.referrer!=="no-referrer"?t[at].referrer=AA(t):t[at].referrer="no-referrer",t[at].referrer instanceof URL&&n.set("Referer",t.referrer),n.has("User-Agent")||n.set("User-Agent","node-fetch"),t.compress&&!n.has("Accept-Encoding")&&n.set("Accept-Encoding","gzip, deflate, br");let{agent:o}=t;typeof o=="function"&&(o=o(e));let s=sN(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"),xA=class extends dl{constructor(e,n="aborted"){super(e,n)}};m(xA,"AbortError");Pg=xA;m(RA,"requireNodeDomexception");uN=RA(),lN=mg(uN),{stat:Ig}=HF,DA=m((t,e)=>FA(aA(t),t,e),"blobFromSync"),OA=m((t,e)=>Ig(t).then(n=>FA(n,t,e)),"blobFrom"),PA=m((t,e)=>Ig(t).then(n=>NA(n,t,e)),"fileFrom"),IA=m((t,e)=>NA(aA(t),t,e),"fileFromSync"),FA=m((t,e,n="")=>new Do([new UA({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],{type:n}),"fromBlob"),NA=m((t,e,n="")=>new Ss([new UA({path:e,size:t.size,lastModified:t.mtimeMs,start:0})],WF(e),{type:n,lastModified:t.mtimeMs}),"fromFile"),MA=class BA{constructor(e){fr(this,Ts),fr(this,xs),rn(this,Ts,e.path),rn(this,xs,e.start),this.size=e.size,this.lastModified=e.lastModified}slice(e,n){return new BA({path:ze(this,Ts),lastModified:this.lastModified,size:n-e,start:ze(this,xs)+e})}async*stream(){let{mtimeMs:e}=await Ig(ze(this,Ts));if(e>this.lastModified)throw new lN("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*zF(ze(this,Ts),{start:ze(this,xs),end:ze(this,xs)+this.size-1})}get[Symbol.toStringTag](){return"Blob"}};Ts=new WeakMap,xs=new WeakMap,m(MA,"BlobDataItem");UA=MA,dN=new Set(["data:","http:","https:"]);m(Fg,"fetch$1");m(jA,"fixResponseChunkedTransferBadEnding");LA=new WeakMap,Eg=new WeakMap;m(Le,"pd");m(vg,"setCancelFlag");m(Ro,"Event"),Ro.prototype={get type(){return Le(this).event.type},get target(){return Le(this).eventTarget},get currentTarget(){return Le(this).currentTarget},composedPath(){let t=Le(this).currentTarget;return t==null?[]:[t]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return Le(this).eventPhase},stopPropagation(){let t=Le(this);t.stopped=!0,typeof t.event.stopPropagation=="function"&&t.event.stopPropagation()},stopImmediatePropagation(){let t=Le(this);t.stopped=!0,t.immediateStopped=!0,typeof t.event.stopImmediatePropagation=="function"&&t.event.stopImmediatePropagation()},get bubbles(){return!!Le(this).event.bubbles},get cancelable(){return!!Le(this).event.cancelable},preventDefault(){vg(Le(this))},get defaultPrevented(){return Le(this).canceled},get composed(){return!!Le(this).event.composed},get timeStamp(){return Le(this).timeStamp},get srcElement(){return Le(this).eventTarget},get cancelBubble(){return Le(this).stopped},set cancelBubble(t){if(!t)return;let e=Le(this);e.stopped=!0,typeof e.event.cancelBubble=="boolean"&&(e.event.cancelBubble=!0)},get returnValue(){return!Le(this).canceled},set returnValue(t){t||vg(Le(this))},initEvent(){}},Object.defineProperty(Ro.prototype,"constructor",{value:Ro,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.Event<"u"&&(Object.setPrototypeOf(Ro.prototype,window.Event.prototype),Eg.set(window.Event.prototype,Ro));m(Ng,"defineRedirectDescriptor");m($A,"defineCallDescriptor");m(qA,"defineWrapper");m(Mg,"getWrapper");m(HA,"wrapEvent");m(zA,"isStopped");m(WA,"setEventPhase");m(GA,"setCurrentTarget");m(Tg,"setPassiveListener");JA=new WeakMap,rA=1,oA=2,nl=3;m(ca,"isObject");m(Rs,"getListeners");m(KA,"defineEventAttributeDescriptor");m(Bg,"defineEventAttribute");m(xg,"defineCustomEventTarget");m(Nn,"EventTarget"),Nn.prototype={addEventListener(t,e,n){if(e==null)return;if(typeof e!="function"&&!ca(e))throw new TypeError("'listener' should be a function or an object.");let r=Rs(this),o=ca(n),s=(o?n.capture:n)?rA:oA,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=Rs(this),o=(ca(n)?n.capture:n)?rA:oA,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=Rs(this),n=t.type,r=e.get(n);if(r==null)return!0;let o=HA(this,t),s=null;for(;r!=null;){if(r.once?s!==null?s.next=r.next:r.next!==null?e.set(n,r.next):e.delete(n):s=r,Tg(o,r.passive?r.listener:null),typeof r.listener=="function")try{r.listener.call(this,o)}catch(i){typeof console<"u"&&typeof console.error=="function"&&console.error(i)}else r.listenerType!==nl&&typeof r.listener.handleEvent=="function"&&r.listener.handleEvent(o);if(zA(o))break;r=r.next}return Tg(o,null),WA(o,0),GA(o,null),!o.defaultPrevented}},Object.defineProperty(Nn.prototype,"constructor",{value:Nn,configurable:!0,writable:!0}),typeof window<"u"&&typeof window.EventTarget<"u"&&Object.setPrototypeOf(Nn.prototype,window.EventTarget.prototype);VA=class extends Nn{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){let e=ul.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}};m(VA,"AbortSignal");cl=VA;Bg(cl.prototype,"abort");m(YA,"createAbortSignal");m(XA,"abortSignal");ul=new WeakMap;Object.defineProperties(cl.prototype,{aborted:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(cl.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});ll=(Cg=class{constructor(){QA.set(this,YA())}get signal(){return Rg(this)}abort(){XA(Rg(this))}},m(Cg,"AbortController"),Cg),QA=new WeakMap;m(Rg,"getSignal"),Object.defineProperties(ll.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),typeof Symbol=="function"&&typeof Symbol.toStringTag=="symbol"&&Object.defineProperty(ll.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"});fN=Object.defineProperty,pN=m((t,e)=>fN(t,"name",{value:e,configurable:!0}),"e"),ZA=Fg;Dg();m(Dg,"s"),pN(Dg,"checkNodeEnvironment")});var eE={};Qb(eE,{AbortController:()=>wN,AbortError:()=>Pg,Blob:()=>gN,FetchError:()=>Wt,File:()=>mN,FormData:()=>yN,Headers:()=>_N,Request:()=>bN,Response:()=>CN,blobFrom:()=>OA,blobFromSync:()=>DA,default:()=>hN,fetch:()=>hN,fileFrom:()=>PA,fileFromSync:()=>IA,isRedirect:()=>fl});var Wr,hN,gN,mN,yN,_N,bN,CN,wN,tE=Mr(()=>{Ku();Ku();Wu();Wr=!!globalThis.process?.env?.FORCE_NODE_FETCH,hN=!Wr&&globalThis.fetch||ZA,gN=!Wr&&globalThis.Blob||Do,mN=!Wr&&globalThis.File||Ss,yN=!Wr&&globalThis.FormData||vo,_N=!Wr&&globalThis.Headers||pr,bN=!Wr&&globalThis.Request||la,CN=!Wr&&globalThis.Response||Fn,wN=!Wr&&globalThis.AbortController||ll});var oE=G(Os=>{"use strict";var kN=Os&&Os.__importDefault||function(t){return t&&t.__esModule?t:{default:t}},Ds;Object.defineProperty(Os,"__esModule",{value:!0});Os.Gaxios=void 0;var SN=kN(rg()),AN=re("https"),Oo=ig(),EN=yS(),nE=re("stream"),rE=ug(),vN=async()=>globalThis.crypto?.randomUUID()||(await import("crypto")).randomUUID(),TN=204,pl=class{agentCache=new Map;defaults;interceptors;constructor(e){this.defaults=e||{},this.interceptors={request:new rE.GaxiosInterceptorManager,response:new rE.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&&Ds.mergeHeaders(s,n.headers),r&&Ds.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 Ds.#c(),r={...e};delete r.data;let o=await n(e.url,r),s=await this.getResponseData(e,o);return Object.getOwnPropertyDescriptor(o,"data")?.configurable||Object.defineProperties(o,{data:{configurable:!0,writable:!0,enumerable:!0,value:s}}),Object.assign(o,{config:e,data:s})}async _request(e){try{let n;if(e.adapter?n=await e.adapter(e,this._defaultAdapter.bind(this)):n=await this._defaultAdapter(e),!e.validateStatus(n.status)){if(e.responseType==="stream"){let o=[];for await(let s of n.data)o.push(s);n.data=Buffer.concat(o.map(s=>typeof s=="string"?Buffer.from(s):s)).toString("utf8")}let r=Oo.GaxiosError.extractAPIErrorFromResponse(n,`Request failed with status code ${n.status}`);throw new Oo.GaxiosError(r?.message,e,n,r)}return n}catch(n){let r;n instanceof Oo.GaxiosError?r=n:n instanceof Error?r=new Oo.GaxiosError(n.message,e,void 0,n):r=new Oo.GaxiosError("Unexpected Gaxios Error",e,void 0,n);let{shouldRetry:o,config:s}=await(0,EN.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===TN)return"";if(e.maxContentLength&&n.headers.has("content-length")&&e.maxContentLength<Number.parseInt(n.headers?.get("content-length")||""))throw new Oo.GaxiosError("Response's `Content-Length` is over the limit.",e,Object.assign(n,{config:e}));switch(e.responseType){case"stream":return n.body;case"json":{let r=await n.text();try{return JSON.parse(r)}catch{return r}}case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"text":return n.text();default:return this.getResponseDataFromContentType(n)}}#e(e,n=[]){let r=new URL(e),o=[...n],s=(process.env.NO_PROXY??process.env.no_proxy)?.split(",")||[];for(let i of s)o.push(i.trim());for(let i of o)if(i instanceof RegExp){if(i.test(r.toString()))return!1}else if(i instanceof URL){if(i.origin===r.origin)return!1}else if(i.startsWith("*.")||i.startsWith(".")){let a=i.replace(/^\*\./,".");if(r.hostname.endsWith(a))return!1}else if(i===r.origin||i===r.hostname||i===r.href)return!1;return!0}async#t(e){let n=Promise.resolve(e);for(let r of this.interceptors.request.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#n(e){let n=Promise.resolve(e);for(let r of this.interceptors.response.values())r&&(n=n.then(r.resolved,r.rejected));return n}async#r(e){let n=new Headers(this.defaults.headers);Ds.mergeHeaders(n,e.headers);let r=(0,SN.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 nE.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 vN();n.set("content-type",`multipart/related; boundary=${i}`),r.body=nE.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 Ds.#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 AN.Agent({cert:r.cert,key:r.key}),this.agentCache.set(r.key,r.agent)));return typeof r.errorRedactor!="function"&&r.errorRedactor!==!1&&(r.errorRedactor=Oo.defaultErrorRedactor),r.body&&!("duplex"in r)&&(r.duplex="half"),this.#o(r),Object.assign(r,{headers:n,url:r.url instanceof URL?r.url:new URL(r.url)})}#o(e){if(e.timeout){let n=AbortSignal.timeout(e.timeout);e.signal&&!e.signal.aborted?e.signal=AbortSignal.any([e.signal,n]):e.signal=n}}validateStatus(e){return e>=200&&e<300}async getResponseDataFromContentType(e){let n=e.headers.get("Content-Type");if(n===null)return e.text();if(n=n.toLowerCase(),n.includes("application/json")){let r=await e.text();try{r=JSON.parse(r)}catch{}return r}else return n.match(/^text\//)?e.text():e.blob()}async*getMultipartRequest(e,n){let r=`--${n}--`;for(let o of e){let s=o.headers.get("Content-Type")||"application/octet-stream";yield`--${n}\r
|
|
91
91
|
Content-Type: ${s}\r
|
|
92
92
|
\r
|
|
93
93
|
`,typeof o.content=="string"?yield o.content:yield*o.content,yield`\r
|
|
94
|
-
`}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>nr(MS()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(VA(),KA))).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}};Os.Gaxios=al;Ds=al});var lt=G(bt=>{"use strict";var SN=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]})),AN=bt&&bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&SN(e,t,n)};Object.defineProperty(bt,"__esModule",{value:!0});bt.instance=bt.Gaxios=bt.GaxiosError=void 0;bt.request=vN;var ZA=QA();Object.defineProperty(bt,"Gaxios",{enumerable:!0,get:function(){return ZA.Gaxios}});var EN=Qh();Object.defineProperty(bt,"GaxiosError",{enumerable:!0,get:function(){return EN.GaxiosError}});AN(tg(),bt);bt.instance=new ZA.Gaxios;async function vN(t){return bt.instance.request(t)}});var Dg=G((eE,cl)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",i=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(x){var O,q,V,U=H.prototype={constructor:H,toString:null,valueOf:null},ee=new H(1),z=20,te=4,Q=-7,_e=21,Oe=-1e7,Te=1e7,Ge=!1,ne=1,Z=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",we=!0;function H(S,T){var R,M,D,F,L,P,N,j,B=this;if(!(B instanceof H))return new H(S,T);if(T==null){if(S&&S._isBigNumber===!0){B.s=S.s,!S.c||S.e>Te?B.c=B.e=null:S.e<Oe?B.c=[B.e=0]:(B.e=S.e,B.c=S.c.slice());return}if((P=typeof S=="number")&&S*0==0){if(B.s=1/S<0?(S=-S,-1):1,S===~~S){for(F=0,L=S;L>=10;L/=10,F++);F>Te?B.c=B.e=null:(B.e=F,B.c=[S]);return}j=String(S)}else{if(!n.test(j=String(S)))return V(B,j,P);B.s=j.charCodeAt(0)==45?(j=j.slice(1),-1):1}(F=j.indexOf("."))>-1&&(j=j.replace(".","")),(L=j.search(/e/i))>0?(F<0&&(F=L),F+=+j.slice(L+1),j=j.substring(0,L)):F<0&&(F=j.length)}else{if(b(T,2,Ie.length,"Base"),T==10&&we)return B=new H(S),de(B,z+B.e+1,te);if(j=String(S),P=typeof S=="number"){if(S*0!=0)return V(B,j,P,T);if(B.s=1/S<0?(j=j.slice(1),-1):1,H.DEBUG&&j.replace(/^0\.0*|\./,"").length>15)throw Error(i+S)}else B.s=j.charCodeAt(0)===45?(j=j.slice(1),-1):1;for(R=Ie.slice(0,T),F=L=0,N=j.length;L<N;L++)if(R.indexOf(M=j.charAt(L))<0){if(M=="."){if(L>F){F=N;continue}}else if(!D&&(j==j.toUpperCase()&&(j=j.toLowerCase())||j==j.toLowerCase()&&(j=j.toUpperCase()))){D=!0,L=-1,F=0;continue}return V(B,String(S),P,T)}P=!1,j=q(j,T,10,B.s),(F=j.indexOf("."))>-1?j=j.replace(".",""):F=j.length}for(L=0;j.charCodeAt(L)===48;L++);for(N=j.length;j.charCodeAt(--N)===48;);if(j=j.slice(L,++N)){if(N-=L,P&&H.DEBUG&&N>15&&(S>d||S!==o(S)))throw Error(i+B.s*S);if((F=F-L-1)>Te)B.c=B.e=null;else if(F<Oe)B.c=[B.e=0];else{if(B.e=F,B.c=[],L=(F+1)%u,F<0&&(L+=u),L<N){for(L&&B.c.push(+j.slice(0,L)),N-=u;L<N;)B.c.push(+j.slice(L,L+=u));L=u-(j=j.slice(L)).length}else L-=N;for(;L--;j+="0");B.c.push(+j)}}else B.c=[B.e=0]}H.clone=g,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(S){var T,R;if(S!=null)if(typeof S=="object"){if(S.hasOwnProperty(T="DECIMAL_PLACES")&&(R=S[T],b(R,0,h,T),z=R),S.hasOwnProperty(T="ROUNDING_MODE")&&(R=S[T],b(R,0,8,T),te=R),S.hasOwnProperty(T="EXPONENTIAL_AT")&&(R=S[T],R&&R.pop?(b(R[0],-h,0,T),b(R[1],0,h,T),Q=R[0],_e=R[1]):(b(R,-h,h,T),Q=-(_e=R<0?-R:R))),S.hasOwnProperty(T="RANGE"))if(R=S[T],R&&R.pop)b(R[0],-h,-1,T),b(R[1],1,h,T),Oe=R[0],Te=R[1];else if(b(R,-h,h,T),R)Oe=-(Te=R<0?-R:R);else throw Error(s+T+" cannot be zero: "+R);if(S.hasOwnProperty(T="CRYPTO"))if(R=S[T],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ge=R;else throw Ge=!R,Error(s+"crypto unavailable");else Ge=R;else throw Error(s+T+" not true or false: "+R);if(S.hasOwnProperty(T="MODULO_MODE")&&(R=S[T],b(R,0,9,T),ne=R),S.hasOwnProperty(T="POW_PRECISION")&&(R=S[T],b(R,0,h,T),Z=R),S.hasOwnProperty(T="FORMAT"))if(R=S[T],typeof R=="object")ae=R;else throw Error(s+T+" not an object: "+R);if(S.hasOwnProperty(T="ALPHABET"))if(R=S[T],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))we=R.slice(0,10)=="0123456789",Ie=R;else throw Error(s+T+" invalid: "+R)}else throw Error(s+"Object expected: "+S);return{DECIMAL_PLACES:z,ROUNDING_MODE:te,EXPONENTIAL_AT:[Q,_e],RANGE:[Oe,Te],CRYPTO:Ge,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ae,ALPHABET:Ie}},H.isBigNumber=function(S){if(!S||S._isBigNumber!==!0)return!1;if(!H.DEBUG)return!0;var T,R,M=S.c,D=S.e,F=S.s;e:if({}.toString.call(M)=="[object Array]"){if((F===1||F===-1)&&D>=-h&&D<=h&&D===o(D)){if(M[0]===0){if(D===0&&M.length===1)return!0;break e}if(T=(D+1)%u,T<1&&(T+=u),String(M[0]).length==T){for(T=0;T<M.length;T++)if(R=M[T],R<0||R>=a||R!==o(R))break e;if(R!==0)return!0}}}else if(M===null&&D===null&&(F===null||F===1||F===-1))return!0;throw Error(s+"Invalid BigNumber: "+S)},H.maximum=H.max=function(){return Ze(arguments,-1)},H.minimum=H.min=function(){return Ze(arguments,1)},H.random=(function(){var S=9007199254740992,T=Math.random()*S&2097151?function(){return o(Math.random()*S)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var M,D,F,L,P,N=0,j=[],B=new H(ee);if(R==null?R=z:b(R,0,h),L=r(R/u),Ge)if(crypto.getRandomValues){for(M=crypto.getRandomValues(new Uint32Array(L*=2));N<L;)P=M[N]*131072+(M[N+1]>>>11),P>=9e15?(D=crypto.getRandomValues(new Uint32Array(2)),M[N]=D[0],M[N+1]=D[1]):(j.push(P%1e14),N+=2);N=L/2}else if(crypto.randomBytes){for(M=crypto.randomBytes(L*=7);N<L;)P=(M[N]&31)*281474976710656+M[N+1]*1099511627776+M[N+2]*4294967296+M[N+3]*16777216+(M[N+4]<<16)+(M[N+5]<<8)+M[N+6],P>=9e15?crypto.randomBytes(7).copy(M,N):(j.push(P%1e14),N+=7);N=L/7}else throw Ge=!1,Error(s+"crypto unavailable");if(!Ge)for(;N<L;)P=T(),P<9e15&&(j[N++]=P%1e14);for(L=j[--N],R%=u,L&&R&&(P=f[u-R],j[N]=o(L/P)*P);j[N]===0;j.pop(),N--);if(N<0)j=[F=0];else{for(F=-1;j[0]===0;j.splice(0,1),F-=u);for(N=1,P=j[0];P>=10;P/=10,N++);N<u&&(F-=u-N)}return B.e=F,B.c=j,B}})(),H.sum=function(){for(var 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,j=0,B=R.length;j<B;){for(N=P.length;N--;P[N]*=M);for(P[0]+=F.indexOf(R.charAt(j++)),L=0;L<P.length;L++)P[L]>D-1&&(P[L+1]==null&&(P[L+1]=0),P[L+1]+=P[L]/D|0,P[L]%=D)}return P.reverse()}return function(R,M,D,F,L){var P,N,j,B,K,ie,ue,be,me=R.indexOf("."),he=z,ye=te;for(me>=0&&(B=Z,Z=0,R=R.replace(".",""),be=new H(M),ie=be.pow(R.length-me),Z=B,be.c=T(E(_(ie.c),ie.e,"0"),10,D,S),be.e=be.c.length),ue=T(R,M,D,L?(P=Ie,S):(P=S,Ie)),j=B=ue.length;ue[--B]==0;ue.pop());if(!ue[0])return P.charAt(0);if(me<0?--j:(ie.c=ue,ie.e=j,ie.s=F,ie=O(ie,be,he,ye,D),ue=ie.c,K=ie.r,j=ie.e),N=j+he+1,me=ue[N],B=D/2,K=K||N<0||ue[N+1]!=null,K=ye<4?(me!=null||K)&&(ye==0||ye==(ie.s<0?3:2)):me>B||me==B&&(ye==4||K||ye==6&&ue[N-1]&1||ye==(ie.s<0?8:7)),N<1||!ue[0])R=K?E(P.charAt(1),-he,P.charAt(0)):P.charAt(0);else{if(ue.length=N,K)for(--D;++ue[--N]>D;)ue[N]=0,N||(++j,ue=[1].concat(ue));for(B=ue.length;!ue[--B];);for(me=0,R="";me<=B;R+=P.charAt(ue[me++]));R=E(R,j,P.charAt(0))}return R}})(),O=(function(){function S(M,D,F){var L,P,N,j,B=0,K=M.length,ie=D%p,ue=D/p|0;for(M=M.slice();K--;)N=M[K]%p,j=M[K]/p|0,L=ue*N+j*ie,P=ie*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ue*j,M[K]=P%F;return B&&(M=[B].concat(M)),M}function T(M,D,F,L){var P,N;if(F!=L)N=F>L?1:-1;else for(P=N=0;P<F;P++)if(M[P]!=D[P]){N=M[P]>D[P]?1:-1;break}return N}function R(M,D,F,L){for(var P=0;F--;)M[F]-=P,P=M[F]<D[F]?1:0,M[F]=P*L+M[F]-D[F];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,D,F,L,P){var N,j,B,K,ie,ue,be,me,he,ye,Fe,Ye,mn,ui,Uo,xt,Sr,ht=M.s==D.s?1:-1,et=M.c,je=D.c;if(!et||!et[0]||!je||!je[0])return new H(!M.s||!D.s||(et?je&&et[0]==je[0]:!je)?NaN:et&&et[0]==0||!je?ht*0:ht/0);for(me=new H(ht),he=me.c=[],j=M.e-D.e,ht=F+j+1,P||(P=a,j=C(M.e/u)-C(D.e/u),ht=ht/u|0),B=0;je[B]==(et[B]||0);B++);if(je[B]>(et[B]||0)&&j--,ht<0)he.push(1),K=!0;else{for(ui=et.length,xt=je.length,B=0,ht+=2,ie=o(P/(je[0]+1)),ie>1&&(je=S(je,ie,P),et=S(et,ie,P),xt=je.length,ui=et.length),mn=xt,ye=et.slice(0,xt),Fe=ye.length;Fe<xt;ye[Fe++]=0);Sr=je.slice(),Sr=[0].concat(Sr),Uo=je[0],je[1]>=P/2&&Uo++;do{if(ie=0,N=T(je,ye,xt,Fe),N<0){if(Ye=ye[0],xt!=Fe&&(Ye=Ye*P+(ye[1]||0)),ie=o(Ye/Uo),ie>1)for(ie>=P&&(ie=P-1),ue=S(je,ie,P),be=ue.length,Fe=ye.length;T(ue,ye,be,Fe)==1;)ie--,R(ue,xt<be?Sr:je,be,P),be=ue.length,N=1;else ie==0&&(N=ie=1),ue=je.slice(),be=ue.length;if(be<Fe&&(ue=[0].concat(ue)),R(ye,ue,Fe,P),Fe=ye.length,N==-1)for(;T(je,ye,xt,Fe)<1;)ie++,R(ye,xt<Fe?Sr:je,Fe,P),Fe=ye.length}else N===0&&(ie++,ye=[0]);he[B++]=ie,ye[0]?ye[Fe++]=et[mn]||0:(ye=[et[mn]],Fe=1)}while((mn++<ui||ye[0]!=null)&&ht--);K=ye[0]!=null,he[0]||he.splice(0,1)}if(P==a){for(B=1,ht=he[0];ht>=10;ht/=10,B++);de(me,F+(me.e=B+j*u-1)+1,L,K)}else me.e=j,me.r=+K;return me}})();function Ee(S,T,R,M){var D,F,L,P,N;if(R==null?R=te:b(R,0,8),!S.c)return S.toString();if(D=S.c[0],L=S.e,T==null)N=_(S.c),N=M==1||M==2&&(L<=Q||L>=_e)?w(N,L):E(N,L,"0");else if(S=de(new H(S),T,R),F=S.e,N=_(S.c),P=N.length,M==1||M==2&&(T<=F||F<=Q)){for(;P<T;N+="0",P++);N=w(N,F)}else if(T-=L+(M===2&&F>L),N=E(N,F,"0"),F+1>P){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=F-P,T>0)for(F+1==P&&(N+=".");T--;N+="0");return S.s<0&&D?"-"+N:N}function Ze(S,T){for(var R,M,D=1,F=new H(S[0]);D<S.length;D++)M=new H(S[D]),(!M.s||(R=k(F,M))===T||R===0&&F.s===T)&&(F=M);return F}function X(S,T,R){for(var M=1,D=T.length;!T[--D];T.pop());for(D=T[0];D>=10;D/=10,M++);return(R=M+R*u-1)>Te?S.c=S.e=null:R<Oe?S.c=[S.e=0]:(S.e=R,S.c=T),S}V=(function(){var S=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,R=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,D=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(F,L,P,N){var j,B=P?L:L.replace(D,"");if(M.test(B))F.s=isNaN(B)?null:B<0?-1:1;else{if(!P&&(B=B.replace(S,function(K,ie,ue){return j=(ue=ue.toLowerCase())=="x"?16:ue=="b"?2:8,!N||N==j?ie:K}),N&&(j=N,B=B.replace(T,"$1").replace(R,"0.$1")),L!=B))return new H(B,j);if(H.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+L);F.s=null}F.c=F.e=null}})();function de(S,T,R,M){var D,F,L,P,N,j,B,K=S.c,ie=f;if(K){e:{for(D=1,P=K[0];P>=10;P/=10,D++);if(F=T-D,F<0)F+=u,L=T,N=K[j=0],B=o(N/ie[D-L-1]%10);else if(j=r((F+1)/u),j>=K.length)if(M){for(;K.length<=j;K.push(0));N=B=0,D=1,F%=u,L=F-u+1}else break e;else{for(N=P=K[j],D=1;P>=10;P/=10,D++);F%=u,L=F-u+D,B=L<0?0:o(N/ie[D-L-1]%10)}if(M=M||T<0||K[j+1]!=null||(L<0?N:N%ie[D-L-1]),M=R<4?(B||M)&&(R==0||R==(S.s<0?3:2)):B>5||B==5&&(R==4||M||R==6&&(F>0?L>0?N/ie[D-L]:0:K[j-1])%10&1||R==(S.s<0?8:7)),T<1||!K[0])return K.length=0,M?(T-=S.e+1,K[0]=ie[(u-T%u)%u],S.e=-T||0):K[0]=S.e=0,S;if(F==0?(K.length=j,P=1,j--):(K.length=j+1,P=ie[u-F],K[j]=L>0?o(N/ie[D-L]%ie[L])*P:0),M)for(;;)if(j==0){for(F=1,L=K[0];L>=10;L/=10,F++);for(L=K[0]+=P,P=1;L>=10;L/=10,P++);F!=P&&(S.e++,K[0]==a&&(K[0]=1));break}else{if(K[j]+=P,K[j]!=a)break;K[j--]=0,P=1}for(F=K.length;K[--F]===0;K.pop());}S.e>Te?S.c=S.e=null:S.e<Oe&&(S.c=[S.e=0])}return S}function ce(S){var T,R=S.e;return R===null?S.toString():(T=_(S.c),T=R<=Q||R>=_e?w(T,R):E(T,R,"0"),S.s<0?"-"+T:T)}return U.absoluteValue=U.abs=function(){var S=new H(this);return S.s<0&&(S.s=1),S},U.comparedTo=function(S,T){return k(this,new H(S,T))},U.decimalPlaces=U.dp=function(S,T){var R,M,D,F=this;if(S!=null)return b(S,0,h),T==null?T=te:b(T,0,8),de(new H(F),S+F.e+1,T);if(!(R=F.c))return null;if(M=((D=R.length-1)-C(this.e/u))*u,D=R[D])for(;D%10==0;D/=10,M--);return M<0&&(M=0),M},U.dividedBy=U.div=function(S,T){return O(this,new H(S,T),z,te)},U.dividedToIntegerBy=U.idiv=function(S,T){return O(this,new H(S,T),0,1)},U.exponentiatedBy=U.pow=function(S,T){var R,M,D,F,L,P,N,j,B,K=this;if(S=new H(S),S.c&&!S.isInteger())throw Error(s+"Exponent not an integer: "+ce(S));if(T!=null&&(T=new H(T)),P=S.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!S.c||!S.c[0])return B=new H(Math.pow(+ce(K),P?S.s*(2-A(S)):+ce(S))),T?B.mod(T):B;if(N=S.s<0,T){if(T.c?!T.c[0]:!T.s)return new H(NaN);M=!N&&K.isInteger()&&T.isInteger(),M&&(K=K.mod(T))}else{if(S.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||P&&K.c[1]>=24e7:K.c[0]<8e13||P&&K.c[0]<=9999975e7)))return F=K.s<0&&A(S)?-0:0,K.e>-1&&(F=1/F),new H(N?1/F:F);Z&&(F=r(Z/u+2))}for(P?(R=new H(.5),N&&(S.s=1),j=A(S)):(D=Math.abs(+ce(S)),j=D%2),B=new H(ee);;){if(j){if(B=B.times(K),!B.c)break;F?B.c.length>F&&(B.c.length=F):M&&(B=B.mod(T))}if(D){if(D=o(D/2),D===0)break;j=D%2}else if(S=S.times(R),de(S,S.e+1,1),S.e>14)j=A(S);else{if(D=+ce(S),D===0)break;j=D%2}K=K.times(K),F?K.c&&K.c.length>F&&(K.c.length=F):M&&(K=K.mod(T))}return M?B:(N&&(B=ee.div(B)),T?B.mod(T):F?de(B,Z,te,L):B)},U.integerValue=function(S){var T=new H(this);return S==null?S=te:b(S,0,8),de(T,T.e+1,S)},U.isEqualTo=U.eq=function(S,T){return k(this,new H(S,T))===0},U.isFinite=function(){return!!this.c},U.isGreaterThan=U.gt=function(S,T){return k(this,new H(S,T))>0},U.isGreaterThanOrEqualTo=U.gte=function(S,T){return(T=k(this,new H(S,T)))===1||T===0},U.isInteger=function(){return!!this.c&&C(this.e/u)>this.c.length-2},U.isLessThan=U.lt=function(S,T){return k(this,new H(S,T))<0},U.isLessThanOrEqualTo=U.lte=function(S,T){return(T=k(this,new H(S,T)))===-1||T===0},U.isNaN=function(){return!this.s},U.isNegative=function(){return this.s<0},U.isPositive=function(){return this.s>0},U.isZero=function(){return!!this.c&&this.c[0]==0},U.minus=function(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,j=S.e/u,B=L.c,K=S.c;if(!N||!j){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=C(N),j=C(j),B=B.slice(),P=N-j){for((F=P<0)?(P=-P,D=B):(j=N,D=K),D.reverse(),T=P;T--;D.push(0));D.reverse()}else for(M=(F=(P=B.length)<(T=K.length))?P:T,P=T=0;T<M;T++)if(B[T]!=K[T]){F=B[T]<K[T];break}if(F&&(D=B,B=K,K=D,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),--j);return B[0]?X(S,B,j):(S.s=te==3?-1:1,S.c=[S.e=0],S)},U.modulo=U.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)},U.multipliedBy=U.times=function(S,T){var R,M,D,F,L,P,N,j,B,K,ie,ue,be,me,he,ye=this,Fe=ye.c,Ye=(S=new H(S,T)).c;if(!Fe||!Ye||!Fe[0]||!Ye[0])return!ye.s||!S.s||Fe&&!Fe[0]&&!Ye||Ye&&!Ye[0]&&!Fe?S.c=S.e=S.s=null:(S.s*=ye.s,!Fe||!Ye?S.c=S.e=null:(S.c=[0],S.e=0)),S;for(M=C(ye.e/u)+C(S.e/u),S.s*=ye.s,N=Fe.length,K=Ye.length,N<K&&(be=Fe,Fe=Ye,Ye=be,D=N,N=K,K=D),D=N+K,be=[];D--;be.push(0));for(me=a,he=p,D=K;--D>=0;){for(R=0,ie=Ye[D]%he,ue=Ye[D]/he|0,L=N,F=D+L;F>D;)j=Fe[--L]%he,B=Fe[L]/he|0,P=ue*j+B*ie,j=ie*j+P%he*he+be[F]+R,R=(j/me|0)+(P/he|0)+ue*B,be[F--]=j%me;be[F]=R}return R?++M:be.splice(0,1),X(S,be,M)},U.negated=function(){var S=new H(this);return S.s=-S.s||null,S},U.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=C(F),L=C(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)},U.precision=U.sd=function(S,T){var R,M,D,F=this;if(S!=null&&S!==!!S)return b(S,1,h),T==null?T=te:b(T,0,8),de(new H(F),S,T);if(!(R=F.c))return null;if(D=R.length-1,M=D*u+1,D=R[D]){for(;D%10==0;D/=10,M--);for(D=R[0];D>=10;D/=10,M++);}return S&&F.e+1>M&&(M=F.e+1),M},U.shiftedBy=function(S){return b(S,-d,d),this.times("1e"+S)},U.squareRoot=U.sqrt=function(){var S,T,R,M,D,F=this,L=F.c,P=F.s,N=F.e,j=z+4,B=new H("0.5");if(P!==1||!L||!L[0])return new H(!P||P<0&&(!L||L[0])?NaN:L?F:1/0);if(P=Math.sqrt(+ce(F)),P==0||P==1/0?(T=_(L),(T.length+N)%2==0&&(T+="0"),P=Math.sqrt(+T),N=C((N+1)/2)-(N<0||N%2),P==1/0?T="5e"+N:(T=P.toExponential(),T=T.slice(0,T.indexOf("e")+1)+N),R=new H(T)):R=new H(P+""),R.c[0]){for(N=R.e,P=N+j,P<3&&(P=0);;)if(D=R,R=B.times(D.plus(O(F,D,j,1))),_(D.c).slice(0,P)===(T=_(R.c)).slice(0,P))if(R.e<N&&--P,T=T.slice(P-3,P+1),T=="9999"||!M&&T=="4999"){if(!M&&(de(D,D.e+z+2,0),D.times(D).eq(F))){R=D;break}j+=4,P+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(de(R,R.e+z+2,1),S=!R.times(R).eq(F));break}}return de(R,R.e+z+1,te,S)},U.toExponential=function(S,T){return S!=null&&(b(S,0,h),S++),Ee(this,S,T,1)},U.toFixed=function(S,T){return S!=null&&(b(S,0,h),S=S+this.e+1),Ee(this,S,T)},U.toFormat=function(S,T,R){var M,D=this;if(R==null)S!=null&&T&&typeof T=="object"?(R=T,T=null):S&&typeof S=="object"?(R=S,S=T=null):R=ae;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(M=D.toFixed(S,T),D.c){var F,L=M.split("."),P=+R.groupSize,N=+R.secondaryGroupSize,j=R.groupSeparator||"",B=L[0],K=L[1],ie=D.s<0,ue=ie?B.slice(1):B,be=ue.length;if(N&&(F=P,P=N,N=F,be-=F),P>0&&be>0){for(F=be%P||P,B=ue.substr(0,F);F<be;F+=P)B+=j+ue.substr(F,P);N>0&&(B+=j+ue.slice(F)),ie&&(B="-"+B)}M=K?B+(R.decimalSeparator||"")+((N=+R.fractionGroupSize)?K.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):K):B}return(R.prefix||"")+M+(R.suffix||"")},U.toFraction=function(S){var T,R,M,D,F,L,P,N,j,B,K,ie,ue=this,be=ue.c;if(S!=null&&(P=new H(S),!P.isInteger()&&(P.c||P.s!==1)||P.lt(ee)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+ce(P));if(!be)return new H(ue);for(T=new H(ee),j=R=new H(ee),M=N=new H(ee),ie=_(be),F=T.e=ie.length-ue.e-1,T.c[0]=f[(L=F%u)<0?u+L:L],S=!S||P.comparedTo(T)>0?F>0?T:j:P,L=Te,Te=1/0,P=new H(ie),N.c[0]=0;B=O(P,T,0,1),D=R.plus(B.times(M)),D.comparedTo(S)!=1;)R=M,M=D,j=N.plus(B.times(D=j)),N=D,T=P.minus(B.times(D=T)),P=D;return D=O(S.minus(R),M,0,1),N=N.plus(D.times(j)),R=R.plus(D.times(M)),N.s=j.s=ue.s,F=F*2,K=O(j,M,F,te).minus(ue).abs().comparedTo(O(N,R,F,te).minus(ue).abs())<1?[j,M]:[N,R],Te=L,K},U.toNumber=function(){return+ce(this)},U.toPrecision=function(S,T){return S!=null&&b(S,1,h),Ee(this,S,T,2)},U.toString=function(S){var T,R=this,M=R.s,D=R.e;return D===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(S==null?T=D<=Q||D>=_e?w(_(R.c),D):E(_(R.c),D,"0"):S===10&&we?(R=de(new H(R),z+D+1,te),T=E(_(R.c),R.e,"0")):(b(S,2,Ie.length,"Base"),T=q(E(_(R.c),D,"0"),10,S,M,!0)),M<0&&R.c[0]&&(T="-"+T)),T},U.valueOf=U.toJSON=function(){return ce(this)},U._isBigNumber=!0,x!=null&&H.set(x),H}function C(x){var O=x|0;return x>0||x===O?O:O-1}function _(x){for(var O,q,V=1,U=x.length,ee=x[0]+"";V<U;){for(O=x[V++]+"",q=u-O.length;q--;O="0"+O);ee+=O}for(U=ee.length;ee.charCodeAt(--U)===48;);return ee.slice(0,U+1||1)}function k(x,O){var q,V,U=x.c,ee=O.c,z=x.s,te=O.s,Q=x.e,_e=O.e;if(!z||!te)return null;if(q=U&&!U[0],V=ee&&!ee[0],q||V)return q?V?0:-te:z;if(z!=te)return z;if(q=z<0,V=Q==_e,!U||!ee)return V?0:!U^q?1:-1;if(!V)return Q>_e^q?1:-1;for(te=(Q=U.length)<(_e=ee.length)?Q:_e,z=0;z<te;z++)if(U[z]!=ee[z])return U[z]>ee[z]^q?1:-1;return Q==_e?0:Q>_e^q?1:-1}function b(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 C(x.e/u)==O&&x.c[O]%2!=0}function w(x,O){return(x.length>1?x.charAt(0)+"."+x.slice(1):x)+(O<0?"e":"e+")+O}function E(x,O,q){var V,U;if(O<0){for(U=q+".";++O;U+=q);x=U+x}else if(V=x.length,++O>V){for(U=q,O-=V;--O;U+=q);x+=U}else O<V&&(x=x.slice(0,O)+"."+x.slice(O));return x}e=g(),e.default=e.BigNumber=e,typeof define=="function"&&define.amd?define(function(){return e}):typeof cl<"u"&&cl.exports?cl.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(eE)});var oE=G((MW,rE)=>{var tE=Dg(),nE=rE.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,C,_=r,k,b=f[d],A=b!=null&&(b instanceof tE||tE.isBigNumber(b));switch(b&&typeof b=="object"&&typeof b.toJSON=="function"&&(b=b.toJSON(d)),typeof i=="function"&&(b=i.call(f,d,b)),typeof b){case"string":return A?b:a(b);case"number":return isFinite(b)?String(b):"null";case"boolean":case"null":case"bigint":return String(b);case"object":if(!b)return"null";if(r+=o,k=[],Object.prototype.toString.apply(b)==="[object Array]"){for(C=b.length,p=0;p<C;p+=1)k[p]=u(p,b)||"null";return g=k.length===0?"[]":r?`[
|
|
94
|
+
`}yield r}static#s;static#i;static async#a(){return this.#s||=(await Promise.resolve().then(()=>nr(qS()))).HttpsProxyAgent,this.#s}static async#c(){let e=typeof window<"u"&&!!window;return this.#i||=e?window.fetch:(await Promise.resolve().then(()=>(tE(),eE))).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}};Os.Gaxios=pl;Ds=pl});var lt=G(bt=>{"use strict";var xN=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]})),RN=bt&&bt.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&xN(e,t,n)};Object.defineProperty(bt,"__esModule",{value:!0});bt.instance=bt.Gaxios=bt.GaxiosError=void 0;bt.request=ON;var sE=oE();Object.defineProperty(bt,"Gaxios",{enumerable:!0,get:function(){return sE.Gaxios}});var DN=ig();Object.defineProperty(bt,"GaxiosError",{enumerable:!0,get:function(){return DN.GaxiosError}});RN(ug(),bt);bt.instance=new sE.Gaxios;async function ON(t){return bt.instance.request(t)}});var Ug=G((iE,hl)=>{(function(t){"use strict";var e,n=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,r=Math.ceil,o=Math.floor,s="[BigNumber Error] ",i=s+"Number primitive has more than 15 significant digits: ",a=1e14,u=14,d=9007199254740991,f=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],p=1e7,h=1e9;function g(x){var O,q,V,j=H.prototype={constructor:H,toString:null,valueOf:null},ee=new H(1),z=20,te=4,Q=-7,_e=21,Oe=-1e7,Te=1e7,Ge=!1,ne=1,Z=0,ae={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},Ie="0123456789abcdefghijklmnopqrstuvwxyz",we=!0;function H(S,T){var R,M,D,F,L,P,N,U,B=this;if(!(B instanceof H))return new H(S,T);if(T==null){if(S&&S._isBigNumber===!0){B.s=S.s,!S.c||S.e>Te?B.c=B.e=null:S.e<Oe?B.c=[B.e=0]:(B.e=S.e,B.c=S.c.slice());return}if((P=typeof S=="number")&&S*0==0){if(B.s=1/S<0?(S=-S,-1):1,S===~~S){for(F=0,L=S;L>=10;L/=10,F++);F>Te?B.c=B.e=null:(B.e=F,B.c=[S]);return}U=String(S)}else{if(!n.test(U=String(S)))return V(B,U,P);B.s=U.charCodeAt(0)==45?(U=U.slice(1),-1):1}(F=U.indexOf("."))>-1&&(U=U.replace(".","")),(L=U.search(/e/i))>0?(F<0&&(F=L),F+=+U.slice(L+1),U=U.substring(0,L)):F<0&&(F=U.length)}else{if(b(T,2,Ie.length,"Base"),T==10&&we)return B=new H(S),de(B,z+B.e+1,te);if(U=String(S),P=typeof S=="number"){if(S*0!=0)return V(B,U,P,T);if(B.s=1/S<0?(U=U.slice(1),-1):1,H.DEBUG&&U.replace(/^0\.0*|\./,"").length>15)throw Error(i+S)}else B.s=U.charCodeAt(0)===45?(U=U.slice(1),-1):1;for(R=Ie.slice(0,T),F=L=0,N=U.length;L<N;L++)if(R.indexOf(M=U.charAt(L))<0){if(M=="."){if(L>F){F=N;continue}}else if(!D&&(U==U.toUpperCase()&&(U=U.toLowerCase())||U==U.toLowerCase()&&(U=U.toUpperCase()))){D=!0,L=-1,F=0;continue}return V(B,String(S),P,T)}P=!1,U=q(U,T,10,B.s),(F=U.indexOf("."))>-1?U=U.replace(".",""):F=U.length}for(L=0;U.charCodeAt(L)===48;L++);for(N=U.length;U.charCodeAt(--N)===48;);if(U=U.slice(L,++N)){if(N-=L,P&&H.DEBUG&&N>15&&(S>d||S!==o(S)))throw Error(i+B.s*S);if((F=F-L-1)>Te)B.c=B.e=null;else if(F<Oe)B.c=[B.e=0];else{if(B.e=F,B.c=[],L=(F+1)%u,F<0&&(L+=u),L<N){for(L&&B.c.push(+U.slice(0,L)),N-=u;L<N;)B.c.push(+U.slice(L,L+=u));L=u-(U=U.slice(L)).length}else L-=N;for(;L--;U+="0");B.c.push(+U)}}else B.c=[B.e=0]}H.clone=g,H.ROUND_UP=0,H.ROUND_DOWN=1,H.ROUND_CEIL=2,H.ROUND_FLOOR=3,H.ROUND_HALF_UP=4,H.ROUND_HALF_DOWN=5,H.ROUND_HALF_EVEN=6,H.ROUND_HALF_CEIL=7,H.ROUND_HALF_FLOOR=8,H.EUCLID=9,H.config=H.set=function(S){var T,R;if(S!=null)if(typeof S=="object"){if(S.hasOwnProperty(T="DECIMAL_PLACES")&&(R=S[T],b(R,0,h,T),z=R),S.hasOwnProperty(T="ROUNDING_MODE")&&(R=S[T],b(R,0,8,T),te=R),S.hasOwnProperty(T="EXPONENTIAL_AT")&&(R=S[T],R&&R.pop?(b(R[0],-h,0,T),b(R[1],0,h,T),Q=R[0],_e=R[1]):(b(R,-h,h,T),Q=-(_e=R<0?-R:R))),S.hasOwnProperty(T="RANGE"))if(R=S[T],R&&R.pop)b(R[0],-h,-1,T),b(R[1],1,h,T),Oe=R[0],Te=R[1];else if(b(R,-h,h,T),R)Oe=-(Te=R<0?-R:R);else throw Error(s+T+" cannot be zero: "+R);if(S.hasOwnProperty(T="CRYPTO"))if(R=S[T],R===!!R)if(R)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Ge=R;else throw Ge=!R,Error(s+"crypto unavailable");else Ge=R;else throw Error(s+T+" not true or false: "+R);if(S.hasOwnProperty(T="MODULO_MODE")&&(R=S[T],b(R,0,9,T),ne=R),S.hasOwnProperty(T="POW_PRECISION")&&(R=S[T],b(R,0,h,T),Z=R),S.hasOwnProperty(T="FORMAT"))if(R=S[T],typeof R=="object")ae=R;else throw Error(s+T+" not an object: "+R);if(S.hasOwnProperty(T="ALPHABET"))if(R=S[T],typeof R=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(R))we=R.slice(0,10)=="0123456789",Ie=R;else throw Error(s+T+" invalid: "+R)}else throw Error(s+"Object expected: "+S);return{DECIMAL_PLACES:z,ROUNDING_MODE:te,EXPONENTIAL_AT:[Q,_e],RANGE:[Oe,Te],CRYPTO:Ge,MODULO_MODE:ne,POW_PRECISION:Z,FORMAT:ae,ALPHABET:Ie}},H.isBigNumber=function(S){if(!S||S._isBigNumber!==!0)return!1;if(!H.DEBUG)return!0;var T,R,M=S.c,D=S.e,F=S.s;e:if({}.toString.call(M)=="[object Array]"){if((F===1||F===-1)&&D>=-h&&D<=h&&D===o(D)){if(M[0]===0){if(D===0&&M.length===1)return!0;break e}if(T=(D+1)%u,T<1&&(T+=u),String(M[0]).length==T){for(T=0;T<M.length;T++)if(R=M[T],R<0||R>=a||R!==o(R))break e;if(R!==0)return!0}}}else if(M===null&&D===null&&(F===null||F===1||F===-1))return!0;throw Error(s+"Invalid BigNumber: "+S)},H.maximum=H.max=function(){return Ze(arguments,-1)},H.minimum=H.min=function(){return Ze(arguments,1)},H.random=(function(){var S=9007199254740992,T=Math.random()*S&2097151?function(){return o(Math.random()*S)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(R){var M,D,F,L,P,N=0,U=[],B=new H(ee);if(R==null?R=z:b(R,0,h),L=r(R/u),Ge)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 Ge=!1,Error(s+"crypto unavailable");if(!Ge)for(;N<L;)P=T(),P<9e15&&(U[N++]=P%1e14);for(L=U[--N],R%=u,L&&R&&(P=f[u-R],U[N]=o(L/P)*P);U[N]===0;U.pop(),N--);if(N<0)U=[F=0];else{for(F=-1;U[0]===0;U.splice(0,1),F-=u);for(N=1,P=U[0];P>=10;P/=10,N++);N<u&&(F-=u-N)}return B.e=F,B.c=U,B}})(),H.sum=function(){for(var S=1,T=arguments,R=new H(T[0]);S<T.length;)R=R.plus(T[S++]);return R},q=(function(){var S="0123456789";function T(R,M,D,F){for(var L,P=[0],N,U=0,B=R.length;U<B;){for(N=P.length;N--;P[N]*=M);for(P[0]+=F.indexOf(R.charAt(U++)),L=0;L<P.length;L++)P[L]>D-1&&(P[L+1]==null&&(P[L+1]=0),P[L+1]+=P[L]/D|0,P[L]%=D)}return P.reverse()}return function(R,M,D,F,L){var P,N,U,B,K,ie,ue,be,me=R.indexOf("."),he=z,ye=te;for(me>=0&&(B=Z,Z=0,R=R.replace(".",""),be=new H(M),ie=be.pow(R.length-me),Z=B,be.c=T(E(y(ie.c),ie.e,"0"),10,D,S),be.e=be.c.length),ue=T(R,M,D,L?(P=Ie,S):(P=S,Ie)),U=B=ue.length;ue[--B]==0;ue.pop());if(!ue[0])return P.charAt(0);if(me<0?--U:(ie.c=ue,ie.e=U,ie.s=F,ie=O(ie,be,he,ye,D),ue=ie.c,K=ie.r,U=ie.e),N=U+he+1,me=ue[N],B=D/2,K=K||N<0||ue[N+1]!=null,K=ye<4?(me!=null||K)&&(ye==0||ye==(ie.s<0?3:2)):me>B||me==B&&(ye==4||K||ye==6&&ue[N-1]&1||ye==(ie.s<0?8:7)),N<1||!ue[0])R=K?E(P.charAt(1),-he,P.charAt(0)):P.charAt(0);else{if(ue.length=N,K)for(--D;++ue[--N]>D;)ue[N]=0,N||(++U,ue=[1].concat(ue));for(B=ue.length;!ue[--B];);for(me=0,R="";me<=B;R+=P.charAt(ue[me++]));R=E(R,U,P.charAt(0))}return R}})(),O=(function(){function S(M,D,F){var L,P,N,U,B=0,K=M.length,ie=D%p,ue=D/p|0;for(M=M.slice();K--;)N=M[K]%p,U=M[K]/p|0,L=ue*N+U*ie,P=ie*N+L%p*p+B,B=(P/F|0)+(L/p|0)+ue*U,M[K]=P%F;return B&&(M=[B].concat(M)),M}function T(M,D,F,L){var P,N;if(F!=L)N=F>L?1:-1;else for(P=N=0;P<F;P++)if(M[P]!=D[P]){N=M[P]>D[P]?1:-1;break}return N}function R(M,D,F,L){for(var P=0;F--;)M[F]-=P,P=M[F]<D[F]?1:0,M[F]=P*L+M[F]-D[F];for(;!M[0]&&M.length>1;M.splice(0,1));}return function(M,D,F,L,P){var N,U,B,K,ie,ue,be,me,he,ye,Fe,Ye,mn,ui,jo,xt,Sr,ht=M.s==D.s?1:-1,et=M.c,Ue=D.c;if(!et||!et[0]||!Ue||!Ue[0])return new H(!M.s||!D.s||(et?Ue&&et[0]==Ue[0]:!Ue)?NaN:et&&et[0]==0||!Ue?ht*0:ht/0);for(me=new H(ht),he=me.c=[],U=M.e-D.e,ht=F+U+1,P||(P=a,U=C(M.e/u)-C(D.e/u),ht=ht/u|0),B=0;Ue[B]==(et[B]||0);B++);if(Ue[B]>(et[B]||0)&&U--,ht<0)he.push(1),K=!0;else{for(ui=et.length,xt=Ue.length,B=0,ht+=2,ie=o(P/(Ue[0]+1)),ie>1&&(Ue=S(Ue,ie,P),et=S(et,ie,P),xt=Ue.length,ui=et.length),mn=xt,ye=et.slice(0,xt),Fe=ye.length;Fe<xt;ye[Fe++]=0);Sr=Ue.slice(),Sr=[0].concat(Sr),jo=Ue[0],Ue[1]>=P/2&&jo++;do{if(ie=0,N=T(Ue,ye,xt,Fe),N<0){if(Ye=ye[0],xt!=Fe&&(Ye=Ye*P+(ye[1]||0)),ie=o(Ye/jo),ie>1)for(ie>=P&&(ie=P-1),ue=S(Ue,ie,P),be=ue.length,Fe=ye.length;T(ue,ye,be,Fe)==1;)ie--,R(ue,xt<be?Sr:Ue,be,P),be=ue.length,N=1;else ie==0&&(N=ie=1),ue=Ue.slice(),be=ue.length;if(be<Fe&&(ue=[0].concat(ue)),R(ye,ue,Fe,P),Fe=ye.length,N==-1)for(;T(Ue,ye,xt,Fe)<1;)ie++,R(ye,xt<Fe?Sr:Ue,Fe,P),Fe=ye.length}else N===0&&(ie++,ye=[0]);he[B++]=ie,ye[0]?ye[Fe++]=et[mn]||0:(ye=[et[mn]],Fe=1)}while((mn++<ui||ye[0]!=null)&&ht--);K=ye[0]!=null,he[0]||he.splice(0,1)}if(P==a){for(B=1,ht=he[0];ht>=10;ht/=10,B++);de(me,F+(me.e=B+U*u-1)+1,L,K)}else me.e=U,me.r=+K;return me}})();function Ee(S,T,R,M){var D,F,L,P,N;if(R==null?R=te:b(R,0,8),!S.c)return S.toString();if(D=S.c[0],L=S.e,T==null)N=y(S.c),N=M==1||M==2&&(L<=Q||L>=_e)?w(N,L):E(N,L,"0");else if(S=de(new H(S),T,R),F=S.e,N=y(S.c),P=N.length,M==1||M==2&&(T<=F||F<=Q)){for(;P<T;N+="0",P++);N=w(N,F)}else if(T-=L+(M===2&&F>L),N=E(N,F,"0"),F+1>P){if(--T>0)for(N+=".";T--;N+="0");}else if(T+=F-P,T>0)for(F+1==P&&(N+=".");T--;N+="0");return S.s<0&&D?"-"+N:N}function Ze(S,T){for(var R,M,D=1,F=new H(S[0]);D<S.length;D++)M=new H(S[D]),(!M.s||(R=k(F,M))===T||R===0&&F.s===T)&&(F=M);return F}function X(S,T,R){for(var M=1,D=T.length;!T[--D];T.pop());for(D=T[0];D>=10;D/=10,M++);return(R=M+R*u-1)>Te?S.c=S.e=null:R<Oe?S.c=[S.e=0]:(S.e=R,S.c=T),S}V=(function(){var S=/^(-?)0([xbo])(?=\w[\w.]*$)/i,T=/^([^.]+)\.$/,R=/^\.([^.]+)$/,M=/^-?(Infinity|NaN)$/,D=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(F,L,P,N){var U,B=P?L:L.replace(D,"");if(M.test(B))F.s=isNaN(B)?null:B<0?-1:1;else{if(!P&&(B=B.replace(S,function(K,ie,ue){return U=(ue=ue.toLowerCase())=="x"?16:ue=="b"?2:8,!N||N==U?ie:K}),N&&(U=N,B=B.replace(T,"$1").replace(R,"0.$1")),L!=B))return new H(B,U);if(H.DEBUG)throw Error(s+"Not a"+(N?" base "+N:"")+" number: "+L);F.s=null}F.c=F.e=null}})();function de(S,T,R,M){var D,F,L,P,N,U,B,K=S.c,ie=f;if(K){e:{for(D=1,P=K[0];P>=10;P/=10,D++);if(F=T-D,F<0)F+=u,L=T,N=K[U=0],B=o(N/ie[D-L-1]%10);else if(U=r((F+1)/u),U>=K.length)if(M){for(;K.length<=U;K.push(0));N=B=0,D=1,F%=u,L=F-u+1}else break e;else{for(N=P=K[U],D=1;P>=10;P/=10,D++);F%=u,L=F-u+D,B=L<0?0:o(N/ie[D-L-1]%10)}if(M=M||T<0||K[U+1]!=null||(L<0?N:N%ie[D-L-1]),M=R<4?(B||M)&&(R==0||R==(S.s<0?3:2)):B>5||B==5&&(R==4||M||R==6&&(F>0?L>0?N/ie[D-L]:0:K[U-1])%10&1||R==(S.s<0?8:7)),T<1||!K[0])return K.length=0,M?(T-=S.e+1,K[0]=ie[(u-T%u)%u],S.e=-T||0):K[0]=S.e=0,S;if(F==0?(K.length=U,P=1,U--):(K.length=U+1,P=ie[u-F],K[U]=L>0?o(N/ie[D-L]%ie[L])*P:0),M)for(;;)if(U==0){for(F=1,L=K[0];L>=10;L/=10,F++);for(L=K[0]+=P,P=1;L>=10;L/=10,P++);F!=P&&(S.e++,K[0]==a&&(K[0]=1));break}else{if(K[U]+=P,K[U]!=a)break;K[U--]=0,P=1}for(F=K.length;K[--F]===0;K.pop());}S.e>Te?S.c=S.e=null:S.e<Oe&&(S.c=[S.e=0])}return S}function ce(S){var T,R=S.e;return R===null?S.toString():(T=y(S.c),T=R<=Q||R>=_e?w(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 k(this,new H(S,T))},j.decimalPlaces=j.dp=function(S,T){var R,M,D,F=this;if(S!=null)return b(S,0,h),T==null?T=te:b(T,0,8),de(new H(F),S+F.e+1,T);if(!(R=F.c))return null;if(M=((D=R.length-1)-C(this.e/u))*u,D=R[D])for(;D%10==0;D/=10,M--);return M<0&&(M=0),M},j.dividedBy=j.div=function(S,T){return O(this,new H(S,T),z,te)},j.dividedToIntegerBy=j.idiv=function(S,T){return O(this,new H(S,T),0,1)},j.exponentiatedBy=j.pow=function(S,T){var R,M,D,F,L,P,N,U,B,K=this;if(S=new H(S),S.c&&!S.isInteger())throw Error(s+"Exponent not an integer: "+ce(S));if(T!=null&&(T=new H(T)),P=S.e>14,!K.c||!K.c[0]||K.c[0]==1&&!K.e&&K.c.length==1||!S.c||!S.c[0])return B=new H(Math.pow(+ce(K),P?S.s*(2-A(S)):+ce(S))),T?B.mod(T):B;if(N=S.s<0,T){if(T.c?!T.c[0]:!T.s)return new H(NaN);M=!N&&K.isInteger()&&T.isInteger(),M&&(K=K.mod(T))}else{if(S.e>9&&(K.e>0||K.e<-1||(K.e==0?K.c[0]>1||P&&K.c[1]>=24e7:K.c[0]<8e13||P&&K.c[0]<=9999975e7)))return F=K.s<0&&A(S)?-0:0,K.e>-1&&(F=1/F),new H(N?1/F:F);Z&&(F=r(Z/u+2))}for(P?(R=new H(.5),N&&(S.s=1),U=A(S)):(D=Math.abs(+ce(S)),U=D%2),B=new H(ee);;){if(U){if(B=B.times(K),!B.c)break;F?B.c.length>F&&(B.c.length=F):M&&(B=B.mod(T))}if(D){if(D=o(D/2),D===0)break;U=D%2}else if(S=S.times(R),de(S,S.e+1,1),S.e>14)U=A(S);else{if(D=+ce(S),D===0)break;U=D%2}K=K.times(K),F?K.c&&K.c.length>F&&(K.c.length=F):M&&(K=K.mod(T))}return M?B:(N&&(B=ee.div(B)),T?B.mod(T):F?de(B,Z,te,L):B)},j.integerValue=function(S){var T=new H(this);return S==null?S=te:b(S,0,8),de(T,T.e+1,S)},j.isEqualTo=j.eq=function(S,T){return k(this,new H(S,T))===0},j.isFinite=function(){return!!this.c},j.isGreaterThan=j.gt=function(S,T){return k(this,new H(S,T))>0},j.isGreaterThanOrEqualTo=j.gte=function(S,T){return(T=k(this,new H(S,T)))===1||T===0},j.isInteger=function(){return!!this.c&&C(this.e/u)>this.c.length-2},j.isLessThan=j.lt=function(S,T){return k(this,new H(S,T))<0},j.isLessThanOrEqualTo=j.lte=function(S,T){return(T=k(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=C(N),U=C(U),B=B.slice(),P=N-U){for((F=P<0)?(P=-P,D=B):(U=N,D=K),D.reverse(),T=P;T--;D.push(0));D.reverse()}else for(M=(F=(P=B.length)<(T=K.length))?P:T,P=T=0;T<M;T++)if(B[T]!=K[T]){F=B[T]<K[T];break}if(F&&(D=B,B=K,K=D,S.s=-S.s),T=(M=K.length)-(R=B.length),T>0)for(;T--;B[R++]=0);for(T=a-1;M>P;){if(B[--M]<K[M]){for(R=M;R&&!B[--R];B[R]=T);--B[R],B[M]+=a}B[M]-=K[M]}for(;B[0]==0;B.splice(0,1),--U);return B[0]?X(S,B,U):(S.s=te==3?-1:1,S.c=[S.e=0],S)},j.modulo=j.mod=function(S,T){var R,M,D=this;return S=new H(S,T),!D.c||!S.s||S.c&&!S.c[0]?new H(NaN):!S.c||D.c&&!D.c[0]?new H(D):(ne==9?(M=S.s,S.s=1,R=O(D,S,0,3),S.s=M,R.s*=M):R=O(D,S,0,ne),S=D.minus(R.times(S)),!S.c[0]&&ne==1&&(S.s=D.s),S)},j.multipliedBy=j.times=function(S,T){var R,M,D,F,L,P,N,U,B,K,ie,ue,be,me,he,ye=this,Fe=ye.c,Ye=(S=new H(S,T)).c;if(!Fe||!Ye||!Fe[0]||!Ye[0])return!ye.s||!S.s||Fe&&!Fe[0]&&!Ye||Ye&&!Ye[0]&&!Fe?S.c=S.e=S.s=null:(S.s*=ye.s,!Fe||!Ye?S.c=S.e=null:(S.c=[0],S.e=0)),S;for(M=C(ye.e/u)+C(S.e/u),S.s*=ye.s,N=Fe.length,K=Ye.length,N<K&&(be=Fe,Fe=Ye,Ye=be,D=N,N=K,K=D),D=N+K,be=[];D--;be.push(0));for(me=a,he=p,D=K;--D>=0;){for(R=0,ie=Ye[D]%he,ue=Ye[D]/he|0,L=N,F=D+L;F>D;)U=Fe[--L]%he,B=Fe[L]/he|0,P=ue*U+B*ie,U=ie*U+P%he*he+be[F]+R,R=(U/me|0)+(P/he|0)+ue*B,be[F--]=U%me;be[F]=R}return R?++M:be.splice(0,1),X(S,be,M)},j.negated=function(){var S=new H(this);return S.s=-S.s||null,S},j.plus=function(S,T){var R,M=this,D=M.s;if(S=new H(S,T),T=S.s,!D||!T)return new H(NaN);if(D!=T)return S.s=-T,M.minus(S);var F=M.e/u,L=S.e/u,P=M.c,N=S.c;if(!F||!L){if(!P||!N)return new H(D/0);if(!P[0]||!N[0])return N[0]?S:new H(P[0]?M:D*0)}if(F=C(F),L=C(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 b(S,1,h),T==null?T=te:b(T,0,8),de(new H(F),S,T);if(!(R=F.c))return null;if(D=R.length-1,M=D*u+1,D=R[D]){for(;D%10==0;D/=10,M--);for(D=R[0];D>=10;D/=10,M++);}return S&&F.e+1>M&&(M=F.e+1),M},j.shiftedBy=function(S){return b(S,-d,d),this.times("1e"+S)},j.squareRoot=j.sqrt=function(){var S,T,R,M,D,F=this,L=F.c,P=F.s,N=F.e,U=z+4,B=new H("0.5");if(P!==1||!L||!L[0])return new H(!P||P<0&&(!L||L[0])?NaN:L?F:1/0);if(P=Math.sqrt(+ce(F)),P==0||P==1/0?(T=y(L),(T.length+N)%2==0&&(T+="0"),P=Math.sqrt(+T),N=C((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))),y(D.c).slice(0,P)===(T=y(R.c)).slice(0,P))if(R.e<N&&--P,T=T.slice(P-3,P+1),T=="9999"||!M&&T=="4999"){if(!M&&(de(D,D.e+z+2,0),D.times(D).eq(F))){R=D;break}U+=4,P+=4,M=1}else{(!+T||!+T.slice(1)&&T.charAt(0)=="5")&&(de(R,R.e+z+2,1),S=!R.times(R).eq(F));break}}return de(R,R.e+z+1,te,S)},j.toExponential=function(S,T){return S!=null&&(b(S,0,h),S++),Ee(this,S,T,1)},j.toFixed=function(S,T){return S!=null&&(b(S,0,h),S=S+this.e+1),Ee(this,S,T)},j.toFormat=function(S,T,R){var M,D=this;if(R==null)S!=null&&T&&typeof T=="object"?(R=T,T=null):S&&typeof S=="object"?(R=S,S=T=null):R=ae;else if(typeof R!="object")throw Error(s+"Argument not an object: "+R);if(M=D.toFixed(S,T),D.c){var F,L=M.split("."),P=+R.groupSize,N=+R.secondaryGroupSize,U=R.groupSeparator||"",B=L[0],K=L[1],ie=D.s<0,ue=ie?B.slice(1):B,be=ue.length;if(N&&(F=P,P=N,N=F,be-=F),P>0&&be>0){for(F=be%P||P,B=ue.substr(0,F);F<be;F+=P)B+=U+ue.substr(F,P);N>0&&(B+=U+ue.slice(F)),ie&&(B="-"+B)}M=K?B+(R.decimalSeparator||"")+((N=+R.fractionGroupSize)?K.replace(new RegExp("\\d{"+N+"}\\B","g"),"$&"+(R.fractionGroupSeparator||"")):K):B}return(R.prefix||"")+M+(R.suffix||"")},j.toFraction=function(S){var T,R,M,D,F,L,P,N,U,B,K,ie,ue=this,be=ue.c;if(S!=null&&(P=new H(S),!P.isInteger()&&(P.c||P.s!==1)||P.lt(ee)))throw Error(s+"Argument "+(P.isInteger()?"out of range: ":"not an integer: ")+ce(P));if(!be)return new H(ue);for(T=new H(ee),U=R=new H(ee),M=N=new H(ee),ie=y(be),F=T.e=ie.length-ue.e-1,T.c[0]=f[(L=F%u)<0?u+L:L],S=!S||P.comparedTo(T)>0?F>0?T:U:P,L=Te,Te=1/0,P=new H(ie),N.c[0]=0;B=O(P,T,0,1),D=R.plus(B.times(M)),D.comparedTo(S)!=1;)R=M,M=D,U=N.plus(B.times(D=U)),N=D,T=P.minus(B.times(D=T)),P=D;return D=O(S.minus(R),M,0,1),N=N.plus(D.times(U)),R=R.plus(D.times(M)),N.s=U.s=ue.s,F=F*2,K=O(U,M,F,te).minus(ue).abs().comparedTo(O(N,R,F,te).minus(ue).abs())<1?[U,M]:[N,R],Te=L,K},j.toNumber=function(){return+ce(this)},j.toPrecision=function(S,T){return S!=null&&b(S,1,h),Ee(this,S,T,2)},j.toString=function(S){var T,R=this,M=R.s,D=R.e;return D===null?M?(T="Infinity",M<0&&(T="-"+T)):T="NaN":(S==null?T=D<=Q||D>=_e?w(y(R.c),D):E(y(R.c),D,"0"):S===10&&we?(R=de(new H(R),z+D+1,te),T=E(y(R.c),R.e,"0")):(b(S,2,Ie.length,"Base"),T=q(E(y(R.c),D,"0"),10,S,M,!0)),M<0&&R.c[0]&&(T="-"+T)),T},j.valueOf=j.toJSON=function(){return ce(this)},j._isBigNumber=!0,x!=null&&H.set(x),H}function C(x){var O=x|0;return x>0||x===O?O:O-1}function y(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 k(x,O){var q,V,j=x.c,ee=O.c,z=x.s,te=O.s,Q=x.e,_e=O.e;if(!z||!te)return null;if(q=j&&!j[0],V=ee&&!ee[0],q||V)return q?V?0:-te:z;if(z!=te)return z;if(q=z<0,V=Q==_e,!j||!ee)return V?0:!j^q?1:-1;if(!V)return Q>_e^q?1:-1;for(te=(Q=j.length)<(_e=ee.length)?Q:_e,z=0;z<te;z++)if(j[z]!=ee[z])return j[z]>ee[z]^q?1:-1;return Q==_e?0:Q>_e^q?1:-1}function b(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 C(x.e/u)==O&&x.c[O]%2!=0}function w(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 hl<"u"&&hl.exports?hl.exports=e:(t||(t=typeof self<"u"&&self?self:window),t.BigNumber=e)})(iE)});var lE=G((KW,uE)=>{var aE=Ug(),cE=uE.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,C,y=r,k,b=f[d],A=b!=null&&(b instanceof aE||aE.isBigNumber(b));switch(b&&typeof b=="object"&&typeof b.toJSON=="function"&&(b=b.toJSON(d)),typeof i=="function"&&(b=i.call(f,d,b)),typeof b){case"string":return A?b:a(b);case"number":return isFinite(b)?String(b):"null";case"boolean":case"null":case"bigint":return String(b);case"object":if(!b)return"null";if(r+=o,k=[],Object.prototype.toString.apply(b)==="[object Array]"){for(C=b.length,p=0;p<C;p+=1)k[p]=u(p,b)||"null";return g=k.length===0?"[]":r?`[
|
|
95
95
|
`+r+k.join(`,
|
|
96
96
|
`+r)+`
|
|
97
|
-
`+
|
|
97
|
+
`+y+"]":"["+k.join(",")+"]",r=y,g}if(i&&typeof i=="object")for(C=i.length,p=0;p<C;p+=1)typeof i[p]=="string"&&(h=i[p],g=u(h,b),g&&k.push(a(h)+(r?": ":":")+g));else Object.keys(b).forEach(function(w){var E=u(w,b);E&&k.push(a(w)+(r?": ":":")+E)});return g=k.length===0?"{}":r?`{
|
|
98
98
|
`+r+k.join(`,
|
|
99
99
|
`+r)+`
|
|
100
|
-
`+
|
|
101
|
-
`,r:"\r",t:" "},s,i=function(_){throw{name:"SyntaxError",message:_,at:n,text:s}},a=function(_){return _&&_!==r&&i("Expected '"+_+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},u=function(){var _,k="";for(r==="-"&&(k="-",a("-"));r>="0"&&r<="9";)k+=r,a();if(r===".")for(k+=".";a()&&r>="0"&&r<="9";)k+=r;if(r==="e"||r==="E")for(k+=r,a(),(r==="-"||r==="+")&&(k+=r,a());r>="0"&&r<="9";)k+=r,a();if(_=+k,!isFinite(_))i("Bad number");else return ul==null&&(ul=Dg()),k.length>15?e.storeAsString?k:e.useNativeBigInt?BigInt(k):new ul(k):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(_):new ul(_):_},d=function(){var _,k,b="",A;if(r==='"')for(var w=n;a();){if(r==='"')return n-1>w&&(b+=s.substring(w,n-1)),a(),b;if(r==="\\"){if(n-1>w&&(b+=s.substring(w,n-1)),a(),r==="u"){for(A=0,k=0;k<4&&(_=parseInt(a(),16),!!isFinite(_));k+=1)A=A*16+_;b+=String.fromCharCode(A)}else if(typeof o[r]=="string")b+=o[r];else break;w=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 _=[];if(r==="["){if(a("["),f(),r==="]")return a("]"),_;for(;r;){if(_.push(h()),f(),r==="]")return a("]"),_;a(","),f()}}i("Bad array")},C=function(){var _,k=Object.create(null);if(r==="{"){if(a("{"),f(),r==="}")return a("}"),k;for(;r;){if(_=d(),f(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(k,_)&&i('Duplicate key "'+_+'"'),TN.test(_)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():k[_]=h():xN.test(_)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():k[_]=h():k[_]=h(),f(),r==="}")return a("}"),k;a(","),f()}}i("Bad object")};return h=function(){switch(f(),r){case"{":return C();case"[":return g();case'"':return d();case"-":return u();default:return r>="0"&&r<="9"?u():p()}},function(_,k){var b;return s=_+"",n=0,r=" ",b=h(),f(),r&&i("Syntax error"),typeof k=="function"?(function A(w,E){var x,O,q=w[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]}),k.call(w,E,q)})({"":b},""):b}};sE.exports=RN});var uE=G((jW,ll)=>{var aE=oE().stringify,cE=iE();ll.exports=function(t){return{parse:cE(t),stringify:aE}};ll.exports.parse=cE();ll.exports.stringify=aE});var Og=G(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.GCE_LINUX_BIOS_PATHS=void 0;on.isGoogleCloudServerless=fE;on.isGoogleComputeEngineLinux=pE;on.isGoogleComputeEngineMACAddress=hE;on.isGoogleComputeEngine=gE;on.detectGCPResidency=ON;var lE=re("fs"),dE=re("os");on.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var DN=/^42:01/;function fE(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function pE(){if((0,dE.platform)()!=="linux")return!1;try{(0,lE.statSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,lE.readFileSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function hE(){let t=(0,dE.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(DN.test(n))return!0}return!1}function gE(){return pE()||hE()}function ON(){return fE()||gE()}});var mE=G(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.Colours=void 0;var dl=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="")}};fl.Colours=dl;dl.refresh()});var _E=G(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.LogSeverity=void 0;var yE;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(yE||(pl.LogSeverity=yE={}))});var kE=G($e=>{"use strict";var PN=$e&&$e.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),IN=$e&&$e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),bE=$e&&$e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&PN(n,e,r[o]);return IN(n,e),n}})();Object.defineProperty($e,"__esModule",{value:!0});$e.env=$e.DebugLogBackendBase=$e.placeholder=$e.AdhocDebugLogger=void 0;$e.getNodeBackend=Ig;$e.getDebugBackend=NN;$e.getStructuredBackend=MN;$e.setBackend=BN;$e.log=wE;var FN=re("events"),da=bE(re("process")),CE=bE(re("util")),Ft=mE(),hr=_E(),fa=class extends FN.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(hr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(hr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(hr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(hr.LogSeverity.ERROR,...r),this.func.sublog=r=>wE(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};$e.AdhocDebugLogger=fa;$e.placeholder=new fa("",()=>{}).func;var Ps=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=da.env[$e.env.nodeEnables]??"*";e==="all"&&(e="*"),this.filters=e.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};$e.DebugLogBackendBase=Ps;var Pg=class extends Ps{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${Ft.Colours.green}${e}${Ft.Colours.reset}`,s=`${Ft.Colours.yellow}${da.pid}${Ft.Colours.reset}`,i;switch(n.severity){case hr.LogSeverity.ERROR:i=`${Ft.Colours.red}${n.severity}${Ft.Colours.reset}`;break;case hr.LogSeverity.INFO:i=`${Ft.Colours.magenta}${n.severity}${Ft.Colours.reset}`;break;case hr.LogSeverity.WARNING:i=`${Ft.Colours.yellow}${n.severity}${Ft.Colours.reset}`;break;default:i=n.severity??hr.LogSeverity.DEFAULT;break}let a=CE.formatWithOptions({colors:Ft.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${Ft.Colours.grey}${d}${Ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,i,a,d?` ${f}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function Ig(){return new Pg}var Fg=class extends Ps{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=da.env.NODE_DEBUG??"";da.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function NN(t){return new Fg(t)}var Ng=class extends Ps{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??hr.LogSeverity.INFO,i=Object.assign({severity:s,message:CE.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function MN(t){return new Ng(t)}$e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var Mg=new Map,sn;function BN(t){sn=t,Mg.clear()}function wE(t,e){if(!sn&&!da.env[$e.env.nodeEnables]||!t)return $e.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=Mg.get(t);if(n)return n.func;if(sn===null)return $e.placeholder;sn===void 0&&(sn=Ig());let r=(()=>{let o;return new fa(t,(i,...a)=>{if(o!==sn){if(sn===null)return;sn===void 0&&(sn=Ig()),o=sn}sn?.log(t,i,...a)})})();return Mg.set(t,r),r.func}});var Bg=G(Po=>{"use strict";var jN=Po&&Po.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),UN=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&jN(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});UN(kE(),Po)});var ha=G(pe=>{"use strict";var AE=pe&&pe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),LN=pe&&pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),$N=pe&&pe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&AE(n,e,r[o]);return LN(n,e),n}})(),qN=pe&&pe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&AE(e,t,n)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=KN;pe.project=VN;pe.universe=YN;pe.bulk=XN;pe.isAvailable=ZN;pe.resetIsAvailableCache=eM;pe.getGCPResidency=Lg;pe.setGCPResidency=EE;pe.requestTimeout=vE;var jg=lt(),HN=uE(),zN=Og(),WN=$N(Bg());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var SE=WN.log("gcp-metadata");pe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Ug(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function GN(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 pa(t,e={},n=3,r=!1){let o=new Headers(pe.HEADERS),s="",i={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>o.set(g,h)),s=p.metadataKey,i=p.params||i,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(GN(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?JN:jg.request,u={url:`${Ug()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:vE()};SE.info("instance request %j",u);let d=await a(u);SE.info("instance metadata is %s",d.data);let f=d.headers.get(pe.HEADER_NAME);if(f!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return HN.parse(d.data)}catch{}return d.data}async function JN(t){let e={...t,url:t.url?.toString().replace(Ug(),Ug(pe.SECONDARY_HOST_ADDRESS))},n=(0,jg.request)(t),r=(0,jg.request)(e);return Promise.any([n,r])}function KN(t){return pa("instance",t)}function VN(t){return pa("project",t)}function YN(t){return pa("universe",t)}async function XN(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await pa(n),o=n.metadataKey;e[o]=r})())),e}function QN(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var hl;async function ZN(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Lg();case"ping-only":}}try{return hl===void 0&&(hl=(async()=>{try{return await pa("instance",void 0,QN(),!(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 eM(){hl=void 0}pe.gcpResidencyCache=null;function Lg(){return pe.gcpResidencyCache===null&&EE(),pe.gcpResidencyCache}function EE(t=null){pe.gcpResidencyCache=t!==null?t:(0,zN.detectGCPResidency)()}function vE(){return Lg()?0:3e3}qN(Og(),pe)});var RE=G(gl=>{"use strict";gl.byteLength=nM;gl.toByteArray=oM;gl.fromByteArray=aM;var Bn=[],Gt=[],tM=typeof Uint8Array<"u"?Uint8Array:Array,$g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Io=0,TE=$g.length;Io<TE;++Io)Bn[Io]=$g[Io],Gt[$g.charCodeAt(Io)]=Io;var Io,TE;Gt[45]=62;Gt[95]=63;function xE(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 nM(t){var e=xE(t),n=e[0],r=e[1];return(n+r)*3/4-r}function rM(t,e,n){return(e+n)*3/4-n}function oM(t){var e,n=xE(t),r=n[0],o=n[1],s=new tM(rM(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Gt[t.charCodeAt(u)]<<18|Gt[t.charCodeAt(u+1)]<<12|Gt[t.charCodeAt(u+2)]<<6|Gt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Gt[t.charCodeAt(u)]<<2|Gt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Gt[t.charCodeAt(u)]<<10|Gt[t.charCodeAt(u+1)]<<4|Gt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function sM(t){return Bn[t>>18&63]+Bn[t>>12&63]+Bn[t>>6&63]+Bn[t&63]}function iM(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(sM(r));return o.join("")}function aM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(iM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Bn[e>>2]+Bn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Bn[e>>10]+Bn[e>>4&63]+Bn[e<<2&63]+"=")),o.join("")}});var Hg=G(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});qg.fromArrayBufferToHex=cM;function cM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var DE=G(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.BrowserCrypto=void 0;var Is=RE(),uM=Hg(),zg=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Is.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Is.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=Is.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 Is.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Is.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Is.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,uM.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))}};ml.BrowserCrypto=zg});var OE=G(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.NodeCrypto=void 0;var Fs=re("crypto"),Wg=class{async sha256DigestBase64(e){return Fs.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Fs.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Fs.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Fs.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 Fs.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:dM(e);return lM(Fs.createHmac("sha256",r).update(n).digest())}};yl.NodeCrypto=Wg;function lM(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 dM(t){return Buffer.from(t)}});var ga=G(gr=>{"use strict";var fM=gr&&gr.__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]})),pM=gr&&gr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&fM(e,t,n)};Object.defineProperty(gr,"__esModule",{value:!0});gr.createCrypto=mM;gr.hasBrowserCrypto=PE;var hM=DE(),gM=OE();pM(Hg(),gr);function mM(){return PE()?new hM.BrowserCrypto:new gM.NodeCrypto}function PE(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Ns=G((Gg,FE)=>{var _l=re("buffer"),jn=_l.Buffer;function IE(t,e){for(var n in t)e[n]=t[n]}jn.from&&jn.alloc&&jn.allocUnsafe&&jn.allocUnsafeSlow?FE.exports=_l:(IE(_l,Gg),Gg.Buffer=Fo);function Fo(t,e,n){return jn(t,e,n)}Fo.prototype=Object.create(jn.prototype);IE(jn,Fo);Fo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return jn(t,e,n)};Fo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=jn(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Fo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return jn(t)};Fo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return _l.SlowBuffer(t)}});var ME=G((YW,NE)=>{"use strict";function Jg(t){var e=(t/8|0)+(t%8===0?0:1);return e}var yM={ES256:Jg(256),ES384:Jg(384),ES512:Jg(521)};function _M(t){var e=yM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}NE.exports=_M});var Kg=G((XW,qE)=>{"use strict";var bl=Ns().Buffer,jE=ME(),Cl=128,UE=0,bM=32,CM=16,wM=2,LE=CM|bM|UE<<6,wl=wM|UE<<6;function kM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function $E(t){if(bl.isBuffer(t))return t;if(typeof t=="string")return bl.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function SM(t,e){t=$E(t);var n=jE(e),r=n+1,o=t.length,s=0;if(t[s++]!==LE)throw new Error('Could not find expected "seq"');var i=t[s++];if(i===(Cl|1)&&(i=t[s++]),o-s<i)throw new Error('"seq" specified length of "'+i+'", only "'+(o-s)+'" remaining');if(t[s++]!==wl)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++]!==wl)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=bl.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 C=s;s<C+h;++s)g[s]=0;return t.copy(g,s,f+Math.max(-h,0),f+d),g=g.toString("base64"),g=kM(g),g}function BE(t,e,n){for(var r=0;e+r<n&&t[e+r]===0;)++r;var o=t[e+r]>=Cl;return o&&--r,r}function AM(t,e){t=$E(t);var n=jE(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=BE(t,0,n),s=BE(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<Cl,f=bl.allocUnsafe((d?2:3)+u),p=0;return f[p++]=LE,d?f[p++]=u:(f[p++]=Cl|1,f[p++]=u&255),f[p++]=wl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=wl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}qE.exports={derToJose:SM,joseToDer:AM}});var an=G(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.LRUCache=void 0;mr.snakeToCamel=zE;mr.originalOrCamelOptions=xM;mr.removeUndefinedValuesInObject=RM;mr.isValidFile=DM;mr.getWellKnownCertificateConfigFileLocation=OM;var EM=re("fs"),vM=re("os"),Vg=re("path"),TM="certificate_config.json",HE="gcloud";function zE(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function xM(t){function e(n){let r=t||{};return r[n]??r[zE(n)]}return{get:e}}var Yg=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()}};mr.LRUCache=Yg;function RM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function DM(t){try{return(await EM.promises.lstat(t)).isFile()}catch{return!1}}function OM(){let t=process.env.CLOUDSDK_CONFIG||(PM()?Vg.join(process.env.APPDATA||"",HE):Vg.join(process.env.HOME||"",".config",HE));return Vg.join(t,TM)}function PM(){return vM.platform().startsWith("win")}});var WE=G((ZW,IM)=>{IM.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 Xg=G(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.USER_AGENT=Gr.PRODUCT_NAME=Gr.pkg=void 0;var GE=WE();Gr.pkg=GE;var JE="google-api-nodejs-client";Gr.PRODUCT_NAME=JE;var FM=`${JE}/${GE.version}`;Gr.USER_AGENT=FM});var Nt=G(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.AuthClient=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=cn.DEFAULT_UNIVERSE=void 0;var NM=re("events"),Qg=lt(),MM=an(),BM=Bg(),Zg=Xg();cn.DEFAULT_UNIVERSE="googleapis.com";cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var em=class t extends NM.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=cn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,MM.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??cn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new Qg.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&&Qg.Gaxios.mergeHeaders(s,n.headers),r&&Qg.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,BM.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(`${Zg.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${Zg.USER_AGENT}`):e.headers.set("User-Agent",Zg.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,i):t.log.info("[%s] request %j",s,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};cn.AuthClient=em});var nm=G(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.LoginTicket=void 0;var tm=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()}}};kl.LoginTicket=tm});var Jr=G(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.OAuth2Client=Un.ClientAuthentication=Un.CertificateFormat=Un.CodeChallengeMethod=void 0;var KE=lt(),jM=re("querystring"),UM=re("stream"),LM=Kg(),VE=an(),rm=ga(),Ms=Nt(),$M=nm(),YE;(function(t){t.Plain="plain",t.S256="S256"})(YE||(Un.CodeChallengeMethod=YE={}));var yr;(function(t){t.PEM="PEM",t.JWK="JWK"})(yr||(Un.CertificateFormat=yr={}));var ma;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ma||(Un.ClientAuthentication=ma={}));var om=class t extends Ms.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=yr.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||ma.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()+"?"+jM.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,rm.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===ma.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===ma.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,VE.removeUndefinedValuesInObject)(o)),headers:r};Ms.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,VE.removeUndefinedValuesInObject)(r))};Ms.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof KE.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(Ms.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=KE.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 UM.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,rm.hasBrowserCrypto)()?yr.JWK:yr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case yr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case yr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Ms.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 yr.PEM:a=r.data;break;case yr.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};Ms.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,rm.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(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${a[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+a[0]);try{p=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${a[0]}`),w}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=LM.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 C=Number(p.iat);if(isNaN(C))throw new Error("iat field using invalid format");let _=Number(p.exp);if(isNaN(_))throw new Error("exp field using invalid format");let k=new Date().getTime()/1e3;if(_>=k+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let b=C-t.CLOCK_SKEW_SECS_,A=_+t.CLOCK_SKEW_SECS_;if(k<b)throw new Error("Token used too early, "+k+" < "+b+": "+JSON.stringify(p));if(k>A)throw new Error("Token used too late, "+k+" > "+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 w=p.aud,E=!1;if(r.constructor===Array?E=r.indexOf(w)>-1:E=w===r,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new $M.LoginTicket(f,p)}async processAndValidateRefreshHandler(){if(this.refreshHandler){let e=await this.refreshHandler();if(!e.access_token)throw new Error("No access token is returned by the refreshHandler callback.");return e}}isTokenExpiring(){let e=this.credentials.expiry_date;return e?e<=new Date().getTime()+this.eagerRefreshThresholdMillis:!1}};Un.OAuth2Client=om});var im=G(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.Compute=void 0;var qM=lt(),XE=ha(),HM=Jr(),sm=class extends HM.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 XE.instance(o)}catch(o){throw o instanceof qM.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 XE.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))}};Sl.Compute=sm});var cm=G(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.IdTokenClient=void 0;var zM=Jr(),am=class extends zM.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}};Al.IdTokenClient=am});var um=G(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.GCPEnv=void 0;Bs.clear=WM;Bs.getEnv=GM;var QE=ha(),Ln;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Ln||(Bs.GCPEnv=Ln={}));var ya;function WM(){ya=void 0}async function GM(){return ya||(ya=JM(),ya)}async function JM(){let t=Ln.NONE;return KM()?t=Ln.APP_ENGINE:VM()?t=Ln.CLOUD_FUNCTIONS:await ZM()?await QM()?t=Ln.KUBERNETES_ENGINE:YM()?t=Ln.CLOUD_RUN:XM()?t=Ln.CLOUD_RUN_JOBS:t=Ln.COMPUTE_ENGINE:t=Ln.NONE,t}function KM(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function VM(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function YM(){return!!process.env.K_CONFIGURATION}function XM(){return!!process.env.CLOUD_RUN_JOB}async function QM(){try{return await QE.instance("attributes/cluster-name"),!0}catch{return!1}}async function ZM(){return QE.isAvailable()}});var lm=G((a5,ZE)=>{var El=Ns().Buffer,eB=re("stream"),tB=re("util");function vl(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=El.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=El.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+")")}tB.inherits(vl,eB);vl.prototype.write=function(e){this.buffer=El.concat([this.buffer,El.from(e)]),this.emit("data",e)};vl.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};ZE.exports=vl});var tv=G((c5,ev)=>{"use strict";var _a=re("buffer").Buffer,dm=re("buffer").SlowBuffer;ev.exports=Tl;function Tl(t,e){if(!_a.isBuffer(t)||!_a.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}Tl.install=function(){_a.prototype.equal=dm.prototype.equal=function(e){return Tl(this,e)}};var nB=_a.prototype.equal,rB=dm.prototype.equal;Tl.restore=function(){_a.prototype.equal=nB,dm.prototype.equal=rB}});var gm=G((u5,lv)=>{var Us=Ns().Buffer,Jt=re("crypto"),rv=Kg(),nv=re("util"),oB=`"%s" is not a valid algorithm.
|
|
100
|
+
`+y+"}":"{"+k.join(",")+"}",r=y,g}}typeof cE.stringify!="function"&&(cE.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 fE=G((VW,dE)=>{var gl=null,PN=/(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/,IN=/(?: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)/,FN=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(y){throw{name:"SyntaxError",message:y,at:n,text:s}},a=function(y){return y&&y!==r&&i("Expected '"+y+"' instead of '"+r+"'"),r=s.charAt(n),n+=1,r},u=function(){var y,k="";for(r==="-"&&(k="-",a("-"));r>="0"&&r<="9";)k+=r,a();if(r===".")for(k+=".";a()&&r>="0"&&r<="9";)k+=r;if(r==="e"||r==="E")for(k+=r,a(),(r==="-"||r==="+")&&(k+=r,a());r>="0"&&r<="9";)k+=r,a();if(y=+k,!isFinite(y))i("Bad number");else return gl==null&&(gl=Ug()),k.length>15?e.storeAsString?k:e.useNativeBigInt?BigInt(k):new gl(k):e.alwaysParseAsBig?e.useNativeBigInt?BigInt(y):new gl(y):y},d=function(){var y,k,b="",A;if(r==='"')for(var w=n;a();){if(r==='"')return n-1>w&&(b+=s.substring(w,n-1)),a(),b;if(r==="\\"){if(n-1>w&&(b+=s.substring(w,n-1)),a(),r==="u"){for(A=0,k=0;k<4&&(y=parseInt(a(),16),!!isFinite(y));k+=1)A=A*16+y;b+=String.fromCharCode(A)}else if(typeof o[r]=="string")b+=o[r];else break;w=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 y=[];if(r==="["){if(a("["),f(),r==="]")return a("]"),y;for(;r;){if(y.push(h()),f(),r==="]")return a("]"),y;a(","),f()}}i("Bad array")},C=function(){var y,k=Object.create(null);if(r==="{"){if(a("{"),f(),r==="}")return a("}"),k;for(;r;){if(y=d(),f(),a(":"),e.strict===!0&&Object.hasOwnProperty.call(k,y)&&i('Duplicate key "'+y+'"'),PN.test(y)===!0?e.protoAction==="error"?i("Object contains forbidden prototype property"):e.protoAction==="ignore"?h():k[y]=h():IN.test(y)===!0?e.constructorAction==="error"?i("Object contains forbidden constructor property"):e.constructorAction==="ignore"?h():k[y]=h():k[y]=h(),f(),r==="}")return a("}"),k;a(","),f()}}i("Bad object")};return h=function(){switch(f(),r){case"{":return C();case"[":return g();case'"':return d();case"-":return u();default:return r>="0"&&r<="9"?u():p()}},function(y,k){var b;return s=y+"",n=0,r=" ",b=h(),f(),r&&i("Syntax error"),typeof k=="function"?(function A(w,E){var x,O,q=w[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]}),k.call(w,E,q)})({"":b},""):b}};dE.exports=FN});var gE=G((YW,ml)=>{var pE=lE().stringify,hE=fE();ml.exports=function(t){return{parse:hE(t),stringify:pE}};ml.exports.parse=hE();ml.exports.stringify=pE});var jg=G(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.GCE_LINUX_BIOS_PATHS=void 0;on.isGoogleCloudServerless=_E;on.isGoogleComputeEngineLinux=bE;on.isGoogleComputeEngineMACAddress=CE;on.isGoogleComputeEngine=wE;on.detectGCPResidency=MN;var mE=re("fs"),yE=re("os");on.GCE_LINUX_BIOS_PATHS={BIOS_DATE:"/sys/class/dmi/id/bios_date",BIOS_VENDOR:"/sys/class/dmi/id/bios_vendor"};var NN=/^42:01/;function _E(){return!!(process.env.CLOUD_RUN_JOB||process.env.FUNCTION_NAME||process.env.K_SERVICE)}function bE(){if((0,yE.platform)()!=="linux")return!1;try{(0,mE.statSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_DATE);let t=(0,mE.readFileSync)(on.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR,"utf8");return/Google/.test(t)}catch{return!1}}function CE(){let t=(0,yE.networkInterfaces)();for(let e of Object.values(t))if(e){for(let{mac:n}of e)if(NN.test(n))return!0}return!1}function wE(){return bE()||CE()}function MN(){return _E()||wE()}});var kE=G(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});_l.Colours=void 0;var yl=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=yl;yl.refresh()});var AE=G(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});bl.LogSeverity=void 0;var SE;(function(t){t.DEFAULT="DEFAULT",t.DEBUG="DEBUG",t.INFO="INFO",t.WARNING="WARNING",t.ERROR="ERROR"})(SE||(bl.LogSeverity=SE={}))});var xE=G($e=>{"use strict";var BN=$e&&$e.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),UN=$e&&$e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),EE=$e&&$e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&BN(n,e,r[o]);return UN(n,e),n}})();Object.defineProperty($e,"__esModule",{value:!0});$e.env=$e.DebugLogBackendBase=$e.placeholder=$e.AdhocDebugLogger=void 0;$e.getNodeBackend=$g;$e.getDebugBackend=LN;$e.getStructuredBackend=$N;$e.setBackend=qN;$e.log=TE;var jN=re("events"),da=EE(re("process")),vE=EE(re("util")),Ft=kE(),hr=AE(),fa=class extends jN.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(hr.LogSeverity.DEBUG,...r),this.func.info=(...r)=>this.invokeSeverity(hr.LogSeverity.INFO,...r),this.func.warn=(...r)=>this.invokeSeverity(hr.LogSeverity.WARNING,...r),this.func.error=(...r)=>this.invokeSeverity(hr.LogSeverity.ERROR,...r),this.func.sublog=r=>TE(r,this.func)}invoke(e,...n){if(this.upstream)try{this.upstream(e,...n)}catch{}try{this.emit("log",e,n)}catch{}}invokeSeverity(e,...n){this.invoke({severity:e},...n)}};$e.AdhocDebugLogger=fa;$e.placeholder=new fa("",()=>{}).func;var Ps=class{cached=new Map;filters=[];filtersSet=!1;constructor(){let e=da.env[$e.env.nodeEnables]??"*";e==="all"&&(e="*"),this.filters=e.split(",")}log(e,n,...r){try{this.filtersSet||(this.setFilters(),this.filtersSet=!0);let o=this.cached.get(e);o||(o=this.makeLogger(e),this.cached.set(e,o)),o(n,...r)}catch(o){console.error(o)}}};$e.DebugLogBackendBase=Ps;var Lg=class extends Ps{enabledRegexp=/.*/g;isEnabled(e){return this.enabledRegexp.test(e)}makeLogger(e){return this.enabledRegexp.test(e)?(n,...r)=>{let o=`${Ft.Colours.green}${e}${Ft.Colours.reset}`,s=`${Ft.Colours.yellow}${da.pid}${Ft.Colours.reset}`,i;switch(n.severity){case hr.LogSeverity.ERROR:i=`${Ft.Colours.red}${n.severity}${Ft.Colours.reset}`;break;case hr.LogSeverity.INFO:i=`${Ft.Colours.magenta}${n.severity}${Ft.Colours.reset}`;break;case hr.LogSeverity.WARNING:i=`${Ft.Colours.yellow}${n.severity}${Ft.Colours.reset}`;break;default:i=n.severity??hr.LogSeverity.DEFAULT;break}let a=vE.formatWithOptions({colors:Ft.Colours.enabled},...r),u=Object.assign({},n);delete u.severity;let d=Object.getOwnPropertyNames(u).length?JSON.stringify(u):"",f=d?`${Ft.Colours.grey}${d}${Ft.Colours.reset}`:"";console.error("%s [%s|%s] %s%s",s,o,i,a,d?` ${f}`:"")}:()=>{}}setFilters(){let n=this.filters.join(",").replace(/[|\\{}()[\]^$+?.]/g,"\\$&").replace(/\*/g,".*").replace(/,/g,"$|^");this.enabledRegexp=new RegExp(`^${n}$`,"i")}};function $g(){return new Lg}var qg=class extends Ps{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=da.env.NODE_DEBUG??"";da.env.NODE_DEBUG=`${e}${e?",":""}${this.filters.join(",")}`}};function LN(t){return new qg(t)}var Hg=class extends Ps{upstream;constructor(e){super(),this.upstream=e??void 0}makeLogger(e){let n=this.upstream?.makeLogger(e);return(r,...o)=>{let s=r.severity??hr.LogSeverity.INFO,i=Object.assign({severity:s,message:vE.format(...o)},r),a=JSON.stringify(i);n?n(r,a):console.log("%s",a)}}setFilters(){this.upstream?.setFilters()}};function $N(t){return new Hg(t)}$e.env={nodeEnables:"GOOGLE_SDK_NODE_LOGGING"};var zg=new Map,sn;function qN(t){sn=t,zg.clear()}function TE(t,e){if(!sn&&!da.env[$e.env.nodeEnables]||!t)return $e.placeholder;e&&(t=`${e.instance.namespace}:${t}`);let n=zg.get(t);if(n)return n.func;if(sn===null)return $e.placeholder;sn===void 0&&(sn=$g());let r=(()=>{let o;return new fa(t,(i,...a)=>{if(o!==sn){if(sn===null)return;sn===void 0&&(sn=$g()),o=sn}sn?.log(t,i,...a)})})();return zg.set(t,r),r.func}});var Wg=G(Po=>{"use strict";var HN=Po&&Po.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),zN=Po&&Po.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&HN(e,t,n)};Object.defineProperty(Po,"__esModule",{value:!0});zN(xE(),Po)});var ha=G(pe=>{"use strict";var DE=pe&&pe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),WN=pe&&pe.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),GN=pe&&pe.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&DE(n,e,r[o]);return WN(n,e),n}})(),JN=pe&&pe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&DE(e,t,n)};Object.defineProperty(pe,"__esModule",{value:!0});pe.gcpResidencyCache=pe.METADATA_SERVER_DETECTION=pe.HEADERS=pe.HEADER_VALUE=pe.HEADER_NAME=pe.SECONDARY_HOST_ADDRESS=pe.HOST_ADDRESS=pe.BASE_PATH=void 0;pe.instance=ZN;pe.project=eM;pe.universe=tM;pe.bulk=nM;pe.isAvailable=oM;pe.resetIsAvailableCache=sM;pe.getGCPResidency=Kg;pe.setGCPResidency=OE;pe.requestTimeout=PE;var Gg=lt(),KN=gE(),VN=jg(),YN=GN(Wg());pe.BASE_PATH="/computeMetadata/v1";pe.HOST_ADDRESS="http://169.254.169.254";pe.SECONDARY_HOST_ADDRESS="http://metadata.google.internal.";pe.HEADER_NAME="Metadata-Flavor";pe.HEADER_VALUE="Google";pe.HEADERS=Object.freeze({[pe.HEADER_NAME]:pe.HEADER_VALUE});var RE=YN.log("gcp-metadata");pe.METADATA_SERVER_DETECTION=Object.freeze({"assume-present":"don't try to ping the metadata server, but assume it's present",none:"don't try to ping the metadata server, but don't try to use it either","bios-only":"treat the result of a BIOS probe as canonical (don't fall back to pinging)","ping-only":"skip the BIOS probe, and go straight to pinging"});function Jg(t){return t||(t=process.env.GCE_METADATA_IP||process.env.GCE_METADATA_HOST||pe.HOST_ADDRESS),/^https?:\/\//.test(t)||(t=`http://${t}`),new URL(pe.BASE_PATH,t).href}function XN(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 pa(t,e={},n=3,r=!1){let o=new Headers(pe.HEADERS),s="",i={};if(typeof t=="object"){let p=t;new Headers(p.headers).forEach((h,g)=>o.set(g,h)),s=p.metadataKey,i=p.params||i,n=p.noResponseRetries||n,r=p.fastFail||r}else s=t;typeof e=="string"?s+=`/${e}`:(XN(e),e.property&&(s+=`/${e.property}`),new Headers(e.headers).forEach((p,h)=>o.set(h,p)),i=e.params||i);let a=r?QN:Gg.request,u={url:`${Jg()}/${s}`,headers:o,retryConfig:{noResponseRetries:n},params:i,responseType:"text",timeout:PE()};RE.info("instance request %j",u);let d=await a(u);RE.info("instance metadata is %s",d.data);let f=d.headers.get(pe.HEADER_NAME);if(f!==pe.HEADER_VALUE)throw new RangeError(`Invalid response from metadata service: incorrect ${pe.HEADER_NAME} header. Expected '${pe.HEADER_VALUE}', got ${f?`'${f}'`:"no header"}`);if(typeof d.data=="string")try{return KN.parse(d.data)}catch{}return d.data}async function QN(t){let e={...t,url:t.url?.toString().replace(Jg(),Jg(pe.SECONDARY_HOST_ADDRESS))},n=(0,Gg.request)(t),r=(0,Gg.request)(e);return Promise.any([n,r])}function ZN(t){return pa("instance",t)}function eM(t){return pa("project",t)}function tM(t){return pa("universe",t)}async function nM(t){let e={};return await Promise.all(t.map(n=>(async()=>{let r=await pa(n),o=n.metadataKey;e[o]=r})())),e}function rM(){return process.env.DETECT_GCP_RETRIES?Number(process.env.DETECT_GCP_RETRIES):0}var Cl;async function oM(){if(process.env.METADATA_SERVER_DETECTION){let t=process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase();if(!(t in pe.METADATA_SERVER_DETECTION))throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${t}\`, but it should be \`${Object.keys(pe.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`);switch(t){case"assume-present":return!0;case"none":return!1;case"bios-only":return Kg();case"ping-only":}}try{return Cl===void 0&&(Cl=(async()=>{try{return await pa("instance",void 0,rM(),!(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 Cl}catch{return!1}}function sM(){Cl=void 0}pe.gcpResidencyCache=null;function Kg(){return pe.gcpResidencyCache===null&&OE(),pe.gcpResidencyCache}function OE(t=null){pe.gcpResidencyCache=t!==null?t:(0,VN.detectGCPResidency)()}function PE(){return Kg()?0:3e3}JN(jg(),pe)});var NE=G(wl=>{"use strict";wl.byteLength=aM;wl.toByteArray=uM;wl.fromByteArray=fM;var Bn=[],Gt=[],iM=typeof Uint8Array<"u"?Uint8Array:Array,Vg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Io=0,IE=Vg.length;Io<IE;++Io)Bn[Io]=Vg[Io],Gt[Vg.charCodeAt(Io)]=Io;var Io,IE;Gt[45]=62;Gt[95]=63;function FE(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=FE(t),n=e[0],r=e[1];return(n+r)*3/4-r}function cM(t,e,n){return(e+n)*3/4-n}function uM(t){var e,n=FE(t),r=n[0],o=n[1],s=new iM(cM(t,r,o)),i=0,a=o>0?r-4:r,u;for(u=0;u<a;u+=4)e=Gt[t.charCodeAt(u)]<<18|Gt[t.charCodeAt(u+1)]<<12|Gt[t.charCodeAt(u+2)]<<6|Gt[t.charCodeAt(u+3)],s[i++]=e>>16&255,s[i++]=e>>8&255,s[i++]=e&255;return o===2&&(e=Gt[t.charCodeAt(u)]<<2|Gt[t.charCodeAt(u+1)]>>4,s[i++]=e&255),o===1&&(e=Gt[t.charCodeAt(u)]<<10|Gt[t.charCodeAt(u+1)]<<4|Gt[t.charCodeAt(u+2)]>>2,s[i++]=e>>8&255,s[i++]=e&255),s}function lM(t){return Bn[t>>18&63]+Bn[t>>12&63]+Bn[t>>6&63]+Bn[t&63]}function dM(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(lM(r));return o.join("")}function fM(t){for(var e,n=t.length,r=n%3,o=[],s=16383,i=0,a=n-r;i<a;i+=s)o.push(dM(t,i,i+s>a?a:i+s));return r===1?(e=t[n-1],o.push(Bn[e>>2]+Bn[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Bn[e>>10]+Bn[e>>4&63]+Bn[e<<2&63]+"=")),o.join("")}});var Xg=G(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});Yg.fromArrayBufferToHex=pM;function pM(t){return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}});var ME=G(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});kl.BrowserCrypto=void 0;var Is=NE(),hM=Xg(),Qg=class t{constructor(){if(typeof window>"u"||window.crypto===void 0||window.crypto.subtle===void 0)throw new Error("SubtleCrypto not found. Make sure it's an https:// website.")}async sha256DigestBase64(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return Is.fromByteArray(new Uint8Array(r))}randomBytesBase64(e){let n=new Uint8Array(e);return window.crypto.getRandomValues(n),Is.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=Is.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 Is.fromByteArray(new Uint8Array(i))}decodeBase64StringUtf8(e){let n=Is.toByteArray(t.padBase64(e));return new TextDecoder().decode(n)}encodeBase64StringUtf8(e){let n=new TextEncoder().encode(e);return Is.fromByteArray(n)}async sha256DigestHex(e){let n=new TextEncoder().encode(e),r=await window.crypto.subtle.digest("SHA-256",n);return(0,hM.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))}};kl.BrowserCrypto=Qg});var BE=G(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});Sl.NodeCrypto=void 0;var Fs=re("crypto"),Zg=class{async sha256DigestBase64(e){return Fs.createHash("sha256").update(e).digest("base64")}randomBytesBase64(e){return Fs.randomBytes(e).toString("base64")}async verify(e,n,r){let o=Fs.createVerify("RSA-SHA256");return o.update(n),o.end(),o.verify(e,r,"base64")}async sign(e,n){let r=Fs.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 Fs.createHash("sha256").update(e).digest("hex")}async signWithHmacSha256(e,n){let r=typeof e=="string"?e:mM(e);return gM(Fs.createHmac("sha256",r).update(n).digest())}};Sl.NodeCrypto=Zg;function gM(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 mM(t){return Buffer.from(t)}});var ga=G(gr=>{"use strict";var yM=gr&&gr.__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]})),_M=gr&&gr.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&yM(e,t,n)};Object.defineProperty(gr,"__esModule",{value:!0});gr.createCrypto=wM;gr.hasBrowserCrypto=UE;var bM=ME(),CM=BE();_M(Xg(),gr);function wM(){return UE()?new bM.BrowserCrypto:new CM.NodeCrypto}function UE(){return typeof window<"u"&&typeof window.crypto<"u"&&typeof window.crypto.subtle<"u"}});var Ns=G((em,LE)=>{var Al=re("buffer"),Un=Al.Buffer;function jE(t,e){for(var n in t)e[n]=t[n]}Un.from&&Un.alloc&&Un.allocUnsafe&&Un.allocUnsafeSlow?LE.exports=Al:(jE(Al,em),em.Buffer=Fo);function Fo(t,e,n){return Un(t,e,n)}Fo.prototype=Object.create(Un.prototype);jE(Un,Fo);Fo.from=function(t,e,n){if(typeof t=="number")throw new TypeError("Argument must not be a number");return Un(t,e,n)};Fo.alloc=function(t,e,n){if(typeof t!="number")throw new TypeError("Argument must be a number");var r=Un(t);return e!==void 0?typeof n=="string"?r.fill(e,n):r.fill(e):r.fill(0),r};Fo.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Un(t)};Fo.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Al.SlowBuffer(t)}});var qE=G((c5,$E)=>{"use strict";function tm(t){var e=(t/8|0)+(t%8===0?0:1);return e}var kM={ES256:tm(256),ES384:tm(384),ES512:tm(521)};function SM(t){var e=kM[t];if(e)return e;throw new Error('Unknown algorithm "'+t+'"')}$E.exports=SM});var nm=G((u5,KE)=>{"use strict";var El=Ns().Buffer,zE=qE(),vl=128,WE=0,AM=32,EM=16,vM=2,GE=EM|AM|WE<<6,Tl=vM|WE<<6;function TM(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function JE(t){if(El.isBuffer(t))return t;if(typeof t=="string")return El.from(t,"base64");throw new TypeError("ECDSA signature must be a Base64 string or a Buffer")}function xM(t,e){t=JE(t);var n=zE(e),r=n+1,o=t.length,s=0;if(t[s++]!==GE)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++]!==Tl)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++]!==Tl)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=El.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 C=s;s<C+h;++s)g[s]=0;return t.copy(g,s,f+Math.max(-h,0),f+d),g=g.toString("base64"),g=TM(g),g}function HE(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 RM(t,e){t=JE(t);var n=zE(e),r=t.length;if(r!==n*2)throw new TypeError('"'+e+'" signatures must be "'+n*2+'" bytes, saw "'+r+'"');var o=HE(t,0,n),s=HE(t,n,t.length),i=n-o,a=n-s,u=2+i+1+1+a,d=u<vl,f=El.allocUnsafe((d?2:3)+u),p=0;return f[p++]=GE,d?f[p++]=u:(f[p++]=vl|1,f[p++]=u&255),f[p++]=Tl,f[p++]=i,o<0?(f[p++]=0,p+=t.copy(f,p,0,n)):p+=t.copy(f,p,o,n),f[p++]=Tl,f[p++]=a,s<0?(f[p++]=0,t.copy(f,p,n)):t.copy(f,p,n+s),f}KE.exports={derToJose:xM,joseToDer:RM}});var an=G(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.LRUCache=void 0;mr.snakeToCamel=YE;mr.originalOrCamelOptions=IM;mr.removeUndefinedValuesInObject=FM;mr.isValidFile=NM;mr.getWellKnownCertificateConfigFileLocation=MM;var DM=re("fs"),OM=re("os"),rm=re("path"),PM="certificate_config.json",VE="gcloud";function YE(t){return t.replace(/([_][^_])/g,e=>e.slice(1).toUpperCase())}function IM(t){function e(n){let r=t||{};return r[n]??r[YE(n)]}return{get:e}}var om=class{capacity;#e=new Map;maxAge;constructor(e){this.capacity=e.capacity,this.maxAge=e.maxAge}#t(e,n){this.#e.delete(e),this.#e.set(e,{value:n,lastAccessed:Date.now()})}set(e,n){this.#t(e,n),this.#n()}get(e){let n=this.#e.get(e);if(n)return this.#t(e,n.value),this.#n(),n.value}#n(){let e=this.maxAge?Date.now()-this.maxAge:0,n=this.#e.entries().next();for(;!n.done&&(this.#e.size>this.capacity||n.value[1].lastAccessed<e);)this.#e.delete(n.value[0]),n=this.#e.entries().next()}};mr.LRUCache=om;function FM(t){return Object.entries(t).forEach(([e,n])=>{(n===void 0||n==="undefined")&&delete t[e]}),t}async function NM(t){try{return(await DM.promises.lstat(t)).isFile()}catch{return!1}}function MM(){let t=process.env.CLOUDSDK_CONFIG||(BM()?rm.join(process.env.APPDATA||"",VE):rm.join(process.env.HOME||"",".config",VE));return rm.join(t,PM)}function BM(){return OM.platform().startsWith("win")}});var XE=G((d5,UM)=>{UM.exports={name:"google-auth-library",version:"11.0.2",author:"Google Inc.",description:"Google APIs Authentication Client Library for Node.js",engines:{node:">=22"},main:"./build/src/index.js",types:"./build/src/index.d.ts",repository:{type:"git",directory:"core/packages/google-auth-library-nodejs",url:"https://github.com/googleapis/google-cloud-node.git"},keywords:["google","api","google apis","client","client library"],dependencies:{"base64-js":"^1.3.0","ecdsa-sig-formatter":"^1.0.11",gaxios:"^7.1.4","gcp-metadata":"^9.0.0","google-logging-utils":"^2.0.0",jws:"^4.0.0"},devDependencies:{"@types/base64-js":"^1.2.5","@types/jws":"^3.1.0","@types/mocha":"^10.0.10","@types/mv":"^2.1.0","@types/ncp":"^2.0.8","@types/node":"^24.0.0","@types/sinon":"^21.0.0","assert-rejects":"^1.0.0",c8:"^10.1.3",codecov:"^3.8.3",gts:"^6.0.2","is-docker":"^3.0.0",jsdoc:"^4.0.4","jsdoc-fresh":"^6.0.0","jsdoc-region-tag":"^5.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.0",keypair:"^1.0.4",mocha:"^11.1.0",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.5","null-loader":"^4.0.1",puppeteer:"^24.0.0",sinon:"21.0.3","ts-loader":"^9.5.2",typescript:"5.8.3",webpack:"^5.97.1","webpack-cli":"^6.0.1"},files:["build/src","!build/src/**/*.map"],scripts:{test:"c8 mocha build/test",clean:"gts clean",prepare:"npm run compile",lint:"gts check --no-inline-config",compile:"tsc -p .",fix:"gts fix",pretest:"npm run compile -- --sourceMap",docs:"jsdoc -c .jsdoc.js","samples-setup":"cd samples/ && npm link ../ && npm run setup && cd ../","samples-test":"cd samples/ && npm link ../ && npm test && cd ../","system-test":"mocha build/system-test --timeout 60000","presystem-test":"npm run compile -- --sourceMap",webpack:"webpack","browser-test":"karma start",prelint:"cd samples; npm link ../; npm install"},license:"Apache-2.0",homepage:"https://github.com/googleapis/google-cloud-node/tree/main/core/packages/google-auth-library-nodejs"}});var sm=G(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.USER_AGENT=Gr.PRODUCT_NAME=Gr.pkg=void 0;var QE=XE();Gr.pkg=QE;var ZE="google-api-nodejs-client";Gr.PRODUCT_NAME=ZE;var jM=`${ZE}/${QE.version}`;Gr.USER_AGENT=jM});var Nt=G(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.AuthClient=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=cn.DEFAULT_UNIVERSE=void 0;var LM=re("events"),im=lt(),$M=an(),qM=Wg(),am=sm();cn.DEFAULT_UNIVERSE="googleapis.com";cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS=300*1e3;var cm=class t extends LM.EventEmitter{apiKey;projectId;quotaProjectId;transporter;credentials={};eagerRefreshThresholdMillis=cn.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS;forceRefreshOnFailure=!1;universeDomain=cn.DEFAULT_UNIVERSE;static RequestMethodNameSymbol=Symbol("request method name");static RequestLogIdSymbol=Symbol("request log id");constructor(e={}){super();let n=(0,$M.originalOrCamelOptions)(e);this.apiKey=e.apiKey,this.projectId=n.get("project_id")??null,this.quotaProjectId=n.get("quota_project_id"),this.credentials=n.get("credentials")??{},this.universeDomain=n.get("universe_domain")??cn.DEFAULT_UNIVERSE,this.transporter=e.transporter??new im.Gaxios(e.transporterOptions),n.get("useAuthRequestParameters")!==!1&&(this.transporter.interceptors.request.add(t.DEFAULT_REQUEST_INTERCEPTOR),this.transporter.interceptors.response.add(t.DEFAULT_RESPONSE_INTERCEPTOR)),e.eagerRefreshThresholdMillis&&(this.eagerRefreshThresholdMillis=e.eagerRefreshThresholdMillis),this.forceRefreshOnFailure=e.forceRefreshOnFailure??!1}fetch(...e){let n=e[0],r=e[1],o,s=new Headers;return typeof n=="string"?o=new URL(n):n instanceof URL?o=n:n&&n.url&&(o=new URL(n.url)),n&&typeof n=="object"&&"headers"in n&&im.Gaxios.mergeHeaders(s,n.headers),r&&im.Gaxios.mergeHeaders(s,new Headers(r.headers)),typeof n=="object"&&!(n instanceof URL)?this.request({...r,...n,headers:s,url:o}):this.request({...r,headers:s,url:o})}setCredentials(e){this.credentials=e}addSharedMetadataHeaders(e){return!e.has("x-goog-user-project")&&this.quotaProjectId&&e.set("x-goog-user-project",this.quotaProjectId),e}addUserProjectAndAuthHeaders(e,n){let r=n.get("x-goog-user-project"),o=n.get("authorization");return r&&e.set("x-goog-user-project",r),o&&e.set("authorization",o),e}static log=(0,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(`${am.PRODUCT_NAME}/`)||e.headers.set("User-Agent",`${n} ${am.USER_AGENT}`):e.headers.set("User-Agent",am.USER_AGENT);try{let r=e,o=r[t.RequestMethodNameSymbol],s=`${Math.floor(Math.random()*1e3)}`;r[t.RequestLogIdSymbol]=s;let i={url:e.url,headers:e.headers};o?t.log.info("%s [%s] request %j",o,s,i):t.log.info("[%s] request %j",s,i)}catch{}return e}};static DEFAULT_RESPONSE_INTERCEPTOR={resolved:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] response %j",r,o,e.data):t.log.info("[%s] response %j",o,e.data)}catch{}return e},rejected:async e=>{try{let n=e.config,r=n[t.RequestMethodNameSymbol],o=n[t.RequestLogIdSymbol];r?t.log.info("%s [%s] error %j",r,o,e.response?.data):t.log.error("[%s] error %j",o,e.response?.data)}catch{}throw e}};static setMethodName(e,n){try{let r=e;r[t.RequestMethodNameSymbol]=n}catch{}}static get RETRY_CONFIG(){return{retry:!0,retryConfig:{httpMethodsToRetry:["GET","PUT","POST","HEAD","OPTIONS","DELETE"]}}}};cn.AuthClient=cm});var lm=G(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 Jr=G(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.OAuth2Client=jn.ClientAuthentication=jn.CertificateFormat=jn.CodeChallengeMethod=void 0;var ev=lt(),HM=re("querystring"),zM=re("stream"),WM=nm(),tv=an(),dm=ga(),Ms=Nt(),GM=lm(),nv;(function(t){t.Plain="plain",t.S256="S256"})(nv||(jn.CodeChallengeMethod=nv={}));var yr;(function(t){t.PEM="PEM",t.JWK="JWK"})(yr||(jn.CertificateFormat=yr={}));var ma;(function(t){t.ClientSecretPost="ClientSecretPost",t.ClientSecretBasic="ClientSecretBasic",t.None="None"})(ma||(jn.ClientAuthentication=ma={}));var fm=class t extends Ms.AuthClient{redirectUri;certificateCache={};certificateExpiry=null;certificateCacheFormat=yr.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||ma.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()+"?"+HM.stringify(e)}generateCodeVerifier(){throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.")}async generateCodeVerifierAsync(){let e=(0,dm.createCrypto)(),r=e.randomBytesBase64(96).replace(/\+/g,"~").replace(/=/g,"_").replace(/\//g,"-"),s=(await e.sha256DigestBase64(r)).split("=")[0].replace(/\+/g,"-").replace(/\//g,"_");return{codeVerifier:r,codeChallenge:s}}getToken(e,n){let r=typeof e=="string"?{code:e}:e;if(n)this.getTokenAsync(r).then(o=>n(null,o.tokens,o.res),o=>n(o,null,o.response));else return this.getTokenAsync(r)}async getTokenAsync(e){let n=this.endpoints.oauth2TokenUrl.toString(),r=new Headers,o={client_id:e.client_id||this._clientId,code_verifier:e.codeVerifier,code:e.code,grant_type:"authorization_code",redirect_uri:e.redirect_uri||this.redirectUri};if(this.clientAuthentication===ma.ClientSecretBasic){let u=Buffer.from(`${this._clientId}:${this._clientSecret}`);r.set("authorization",`Basic ${u.toString("base64")}`)}this.clientAuthentication===ma.ClientSecretPost&&(o.client_secret=this._clientSecret);let s={...t.RETRY_CONFIG,method:"POST",url:n,data:new URLSearchParams((0,tv.removeUndefinedValuesInObject)(o)),headers:r};Ms.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,tv.removeUndefinedValuesInObject)(r))};Ms.AuthClient.setMethodName(i,"refreshTokenNoCache"),o=await this.transporter.request(i)}catch(i){throw i instanceof ev.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(Ms.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=ev.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 zM.Readable,d=s===401||s===403;if(!n&&d&&!u&&i)return await this.refreshAccessTokenAsync(),this.requestAsync(e,!0);if(!n&&d&&!u&&a){let f=await this.processAndValidateRefreshHandler();return f?.access_token&&this.setCredentials(f),this.requestAsync(e,!0)}}throw r}}verifyIdToken(e,n){if(n&&typeof n!="function")throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.");if(n)this.verifyIdTokenAsync(e).then(r=>n(null,r),n);else return this.verifyIdTokenAsync(e)}async verifyIdTokenAsync(e){if(!e.idToken)throw new Error("The verifyIdToken method requires an ID Token");let n=await this.getFederatedSignonCertsAsync();return await this.verifySignedJwtWithCertsAsync(e.idToken,n.certs,e.audience,this.issuers,e.maxExpiry)}async getTokenInfo(e){let{data:n}=await this.transporter.request({...t.RETRY_CONFIG,method:"POST",headers:{"content-type":"application/x-www-form-urlencoded;charset=UTF-8",authorization:`Bearer ${e}`},url:this.endpoints.tokenInfoUrl.toString()}),r=Object.assign({expiry_date:new Date().getTime()+n.expires_in*1e3,scopes:n.scope.split(" ")},n);return delete r.expires_in,delete r.scope,r}getFederatedSignonCerts(e){if(e)this.getFederatedSignonCertsAsync().then(n=>e(null,n.certs,n.res),e);else return this.getFederatedSignonCertsAsync()}async getFederatedSignonCertsAsync(){let e=new Date().getTime(),n=(0,dm.hasBrowserCrypto)()?yr.JWK:yr.PEM;if(this.certificateExpiry&&e<this.certificateExpiry.getTime()&&this.certificateCacheFormat===n)return{certs:this.certificateCache,format:n};let r,o;switch(n){case yr.PEM:o=this.endpoints.oauth2FederatedSignonPemCertsUrl.toString();break;case yr.JWK:o=this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString();break;default:throw new Error(`Unsupported certificate format ${n}`)}try{let d={...t.RETRY_CONFIG,url:o};Ms.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 yr.PEM:a=r.data;break;case yr.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};Ms.AuthClient.setMethodName(r,"getIapPublicKeysAsync"),e=await this.transporter.request(r)}catch(r){throw r instanceof Error&&(r.message=`Failed to retrieve verification certificates: ${r.message}`),r}return{pubkeys:e.data,res:e}}verifySignedJwtWithCerts(){throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.")}async verifySignedJwtWithCertsAsync(e,n,r,o,s){let i=(0,dm.createCrypto)();s||(s=t.DEFAULT_MAX_TOKEN_LIFETIME_SECS_);let a=e.split(".");if(a.length!==3)throw new Error("Wrong number of segments in token: "+e);let u=a[0]+"."+a[1],d=a[2],f,p;try{f=JSON.parse(i.decodeBase64StringUtf8(a[0]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token envelope: ${a[0]}': ${w.message}`),w}if(!f)throw new Error("Can't parse token envelope: "+a[0]);try{p=JSON.parse(i.decodeBase64StringUtf8(a[1]))}catch(w){throw w instanceof Error&&(w.message=`Can't parse token payload '${a[0]}`),w}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=WM.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 C=Number(p.iat);if(isNaN(C))throw new Error("iat field using invalid format");let y=Number(p.exp);if(isNaN(y))throw new Error("exp field using invalid format");let k=new Date().getTime()/1e3;if(y>=k+s)throw new Error("Expiration time too far in future: "+JSON.stringify(p));let b=C-t.CLOCK_SKEW_SECS_,A=y+t.CLOCK_SKEW_SECS_;if(k<b)throw new Error("Token used too early, "+k+" < "+b+": "+JSON.stringify(p));if(k>A)throw new Error("Token used too late, "+k+" > "+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 w=p.aud,E=!1;if(r.constructor===Array?E=r.indexOf(w)>-1:E=w===r,!E)throw new Error("Wrong recipient, payload audience != requiredAudience")}return new GM.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=fm});var hm=G(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.Compute=void 0;var JM=lt(),rv=ha(),KM=Jr(),pm=class extends KM.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 rv.instance(o)}catch(o){throw o instanceof JM.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 rv.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))}};Rl.Compute=pm});var mm=G(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.IdTokenClient=void 0;var VM=Jr(),gm=class extends VM.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}};Dl.IdTokenClient=gm});var ym=G(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.GCPEnv=void 0;Bs.clear=YM;Bs.getEnv=XM;var ov=ha(),Ln;(function(t){t.APP_ENGINE="APP_ENGINE",t.KUBERNETES_ENGINE="KUBERNETES_ENGINE",t.CLOUD_FUNCTIONS="CLOUD_FUNCTIONS",t.COMPUTE_ENGINE="COMPUTE_ENGINE",t.CLOUD_RUN="CLOUD_RUN",t.CLOUD_RUN_JOBS="CLOUD_RUN_JOBS",t.NONE="NONE"})(Ln||(Bs.GCPEnv=Ln={}));var ya;function YM(){ya=void 0}async function XM(){return ya||(ya=QM(),ya)}async function QM(){let t=Ln.NONE;return ZM()?t=Ln.APP_ENGINE:eB()?t=Ln.CLOUD_FUNCTIONS:await oB()?await rB()?t=Ln.KUBERNETES_ENGINE:tB()?t=Ln.CLOUD_RUN:nB()?t=Ln.CLOUD_RUN_JOBS:t=Ln.COMPUTE_ENGINE:t=Ln.NONE,t}function ZM(){return!!(process.env.GAE_SERVICE||process.env.GAE_MODULE_NAME)}function eB(){return!!(process.env.FUNCTION_NAME||process.env.FUNCTION_TARGET)}function tB(){return!!process.env.K_CONFIGURATION}function nB(){return!!process.env.CLOUD_RUN_JOB}async function rB(){try{return await ov.instance("attributes/cluster-name"),!0}catch{return!1}}async function oB(){return ov.isAvailable()}});var _m=G((b5,sv)=>{var Ol=Ns().Buffer,sB=re("stream"),iB=re("util");function Pl(t){if(this.buffer=null,this.writable=!0,this.readable=!0,!t)return this.buffer=Ol.alloc(0),this;if(typeof t.pipe=="function")return this.buffer=Ol.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+")")}iB.inherits(Pl,sB);Pl.prototype.write=function(e){this.buffer=Ol.concat([this.buffer,Ol.from(e)]),this.emit("data",e)};Pl.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};sv.exports=Pl});var av=G((C5,iv)=>{"use strict";var _a=re("buffer").Buffer,bm=re("buffer").SlowBuffer;iv.exports=Il;function Il(t,e){if(!_a.isBuffer(t)||!_a.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}Il.install=function(){_a.prototype.equal=bm.prototype.equal=function(e){return Il(this,e)}};var aB=_a.prototype.equal,cB=bm.prototype.equal;Il.restore=function(){_a.prototype.equal=aB,bm.prototype.equal=cB}});var Sm=G((w5,mv)=>{var js=Ns().Buffer,Jt=re("crypto"),uv=nm(),cv=re("util"),uB=`"%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".`,ba="secret must be a string or buffer",js="key must be a string or a buffer",sB="key must be a string, a buffer or an object",pm=typeof Jt.createPublicKey=="function";pm&&(js+=" or a KeyObject",ba+="or a KeyObject");function ov(t){if(!Us.isBuffer(t)&&typeof t!="string"&&(!pm||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw un(js)}function sv(t){if(!Us.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw un(sB)}function iB(t){if(!Us.isBuffer(t)){if(typeof t=="string")return t;if(!pm||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw un(ba)}}function hm(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function iv(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function un(t){var e=[].slice.call(arguments,1),n=nv.format.bind(nv,t).apply(null,e);return new TypeError(n)}function aB(t){return Us.isBuffer(t)||typeof t=="string"}function Ca(t){return aB(t)||(t=JSON.stringify(t)),t}function av(t){return function(n,r){iB(r),n=Ca(n);var o=Jt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return hm(s)}}var fm,cB="timingSafeEqual"in Jt?function(e,n){return e.byteLength!==n.byteLength?!1:Jt.timingSafeEqual(e,n)}:function(e,n){return fm||(fm=tv()),fm(e,n)};function uB(t){return function(n,r,o){var s=av(t)(n,o);return cB(Us.from(r),Us.from(s))}}function cv(t){return function(n,r){sv(r),n=Ca(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return hm(s)}}function uv(t){return function(n,r,o){ov(o),n=Ca(n),r=iv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function lB(t){return function(n,r){sv(r),n=Ca(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return hm(s)}}function dB(t){return function(n,r,o){ov(o),n=Ca(n),r=iv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function fB(t){var e=cv(t);return function(){var r=e.apply(null,arguments);return r=rv.derToJose(r,"ES"+t),r}}function pB(t){var e=uv(t);return function(r,o,s){o=rv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function hB(){return function(){return""}}function gB(){return function(e,n){return n===""}}lv.exports=function(e){var n={hs:av,rs:cv,ps:lB,es:fB,none:hB},r={hs:uB,rs:uv,ps:dB,es:pB,none:gB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw un(oB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var mm=G((l5,dv)=>{var mB=re("buffer").Buffer;dv.exports=function(e){return typeof e=="string"?e:typeof e=="number"||mB.isBuffer(e)?e.toString():JSON.stringify(e)}});var yv=G((d5,mv)=>{var yB=Ns().Buffer,fv=lm(),_B=gm(),bB=re("stream"),pv=mm(),ym=re("util");function hv(t,e){return yB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function CB(t,e,n){n=n||"utf8";var r=hv(pv(t),"binary"),o=hv(pv(e),n);return ym.format("%s.%s",r,o)}function gv(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=_B(e.alg),i=CB(e,n,o),a=s.sign(i,r);return ym.format("%s.%s",i,a)}function xl(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 fv(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new fv(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))}ym.inherits(xl,bB);xl.prototype.sign=function(){try{var e=gv({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")}};xl.sign=gv;mv.exports=xl});var Tv=G((f5,vv)=>{var bv=Ns().Buffer,_v=lm(),wB=gm(),kB=re("stream"),Cv=mm(),SB=re("util"),AB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function EB(t){return Object.prototype.toString.call(t)==="[object Object]"}function vB(t){if(EB(t))return t;try{return JSON.parse(t)}catch{return}}function wv(t){var e=t.split(".",1)[0];return vB(bv.from(e,"base64").toString("binary"))}function TB(t){return t.split(".",2).join(".")}function kv(t){return t.split(".")[2]}function xB(t,e){e=e||"utf8";var n=t.split(".")[1];return bv.from(n,"base64").toString(e)}function Sv(t){return AB.test(t)&&!!wv(t)}function Av(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=Cv(t);var o=kv(t),s=TB(t),i=wB(e);return i.verify(s,o,n)}function Ev(t,e){if(e=e||{},t=Cv(t),!Sv(t))return null;var n=wv(t);if(!n)return null;var r=xB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:kv(t)}}function Ls(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 _v(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new _v(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))}SB.inherits(Ls,kB);Ls.prototype.verify=function(){try{var e=Av(this.signature.buffer,this.algorithm,this.key.buffer),n=Ev(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")}};Ls.decode=Ev;Ls.isValid=Sv;Ls.verify=Av;vv.exports=Ls});var _m=G(Kr=>{var xv=yv(),Rl=Tv(),RB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Kr.ALGORITHMS=RB;Kr.sign=xv.sign;Kr.verify=Rl.verify;Kr.decode=Rl.decode;Kr.isValid=Rl.isValid;Kr.createSign=function(e){return new xv(e)};Kr.createVerify=function(e){return new Rl(e)}});var Dv=G(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});Dl.buildPayloadForJwsSign=Rv;Dl.getJwsSign=IB;var DB=_m(),OB="RS256",PB="https://oauth2.googleapis.com/token";function Rv(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:PB,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function IB(t){let e=Rv(t);return(0,DB.sign)({header:{alg:OB},payload:e,secret:t.key})}});var Ov=G(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.getToken=jB;var FB=Dv(),NB="https://oauth2.googleapis.com/token",MB="urn:ietf:params:oauth:grant-type:jwt-bearer",BB=t=>({method:"POST",url:NB,data:new URLSearchParams({grant_type:MB,assertion:(0,FB.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function jB(t){if(!t.transporter)throw new Error("No transporter set.");try{let e=BB(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 Pv=G(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});Ol.ErrorWithCode=void 0;var Cm=class extends Error{code;constructor(e,n){super(e),this.code=n}};Ol.ErrorWithCode=Cm});var vm=G(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});Em.getCredentials=$B;var UB=re("path"),Iv=re("fs"),LB=re("util"),Pl=Pv(),Fv=Iv.readFile?(0,LB.promisify)(Iv.readFile):async()=>{throw new Pl.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Vr;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Vr||(Vr={}));var wm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Fv(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 Pl.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},km=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Fv(this.keyFilePath,"utf8")}}},Sm=class{async getCredentials(){throw new Pl.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")}},Am=class{static create(e){switch(UB.extname(e)){case Vr.JSON:return new wm(e);case Vr.DER:case Vr.CRT:case Vr.PEM:return new km(e);case Vr.P12:case Vr.PFX:return new Sm;default:throw new Pl.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function $B(t){return Am.create(t).getCredentials()}});var Nv=G(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.TokenHandler=void 0;var qB=Ov(),HB=vm(),Tm=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,HB.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,qB.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}}};Il.TokenHandler=Tm});var Mv=G(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});xm.revokeToken=GB;var zB="https://oauth2.googleapis.com/revoke?token=",WB=!0;async function GB(t,e){let n=zB+t;return await e.request({url:n,retry:WB})}});var Dm=G(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});Fl.GoogleToken=void 0;var JB=lt(),Bv=Nv(),KB=Mv(),Rm=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,JB.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 Bv.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,KB.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Bv.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};Fl.GoogleToken=Rm});var Pm=G(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});Nl.JWTAccess=void 0;var VB=_m(),YB=an(),jv={alg:"RS256",typ:"JWT"},Om=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new YB.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 C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...jv,kid:this.keyId}:jv,p=Object.assign(d,n),h=VB.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)}})})}};Nl.JWTAccess=Om});var Fm=G(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.JWT=void 0;var Uv=Dm(),XB=vm(),QB=Pm(),ZB=Jr(),Ml=Nt(),Im=class t extends ZB.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!==Ml.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==Ml.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${Ml.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 QB.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!==Ml.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 Uv.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 Uv.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,XB.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.")}};Bl.JWT=Im});var Mm=G($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.UserRefreshClient=$s.USER_REFRESH_ACCOUNT_TYPE=void 0;var ej=Jr(),tj=Nt();$s.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Nm=class t extends ej.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 tj.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}};$s.UserRefreshClient=Nm});var jm=G(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.Impersonated=qs.IMPERSONATED_ACCOUNT_TYPE=void 0;var Lv=Jr(),nj=lt(),rj=an();qs.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Bm=class t extends Lv.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 Lv.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,rj.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 nj.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}};qs.Impersonated=Bm});var Lm=G(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.OAuthClientAuthHandler=void 0;wa.getErrorFromOAuthErrorResponse=ij;var Hs=lt(),oj=ga(),sj=["PUT","POST","PATCH"],Um=class{#e=(0,oj.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Hs.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Hs.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=Hs.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=Hs.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Hs.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);Hs.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!sj.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"]}}}};wa.OAuthClientAuthHandler=Um;function ij(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 Ul=G(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.StsCredentials=void 0;var aj=lt(),cj=Nt(),$v=Lm(),uj=an(),$m=class t extends $v.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,uj.removeUndefinedValuesInObject)(o)),responseType:"json"};cj.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 aj.GaxiosError&&i.response?(0,$v.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};jl.StsCredentials=$m});var Yr=G(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.BaseExternalAccountClient=Kt.CLOUD_RESOURCE_MANAGER=Kt.EXTERNAL_ACCOUNT_TYPE=Kt.EXPIRATION_TIME_OFFSET=void 0;var lj=lt(),dj=re("stream"),qm=Nt(),fj=Ul(),qv=an(),pj=Xg(),hj="urn:ietf:params:oauth:grant-type:token-exchange",gj="urn:ietf:params:oauth:token-type:access_token",Hm="https://www.googleapis.com/auth/cloud-platform",mj=3600;Kt.EXPIRATION_TIME_OFFSET=300*1e3;Kt.EXTERNAL_ACCOUNT_TYPE="external_account";Kt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var yj="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",_j="https://sts.{universeDomain}/v1/token",zm=class t extends qm.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,qv.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Kt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Kt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??_j.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,qv.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 fj.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Hm],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(yj);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=mj),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"};qm.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=lj.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(){this.#e=this.#e||this.#t();try{return await this.#e}finally{this.#e=null}}async#t(){let e=await this.retrieveSubjectToken(),n={grantType:hj,audience:this.audience,requestedTokenType:gj,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Hm]: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"};qm.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||[Hm]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${pj.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Kt.BaseExternalAccountClient=zm});var Hv=G(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.FileSubjectTokenSupplier=void 0;var Gm=re("util"),Jm=re("fs"),bj=(0,Gm.promisify)(Jm.readFile??(()=>{})),Cj=(0,Gm.promisify)(Jm.realpath??(()=>{})),wj=(0,Gm.promisify)(Jm.lstat??(()=>{})),Wm=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 Cj(e),!(await wj(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 bj(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}};Ll.FileSubjectTokenSupplier=Wm});var zv=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.UrlSubjectTokenSupplier=void 0;var kj=Nt(),Km=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};kj.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}};$l.UrlSubjectTokenSupplier=Km});var Wv=G(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.CertificateSubjectTokenSupplier=Mt.InvalidConfigurationError=Mt.CertificateSourceUnavailableError=Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var ql=an(),Hl=re("fs"),zl=re("crypto"),Sj=re("https");Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var $n=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Mt.CertificateSourceUnavailableError=$n;var Vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Mt.InvalidConfigurationError=Vt;var Vm=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Vt("Cannot create mTLS Agent with missing certificate or key");return new Sj.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,ql.isValidFile)(e))return e;throw new $n(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,ql.isValidFile)(n))return n;throw new $n(`Path from environment variable "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,ql.getWellKnownCertificateConfigFileLocation)();if(await(0,ql.isValidFile)(r))return r;throw new $n(`Could not find certificate configuration file. Searched override path, the "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Hl.promises.readFile(e,"utf8")}catch{throw new $n(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Vt?r:new Vt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Hl.promises.readFile(e),new zl.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read certificate file at ${e}: ${i}`)}try{o=await Hl.promises.readFile(n),(0,zl.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new zl.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Hl.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new zl.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Vt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),i=s.findIndex(u=>n.raw.equals(u.raw)),a;if(i===-1)a=[n,...s];else if(i===0)a=s;else throw new Vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(a.map(u=>u.raw.toString("base64")))}catch(r){if(r instanceof Vt)throw r;let o=r instanceof Error?r.message:String(r);throw new $n(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Mt.CertificateSubjectTokenSupplier=Vm});var Qm=G(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});Wl.IdentityPoolClient=void 0;var Aj=Yr(),Ym=an(),Ej=Hv(),vj=zv(),Gv=Wv(),Tj=Ul(),Jv=lt(),Xm=class t extends Aj.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,Ym.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,Ym.originalOrCamelOptions)(r),i=(0,Ym.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 Ej.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new vj.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new Gv.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 Gv.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new Tj.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Jv.Gaxios({agent:n})}),this.transporter=new Jv.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Wl.IdentityPoolClient=Xm});var ey=G(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});Jl.AwsRequestSigner=void 0;var Gl=lt(),Vv=ga(),Kv="AWS4-HMAC-SHA256",xj="aws4_request",Zm=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,Vv.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 Dj({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=Gl.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&Gl.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}};Jl.AwsRequestSigner=Zm;async function ka(t,e,n){return await t.signWithHmacSha256(e,n)}async function Rj(t,e,n,r,o){let s=await ka(t,`AWS4${e}`,n),i=await ka(t,s,r),a=await ka(t,i,o);return await ka(t,a,"aws4_request")}async function Dj(t){let e=Gl.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=Gl.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".`,ba="secret must be a string or buffer",Us="key must be a string or a buffer",lB="key must be a string, a buffer or an object",wm=typeof Jt.createPublicKey=="function";wm&&(Us+=" or a KeyObject",ba+="or a KeyObject");function lv(t){if(!js.isBuffer(t)&&typeof t!="string"&&(!wm||typeof t!="object"||typeof t.type!="string"||typeof t.asymmetricKeyType!="string"||typeof t.export!="function"))throw un(Us)}function dv(t){if(!js.isBuffer(t)&&typeof t!="string"&&typeof t!="object")throw un(lB)}function dB(t){if(!js.isBuffer(t)){if(typeof t=="string")return t;if(!wm||typeof t!="object"||t.type!=="secret"||typeof t.export!="function")throw un(ba)}}function km(t){return t.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function fv(t){t=t.toString();var e=4-t.length%4;if(e!==4)for(var n=0;n<e;++n)t+="=";return t.replace(/\-/g,"+").replace(/_/g,"/")}function un(t){var e=[].slice.call(arguments,1),n=cv.format.bind(cv,t).apply(null,e);return new TypeError(n)}function fB(t){return js.isBuffer(t)||typeof t=="string"}function Ca(t){return fB(t)||(t=JSON.stringify(t)),t}function pv(t){return function(n,r){dB(r),n=Ca(n);var o=Jt.createHmac("sha"+t,r),s=(o.update(n),o.digest("base64"));return km(s)}}var Cm,pB="timingSafeEqual"in Jt?function(e,n){return e.byteLength!==n.byteLength?!1:Jt.timingSafeEqual(e,n)}:function(e,n){return Cm||(Cm=av()),Cm(e,n)};function hB(t){return function(n,r,o){var s=pv(t)(n,o);return pB(js.from(r),js.from(s))}}function hv(t){return function(n,r){dv(r),n=Ca(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign(r,"base64"));return km(s)}}function gv(t){return function(n,r,o){lv(o),n=Ca(n),r=fv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify(o,r,"base64")}}function gB(t){return function(n,r){dv(r),n=Ca(n);var o=Jt.createSign("RSA-SHA"+t),s=(o.update(n),o.sign({key:r,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},"base64"));return km(s)}}function mB(t){return function(n,r,o){lv(o),n=Ca(n),r=fv(r);var s=Jt.createVerify("RSA-SHA"+t);return s.update(n),s.verify({key:o,padding:Jt.constants.RSA_PKCS1_PSS_PADDING,saltLength:Jt.constants.RSA_PSS_SALTLEN_DIGEST},r,"base64")}}function yB(t){var e=hv(t);return function(){var r=e.apply(null,arguments);return r=uv.derToJose(r,"ES"+t),r}}function _B(t){var e=gv(t);return function(r,o,s){o=uv.joseToDer(o,"ES"+t).toString("base64");var i=e(r,o,s);return i}}function bB(){return function(){return""}}function CB(){return function(e,n){return n===""}}mv.exports=function(e){var n={hs:pv,rs:hv,ps:gB,es:yB,none:bB},r={hs:hB,rs:gv,ps:mB,es:_B,none:CB},o=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/);if(!o)throw un(uB,e);var s=(o[1]||o[3]).toLowerCase(),i=o[2];return{sign:n[s](i),verify:r[s](i)}}});var Am=G((k5,yv)=>{var wB=re("buffer").Buffer;yv.exports=function(e){return typeof e=="string"?e:typeof e=="number"||wB.isBuffer(e)?e.toString():JSON.stringify(e)}});var Sv=G((S5,kv)=>{var kB=Ns().Buffer,_v=_m(),SB=Sm(),AB=re("stream"),bv=Am(),Em=re("util");function Cv(t,e){return kB.from(t,e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function EB(t,e,n){n=n||"utf8";var r=Cv(bv(t),"binary"),o=Cv(bv(e),n);return Em.format("%s.%s",r,o)}function wv(t){var e=t.header,n=t.payload,r=t.secret||t.privateKey,o=t.encoding,s=SB(e.alg),i=EB(e,n,o),a=s.sign(i,r);return Em.format("%s.%s",i,a)}function Fl(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 _v(e);this.readable=!0,this.header=t.header,this.encoding=t.encoding,this.secret=this.privateKey=this.key=n,this.payload=new _v(t.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}Em.inherits(Fl,AB);Fl.prototype.sign=function(){try{var e=wv({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")}};Fl.sign=wv;kv.exports=Fl});var Iv=G((A5,Pv)=>{var Ev=Ns().Buffer,Av=_m(),vB=Sm(),TB=re("stream"),vv=Am(),xB=re("util"),RB=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;function DB(t){return Object.prototype.toString.call(t)==="[object Object]"}function OB(t){if(DB(t))return t;try{return JSON.parse(t)}catch{return}}function Tv(t){var e=t.split(".",1)[0];return OB(Ev.from(e,"base64").toString("binary"))}function PB(t){return t.split(".",2).join(".")}function xv(t){return t.split(".")[2]}function IB(t,e){e=e||"utf8";var n=t.split(".")[1];return Ev.from(n,"base64").toString(e)}function Rv(t){return RB.test(t)&&!!Tv(t)}function Dv(t,e,n){if(!e){var r=new Error("Missing algorithm parameter for jws.verify");throw r.code="MISSING_ALGORITHM",r}t=vv(t);var o=xv(t),s=PB(t),i=vB(e);return i.verify(s,o,n)}function Ov(t,e){if(e=e||{},t=vv(t),!Rv(t))return null;var n=Tv(t);if(!n)return null;var r=IB(t);return(n.typ==="JWT"||e.json)&&(r=JSON.parse(r,e.encoding)),{header:n,payload:r,signature:xv(t)}}function Ls(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 Av(e);this.readable=!0,this.algorithm=t.algorithm,this.encoding=t.encoding,this.secret=this.publicKey=this.key=n,this.signature=new Av(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))}xB.inherits(Ls,TB);Ls.prototype.verify=function(){try{var e=Dv(this.signature.buffer,this.algorithm,this.key.buffer),n=Ov(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")}};Ls.decode=Ov;Ls.isValid=Rv;Ls.verify=Dv;Pv.exports=Ls});var vm=G(Kr=>{var Fv=Sv(),Nl=Iv(),FB=["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"];Kr.ALGORITHMS=FB;Kr.sign=Fv.sign;Kr.verify=Nl.verify;Kr.decode=Nl.decode;Kr.isValid=Nl.isValid;Kr.createSign=function(e){return new Fv(e)};Kr.createVerify=function(e){return new Nl(e)}});var Mv=G(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});Ml.buildPayloadForJwsSign=Nv;Ml.getJwsSign=UB;var NB=vm(),MB="RS256",BB="https://oauth2.googleapis.com/token";function Nv(t){let e=Math.floor(new Date().getTime()/1e3);return{iss:t.iss,scope:t.scope,aud:BB,exp:e+3600,iat:e,sub:t.sub,...t.additionalClaims}}function UB(t){let e=Nv(t);return(0,NB.sign)({header:{alg:MB},payload:e,secret:t.key})}});var Bv=G(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.getToken=HB;var jB=Mv(),LB="https://oauth2.googleapis.com/token",$B="urn:ietf:params:oauth:grant-type:jwt-bearer",qB=t=>({method:"POST",url:LB,data:new URLSearchParams({grant_type:$B,assertion:(0,jB.getJwsSign)(t)}),responseType:"json",retryConfig:{httpMethodsToRetry:["POST"]}});async function HB(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 Uv=G(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});Bl.ErrorWithCode=void 0;var xm=class extends Error{code;constructor(e,n){super(e),this.code=n}};Bl.ErrorWithCode=xm});var Fm=G(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});Im.getCredentials=GB;var zB=re("path"),jv=re("fs"),WB=re("util"),Ul=Uv(),Lv=jv.readFile?(0,WB.promisify)(jv.readFile):async()=>{throw new Ul.ErrorWithCode("use key rather than keyFile.","MISSING_CREDENTIALS")},Vr;(function(t){t.JSON=".json",t.DER=".der",t.CRT=".crt",t.PEM=".pem",t.P12=".p12",t.PFX=".pfx"})(Vr||(Vr={}));var Rm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){let e=await Lv(this.keyFilePath,"utf8"),n;try{n=JSON.parse(e)}catch(s){let i=s;throw new Error(`Invalid JSON key file: ${i.message}`)}let r=n.private_key,o=n.client_email;if(!r||!o)throw new Ul.ErrorWithCode("private_key and client_email are required.","MISSING_CREDENTIALS");return{privateKey:r,clientEmail:o}}},Dm=class{keyFilePath;constructor(e){this.keyFilePath=e}async getCredentials(){return{privateKey:await Lv(this.keyFilePath,"utf8")}}},Om=class{async getCredentials(){throw new Ul.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.","UNKNOWN_CERTIFICATE_TYPE")}},Pm=class{static create(e){switch(zB.extname(e)){case Vr.JSON:return new Rm(e);case Vr.DER:case Vr.CRT:case Vr.PEM:return new Dm(e);case Vr.P12:case Vr.PFX:return new Om;default:throw new Ul.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. Current supported extensions are *.json, and *.pem.","UNKNOWN_CERTIFICATE_TYPE")}}};async function GB(t){return Pm.create(t).getCredentials()}});var $v=G(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});jl.TokenHandler=void 0;var JB=Bv(),KB=Fm(),Nm=class{token;tokenExpiresAt;inFlightRequest;tokenOptions;constructor(e){this.tokenOptions=e}async processCredentials(){if(!this.tokenOptions.key&&!this.tokenOptions.keyFile)throw new Error("No key or keyFile set.");if(!this.tokenOptions.key&&this.tokenOptions.keyFile){let e=await(0,KB.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,JB.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}}};jl.TokenHandler=Nm});var qv=G(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});Mm.revokeToken=XB;var VB="https://oauth2.googleapis.com/revoke?token=",YB=!0;async function XB(t,e){let n=VB+t;return await e.request({url:n,retry:YB})}});var Um=G(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});Ll.GoogleToken=void 0;var QB=lt(),Hv=$v(),ZB=qv(),Bm=class{tokenOptions;tokenHandler;constructor(e){this.tokenOptions=e||{},this.tokenOptions.transporter=this.tokenOptions.transporter||{request:n=>(0,QB.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 Hv.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,ZB.revokeToken)(this.accessToken,this.tokenOptions.transporter);e&&n.then(()=>e(),e),this.tokenHandler=new Hv.TokenHandler(this.tokenOptions)}get googleTokenOptions(){return this.tokenOptions}};Ll.GoogleToken=Bm});var Lm=G($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});$l.JWTAccess=void 0;var eU=vm(),tU=an(),zv={alg:"RS256",typ:"JWT"},jm=class t{email;key;keyId;projectId;eagerRefreshThresholdMillis;cache=new tU.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 C in d)if(n[C])throw new Error(`The '${C}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`)}let f=this.keyId?{...zv,kid:this.keyId}:zv,p=Object.assign(d,n),h=eU.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)}})})}};$l.JWTAccess=jm});var qm=G(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.JWT=void 0;var Wv=Um(),nU=Fm(),rU=Lm(),oU=Jr(),ql=Nt(),$m=class t extends oU.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!==ql.DEFAULT_UNIVERSE;if(this.subject&&this.universeDomain!==ql.DEFAULT_UNIVERSE)throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${ql.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 rU.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!==ql.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 Wv.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 Wv.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,nU.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.")}};Hl.JWT=$m});var zm=G($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});$s.UserRefreshClient=$s.USER_REFRESH_ACCOUNT_TYPE=void 0;var sU=Jr(),iU=Nt();$s.USER_REFRESH_ACCOUNT_TYPE="authorized_user";var Hm=class t extends sU.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 iU.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}};$s.UserRefreshClient=Hm});var Gm=G(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.Impersonated=qs.IMPERSONATED_ACCOUNT_TYPE=void 0;var Gv=Jr(),aU=lt(),cU=an();qs.IMPERSONATED_ACCOUNT_TYPE="impersonated_service_account";var Wm=class t extends Gv.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 Gv.OAuth2Client,this.targetPrincipal=e.targetPrincipal??"",this.delegates=e.delegates??[],this.targetScopes=e.targetScopes??[],this.lifetime=e.lifetime??3600,!!!(0,cU.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}};qs.Impersonated=Wm});var Km=G(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.OAuthClientAuthHandler=void 0;wa.getErrorFromOAuthErrorResponse=dU;var Hs=lt(),uU=ga(),lU=["PUT","POST","PATCH"],Jm=class{#e=(0,uU.createCrypto)();#t;transporter;constructor(e){e&&"clientId"in e?(this.#t=e,this.transporter=new Hs.Gaxios):(this.#t=e?.clientAuthentication,this.transporter=e?.transporter||new Hs.Gaxios)}applyClientAuthenticationOptions(e,n){e.headers=Hs.Gaxios.mergeHeaders(e.headers),this.injectAuthenticatedHeaders(e,n),n||this.injectAuthenticatedRequestBody(e)}injectAuthenticatedHeaders(e,n){if(n)e.headers=Hs.Gaxios.mergeHeaders(e.headers,{authorization:`Bearer ${n}`});else if(this.#t?.confidentialClientType==="basic"){e.headers=Hs.Gaxios.mergeHeaders(e.headers);let r=this.#t.clientId,o=this.#t.clientSecret||"",s=this.#e.encodeBase64StringUtf8(`${r}:${o}`);Hs.Gaxios.mergeHeaders(e.headers,{authorization:`Basic ${s}`})}}injectAuthenticatedRequestBody(e){if(this.#t?.confidentialClientType==="request-body"){let n=(e.method||"GET").toUpperCase();if(!lU.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"]}}}};wa.OAuthClientAuthHandler=Jm;function dU(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 Wl=G(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});zl.StsCredentials=void 0;var fU=lt(),pU=Nt(),Jv=Km(),hU=an(),Vm=class t extends Jv.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,hU.removeUndefinedValuesInObject)(o)),responseType:"json"};pU.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 fU.GaxiosError&&i.response?(0,Jv.getErrorFromOAuthErrorResponse)(i.response.data,i):i}}};zl.StsCredentials=Vm});var Yr=G(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.BaseExternalAccountClient=Kt.CLOUD_RESOURCE_MANAGER=Kt.EXTERNAL_ACCOUNT_TYPE=Kt.EXPIRATION_TIME_OFFSET=void 0;var gU=lt(),mU=re("stream"),Ym=Nt(),yU=Wl(),Kv=an(),_U=sm(),bU="urn:ietf:params:oauth:grant-type:token-exchange",CU="urn:ietf:params:oauth:token-type:access_token",Xm="https://www.googleapis.com/auth/cloud-platform",wU=3600;Kt.EXPIRATION_TIME_OFFSET=300*1e3;Kt.EXTERNAL_ACCOUNT_TYPE="external_account";Kt.CLOUD_RESOURCE_MANAGER="https://cloudresourcemanager.googleapis.com/v1/projects/";var kU="//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+",SU="https://sts.{universeDomain}/v1/token",Qm=class t extends Ym.AuthClient{scopes;projectNumber;audience;subjectTokenType;stsCredential;clientAuth;credentialSourceType;cachedAccessToken;serviceAccountImpersonationUrl;serviceAccountImpersonationLifetime;workforcePoolUserProject;configLifetimeRequested;tokenUrl;cloudResourceManagerURL;supplierContext;#e=null;constructor(e){super(e);let n=(0,Kv.originalOrCamelOptions)(e),r=n.get("type");if(r&&r!==Kt.EXTERNAL_ACCOUNT_TYPE)throw new Error(`Expected "${Kt.EXTERNAL_ACCOUNT_TYPE}" type but received "${e.type}"`);let o=n.get("client_id"),s=n.get("client_secret");this.tokenUrl=n.get("token_url")??SU.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,Kv.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 yU.StsCredentials({tokenExchangeEndpoint:this.tokenUrl,clientAuthentication:this.clientAuth}),this.scopes=n.get("scopes")||[Xm],this.cachedAccessToken=null,this.audience=n.get("audience"),this.subjectTokenType=i,this.workforcePoolUserProject=a;let p=new RegExp(kU);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=wU),this.projectNumber=this.getProjectNumber(this.audience),this.supplierContext={audience:this.audience,subjectTokenType:this.subjectTokenType,transporter:this.transporter}}getServiceAccountEmail(){if(this.serviceAccountImpersonationUrl){if(this.serviceAccountImpersonationUrl.length>256)throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`);return/serviceAccounts\/(?<email>[^:]+):generateAccessToken$/.exec(this.serviceAccountImpersonationUrl)?.groups?.email||null}return null}setCredentials(e){super.setCredentials(e),this.cachedAccessToken=e}async getAccessToken(){return(!this.cachedAccessToken||this.isExpired(this.cachedAccessToken))&&await this.refreshAccessTokenAsync(),{token:this.cachedAccessToken.access_token,res:this.cachedAccessToken.res}}async getRequestHeaders(){let e=await this.getAccessToken(),n=new Headers({authorization:`Bearer ${e.token}`});return this.addSharedMetadataHeaders(n)}request(e,n){if(n)this.requestAsync(e).then(r=>n(null,r),r=>n(r,r.response));else return this.requestAsync(e)}async getProjectId(){let e=this.projectNumber||this.workforcePoolUserProject;if(this.projectId)return this.projectId;if(e){let n=await this.getRequestHeaders(),r={...t.RETRY_CONFIG,headers:n,url:`${this.cloudResourceManagerURL.toString()}${e}`,responseType:"json"};Ym.AuthClient.setMethodName(r,"getProjectId");let o=await this.transporter.request(r);return this.projectId=o.data.projectId,this.projectId}return null}async requestAsync(e,n=!1){let r;try{let o=await this.getRequestHeaders();e.headers=gU.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 mU.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:bU,audience:this.audience,requestedTokenType:CU,subjectToken:e,subjectTokenType:this.subjectTokenType,scope:this.serviceAccountImpersonationUrl?[Xm]:this.getScopesArray()},r=!this.clientAuth&&this.workforcePoolUserProject?{userProject:this.workforcePoolUserProject}:void 0,o=new Headers({"x-goog-api-client":this.getMetricsHeaderValue()}),s=await this.stsCredential.exchangeToken(n,o,r);return this.serviceAccountImpersonationUrl?this.cachedAccessToken=await this.getImpersonatedAccessToken(s.access_token):s.expires_in?this.cachedAccessToken={access_token:s.access_token,expiry_date:new Date().getTime()+s.expires_in*1e3,res:s.res}:this.cachedAccessToken={access_token:s.access_token,res:s.res},this.credentials={},Object.assign(this.credentials,this.cachedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedAccessToken.expiry_date,access_token:this.cachedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedAccessToken}getProjectNumber(e){let n=e.match(/\/projects\/([^/]+)/);return n?n[1]:null}async getImpersonatedAccessToken(e){let n={...t.RETRY_CONFIG,url:this.serviceAccountImpersonationUrl,method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},data:{scope:this.getScopesArray(),lifetime:this.serviceAccountImpersonationLifetime+"s"},responseType:"json"};Ym.AuthClient.setMethodName(n,"getImpersonatedAccessToken");let r=await this.transporter.request(n),o=r.data;return{access_token:o.accessToken,expiry_date:new Date(o.expireTime).getTime(),res:r}}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}getScopesArray(){return typeof this.scopes=="string"?[this.scopes]:this.scopes||[Xm]}getMetricsHeaderValue(){let e=process.version.replace(/^v/,""),n=this.serviceAccountImpersonationUrl!==void 0,r=this.credentialSourceType?this.credentialSourceType:"unknown";return`gl-node/${e} auth/${_U.pkg.version} google-byoid-sdk source/${r} sa-impersonation/${n} config-lifetime/${this.configLifetimeRequested}`}getTokenUrl(){return this.tokenUrl}};Kt.BaseExternalAccountClient=Qm});var Vv=G(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});Gl.FileSubjectTokenSupplier=void 0;var ey=re("util"),ty=re("fs"),AU=(0,ey.promisify)(ty.readFile??(()=>{})),EU=(0,ey.promisify)(ty.realpath??(()=>{})),vU=(0,ey.promisify)(ty.lstat??(()=>{})),Zm=class{filePath;formatType;subjectTokenFieldName;constructor(e){this.filePath=e.filePath,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName}async getSubjectToken(){let e=this.filePath;try{if(e=await EU(e),!(await vU(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 AU(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}};Gl.FileSubjectTokenSupplier=Zm});var Yv=G(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});Jl.UrlSubjectTokenSupplier=void 0;var TU=Nt(),ny=class{url;headers;formatType;subjectTokenFieldName;additionalGaxiosOptions;constructor(e){this.url=e.url,this.formatType=e.formatType,this.subjectTokenFieldName=e.subjectTokenFieldName,this.headers=e.headers,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getSubjectToken(e){let n={...this.additionalGaxiosOptions,url:this.url,method:"GET",headers:this.headers,responseType:this.formatType};TU.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}};Jl.UrlSubjectTokenSupplier=ny});var Xv=G(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.CertificateSubjectTokenSupplier=Mt.InvalidConfigurationError=Mt.CertificateSourceUnavailableError=Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE=void 0;var Kl=an(),Vl=re("fs"),Yl=re("crypto"),xU=re("https");Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE="GOOGLE_API_CERTIFICATE_CONFIG";var $n=class extends Error{constructor(e){super(e),this.name="CertificateSourceUnavailableError"}};Mt.CertificateSourceUnavailableError=$n;var Vt=class extends Error{constructor(e){super(e),this.name="InvalidConfigurationError"}};Mt.InvalidConfigurationError=Vt;var ry=class{certificateConfigPath;trustChainPath;cert;key;constructor(e){if(!e.useDefaultCertificateConfig&&!e.certificateConfigLocation)throw new Vt("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided.");if(e.useDefaultCertificateConfig&&e.certificateConfigLocation)throw new Vt("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided.");this.trustChainPath=e.trustChainPath,this.certificateConfigPath=e.certificateConfigLocation??""}async createMtlsHttpsAgent(){if(!this.key||!this.cert)throw new Vt("Cannot create mTLS Agent with missing certificate or key");return new xU.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,Kl.isValidFile)(e))return e;throw new $n(`Provided certificate config path is invalid: ${e}`)}let n=process.env[Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE];if(n){if(await(0,Kl.isValidFile)(n))return n;throw new $n(`Path from environment variable "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${n}`)}let r=(0,Kl.getWellKnownCertificateConfigFileLocation)();if(await(0,Kl.isValidFile)(r))return r;throw new $n(`Could not find certificate configuration file. Searched override path, the "${Mt.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${r}).`)}async#t(){let e=this.certificateConfigPath,n;try{n=await Vl.promises.readFile(e,"utf8")}catch{throw new $n(`Failed to read certificate config file at: ${e}`)}try{let r=JSON.parse(n),o=r?.cert_configs?.workload?.cert_path,s=r?.cert_configs?.workload?.key_path;if(!o||!s)throw new Vt(`Certificate config file (${e}) is missing required "cert_path" or "key_path" in the workload config.`);return{certPath:o,keyPath:s}}catch(r){throw r instanceof Vt?r:new Vt(`Failed to parse certificate config from ${e}: ${r.message}`)}}async#n(e,n){let r,o;try{r=await Vl.promises.readFile(e),new Yl.X509Certificate(r)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read certificate file at ${e}: ${i}`)}try{o=await Vl.promises.readFile(n),(0,Yl.createPrivateKey)(o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new $n(`Failed to read private key file at ${n}: ${i}`)}return{cert:r,key:o}}async#r(e){let n=new Yl.X509Certificate(e);if(!this.trustChainPath)return JSON.stringify([n.raw.toString("base64")]);try{let s=((await Vl.promises.readFile(this.trustChainPath,"utf8")).match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g)??[]).map((u,d)=>{try{return new Yl.X509Certificate(u)}catch(f){let p=f instanceof Error?f.message:String(f);throw new Vt(`Failed to parse certificate at index ${d} in trust chain file ${this.trustChainPath}: ${p}`)}}),i=s.findIndex(u=>n.raw.equals(u.raw)),a;if(i===-1)a=[n,...s];else if(i===0)a=s;else throw new Vt(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${i}).`);return JSON.stringify(a.map(u=>u.raw.toString("base64")))}catch(r){if(r instanceof Vt)throw r;let o=r instanceof Error?r.message:String(r);throw new $n(`Failed to process certificate chain from ${this.trustChainPath}: ${o}`)}}};Mt.CertificateSubjectTokenSupplier=ry});var iy=G(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});Xl.IdentityPoolClient=void 0;var RU=Yr(),oy=an(),DU=Vv(),OU=Yv(),Qv=Xv(),PU=Wl(),Zv=lt(),sy=class t extends RU.BaseExternalAccountClient{subjectTokenSupplier;constructor(e){super(e);let n=(0,oy.originalOrCamelOptions)(e),r=n.get("credential_source"),o=n.get("subject_token_supplier");if(!r&&!o)throw new Error("A credential source or subject token supplier must be specified.");if(r&&o)throw new Error("Only one of credential source or subject token supplier can be specified.");if(o)this.subjectTokenSupplier=o,this.credentialSourceType="programmatic";else{let s=(0,oy.originalOrCamelOptions)(r),i=(0,oy.originalOrCamelOptions)(s.get("format")),a=i.get("type")||"text",u=i.get("subject_token_field_name");if(a!=="json"&&a!=="text")throw new Error(`Invalid credential_source format "${a}"`);if(a==="json"&&!u)throw new Error("Missing subject_token_field_name for JSON credential_source format");let d=s.get("file"),f=s.get("url"),p=s.get("certificate"),h=s.get("headers");if(d&&f||f&&p||d&&p)throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.');if(d)this.credentialSourceType="file",this.subjectTokenSupplier=new DU.FileSubjectTokenSupplier({filePath:d,formatType:a,subjectTokenFieldName:u});else if(f)this.credentialSourceType="url",this.subjectTokenSupplier=new OU.UrlSubjectTokenSupplier({url:f,formatType:a,subjectTokenFieldName:u,headers:h,additionalGaxiosOptions:t.RETRY_CONFIG});else if(p){this.credentialSourceType="certificate";let g=new Qv.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 Qv.CertificateSubjectTokenSupplier){let n=await this.subjectTokenSupplier.createMtlsHttpsAgent();this.stsCredential=new PU.StsCredentials({tokenExchangeEndpoint:this.getTokenUrl(),clientAuthentication:this.clientAuth,transporter:new Zv.Gaxios({agent:n})}),this.transporter=new Zv.Gaxios({...this.transporter.defaults||{},agent:n})}return e}};Xl.IdentityPoolClient=sy});var cy=G(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});Zl.AwsRequestSigner=void 0;var Ql=lt(),tT=ga(),eT="AWS4-HMAC-SHA256",IU="aws4_request",ay=class{getCredentials;region;crypto;constructor(e,n){this.getCredentials=e,this.region=n,this.crypto=(0,tT.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 NU({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=Ql.Gaxios.mergeHeaders(d.amzDate?{"x-amz-date":d.amzDate}:{},{authorization:d.authorizationHeader,host:u.host},i||{});a.token&&Ql.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}};Zl.AwsRequestSigner=ay;async function ka(t,e,n){return await t.signWithHmacSha256(e,n)}async function FU(t,e,n,r,o){let s=await ka(t,`AWS4${e}`,n),i=await ka(t,s,r),a=await ka(t,i,o);return await ka(t,a,"aws4_request")}async function NU(t){let e=Ql.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=Ql.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}/${
|
|
109
|
+
${p}`,g=`${i}/${t.region}/${r}/${IU}`,C=`${eT}
|
|
110
110
|
${s}
|
|
111
111
|
${g}
|
|
112
|
-
`+await t.crypto.sha256DigestHex(h),_=await Rj(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),k=await ka(t.crypto,_,C),b=`${Kv} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,Vv.fromArrayBufferToHex)(k)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:b,canonicalQuerystring:t.canonicalQuerystring}}});var Yv=G(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});Vl.DefaultAwsSecurityCredentialsSupplier=void 0;var Kl=Nt(),ty=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};Kl.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 Kl.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 Kl.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 Kl.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}};Vl.DefaultAwsSecurityCredentialsSupplier=ty});var ry=G(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});Yl.AwsClient=void 0;var Oj=ey(),Pj=Yr(),Ij=Yv(),Xv=an(),Fj=lt(),ny=class t extends Pj.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,Xv.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,Xv.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 Ij.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 Oj.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 Fj.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}))}};Yl.AwsClient=ny});var cy=G(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.InvalidSubjectTokenError=Qe.InvalidMessageFieldError=Qe.InvalidCodeFieldError=Qe.InvalidTokenTypeFieldError=Qe.InvalidExpirationTimeFieldError=Qe.InvalidSuccessFieldError=Qe.InvalidVersionFieldError=Qe.ExecutableResponseError=Qe.ExecutableResponse=void 0;var Xl="urn:ietf:params:oauth:token-type:saml2",oy="urn:ietf:params:oauth:token-type:id_token",sy="urn:ietf:params:oauth:token-type:jwt",iy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new Ql("Executable response must contain a 'version' field.");if(e.success===void 0)throw new Zl("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!==Xl&&this.tokenType!==oy&&this.tokenType!==sy)throw new ed(`Executable response must contain a 'token_type' field when successful and it must be one of ${oy}, ${sy}, or ${Xl}.`);if(this.tokenType===Xl){if(!e.saml_response)throw new Sa(`Executable response must contain a 'saml_response' field when token_type=${Xl}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Sa(`Executable response must contain a 'id_token' field when token_type=${oy} or ${sy}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new td("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new nd("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Qe.ExecutableResponse=iy;var qn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Qe.ExecutableResponseError=qn;var Ql=class extends qn{};Qe.InvalidVersionFieldError=Ql;var Zl=class extends qn{};Qe.InvalidSuccessFieldError=Zl;var ay=class extends qn{};Qe.InvalidExpirationTimeFieldError=ay;var ed=class extends qn{};Qe.InvalidTokenTypeFieldError=ed;var td=class extends qn{};Qe.InvalidCodeFieldError=td;var nd=class extends qn{};Qe.InvalidMessageFieldError=nd;var Sa=class extends qn{};Qe.InvalidSubjectTokenError=Sa});var dy=G(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.PluggableAuthHandler=zs.ExecutableError=void 0;var No=cy(),Nj=re("child_process"),uy=re("fs"),rd=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)}};zs.ExecutableError=rd;var ly=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=Nj.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",a=>{s+=a}),o.stderr.on("data",a=>{s+=a});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",a=>{if(clearTimeout(i),a===0)try{let u=JSON.parse(s),d=new No.ExecutableResponse(u);return n(d)}catch(u){return u instanceof No.ExecutableResponseError?r(u):r(new No.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new rd(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await uy.promises.realpath(this.outputFile)}catch{return}if(!(await uy.promises.lstat(e)).isFile())return;let n=await uy.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new No.ExecutableResponse(r).isValid()?new No.ExecutableResponse(r):void 0}catch(r){throw r instanceof No.ExecutableResponseError?r:new No.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};zs.PluggableAuthHandler=ly});var py=G(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.PluggableAuthClient=Ws.ExecutableError=void 0;var Mj=Yr(),Bj=cy(),Qv=dy(),jj=dy();Object.defineProperty(Ws,"ExecutableError",{enumerable:!0,get:function(){return jj.ExecutableError}});var Uj=30*1e3,Zv=5*1e3,eT=120*1e3,Lj="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",tT=1,fy=class extends Mj.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=Uj;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<Zv||this.timeoutMillis>eT)throw new Error(`Timeout must be between ${Zv} and ${eT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new Qv.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[Lj]!=="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>tT)throw new Error(`Version of executable is not currently supported, maximum supported version is ${tT}.`);if(!e.success)throw new Qv.ExecutableError(e.errorMessage,e.errorCode);if(this.outputFile&&!e.expirationTime)throw new Bj.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}};Ws.PluggableAuthClient=fy});var gy=G(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});od.ExternalAccountClient=void 0;var $j=Yr(),qj=Qm(),Hj=ry(),zj=py(),hy=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===$j.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new Hj.AwsClient(e):e.credential_source?.executable?new zj.PluggableAuthClient(e):new qj.IdentityPoolClient(e):null}};od.ExternalAccountClient=hy});var _y=G(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.ExternalAccountAuthorizedUserClient=Gs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var rT=Nt(),nT=Lm(),oT=lt(),Wj=re("stream"),Gj=Yr();Gs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var Jj="https://sts.{universeDomain}/v1/oauthtoken",my=class t extends nT.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"};rT.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 oT.GaxiosError&&o.response?(0,nT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},yy=class extends rT.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 my({tokenRefreshEndpoint:e.token_url??Jj.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=Gj.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=oT.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 Wj.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}};Gs.ExternalAccountAuthorizedUserClient=yy});var Cy=G(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.GdchClient=Xr.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var Kj=re("crypto"),Vj=re("fs"),Yj=re("https"),Xj=Jr(),Qj=3600;Xr.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var by=class t extends Xj.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||Qj,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!==Xr.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Xr.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=Kj.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 Vj.promises.readFile(r);return new Yj.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")}};Xr.GdchClient=by});var cT=G(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.GoogleAuth=ln.GoogleAuthExceptionMessages=void 0;var Zj=re("child_process"),Aa=re("fs"),eU=lt(),Ea=ha(),tU=re("os"),sd=re("path"),nU=ga(),rU=im(),oU=cm(),sU=um(),Js=Fm(),sT=Mm(),Ks=jm(),iU=gy(),va=Yr(),wy=Nt(),iT=_y(),ky=Cy(),aT=an();ln.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
112
|
+
`+await t.crypto.sha256DigestHex(h),y=await FU(t.crypto,t.securityCredentials.secretAccessKey,i,t.region,r),k=await ka(t.crypto,y,C),b=`${eT} Credential=${t.securityCredentials.accessKeyId}/${g}, SignedHeaders=${f}, Signature=${(0,tT.fromArrayBufferToHex)(k)}`;return{amzDate:e.has("date")?void 0:s,authorizationHeader:b,canonicalQuerystring:t.canonicalQuerystring}}});var nT=G(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});td.DefaultAwsSecurityCredentialsSupplier=void 0;var ed=Nt(),uy=class{regionUrl;securityCredentialsUrl;imdsV2SessionTokenUrl;additionalGaxiosOptions;constructor(e){this.regionUrl=e.regionUrl,this.securityCredentialsUrl=e.securityCredentialsUrl,this.imdsV2SessionTokenUrl=e.imdsV2SessionTokenUrl,this.additionalGaxiosOptions=e.additionalGaxiosOptions}async getAwsRegion(e){if(this.#r)return this.#r;let n=new Headers;if(!this.#r&&this.imdsV2SessionTokenUrl&&n.set("x-aws-ec2-metadata-token",await this.#e(e.transporter)),!this.regionUrl)throw new RangeError('Unable to determine AWS region due to missing "options.credential_source.region_url"');let r={...this.additionalGaxiosOptions,url:this.regionUrl,method:"GET",responseType:"text",headers:n};ed.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 ed.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 ed.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 ed.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}};td.DefaultAwsSecurityCredentialsSupplier=uy});var dy=G(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});nd.AwsClient=void 0;var MU=cy(),BU=Yr(),UU=nT(),rT=an(),jU=lt(),ly=class t extends BU.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,rT.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,rT.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 UU.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 MU.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 jU.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}))}};nd.AwsClient=ly});var my=G(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.InvalidSubjectTokenError=Qe.InvalidMessageFieldError=Qe.InvalidCodeFieldError=Qe.InvalidTokenTypeFieldError=Qe.InvalidExpirationTimeFieldError=Qe.InvalidSuccessFieldError=Qe.InvalidVersionFieldError=Qe.ExecutableResponseError=Qe.ExecutableResponse=void 0;var rd="urn:ietf:params:oauth:token-type:saml2",fy="urn:ietf:params:oauth:token-type:id_token",py="urn:ietf:params:oauth:token-type:jwt",hy=class{version;success;expirationTime;tokenType;errorCode;errorMessage;subjectToken;constructor(e){if(!e.version)throw new od("Executable response must contain a 'version' field.");if(e.success===void 0)throw new sd("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!==rd&&this.tokenType!==fy&&this.tokenType!==py)throw new id(`Executable response must contain a 'token_type' field when successful and it must be one of ${fy}, ${py}, or ${rd}.`);if(this.tokenType===rd){if(!e.saml_response)throw new Sa(`Executable response must contain a 'saml_response' field when token_type=${rd}.`);this.subjectToken=e.saml_response}else{if(!e.id_token)throw new Sa(`Executable response must contain a 'id_token' field when token_type=${fy} or ${py}.`);this.subjectToken=e.id_token}}else{if(!e.code)throw new ad("Executable response must contain a 'code' field when unsuccessful.");if(!e.message)throw new cd("Executable response must contain a 'message' field when unsuccessful.");this.errorCode=e.code,this.errorMessage=e.message}}isValid(){return!this.isExpired()&&this.success}isExpired(){return this.expirationTime!==void 0&&this.expirationTime<Math.round(Date.now()/1e3)}};Qe.ExecutableResponse=hy;var qn=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}};Qe.ExecutableResponseError=qn;var od=class extends qn{};Qe.InvalidVersionFieldError=od;var sd=class extends qn{};Qe.InvalidSuccessFieldError=sd;var gy=class extends qn{};Qe.InvalidExpirationTimeFieldError=gy;var id=class extends qn{};Qe.InvalidTokenTypeFieldError=id;var ad=class extends qn{};Qe.InvalidCodeFieldError=ad;var cd=class extends qn{};Qe.InvalidMessageFieldError=cd;var Sa=class extends qn{};Qe.InvalidSubjectTokenError=Sa});var by=G(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.PluggableAuthHandler=zs.ExecutableError=void 0;var No=my(),LU=re("child_process"),yy=re("fs"),ud=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)}};zs.ExecutableError=ud;var _y=class t{commandComponents;timeoutMillis;outputFile;constructor(e){if(!e.command)throw new Error("No command provided.");if(this.commandComponents=t.parseCommand(e.command),this.timeoutMillis=e.timeoutMillis,!this.timeoutMillis)throw new Error("No timeoutMillis provided.");this.outputFile=e.outputFile}retrieveResponseFromExecutable(e){return new Promise((n,r)=>{let o=LU.spawn(this.commandComponents[0],this.commandComponents.slice(1),{env:{...process.env,...Object.fromEntries(e)}}),s="";o.stdout.on("data",a=>{s+=a}),o.stderr.on("data",a=>{s+=a});let i=setTimeout(()=>(o.removeAllListeners(),o.kill(),r(new Error("The executable failed to finish within the timeout specified."))),this.timeoutMillis);o.on("close",a=>{if(clearTimeout(i),a===0)try{let u=JSON.parse(s),d=new No.ExecutableResponse(u);return n(d)}catch(u){return u instanceof No.ExecutableResponseError?r(u):r(new No.ExecutableResponseError(`The executable returned an invalid response: ${s}`))}else return r(new ud(s,a.toString()))})})}async retrieveCachedResponse(){if(!this.outputFile||this.outputFile.length===0)return;let e;try{e=await yy.promises.realpath(this.outputFile)}catch{return}if(!(await yy.promises.lstat(e)).isFile())return;let n=await yy.promises.readFile(e,{encoding:"utf8"});if(n!=="")try{let r=JSON.parse(n);return new No.ExecutableResponse(r).isValid()?new No.ExecutableResponse(r):void 0}catch(r){throw r instanceof No.ExecutableResponseError?r:new No.ExecutableResponseError(`The output file contained an invalid response: ${n}`)}}static parseCommand(e){let n=e.match(/(?:[^\s"]+|"[^"]*")+/g);if(!n)throw new Error(`Provided command: "${e}" could not be parsed.`);for(let r=0;r<n.length;r++)n[r][0]==='"'&&n[r].slice(-1)==='"'&&(n[r]=n[r].slice(1,-1));return n}};zs.PluggableAuthHandler=_y});var wy=G(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.PluggableAuthClient=Ws.ExecutableError=void 0;var $U=Yr(),qU=my(),oT=by(),HU=by();Object.defineProperty(Ws,"ExecutableError",{enumerable:!0,get:function(){return HU.ExecutableError}});var zU=30*1e3,sT=5*1e3,iT=120*1e3,WU="GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES",aT=1,Cy=class extends $U.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=zU;else if(this.timeoutMillis=e.credential_source.executable.timeout_millis,this.timeoutMillis<sT||this.timeoutMillis>iT)throw new Error(`Timeout must be between ${sT} and ${iT} milliseconds.`);this.outputFile=e.credential_source.executable.output_file,this.handler=new oT.PluggableAuthHandler({command:this.command,timeoutMillis:this.timeoutMillis,outputFile:this.outputFile}),this.credentialSourceType="executable"}async retrieveSubjectToken(){if(process.env[WU]!=="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>aT)throw new Error(`Version of executable is not currently supported, maximum supported version is ${aT}.`);if(!e.success)throw new oT.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}};Ws.PluggableAuthClient=Cy});var Sy=G(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});ld.ExternalAccountClient=void 0;var GU=Yr(),JU=iy(),KU=dy(),VU=wy(),ky=class{constructor(){throw new Error("ExternalAccountClients should be initialized via: ExternalAccountClient.fromJSON(), directly via explicit constructors, eg. new AwsClient(options), new IdentityPoolClient(options), newPluggableAuthClientOptions, or via new GoogleAuth(options).getClient()")}static fromJSON(e){return e&&e.type===GU.EXTERNAL_ACCOUNT_TYPE?e.credential_source?.environment_id?new KU.AwsClient(e):e.credential_source?.executable?new VU.PluggableAuthClient(e):new JU.IdentityPoolClient(e):null}};ld.ExternalAccountClient=ky});var vy=G(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.ExternalAccountAuthorizedUserClient=Gs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=void 0;var uT=Nt(),cT=Km(),lT=lt(),YU=re("stream"),XU=Yr();Gs.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE="external_account_authorized_user";var QU="https://sts.{universeDomain}/v1/oauthtoken",Ay=class t extends cT.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"};uT.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 lT.GaxiosError&&o.response?(0,cT.getErrorFromOAuthErrorResponse)(o.response.data,o):o}}},Ey=class extends uT.AuthClient{cachedAccessToken;externalAccountAuthorizedUserHandler;refreshToken;constructor(e){super(e),e.universe_domain&&(this.universeDomain=e.universe_domain),this.refreshToken=e.refresh_token;let n={confidentialClientType:"basic",clientId:e.client_id,clientSecret:e.client_secret};this.externalAccountAuthorizedUserHandler=new Ay({tokenRefreshEndpoint:e.token_url??QU.replace("{universeDomain}",this.universeDomain),transporter:this.transporter,clientAuthentication:n}),this.cachedAccessToken=null,this.quotaProjectId=e.quota_project_id,typeof e?.eagerRefreshThresholdMillis!="number"?this.eagerRefreshThresholdMillis=XU.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=lT.Gaxios.mergeHeaders(e.headers),this.addUserProjectAndAuthHeaders(e.headers,o),r=await this.transporter.request(e)}catch(o){let s=o.response;if(s){let i=s.status,a=s.config.data instanceof YU.Readable;if(!n&&(i===401||i===403)&&!a&&this.forceRefreshOnFailure)return await this.refreshAccessTokenAsync(),await this.requestAsync(e,!0)}throw o}return r}async refreshAccessTokenAsync(){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}};Gs.ExternalAccountAuthorizedUserClient=Ey});var xy=G(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.GdchClient=Xr.GDCH_SERVICE_ACCOUNT_TYPE=void 0;var ZU=re("crypto"),ej=re("fs"),tj=re("https"),nj=Jr(),rj=3600;Xr.GDCH_SERVICE_ACCOUNT_TYPE="gdch_service_account";var Ty=class t extends nj.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||rj,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!==Xr.GDCH_SERVICE_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Xr.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=ZU.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 ej.promises.readFile(r);return new tj.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")}};Xr.GdchClient=Ty});var hT=G(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.GoogleAuth=ln.GoogleAuthExceptionMessages=void 0;var oj=re("child_process"),Aa=re("fs"),sj=lt(),Ea=ha(),ij=re("os"),dd=re("path"),aj=ga(),cj=hm(),uj=mm(),lj=ym(),Js=qm(),dT=zm(),Ks=Gm(),dj=Sy(),va=Yr(),Ry=Nt(),fT=vy(),Dy=xy(),pT=an();ln.GoogleAuthExceptionMessages={API_KEY_WITH_CREDENTIALS:"API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.",NO_PROJECT_ID_FOUND:`Unable to detect a Project Id in the current environment.
|
|
113
113
|
To learn more about authentication and Google APIs, visit:
|
|
114
114
|
https://cloud.google.com/docs/authentication/getting-started`,NO_CREDENTIALS_FOUND:`Unable to find credentials in current environment.
|
|
115
115
|
To learn more about authentication and Google APIs, visit:
|
|
116
116
|
https://cloud.google.com/docs/authentication/getting-started`,NO_ADC_FOUND:"Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.",NO_UNIVERSE_DOMAIN_FOUND:`Unable to detect a Universe Domain in the current environment.
|
|
117
117
|
To learn more about Universe Domain retrieval, visit:
|
|
118
|
-
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Sy=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ln.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Ea.universe("universe-domain"),e||=wy.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=wy.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,aT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=wy.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 Js.JWT?n.scopes=this.scopes:n instanceof va.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Js.JWT?n.scopes=this.scopes:n instanceof va.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new rU.Compute(e));throw new Error(ln.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Ea.getGCPResidency()||await Ea.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=sd.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=sd.join(s,".config","gcloud"))}if(!n)return null;let r=sd.join(n,"application_default_credentials.json");return Aa.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=Aa.realpathSync(e),!Aa.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=Aa.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!==Ks.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Ks.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 Ks.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,aT.originalOrCamelOptions)(n).get("universe_domain");return e.type===sT.USER_REFRESH_ACCOUNT_TYPE?(r=new sT.UserRefreshClient(n),r.fromJSON(e)):e.type===Ks.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===va.EXTERNAL_ACCOUNT_TYPE?(r=iU.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===iT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new iT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===ky.GDCH_SERVICE_ACCOUNT_TYPE?(r=new ky.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Js.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 Js.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 Js.JWT({...n,apiKey:e})}_isWindows(){let e=tU.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,Zj.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!==va.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ea.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 Ks.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof va.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([Ea.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(ln.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof ky.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=sd.resolve(this.keyFilename),n=Aa.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 oU.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=eU.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,sU.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 Ks.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,nU.createCrypto)();if(r instanceof Js.JWT&&r.key)return await s.sign(r.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,i.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ln.GoogleAuth=Sy});var uT=G(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});id.IAMAuth=void 0;var Ay=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}}};id.IAMAuth=Ay});var lT=G(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.DownscopedClient=Hn.EXPIRATION_TIME_OFFSET=Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var aU=lt(),cU=re("stream"),Ey=Nt(),uU=Ul(),lU="urn:ietf:params:oauth:grant-type:token-exchange",dU="urn:ietf:params:oauth:token-type:access_token",fU="urn:ietf:params:oauth:token-type:access_token";Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Hn.EXPIRATION_TIME_OFFSET=300*1e3;var vy=class extends Ey.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Ey.AuthClient?{}:e),e instanceof Ey.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new uU.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=aU.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 cU.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:lU,requestedTokenType:dU,subjectToken:e,subjectTokenType:fU},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Hn.DownscopedClient=vy});var dT=G(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});ad.PassThroughClient=void 0;var pU=Nt(),Ty=class extends pU.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};ad.PassThroughClient=Ty});var cd=G(oe=>{"use strict";var hU=oe&&oe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),gU=oe&&oe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&hU(e,t,n)};Object.defineProperty(oe,"__esModule",{value:!0});oe.GoogleAuth=oe.auth=oe.GDCH_SERVICE_ACCOUNT_TYPE=oe.GdchClient=oe.PassThroughClient=oe.ExternalAccountAuthorizedUserClient=oe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=oe.ExecutableError=oe.PluggableAuthClient=oe.DownscopedClient=oe.BaseExternalAccountClient=oe.ExternalAccountClient=oe.IdentityPoolClient=oe.AwsRequestSigner=oe.AwsClient=oe.UserRefreshClient=oe.LoginTicket=oe.ClientAuthentication=oe.OAuth2Client=oe.CodeChallengeMethod=oe.Impersonated=oe.JWT=oe.JWTAccess=oe.IdTokenClient=oe.IAMAuth=oe.GCPEnv=oe.Compute=oe.DEFAULT_UNIVERSE=oe.AuthClient=oe.gaxios=oe.gcpMetadata=void 0;var fT=cT();Object.defineProperty(oe,"GoogleAuth",{enumerable:!0,get:function(){return fT.GoogleAuth}});oe.gcpMetadata=ha();oe.gaxios=lt();var pT=Nt();Object.defineProperty(oe,"AuthClient",{enumerable:!0,get:function(){return pT.AuthClient}});Object.defineProperty(oe,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return pT.DEFAULT_UNIVERSE}});var mU=im();Object.defineProperty(oe,"Compute",{enumerable:!0,get:function(){return mU.Compute}});var yU=um();Object.defineProperty(oe,"GCPEnv",{enumerable:!0,get:function(){return yU.GCPEnv}});var _U=uT();Object.defineProperty(oe,"IAMAuth",{enumerable:!0,get:function(){return _U.IAMAuth}});var bU=cm();Object.defineProperty(oe,"IdTokenClient",{enumerable:!0,get:function(){return bU.IdTokenClient}});var CU=Pm();Object.defineProperty(oe,"JWTAccess",{enumerable:!0,get:function(){return CU.JWTAccess}});var wU=Fm();Object.defineProperty(oe,"JWT",{enumerable:!0,get:function(){return wU.JWT}});var kU=jm();Object.defineProperty(oe,"Impersonated",{enumerable:!0,get:function(){return kU.Impersonated}});var xy=Jr();Object.defineProperty(oe,"CodeChallengeMethod",{enumerable:!0,get:function(){return xy.CodeChallengeMethod}});Object.defineProperty(oe,"OAuth2Client",{enumerable:!0,get:function(){return xy.OAuth2Client}});Object.defineProperty(oe,"ClientAuthentication",{enumerable:!0,get:function(){return xy.ClientAuthentication}});var SU=nm();Object.defineProperty(oe,"LoginTicket",{enumerable:!0,get:function(){return SU.LoginTicket}});var AU=Mm();Object.defineProperty(oe,"UserRefreshClient",{enumerable:!0,get:function(){return AU.UserRefreshClient}});var EU=ry();Object.defineProperty(oe,"AwsClient",{enumerable:!0,get:function(){return EU.AwsClient}});var vU=ey();Object.defineProperty(oe,"AwsRequestSigner",{enumerable:!0,get:function(){return vU.AwsRequestSigner}});var TU=Qm();Object.defineProperty(oe,"IdentityPoolClient",{enumerable:!0,get:function(){return TU.IdentityPoolClient}});var xU=gy();Object.defineProperty(oe,"ExternalAccountClient",{enumerable:!0,get:function(){return xU.ExternalAccountClient}});var RU=Yr();Object.defineProperty(oe,"BaseExternalAccountClient",{enumerable:!0,get:function(){return RU.BaseExternalAccountClient}});var DU=lT();Object.defineProperty(oe,"DownscopedClient",{enumerable:!0,get:function(){return DU.DownscopedClient}});var hT=py();Object.defineProperty(oe,"PluggableAuthClient",{enumerable:!0,get:function(){return hT.PluggableAuthClient}});Object.defineProperty(oe,"ExecutableError",{enumerable:!0,get:function(){return hT.ExecutableError}});var gT=_y();Object.defineProperty(oe,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return gT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(oe,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return gT.ExternalAccountAuthorizedUserClient}});var OU=dT();Object.defineProperty(oe,"PassThroughClient",{enumerable:!0,get:function(){return OU.PassThroughClient}});var mT=Cy();Object.defineProperty(oe,"GdchClient",{enumerable:!0,get:function(){return mT.GdchClient}});Object.defineProperty(oe,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return mT.GDCH_SERVICE_ACCOUNT_TYPE}});gU(Dm(),oe);var PU=new fT.GoogleAuth;oe.auth=PU});var La,W_=Mr(()=>{"use strict";La=class{type="console";config;colors={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m"};constructor(e={}){this.config={colors:!0,level:"log",...e}}formatData(e,n){let{format:r="text",timestamp:o=!0,prefix:s,metadata:i}=n||{},a="";if(o){let u=new Date().toISOString();a+=this.config.colors?`${this.colors.cyan}[${u}]${this.colors.reset} `:`[${u}] `}switch(s&&(a+=this.config.colors?`${this.colors.bright}${s}${this.colors.reset} `:`${s} `),r){case"json":a+=JSON.stringify(e,null,2);break;case"markdown":typeof e=="object"?a+=this.toMarkdown(e):a+=String(e);break;default:typeof e=="object"?a+=JSON.stringify(e,null,2):a+=String(e);break}return i&&Object.keys(i).length>0&&(a+=`
|
|
118
|
+
https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Oy=class{checkIsGCE=void 0;useJWTAccessWithScope;defaultServicePath;get isGCE(){return this.checkIsGCE}_findProjectIdPromise;_cachedProjectId;jsonContent=null;apiKey;cachedCredential=null;#e=null;defaultScopes;keyFilename;scopes;clientOptions={};constructor(e={}){if(this._cachedProjectId=e.projectId||null,this.cachedCredential=e.authClient||null,this.keyFilename=e.keyFilename||e.keyFile,this.scopes=e.scopes,this.clientOptions=e.clientOptions||{},this.jsonContent=e.credentials||null,this.apiKey=e.apiKey||this.clientOptions.apiKey||null,this.apiKey&&(this.jsonContent||this.clientOptions.credentials))throw new RangeError(ln.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS);e.universeDomain&&(this.clientOptions.universeDomain=e.universeDomain)}setGapicJWTValues(e){e.defaultServicePath=this.defaultServicePath,e.useJWTAccessWithScope=this.useJWTAccessWithScope,e.defaultScopes=this.defaultScopes}getProjectId(e){if(e)this.getProjectIdAsync().then(n=>e(null,n),e);else return this.getProjectIdAsync()}async getProjectIdOptional(){try{return await this.getProjectId()}catch(e){if(e instanceof Error&&e.message===ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)return null;throw e}}async findAndCacheProjectId(){let e=null;if(e||=await this.getProductionProjectId(),e||=await this.getFileProjectId(),e||=await this.getDefaultServiceProjectId(),e||=await this.getGCEProjectId(),e||=await this.getExternalAccountClientProjectId(),e)return this._cachedProjectId=e,e;throw new Error(ln.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND)}async getProjectIdAsync(){return this._cachedProjectId?this._cachedProjectId:(this._findProjectIdPromise||(this._findProjectIdPromise=this.findAndCacheProjectId()),this._findProjectIdPromise)}async getUniverseDomainFromMetadataServer(){let e;try{e=await Ea.universe("universe-domain"),e||=Ry.DEFAULT_UNIVERSE}catch(n){if(n&&n?.response?.status===404)e=Ry.DEFAULT_UNIVERSE;else throw n}return e}async getUniverseDomain(){let e=(0,pT.originalOrCamelOptions)(this.clientOptions).get("universe_domain");try{e??=(await this.getClient()).universeDomain}catch{e??=Ry.DEFAULT_UNIVERSE}return e}getAnyScopes(){return this.scopes||this.defaultScopes}getApplicationDefault(e={},n){let r;if(typeof e=="function"?n=e:r=e,n)this.getApplicationDefaultAsync(r).then(o=>n(null,o.credential,o.projectId),n);else return this.getApplicationDefaultAsync(r)}async getApplicationDefaultAsync(e={}){if(this.cachedCredential)return await this.#t(this.cachedCredential,null);let n;if(n=await this._tryGetApplicationCredentialsFromEnvironmentVariable(e),n)return n instanceof Js.JWT?n.scopes=this.scopes:n instanceof va.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(n=await this._tryGetApplicationCredentialsFromWellKnownFile(e),n)return n instanceof Js.JWT?n.scopes=this.scopes:n instanceof va.BaseExternalAccountClient&&(n.scopes=this.getAnyScopes()),await this.#t(n);if(await this._checkIsGCE())return e.scopes=this.getAnyScopes(),await this.#t(new cj.Compute(e));throw new Error(ln.GoogleAuthExceptionMessages.NO_ADC_FOUND)}async#t(e,n=process.env.GOOGLE_CLOUD_QUOTA_PROJECT||null){let r=await this.getProjectIdOptional();return n&&(e.quotaProjectId=n),this.cachedCredential=e,{credential:e,projectId:r}}async _checkIsGCE(){return this.checkIsGCE===void 0&&(this.checkIsGCE=Ea.getGCPResidency()||await Ea.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=dd.join(process.env.APPDATA,"gcloud"));else{let s=process.env.HOME;s&&(n=dd.join(s,".config","gcloud"))}if(!n)return null;let r=dd.join(n,"application_default_credentials.json");return Aa.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=Aa.realpathSync(e),!Aa.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=Aa.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!==Ks.IMPERSONATED_ACCOUNT_TYPE)throw new Error(`The incoming JSON object does not have the "${Ks.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 Ks.Impersonated({...e,sourceClient:n,targetPrincipal:r,targetScopes:Array.isArray(o)?o:[o]})}fromJSON(e,n={}){let r,o=(0,pT.originalOrCamelOptions)(n).get("universe_domain");return e.type===dT.USER_REFRESH_ACCOUNT_TYPE?(r=new dT.UserRefreshClient(n),r.fromJSON(e)):e.type===Ks.IMPERSONATED_ACCOUNT_TYPE?r=this.fromImpersonatedJSON(e):e.type===va.EXTERNAL_ACCOUNT_TYPE?(r=dj.ExternalAccountClient.fromJSON({...e,...n}),r.scopes=this.getAnyScopes()):e.type===fT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE?r=new fT.ExternalAccountAuthorizedUserClient({...e,...n}):e.type===Dy.GDCH_SERVICE_ACCOUNT_TYPE?(r=new Dy.GdchClient(n),r.fromJSON(e)):(n.scopes=this.scopes,r=new Js.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 Js.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 Js.JWT({...n,apiKey:e})}_isWindows(){let e=ij.platform();return!!(e&&e.length>=3&&e.substring(0,3).toLowerCase()==="win")}async getDefaultServiceProjectId(){return new Promise(e=>{(0,oj.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!==va.EXTERNAL_ACCOUNT_TYPE?null:await(await this.getClient()).getProjectId()}async getGCEProjectId(){try{return await Ea.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 Ks.Impersonated)return{client_email:e.getTargetPrincipal()};if(e instanceof va.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([Ea.instance("service-accounts/default/email"),this.getUniverseDomain()]);return{client_email:n,universe_domain:r}}throw new Error(ln.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND)}async getClient(){if(this.cachedCredential)return this.cachedCredential;this.#e=this.#e||this.#n();try{let e=await this.#e;if(e instanceof Dy.GdchClient&&!e.apiAudience){let n=this.clientOptions,r=n.apiEndpoint||n.servicePath;if(r){let s=`${r.startsWith("http")?"":"https://"}${r}`.replace(/\/+$/,""),i=e.createWithGdchAudience(s);return this.cachedCredential=i,i}}return e}finally{this.#e=null}}async#n(){if(this.jsonContent)return this._cacheClientFromJSON(this.jsonContent,this.clientOptions);if(this.keyFilename){let e=dd.resolve(this.keyFilename),n=Aa.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 uj.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=sj.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,lj.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 Ks.Impersonated)return(await r.sign(e)).signedBlob;let s=(0,aj.createCrypto)();if(r instanceof Js.JWT&&r.key)return await s.sign(r.key,e);let i=await this.getCredentials();if(!i.client_email)throw new Error("Cannot sign data without `client_email`.");return this.signBlob(s,i.client_email,e,n)}async signBlob(e,n,r,o){let s=new URL(o+`${n}:signBlob`);return(await this.request({method:"POST",url:s.href,data:{payload:e.encodeBase64StringUtf8(r)},retry:!0,retryConfig:{httpMethodsToRetry:["POST"]}})).data.signedBlob}};ln.GoogleAuth=Oy});var gT=G(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});fd.IAMAuth=void 0;var Py=class{selector;token;constructor(e,n){this.selector=e,this.token=n,this.selector=e,this.token=n}getRequestHeaders(){return{"x-goog-iam-authority-selector":this.selector,"x-goog-iam-authorization-token":this.token}}};fd.IAMAuth=Py});var mT=G(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.DownscopedClient=Hn.EXPIRATION_TIME_OFFSET=Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=void 0;var fj=lt(),pj=re("stream"),Iy=Nt(),hj=Wl(),gj="urn:ietf:params:oauth:grant-type:token-exchange",mj="urn:ietf:params:oauth:token-type:access_token",yj="urn:ietf:params:oauth:token-type:access_token";Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT=10;Hn.EXPIRATION_TIME_OFFSET=300*1e3;var Fy=class extends Iy.AuthClient{authClient;credentialAccessBoundary;cachedDownscopedAccessToken;stsCredential;constructor(e,n={accessBoundary:{accessBoundaryRules:[]}}){if(super(e instanceof Iy.AuthClient?{}:e),e instanceof Iy.AuthClient?(this.authClient=e,this.credentialAccessBoundary=n):(this.authClient=e.authClient,this.credentialAccessBoundary=e.credentialAccessBoundary),this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length===0)throw new Error("At least one access boundary rule needs to be defined.");if(this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length>Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT)throw new Error(`The provided access boundary has more than ${Hn.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`);for(let r of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules)if(r.availablePermissions.length===0)throw new Error("At least one permission should be defined in access boundary rules.");this.stsCredential=new hj.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=fj.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.authClient.getAccessToken()).token,n={grantType:gj,requestedTokenType:mj,subjectToken:e,subjectTokenType:yj},r=await this.stsCredential.exchangeToken(n,void 0,this.credentialAccessBoundary),o=this.authClient.credentials?.expiry_date||null,s=r.expires_in?new Date().getTime()+r.expires_in*1e3:o;return this.cachedDownscopedAccessToken={access_token:r.access_token,expiry_date:s,res:r.res},this.credentials={},Object.assign(this.credentials,this.cachedDownscopedAccessToken),delete this.credentials.res,this.emit("tokens",{refresh_token:null,expiry_date:this.cachedDownscopedAccessToken.expiry_date,access_token:this.cachedDownscopedAccessToken.access_token,token_type:"Bearer",id_token:null}),this.cachedDownscopedAccessToken}isExpired(e){let n=new Date().getTime();return e.expiry_date?n>=e.expiry_date-this.eagerRefreshThresholdMillis:!1}};Hn.DownscopedClient=Fy});var yT=G(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.PassThroughClient=void 0;var _j=Nt(),Ny=class extends _j.AuthClient{async request(e){return this.transporter.request(e)}async getAccessToken(){return{}}async getRequestHeaders(){return new Headers}};pd.PassThroughClient=Ny});var hd=G(oe=>{"use strict";var bj=oe&&oe.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),Cj=oe&&oe.__exportStar||function(t,e){for(var n in t)n!=="default"&&!Object.prototype.hasOwnProperty.call(e,n)&&bj(e,t,n)};Object.defineProperty(oe,"__esModule",{value:!0});oe.GoogleAuth=oe.auth=oe.GDCH_SERVICE_ACCOUNT_TYPE=oe.GdchClient=oe.PassThroughClient=oe.ExternalAccountAuthorizedUserClient=oe.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE=oe.ExecutableError=oe.PluggableAuthClient=oe.DownscopedClient=oe.BaseExternalAccountClient=oe.ExternalAccountClient=oe.IdentityPoolClient=oe.AwsRequestSigner=oe.AwsClient=oe.UserRefreshClient=oe.LoginTicket=oe.ClientAuthentication=oe.OAuth2Client=oe.CodeChallengeMethod=oe.Impersonated=oe.JWT=oe.JWTAccess=oe.IdTokenClient=oe.IAMAuth=oe.GCPEnv=oe.Compute=oe.DEFAULT_UNIVERSE=oe.AuthClient=oe.gaxios=oe.gcpMetadata=void 0;var _T=hT();Object.defineProperty(oe,"GoogleAuth",{enumerable:!0,get:function(){return _T.GoogleAuth}});oe.gcpMetadata=ha();oe.gaxios=lt();var bT=Nt();Object.defineProperty(oe,"AuthClient",{enumerable:!0,get:function(){return bT.AuthClient}});Object.defineProperty(oe,"DEFAULT_UNIVERSE",{enumerable:!0,get:function(){return bT.DEFAULT_UNIVERSE}});var wj=hm();Object.defineProperty(oe,"Compute",{enumerable:!0,get:function(){return wj.Compute}});var kj=ym();Object.defineProperty(oe,"GCPEnv",{enumerable:!0,get:function(){return kj.GCPEnv}});var Sj=gT();Object.defineProperty(oe,"IAMAuth",{enumerable:!0,get:function(){return Sj.IAMAuth}});var Aj=mm();Object.defineProperty(oe,"IdTokenClient",{enumerable:!0,get:function(){return Aj.IdTokenClient}});var Ej=Lm();Object.defineProperty(oe,"JWTAccess",{enumerable:!0,get:function(){return Ej.JWTAccess}});var vj=qm();Object.defineProperty(oe,"JWT",{enumerable:!0,get:function(){return vj.JWT}});var Tj=Gm();Object.defineProperty(oe,"Impersonated",{enumerable:!0,get:function(){return Tj.Impersonated}});var My=Jr();Object.defineProperty(oe,"CodeChallengeMethod",{enumerable:!0,get:function(){return My.CodeChallengeMethod}});Object.defineProperty(oe,"OAuth2Client",{enumerable:!0,get:function(){return My.OAuth2Client}});Object.defineProperty(oe,"ClientAuthentication",{enumerable:!0,get:function(){return My.ClientAuthentication}});var xj=lm();Object.defineProperty(oe,"LoginTicket",{enumerable:!0,get:function(){return xj.LoginTicket}});var Rj=zm();Object.defineProperty(oe,"UserRefreshClient",{enumerable:!0,get:function(){return Rj.UserRefreshClient}});var Dj=dy();Object.defineProperty(oe,"AwsClient",{enumerable:!0,get:function(){return Dj.AwsClient}});var Oj=cy();Object.defineProperty(oe,"AwsRequestSigner",{enumerable:!0,get:function(){return Oj.AwsRequestSigner}});var Pj=iy();Object.defineProperty(oe,"IdentityPoolClient",{enumerable:!0,get:function(){return Pj.IdentityPoolClient}});var Ij=Sy();Object.defineProperty(oe,"ExternalAccountClient",{enumerable:!0,get:function(){return Ij.ExternalAccountClient}});var Fj=Yr();Object.defineProperty(oe,"BaseExternalAccountClient",{enumerable:!0,get:function(){return Fj.BaseExternalAccountClient}});var Nj=mT();Object.defineProperty(oe,"DownscopedClient",{enumerable:!0,get:function(){return Nj.DownscopedClient}});var CT=wy();Object.defineProperty(oe,"PluggableAuthClient",{enumerable:!0,get:function(){return CT.PluggableAuthClient}});Object.defineProperty(oe,"ExecutableError",{enumerable:!0,get:function(){return CT.ExecutableError}});var wT=vy();Object.defineProperty(oe,"EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE",{enumerable:!0,get:function(){return wT.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE}});Object.defineProperty(oe,"ExternalAccountAuthorizedUserClient",{enumerable:!0,get:function(){return wT.ExternalAccountAuthorizedUserClient}});var Mj=yT();Object.defineProperty(oe,"PassThroughClient",{enumerable:!0,get:function(){return Mj.PassThroughClient}});var kT=xy();Object.defineProperty(oe,"GdchClient",{enumerable:!0,get:function(){return kT.GdchClient}});Object.defineProperty(oe,"GDCH_SERVICE_ACCOUNT_TYPE",{enumerable:!0,get:function(){return kT.GDCH_SERVICE_ACCOUNT_TYPE}});Cj(Um(),oe);var Bj=new _T.GoogleAuth;oe.auth=Bj});var $a,X_=Mr(()=>{"use strict";$a=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 $a,G_=Mr(()=>{"use strict";$a=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{timestamp:r=!0,prefix:o,metadata:s}=n||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),o&&(i.prefix=o),s&&Object.keys(s).length>0&&(i.metadata=s),i}async sendRequest(e,n,r,o,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let u=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(a),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return u}catch(u){throw clearTimeout(a),u}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,i){let a=null;for(let u=1;u<=i.maxAttempts;u++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(a=d,u===i.maxAttempts)break;let f=i.backoffMs*Math.pow(2,u-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${u}/${i.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw a}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n);return await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry),!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`,{cause:o})}}}});import{writeFileSync as F6,existsSync as N6,mkdirSync as M6}from"fs";import{join as LR}from"path";import{tmpdir as B6}from"os";var qa,J_=Mr(()=>{"use strict";qa=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=B6();this.baseDir=LR(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{N6(this.baseDir)||M6(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 LR(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 F6(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var K_,ci,$R=Mr(()=>{"use strict";W_();G_();J_();K_=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 La(e.config);break;case"webhook":n=new $a(e.config);break;case"temp-file":n=new qa(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)}},ci=new K_});var JR=nr(TC(),1);import j6 from"fastify";import U6 from"@fastify/cors";import{RATE_LIMIT_CONFIG as L6}from"@caeliq/ccr-shared";var LC=nr(Yp(),1);import{readFileSync as wO,existsSync as jC}from"fs";import{join as UC}from"path";import{config as kO}from"dotenv";var Qo=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:UC(process.cwd(),this.options.jsonPath);if(jC(e))try{let n=wO(e,"utf-8"),r=LC.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:UC(process.cwd(),this.options.envPath);if(jC(e))try{let n=kO({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 Qp="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Je(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(`"(${Qp})"\\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 SO=new RegExp(`^(?:${Qp})$`,"i"),AO=6,EO=20;function Zo(t,e=0){if(t==null)return t;if(!(e>AO)){if(typeof t=="string")return Je(t);if(Array.isArray(t))return t.slice(0,EO).map(n=>Zo(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=SO.test(r)?"[redacted]":Zo(o,e+1);return n}return t}}var jc=32768;function Zp(t,e=jc){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(`"(${Qp})"\\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 vO(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 qa,Q_=Mr(()=>{"use strict";qa=class{type="webhook";config;defaultTimeout=3e4;logger=null;setLogger(e){this.logger=e,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger)))}constructor(e){if(!e.url)throw new Error("Webhook URL is required");this.config={method:"POST",retry:{maxAttempts:3,backoffMs:1e3},silent:!1,...e}}buildHeaders(){let e={"Content-Type":"application/json",...this.config.headers||{}};if(this.config.auth)switch(this.config.auth.type){case"bearer":this.config.auth.token&&(e.Authorization=`Bearer ${this.config.auth.token}`);break;case"basic":if(this.config.auth.username&&this.config.auth.password){let n=Buffer.from(`${this.config.auth.username}:${this.config.auth.password}`).toString("base64");e.Authorization=`Basic ${n}`}break;case"custom":this.config.auth.custom&&(e[this.config.auth.custom.header]=this.config.auth.custom.value);break}return e}buildBody(e,n){let{timestamp:r=!0,prefix:o,metadata:s}=n||{},i={data:e};return r&&(i.timestamp=new Date().toISOString()),o&&(i.prefix=o),s&&Object.keys(s).length>0&&(i.metadata=s),i}async sendRequest(e,n,r,o,s){let i=new AbortController,a=setTimeout(()=>i.abort(),s);try{let u=await fetch(e,{method:n,headers:r,body:JSON.stringify(o),signal:i.signal});if(clearTimeout(a),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return u}catch(u){throw clearTimeout(a),u}}delay(e){return new Promise(n=>setTimeout(n,e))}async sendWithRetry(e,n,r,o,s,i){let a=null;for(let u=1;u<=i.maxAttempts;u++)try{return await this.sendRequest(e,n,r,o,s)}catch(d){if(a=d,u===i.maxAttempts)break;let f=i.backoffMs*Math.pow(2,u-1);(this.logger?.warn??console.warn)(`[WebhookOutputHandler] Request failed (attempt ${u}/${i.maxAttempts}), retrying in ${f}ms...`,d.message),await this.delay(f)}throw a}async output(e,n={}){let r=n.timeout||this.defaultTimeout;try{let o=this.buildHeaders(),s=this.buildBody(e,n);return await this.sendWithRetry(this.config.url,this.config.method,o,s,r,this.config.retry),!0}catch(o){let s=o instanceof Error?o.message:String(o);if(this.config.silent)return(this.logger?.error??console.error)(`[WebhookOutputHandler] Failed to send data: ${s}`),!1;throw new Error(`Webhook output failed: ${s}`,{cause:o})}}}});import{writeFileSync as H6,existsSync as z6,mkdirSync as W6}from"fs";import{join as zR}from"path";import{tmpdir as G6}from"os";var Ha,Z_=Mr(()=>{"use strict";Ha=class{type="temp-file";config;baseDir;constructor(e={}){this.config={subdirectory:"claude-code-router",extension:"json",includeTimestamp:!1,prefix:"session",...e};let n=G6();this.baseDir=zR(n,this.config.subdirectory),this.ensureDir()}ensureDir(){try{z6(this.baseDir)||W6(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 zR(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 H6(s,JSON.stringify(o,null,2),"utf-8"),!0}catch{return!1}}getBaseDir(){return this.baseDir}}});var e0,ci,WR=Mr(()=>{"use strict";X_();Q_();Z_();e0=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 $a(e.config);break;case"webhook":n=new qa(e.config);break;case"temp-file":n=new Ha(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)}},ci=new e0});var XR=nr(IC(),1);import J6 from"fastify";import K6 from"@fastify/cors";import{RATE_LIMIT_CONFIG as V6}from"@caeliq/ccr-shared";var GC=nr(oh(),1);import{readFileSync as EO,existsSync as zC}from"fs";import{join as WC}from"path";import{config as vO}from"dotenv";var Qo=class{config={};options;logger;constructor(e={jsonPath:"./config.json"}){this.options={envPath:e.envPath||".env",jsonPath:e.jsonPath,useEnvFile:!1,useJsonFile:e.useJsonFile!==!1,useEnvironmentVariables:e.useEnvironmentVariables!==!1,...e},this.logger=e.logger,this.logger&&(typeof this.logger.info=="function"&&(this.logger.info=this.logger.info.bind(this.logger)),typeof this.logger.warn=="function"&&(this.logger.warn=this.logger.warn.bind(this.logger)),typeof this.logger.error=="function"&&(this.logger.error=this.logger.error.bind(this.logger))),this.loadConfig()}loadConfig(){this.options.useJsonFile&&this.options.jsonPath&&this.loadJsonConfig(),this.options.initialConfig&&(this.config={...this.config,...this.options.initialConfig}),this.options.useEnvFile&&this.loadEnvConfig(),this.config.LOG_FILE&&(process.env.LOG_FILE=this.config.LOG_FILE),this.config.LOG&&(process.env.LOG=this.config.LOG)}loadJsonConfig(){if(!this.options.jsonPath)return;let e=this.isAbsolutePath(this.options.jsonPath)?this.options.jsonPath:WC(process.cwd(),this.options.jsonPath);if(zC(e))try{let n=EO(e,"utf-8"),r=GC.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:WC(process.cwd(),this.options.envPath);if(zC(e))try{let n=vO({path:e});n.parsed&&(this.config={...this.config,...this.parseEnvConfig(n.parsed)})}catch(n){(this.logger?.warn??console.warn)(`Failed to load .env config from ${e}:`,n)}}loadEnvironmentVariables(){let e=this.parseEnvConfig(process.env);this.config={...this.config,...e}}parseEnvConfig(e){let n={};return Object.assign(n,e),n}isAbsolutePath(e){return e.startsWith("/")||e.includes(":")}get(e,n){let r=this.config[e];return r!==void 0?r:n}getAll(){return{...this.config}}getHttpsProxy(){return this.get("HTTPS_PROXY")||this.get("https_proxy")||this.get("httpsProxy")||this.get("PROXY_URL")}has(e){return this.config[e]!==void 0}set(e,n){this.config[e]=n}reload(){this.config={},this.loadConfig()}getConfigSummary(){let e=[];return this.options.initialConfig&&e.push("Initial Config"),this.options.useJsonFile&&this.options.jsonPath&&e.push(`JSON: ${this.options.jsonPath}`),this.options.useEnvFile&&e.push(`ENV: ${this.options.envPath}`),this.options.useEnvironmentVariables&&e.push("Environment Variables"),`Config sources: ${e.join(", ")}`}};var ih="(?:proxy[-_])?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|secret|password|passwd|token|cookie|set[-_]?cookie";function Je(t){return t.replace(/\b(?:https?|wss?):\/\/[^\s"'<>]+/gi,"[redacted-url]").replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ih})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"').replace(/\b(?:authorization|x-api-key|api-key|api_key|access_token|token)\s*[:=]\s*["']?[^\s,;"']+/gi,e=>`${e.split(/\s*[:=]/,1)[0]}=[redacted]`).replace(/\[[0-9a-f:]+\](?::\d+)?/gi,"[redacted-address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[redacted-address]").replace(/\b(connect(?:ing)?(?:\s+to)?|from|to)\s+(?:localhost|(?:[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?\.)+[a-z]{2,63})(?::\d+)?\b/gi,"$1 [redacted-address]").replace(/([?&](?:api_?key|key|token|access_token|auth)=)[^&\s]+/gi,"$1[redacted]").replace(/\s+/g," ").trim().slice(0,240)}var TO=new RegExp(`^(?:${ih})$`,"i"),xO=6,RO=20;function Zo(t,e=0){if(t==null)return t;if(!(e>xO)){if(typeof t=="string")return Je(t);if(Array.isArray(t))return t.slice(0,RO).map(n=>Zo(n,e+1));if(typeof t=="object"){let n={};for(let[r,o]of Object.entries(t))n[r]=TO.test(r)?"[redacted]":Zo(o,e+1);return n}return t}}var jc=32768;function ah(t,e=jc){let n=t.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi,"Bearer [redacted]").replace(/\b(?:sk|rk|pk)-[A-Za-z0-9_-]{12,}/gi,"[redacted-secret]").replace(new RegExp(`"(${ih})"\\s*:\\s*"(?:\\\\.|[^"\\\\])*"`,"gi"),'"$1":"[redacted]"'),r=Math.max(0,e);if(n.length<=r)return n;let o=n.length-r;return`${n.slice(0,r)}\u2026[truncated ${o} bytes]`}function DO(t,e){return t.split(`
|
|
124
124
|
`).map(n=>Je(n)).filter(Boolean).join(`
|
|
125
|
-
`).slice(0,e)}function En(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:Je(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"?
|
|
126
|
-
`):""}function en(t,e){let n=t?.req?.sessionId||
|
|
127
|
-
`);return s.trim()?
|
|
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 tw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function zc(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=tw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var KO=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function Wc(t){let e={};return t&&t.forEach((n,r)=>{KO.has(r.toLowerCase())||(e[r]=n)}),e}var VO=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),YO=["anthropic-ratelimit-","x-ratelimit-"];function ah(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();!(VO.has(s)||YO.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function nw(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=tw(n,i);a&&delete n[a],n[i]=o}return n["x-api-key"]?delete n.Authorization:!n.Authorization&&e&&(n.Authorization=`Bearer ${e}`),Object.fromEntries(Object.entries(n).filter(r=>typeof r[1]=="string"))}import{createHash as XO}from"crypto";var QO=512,ZO=16,eP=4,_o=new Map;function cw(t){let e=JSON.stringify(ch(t))??"";return{hash:XO("sha256").update(e).digest("hex").slice(0,ZO),approxTokens:Math.ceil(e.length/eP)}}function uw(t){return cw(t).hash}function ch(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ch);let e={};for(let n of Object.keys(t).sort())e[n]=ch(t[n]);return e}function lw(t){if(!t||typeof t!="object")return!1;let e=t.cache_control;return!!(e&&typeof e=="object"&&e.type==="ephemeral")}function dw(t){return!!(t&&typeof t=="object"&&t.prompt_cache_breakpoint)}function uh(t){if(!t||typeof t!="object")return 0;let e=0;if((lw(t)||dw(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=uh(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=uh(n));return e}function zi(t,e,n){if(!(!t||typeof t!="object")){if((lw(t)||dw(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>zi(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&zi(o,`${e}.${r}`,n)}}function rw(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 ow(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 tP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function lh(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)lh(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&tP(o)?e.add(String(o)):o&&typeof o=="object"&&lh(o,e,n+1)}}function Gc(t,e,n){let r=e,{hash:o,approxTokens:s}=cw(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:uh(e),...ow(r)?{reasoningId:ow(r)}:{}}}function nP(t,e){for(_o.has(t)&&_o.delete(t),_o.set(t,e);_o.size>QO;){let n=_o.keys().next().value;if(n===void 0)break;_o.delete(n)}}function rP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=Gc("system",t.system,{type:"system"});o=p.hash,n.push(p),zi(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=Gc("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=Gc("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),zi(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(Gc(g,p)),zi(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=rw(p.content)||rw(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 lh(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 sw(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 iw(t){return t?uw(t):""}function aw(t){return t.reduce((e,n)=>e+n.approxTokens,0)}function oP(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=iw(e.affinity)!==iw(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),C=e.segments,_=n.segments,k=Math.min(C.length,_.length),b=0;for(;b<k&&C[b].path===_[b].path&&C[b].hash===_[b].hash;)b+=1;let A=b===C.length&&_.length>=C.length,w="none",E,x,O,q;b<k?(w="modified",E=_[b]?.path||C[b]?.path,q={previous:sw(C[b]),current:sw(_[b])}):_.length>C.length?(w="appended",x=_.slice(b).map(U=>U.path)):_.length<C.length&&(w="removed",O=C.slice(b).map(U=>U.path),E=C[b]?.path),w==="none"&&(a||u||d||f||g)&&(w="modified"),E||(a?E="prompt_cache_key":u?E="affinity":f?E="model":d?E="lastAssistantBlockOrder":g&&(E="breakpointPaths"));let V=w==="modified"||w==="removed"?aw(C.slice(b)):0;return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!1,prefixIntact:A&&!a&&!u&&!f,change:w,unchangedPrefixCount:b,previousSegmentCount:C.length,currentSegmentCount:_.length,unchangedPrefixApproxTokens:aw(_.slice(0,b)),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 sP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${uw([t.systemHash||"",t.toolsHash||"",e?.hash||""])}`}function iP(t,e){return typeof t=="string"&&t?{id:t,source:"session"}:e.prompt_cache_key?{id:e.prompt_cache_key,source:"cache_key"}:{id:sP(e),source:"fingerprint"}}function fw(t,e,n,r){let o=rP(e,n);if(!o)return null;let s=r?.stage??"wire",{id:i,source:a}=iP(t,o),u=[s,r?.provider||"-",r?.model||o.model||"-",i].join("|"),d=_o.get(u),f=oP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&nP(u,o),f}function dh(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function fh(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 pw(t,e){let n=Wc(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function aP(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function Jc(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??jc,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:Zp(e,o)}),n!==void 0&&r.debug({...s,response:Zo(n),tppe:"Original Response"})}function At(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function hw(t,e){if(!e||typeof e!="object")return t;let n=e,r=[n.usage,n.message?.usage,n.response?.usage,n.usageMetadata].filter(s=>s&&typeof s=="object"),o=t;for(let s of r){let i=$t($t(At(s.cache_read_input_tokens),At(s.prompt_tokens_details?.cached_tokens)),$t($t(At(s.input_tokens_details?.cached_tokens),At(s.cachedContentTokenCount)),At(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||At(s.cache_read_input_tokens)!==void 0||At(s.cache_creation_input_tokens)!==void 0,promptTokens:$t(o.promptTokens,$t($t(At(s.input_tokens),At(s.prompt_tokens)),At(s.promptTokenCount))),cachedTokens:$t(o.cachedTokens,i),cacheWriteTokens:$t(o.cacheWriteTokens,At(s.cache_creation_input_tokens)),outputTokens:$t(o.outputTokens,$t($t(At(s.output_tokens),At(s.completion_tokens)),At(s.candidatesTokenCount)))}}return o}function cP(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 ph(t,e){if(!fh(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?dh(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:cP(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 uP(t,e){(async()=>{let r=t.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader(),o={cachedExcludedFromPrompt:!1},s=()=>new Promise(i=>setImmediate(i));try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(!a||typeof a!="object")continue;let u=a;if(u.data==null)continue;if(typeof u.data=="object"&&u.data.type==="done"){Jc(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);Jc(e,f),await s();continue}o=hw(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}Jc(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}ph(e,o)}})()}async function lP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return Jc(e,n,r),ph(e,hw({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:pw(t.headers,"application/json")})}async function gw(t,e){if(!fh(e.logger)||!t.body)return t;let n=aP(t);if(n.includes("application/json"))try{return await lP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return ph(e,{cachedExcludedFromPrompt:!1}),t;try{let r=dP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:pw(t.headers,"text/event-stream")})}catch{return t}}function dP(t,e){let n=new TransformStream(void 0,{highWaterMark:1/0},{highWaterMark:1}),r=n.writable.getWriter();uP(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 Wi(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function fP(t){return Array.isArray(t)?t.reduce((e,n)=>e+Wi(n),0):0}function pP(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 hP(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=Wi(i);else t.system&&typeof t.system=="object"&&(e+=Wi(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=Wi(i),n+=fP(i.content),i.role==="assistant"&&(r=pP(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=Wi(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 hh(t,e){if(!fh(e.logger))return null;let n=hP(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=fw(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=dh(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var gP=new TextEncoder().encode(`: keepalive
|
|
125
|
+
`).slice(0,e)}function En(t){let e=t,n=typeof e?.message=="string"?e.message:typeof t=="string"?t:String(t),r=typeof e?.cause?.message=="string"?e.cause.message:typeof e?.cause=="string"?e.cause:void 0;return{message:Je(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"?DO(e.stack,4e3):void 0,cause:r?Je(r):void 0}}var OO=/^(?:authorization|x-api-key|api-key|cookie|set-cookie)$|token|secret|password|passwd/i;function PO(t){return OO.test(t)}function IO(t){if(t==null)return;if(Array.isArray(t)){let n=t.filter(r=>r!=null&&String(r).length>0).map(r=>String(r));return n.length?n.join(", "):void 0}let e=String(t);return e.length?e:void 0}function sh(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){let s=IO(o);if(s!=null){if(PO(r)){e[r]="[redacted]";continue}e[r]=s}}return e}function FO(t,e){let n=sh(t),r=sh(e),o=new Map(Object.entries(n).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),s=new Map(Object.entries(r).map(([f,p])=>[f.toLowerCase(),{key:f,value:p}])),i={},a={},u={},d=0;for(let[f,{key:p,value:h}]of o){let g=s.get(f);if(!g){i[p]=h;continue}g.value===h?d+=1:u[p]={from:h,to:g.value}}for(let[f,{key:p,value:h}]of s)o.has(f)||(a[p]=h);return{onlyInLeft:i,onlyInRight:a,changed:u,sameCount:d}}var St="client disconnected";function uh(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 VC(t,e){let n=new AbortController,r=e?.raw,o=!1,s=(a=St)=>{n.signal.aborted||n.abort(a)},i=()=>{if(!o&&(o=!0,!!r)){if(ch(r)){s(`${St} (already destroyed)`);return}r.on("close",()=>{!r.writableEnded&&ch(r)&&s(`${St} (response close)`)}),r.on("error",a=>{(a?.code==="EPIPE"||a?.code==="ECONNRESET"||a?.code==="ERR_STREAM_PREMATURE_CLOSE"||Xe(a))&&s(`${St} (response error)`)})}};return{signal:n.signal,arm:i}}function NO(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 MO(t){let e=Math.min(10,Math.max(0,t));return Math.min(3e4,1e3*2**e)}function lh(t,e){let n=NO(e);return n!==void 0&&n>0?n:MO(t)}function YC(t,e){if(!t)return;let n=e==="subagent"?t.subagent??t.default:t[e];return Array.isArray(n)?n:void 0}var JC=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 XC(t){let e=t;if(!e)return!1;if(e.name==="TimeoutError"||e.code==="TIMEOUT_ERR"||e.code===23||e.cause&&(e.cause.name==="TimeoutError"||e.cause.code==="TIMEOUT_ERR"||e.cause.code===23))return!0;let n=String(e.message||"");return/aborted due to timeout|operation was aborted due to timeout/i.test(n)}function vn(t=St){let e=typeof t=="string"&&t?t:t instanceof Error&&t.message?t.message:St;return Object.assign(new Error(e),{name:"AbortError",code:"ABORT_ERR",reason:t})}function KC(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 Xe(t){if(t==null||t===!1)return!1;if(typeof t=="string")return t.startsWith(St)||KC(t);let e=t;if(XC(e))return!1;let n=e.reason??e.cause;if(typeof n=="string"&&n.startsWith(St)||typeof e.message=="string"&&e.message.startsWith(St)||e.name==="AbortError"||e.code==="ABORT_ERR"||e.code==="ERR_STREAM_PREMATURE_CLOSE")return!0;let r=String(e.message||"");return KC(r)}function ch(t){if(!t||t.destroyed)return!0;let e=t.socket;return e?e.destroyed?!0:e.readable===!1&&e.writable===!1:!1}function QC(t){return ch(t.raw)}function mo(t){if(!t||Xe(t))return!1;if(XC(t))return!0;let e=t;if(e.code==="provider_network_error"||typeof e.code=="string"&&JC.has(e.code)||e.cause?.code&&JC.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 BO(t){return typeof t!="number"||!Number.isFinite(t)?!1:t===408||t===409||t===425||t===429?!0:t>=500&&t<=599}function dh(t){let e=t;if(!e||Xe(e))return!1;if(mo(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?BO(n):e.code==="provider_response_error"}function qi(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(Je(t)||t);return s.statusCode=e,s.code=n,s.type=r,o&&(s.headers=o),s}async function ZC(t,e,n){if(Xe(t)||n.raw.destroyed||n.sent)return e.log.debug(En(t),"request aborted or already closed"),!n.sent&&!n.raw.destroyed&&!n.raw.headersSent?(n.type("application/json"),n.code(499).send({error:{message:"Client closed request",type:"api_error",code:"client_aborted"}})):void 0;e.log.error(En(t),"request error");let r=t.statusCode||500,o=Je(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=qi(a,o,r,s,i).body),t.headers&&n.headers(t.headers),n.type("application/json"),n.code(r).send(u)}import{Readable as E1}from"stream";import{ProxyAgent as UO}from"undici";function jO(t){return t.trim().toLowerCase().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"")}function LO(t){return/^\d+\.\d+\.\d+\.\d+$/.test(t)}function ew(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 $O(t,e){let[n,r]=e.split("/"),o=parseInt(r,10);if(Number.isNaN(o)||o<0||o>32)return!1;let s=ew(t),i=ew(n);if(s===null||i===null)return!1;let a=o===0?0:-1<<32-o>>>0;return(s&a)===(i&a)}function qO(t){let e;try{e=typeof t=="string"?new URL(t):t}catch{return!0}let n=jO(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=HO(i);if(a.startsWith(".")){if(n.endsWith(a)||n===a.slice(1))return!0;continue}if(a.includes("/")&&LO(n)){if($O(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 HO(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 es(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&&!qO(d)&&(u.dispatcher=new UO(new URL(n.httpsProxy).toString()));try{return await fetch(d,u)}catch(p){if(Xe(p))throw typeof p=="string"?vn(p):p;if(n.signal?.aborted&&Xe(n.signal.reason??St))throw vn(n.signal.reason??p);if(mo(p)){let h=J(p?.message||"Provider network error",502,"provider_network_error");throw h.cause=p,h}throw p}}var fh;function zO(t){fh=t}function tw(){if(fh)try{return fh()}catch{return}}var nw="1.0.62";import{createHash as GO}from"crypto";var ph={type:"ephemeral"};function Ke(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 Ve(t){return Array.isArray(t)?t.map(e=>{if(!e.cache_control)return e;let{cache_control:n,...r}=e;return r}):t}function rw(t){return`ccr_${GO("sha256").update(t).digest("hex").slice(0,48)}`}function JO(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 KO(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e?.type==="text"&&typeof e.text=="string"?e.text:"").filter(Boolean).join(`
|
|
126
|
+
`):""}function en(t,e){let n=t?.req?.sessionId||JO(e?.metadata?.user_id);if(typeof n=="string"&&n)return rw(n);let r=(e.messages||[]).find(i=>i.role==="system"||i.role==="user"),o=r?KO(r.content):"",s=[e.model||"",o].join(`
|
|
127
|
+
`);return s.trim()?rw(s):void 0}function Lc(t,e={}){let n=e.maxBreakpoints??4,r=JSON.parse(JSON.stringify(t)),o=[],s=d=>{d&&typeof d=="object"&&d.cache_control&&o.push(d)};(Array.isArray(r.tools)?r.tools:[]).forEach(s),Array.isArray(r.system)?r.system.forEach(s):s(r.system),(Array.isArray(r.messages)?r.messages:[]).forEach(d=>{s(d),Array.isArray(d?.content)&&d.content.forEach(s)});let i=!!r.cache_control,a=Math.max(0,n-(i?1:0));if(o.length>a)for(let d of o.slice(0,o.length-a))delete d.cache_control;let u=Math.min(o.length,a);if(!i&&u<n){let d=o[o.length-1]?.cache_control;r.cache_control=d?.ttl?{type:"ephemeral",ttl:d.ttl}:ph}return r}function yo(t){let e=Ke(t.messages||[]),n=Ve(t.tools);for(let r=e.length-1;r>=0;r-=1){let o=e[r];if(typeof o.content=="string"&&o.content){o.content=[{type:"text",text:o.content,cache_control:ph}];break}if(Array.isArray(o.content))for(let s=o.content.length-1;s>=0;s-=1){let i=o.content[s];if(i?.type==="text"&&i.text)return o.content[s]={...i,cache_control:ph},{...t,messages:e,...n?{tools:n}:{}}}}return{...t,messages:e,...n?{tools:n}:{}}}function $c(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 ow(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 sw(t){return t?.type==="text"||t?.type==="image_url"||t?.type==="input_audio"||t?.type==="file"||t?.type==="refusal"}function VO(t){for(let e=t.length-1;e>=0;e-=1)if(sw(t[e]))return e;return-1}function Hi(t,e,n){let r={...t,messages:(t.messages||[]).map(s=>({...s,content:Array.isArray(s.content)?s.content.map(i=>({...i})):s.content})),tools:Array.isArray(t.tools)?t.tools.map(s=>s?.function?{...s,function:{...s.function,parameters:{...s.function.parameters}}}:{...s}):t.tools},o=en(n,t);if(o&&!r.prompt_cache_key&&(r.prompt_cache_key=o),ow(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=VO(i.content);u>=0&&s.push({messageIndex:a,contentIndex:u})}}Array.isArray(i.content)&&i.content.forEach((u,d)=>{u?.cache_control&&sw(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=Ke(r.messages),r.tools=Ve(r.tools),r}function qc(t,e){return ow(e)?t?.prompt_cache_breakpoint?{prompt_cache_breakpoint:t.prompt_cache_breakpoint}:{}:{}}function YO(t){return String(t?.name||"").trim().toLowerCase()}function XO(t){let e=t?.baseUrl||t?.api_base_url||"";try{return new URL(e).hostname.toLowerCase()}catch{return String(e).toLowerCase()}}function hh(t,e){let n={...t,messages:Ke(t.messages||[]),tools:Ve(t.tools)},r=en(e,t);return r&&(n.prompt_cache_key=r),n}function Hc(t,e,n){let r=YO(e),o=XO(e);return r==="openai"||r==="azure-openai"||o==="api.openai.com"||o.endsWith(".openai.azure.com")?Hi(t,e,n):r==="qwen"||r==="qwen-auth"||o.includes("dashscope")||o.endsWith(".aliyuncs.com")||o==="qwen.aikit.club"?yo(t):r==="mistral"||r==="cerebras"||o==="api.mistral.ai"||o==="api.cerebras.ai"?hh(t,n):{...t,messages:Ke(t.messages||[]),tools:Ve(t.tools)}}function Dt(t){if(typeof t!="string")return;let e=t.trim().toLowerCase();return e||void 0}function Ot(t,e){return e?.type==="disabled"||t?.enabled===!1||Dt(t?.effort)==="none"}function ts(t,e){let n=Dt(t);if(!(!n&&e===void 0))return{...n?{effort:n}:{},enabled:n==="none"?!1:e??!0}}function zc(t){if(!t.reasoning)return t;let e=Ot(t.reasoning,t.thinking)?"none":Dt(t.reasoning.effort);return e&&(t.reasoning_effort=e),delete t.reasoning,t}function iw(t){let e=Dt(t);if(!(!e||e==="none"))return e==="minimal"?"low":e==="ultra"?"max":e}var Tn=class extends TransformStream{buffer="";currentEvent={};constructor(){super({transform:(e,n)=>{this.buffer+=e;let r=this.buffer.split(`
|
|
128
|
+
`);this.buffer=r.pop()||"";for(let o of r){let s=this.processLine(o);s&&n.enqueue(s)}},flush:e=>{if(this.buffer.trim()){let n=[];this.processLine(this.buffer.trim(),n),n.forEach(r=>e.enqueue(r))}Object.keys(this.currentEvent).length>0&&e.enqueue(this.currentEvent)}})}processLine(e,n){if(!e.trim()){if(Object.keys(this.currentEvent).length>0){let r={...this.currentEvent};return this.currentEvent={},n?(n.push(r),null):r}return null}if(e.startsWith("event:"))this.currentEvent.event=e.slice(6).trim();else if(e.startsWith("data:")){let r=e.slice(5).trim();if(r==="[DONE]")this.currentEvent.data={type:"done"};else try{this.currentEvent.data=JSON.parse(r)}catch{this.currentEvent.data={raw:r,error:"JSON parse failed"}}}else e.startsWith("id:")?this.currentEvent.id=e.slice(3).trim():e.startsWith("retry:")&&(this.currentEvent.retry=parseInt(e.slice(6).trim()));return null}};function aw(t,e){let n=e.toLowerCase();return Object.keys(t).find(r=>r.toLowerCase()===n)}function Wc(t,e){let n={...t||{}};if(!e)return n;for(let[r,o]of Object.entries(e)){let s=aw(n,r);s&&delete n[s],o!==void 0&&o!=="undefined"&&(n[r]=o)}return n}var QO=new Set(["content-length","content-encoding","transfer-encoding","connection","content-type","keep-alive"]);function Gc(t){let e={};return t&&t.forEach((n,r)=>{QO.has(r.toLowerCase())||(e[r]=n)}),e}var ZO=new Set(["retry-after","request-id","x-request-id","openai-request-id"]),eP=["anthropic-ratelimit-","x-ratelimit-"];function gh(t){let e={};if(!t)return e;let n=typeof t.forEach=="function"&&typeof t.entries=="function"?Array.from(t.entries()):Object.entries(t);for(let[r,o]of n){if(typeof o!="string"||!o)continue;let s=r.toLowerCase();!(ZO.has(s)||eP.some(a=>s.startsWith(a)))||e[s]!==void 0||(e[s]=o)}return e}function cw(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=aw(n,i);a&&delete n[a],n[i]=o}return n["x-api-key"]?delete n.Authorization:!n.Authorization&&e&&(n.Authorization=`Bearer ${e}`),Object.fromEntries(Object.entries(n).filter(r=>typeof r[1]=="string"))}import{createHash as tP}from"crypto";var nP=512,rP=16,oP=4,_o=new Map;function hw(t){let e=JSON.stringify(mh(t))??"";return{hash:tP("sha256").update(e).digest("hex").slice(0,rP),approxTokens:Math.ceil(e.length/oP)}}function gw(t){return hw(t).hash}function mh(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(mh);let e={};for(let n of Object.keys(t).sort())e[n]=mh(t[n]);return e}function mw(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 yh(t){if(!t||typeof t!="object")return 0;let e=0;if((mw(t)||yw(t))&&(e+=1),Array.isArray(t)){for(let n of t)e+=yh(n);return e}for(let n of Object.values(t))n&&typeof n=="object"&&(e+=yh(n));return e}function zi(t,e,n){if(!(!t||typeof t!="object")){if((mw(t)||yw(t))&&n.push(e),Array.isArray(t)){t.forEach((r,o)=>zi(r,`${e}[${o}]`,n));return}for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&zi(o,`${e}.${r}`,n)}}function uw(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 lw(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 sP(t){return typeof t=="string"&&/\d{12,}/.test(t)}function _h(t,e,n=0){if(!(!t||typeof t!="object"||n>8)){if(Array.isArray(t)){for(let r of t)_h(r,e,n+1);return}for(let[r,o]of Object.entries(t))(r==="id"||r==="call_id")&&sP(o)?e.add(String(o)):o&&typeof o=="object"&&_h(o,e,n+1)}}function Jc(t,e,n){let r=e,{hash:o,approxTokens:s}=hw(e);return{path:t,...n?.role?{role:n.role}:{},...n?.type?{type:n.type}:{},...typeof r?.role=="string"&&!n?.role?{role:r.role}:{},...typeof r?.type=="string"&&!n?.type?{type:r.type}:{},hash:o,approxTokens:s,breakpoints:yh(e),...lw(r)?{reasoningId:lw(r)}:{}}}function iP(t,e){for(_o.has(t)&&_o.delete(t),_o.set(t,e);_o.size>nP;){let n=_o.keys().next().value;if(n===void 0)break;_o.delete(n)}}function aP(t,e){if(!t||typeof t!="object")return null;let n=[],r=[],o,s;if(t.system!=null){let p=Jc("system",t.system,{type:"system"});o=p.hash,n.push(p),zi(t.system,"system",r)}else if(typeof t.instructions=="string"&&t.instructions){let p=Jc("instructions",t.instructions,{type:"instructions"});o=p.hash,n.push(p)}if(Array.isArray(t.tools)){let p=Jc("tools",t.tools,{type:"tools"});s=p.hash,n.push(p),zi(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(Jc(g,p)),zi(p,g,r),(p?.role==="assistant"||p?.role==="model")&&(a=uw(p.content)||uw(p.parts)||a)});let u=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:typeof t.session_id=="string"&&t.session_id?t.session_id:void 0,d=e?Object.fromEntries(Object.entries(e).filter(([,p])=>typeof p=="string"&&p)):void 0;if(n.length===0&&!u&&!(d&&Object.keys(d).length))return null;let f=new Set;return _h(i?.items,f),{createdAt:Date.now(),...typeof t.model=="string"?{model:t.model}:{},...u?{prompt_cache_key:u}:{},...typeof t.session_id=="string"?{session_id:t.session_id}:{},...d&&Object.keys(d).length?{affinity:d}:{},...a?{lastAssistantBlockOrder:a}:{},breakpointPaths:r,...o?{systemHash:o}:{},...s?{toolsHash:s}:{},approxTokens:n.reduce((p,h)=>p+h.approxTokens,0),unstableIds:[...f],segments:n}}function dw(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 fw(t){return t?gw(t):""}function pw(t){return t.reduce((e,n)=>e+n.approxTokens,0)}function cP(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=fw(e.affinity)!==fw(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),C=e.segments,y=n.segments,k=Math.min(C.length,y.length),b=0;for(;b<k&&C[b].path===y[b].path&&C[b].hash===y[b].hash;)b+=1;let A=b===C.length&&y.length>=C.length,w="none",E,x,O,q;b<k?(w="modified",E=y[b]?.path||C[b]?.path,q={previous:dw(C[b]),current:dw(y[b])}):y.length>C.length?(w="appended",x=y.slice(b).map(j=>j.path)):y.length<C.length&&(w="removed",O=C.slice(b).map(j=>j.path),E=C[b]?.path),w==="none"&&(a||u||d||f||g)&&(w="modified"),E||(a?E="prompt_cache_key":u?E="affinity":f?E="model":d?E="lastAssistantBlockOrder":g&&(E="breakpointPaths"));let V=w==="modified"||w==="removed"?pw(C.slice(b)):0;return{conversationId:t,conversationIdSource:s,stage:o,firstTurn:!1,prefixIntact:A&&!a&&!u&&!f,change:w,unchangedPrefixCount:b,previousSegmentCount:C.length,currentSegmentCount:y.length,unchangedPrefixApproxTokens:pw(y.slice(0,b)),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 uP(t){let e=t.segments.find(n=>/^(messages|input|contents)\[0\]$/.test(n.path));return`fp_${gw([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:uP(e),source:"fingerprint"}}function _w(t,e,n,r){let o=aP(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=_o.get(u),f=cP(i,d,o,{stage:s,conversationIdSource:a});return r?.commit!==!1&&iP(u,o),f}function bh(t,e){if(!(!e||e.firstTurn)){if(e.prefixIntact)return"none";if(!(!t||t.firstTurn))return t.prefixIntact?"wire":"client"}}function Ch(t){if(!t||typeof t.debug!="function")return!1;if(typeof t.isLevelEnabled=="function")try{return t.isLevelEnabled("debug")===!0}catch{return!1}let e=typeof t.level=="string"?t.level.toLowerCase():"";return e==="debug"||e==="trace"?!0:typeof t.levelVal=="number"?t.levelVal<=20:!("level"in t)&&!("levelVal"in t)}function bw(t,e){let n=Gc(t),r=t.get("Content-Type")||e;return r&&(n["Content-Type"]=r),n}function dP(t){return(t.headers.get("Content-Type")||"").toLowerCase()}function Kc(t,e,n){let r=t.logger;if(!r?.debug)return;let o=t.maxBytes??jc,s={reqId:t.reqId,provider:t.provider};r.debug({...s,type:"recieved data",data:ah(e,o)}),n!==void 0&&r.debug({...s,response:Zo(n),tppe:"Original Response"})}function At(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function $t(t,e){return t===void 0?e:e===void 0?t:Math.max(t,e)}function Cw(t,e){if(!e||typeof e!="object")return t;let n=e,r=[n.usage,n.message?.usage,n.response?.usage,n.usageMetadata].filter(s=>s&&typeof s=="object"),o=t;for(let s of r){let i=$t($t(At(s.cache_read_input_tokens),At(s.prompt_tokens_details?.cached_tokens)),$t($t(At(s.input_tokens_details?.cached_tokens),At(s.cachedContentTokenCount)),At(s.prompt_cache_hit_tokens)));o={cachedExcludedFromPrompt:o.cachedExcludedFromPrompt||At(s.cache_read_input_tokens)!==void 0||At(s.cache_creation_input_tokens)!==void 0,promptTokens:$t(o.promptTokens,$t($t(At(s.input_tokens),At(s.prompt_tokens)),At(s.promptTokenCount))),cachedTokens:$t(o.cachedTokens,i),cacheWriteTokens:$t(o.cacheWriteTokens,At(s.cache_creation_input_tokens)),outputTokens:$t(o.outputTokens,$t($t(At(s.output_tokens),At(s.completion_tokens)),At(s.candidatesTokenCount)))}}return o}function fP(t,e){return e===void 0?"unknown":!t||t.firstTurn?e>0?"warm-start":"cold":t.prefixIntact?e>0?"hit":"unexpected-miss":e>0?"partial":"expected-miss"}function wh(t,e){if(!Ch(t.logger))return;let n=t.cacheDiff,r=e.cachedTokens,o=e.promptTokens,s=o===void 0?void 0:e.cachedExcludedFromPrompt?o+(r||0)+(e.cacheWriteTokens||0):o,i=r===void 0||!s?void 0:Math.round(r/s*1e3)/1e3;if(r===void 0&&o===void 0&&!n)return;let a=n?bh(t.clientStageDiff,n):void 0;t.logger.debug({reqId:t.reqId,provider:t.provider,type:"cache outcome",verdict:fP(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 pP(t,e){(async()=>{let r=t.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader(),o={cachedExcludedFromPrompt:!1},s=()=>new Promise(i=>setImmediate(i));try{for(;;){let{done:i,value:a}=await r.read();if(i)break;if(!a||typeof a!="object")continue;let u=a;if(u.data==null)continue;if(typeof u.data=="object"&&u.data.type==="done"){Kc(e,"[DONE]"),await s();continue}if(typeof u.data=="object"&&u.data.raw!=null){let f=String(u.data.raw);Kc(e,f),await s();continue}o=Cw(o,u.data);let d;try{d=JSON.stringify(u.data)}catch{d=String(u.data)}Kc(e,d,u.data),await s()}}catch{}finally{try{r.releaseLock()}catch{}wh(e,o)}})()}async function hP(t,e){let n=await t.text(),r;try{r=JSON.parse(n)}catch{r=void 0}return Kc(e,n,r),wh(e,Cw({cachedExcludedFromPrompt:!1},r)),new Response(n,{status:t.status,statusText:t.statusText,headers:bw(t.headers,"application/json")})}async function ww(t,e){if(!Ch(e.logger)||!t.body)return t;let n=dP(t);if(n.includes("application/json"))try{return await hP(t,e)}catch{return t}if(!n.includes("text/event-stream"))return wh(e,{cachedExcludedFromPrompt:!1}),t;try{let r=gP(t.body,e);return new Response(r,{status:t.status,statusText:t.statusText,headers:bw(t.headers,"text/event-stream")})}catch{return t}}function gP(t,e){let n=new TransformStream(void 0,{highWaterMark:1/0},{highWaterMark:1}),r=n.writable.getWriter();pP(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 Wi(t){if(!t||typeof t!="object")return 0;let e=t.cache_control;return e&&typeof e=="object"&&e.type==="ephemeral"?1:0}function mP(t){return Array.isArray(t)?t.reduce((e,n)=>e+Wi(n),0):0}function yP(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 _P(t){if(!t||typeof t!="object")return null;let e=0;if(Array.isArray(t.system))for(let i of t.system)e+=Wi(i);else t.system&&typeof t.system=="object"&&(e+=Wi(t.system));let n=0,r;if(Array.isArray(t.messages))for(let i of t.messages)!i||typeof i!="object"||(n+=Wi(i),n+=mP(i.content),i.role==="assistant"&&(r=yP(i.content)));let o=0;if(Array.isArray(t.tools))for(let i of t.tools)o+=Wi(i);let s=typeof t.prompt_cache_key=="string"&&t.prompt_cache_key?t.prompt_cache_key:void 0;return e===0&&n===0&&o===0&&!s&&!r?null:{systemBreakpoints:e,messageBreakpoints:n,toolBreakpoints:o,...s?{prompt_cache_key:s}:{},...r?{lastAssistantBlockOrder:r}:{}}}function kh(t,e){if(!Ch(e.logger))return null;let n=_P(t);n&&e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache structure",stage:e.stage??"wire",...n});let r=e.responseStatus,o=_w(e.conversationId,t,e.cacheAffinity,{stage:e.stage??"wire",provider:e.provider,model:e.model,commit:r===void 0||r>=200&&r<300});if(!o)return null;let s=bh(e.clientStageDiff,o);return e.logger.debug({reqId:e.reqId,provider:e.provider,type:"cache prefix diff",...o,...s?{divergenceStage:s}:{}}),o}var bP=new TextEncoder().encode(`: keepalive
|
|
129
129
|
|
|
130
|
-
`);function
|
|
131
|
-
`)
|
|
130
|
+
`);function Sh(t,e){let n=e?.idleMs??1e4;if(!(n>0))return t;let r=null,o=null,s=!1,i=()=>{r&&(clearTimeout(r),r=null)};return new ReadableStream({async start(a){o=t.getReader();let u=()=>{i(),!s&&(r=setTimeout(()=>{if(r=null,!s){try{a.enqueue(bP)}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 Vc(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=CP(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 CP(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 Yc(t){return/^data:\s*\[DONE\]\s*$/.test(t)||/^\s*\[DONE\]\s*$/.test(t)}function Xc(t){t.push(""),t.push("data: [DONE]"),t.push("")}function Ah(t){let e=new TextDecoder,n=new TextEncoder,r="",o=!1,s=null,i=(a,u=!1)=>{if(o)return"";r+=a;let d=r.split(/\r?\n/);r=u?"":d.pop()||"";let f=[],p=h=>{if(!o)for(let g of Vc(h)){if(o)return;if(Yc(g)){Xc(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
|
+
`)}
|
|
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 kw(t,e,n){let r=await t(e);if(r.status!==401||typeof n!="function")return r;let o=await n();if(!o)return r;try{await r.body?.cancel()}catch{}return Object.assign(e,o),t(e)}import{RATE_LIMIT_CONFIG as ps}from"@caeliq/ccr-shared";var Sw=[{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"}],wP=["/v1/completions","/completions","/v1beta/interactions","/v1/interactions"],kP=/^\/preset\/[^/]+/;function SP(t){let e=t.split("?")[0]||"/";return e.length>1&&e.endsWith("/")?e.slice(0,-1):e||"/"}function AP(t){let e=t.match(kP);if(!e)return{suffix:t};let n=e[0];return{suffix:t.slice(n.length)||"/",presetPrefix:n}}function EP(t){return wP.some(e=>t===e)}function vP(t){for(let e of Sw){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 ar(t,e){if(t.toUpperCase()!=="POST")return null;let n=SP(e),{suffix:r,presetPrefix:o}=AP(n);if(EP(r))return null;let s=vP(r);return s?{...s,presetPrefix:o}:null}function TP(t,e){return ar(t,e)!==null}function Eh(){let t=[];for(let e of Sw){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 Aw(t,e){return{protocol:t.protocol,pathname:t.matchedPath,canonicalPath:t.canonicalPath,matchedPath:t.matchedPath,originalModel:e?.originalModel,stream:e?.stream??t.stream,scenarioType:e?.scenarioType,ownerTransformerName:t.ownerTransformerName}}import{createHash as PP}from"crypto";import{createHash as xP}from"crypto";var Ew=/^[a-zA-Z0-9_-]+$/,vw=/[^a-zA-Z0-9_-]+/g,Tw=256;function RP(t){return t.length>0&&t.length<=Tw&&Ew.test(t)}function vh(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===95;)e--;return t.slice(0,e)}function cr(t){if(typeof t!="string"||t.length===0)return;if(RP(t))return t;let e=vh(t.replace(vw,"_").slice(0,Tw));return e.length?e:void 0}var xw=64,Rw=20,DP=xw-Rw-1;function OP(t){return t.length>0&&t.length<=xw&&Ew.test(t)}function _t(t){if(typeof t!="string"||t.length===0)return;if(OP(t))return t;let e=vh(t.replace(vw,"_")),n=vh(e.slice(0,DP))||"call",r=xP("sha256").update(t,"utf8").digest("base64url").slice(0,Rw);return`${n}_${r}`}function ns(){return{forward:new Map,reverse:new Map}}function bo(t,e,n="client_to_unified"){if(typeof e!="string"||!e)return;if(n==="unified_to_client"){let i=_t(e)??e;if(t.reverse.has(i))return i}let r=t.forward.get(e);if(r)return r;let o=_t(e)??e,s=0;for(;t.reverse.has(o)&&t.reverse.get(o)!==e;)s+=1,o=_t(`${e}_${s}`)||`call_${s}`;return t.forward.set(e,o),t.reverse.set(o,e),o}function Qc(t,e=ns(),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(IP(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)UP(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=LP(t.tools,n),a=$P(t.tool_choice),u=t.reasoning&&typeof t.reasoning=="object"?{...ts(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 IP(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 FP(t){return t?.content===null||t?.content===void 0||t?.content===""}function Dw(t,e){let n=t[t.length-1];if(n&&n.role==="assistant"&&FP(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 NP(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 MP=/^rs_[A-Za-z0-9]+$/;function ur(t){return typeof t=="string"&&MP.test(t)}function rs(t){if(!(typeof t!="string"||!t)&&!ur(t))return t}function os(t){let e=typeof t?.signature=="string"?t.signature:"";if(!(!e||ur(e)))return e}function ss(t){if(!t||typeof t!="object")return;let e=NP(t),n=rs(t.encrypted_content),r=typeof t.id=="string"&&t.id?t.id:ur(t.encrypted_content)?t.encrypted_content:void 0;if(!(!e&&!n&&!r))return{content:e,...n?{encrypted_content:n}:{},...r?{id:r}:{}}}function Zc(t,e,n){typeof e!="string"||!e||typeof n!="string"||!n||t.set(e,(t.get(e)||"")+n)}function is(t,e){let n=ss(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 eu(t){if(!(!t||typeof t!="object")){if(t.type==="json_schema")return{type:"json_schema",name:t.json_schema?.name,schema:t.json_schema?.schema,...t.json_schema?.strict!==void 0?{strict:t.json_schema.strict}:{}};if(typeof t.type=="string"&&t.type)return{type:t.type}}}function Rn(t){if(!t||typeof t!="object")return;let e=typeof t.thinking?.content=="string"?t.thinking.content:"",n=typeof t.reasoning_content=="string"?t.reasoning_content:"",r=e||n,o=typeof t.thinking?.signature=="string"&&t.thinking.signature?t.thinking.signature:void 0,s=rs(t.thinking?.encrypted_content),i=typeof t.thinking?.id=="string"&&t.thinking.id||(ur(o)?o:void 0)||(ur(t.thinking?.encrypted_content)?t.thinking.encrypted_content:void 0),a=o&&!ur(o)?o:void 0;if(!(!r&&!a&&!s&&!i))return{content:r,...a?{signature:a}:{},...s?{encrypted_content:s}:{},...i?{id:i}:{}}}function as(t){let e=[],n=[];if(typeof t?.content=="string"&&t.content)e.push({text:t.content});else if(Array.isArray(t?.content))for(let r of t.content)!r||typeof r!="object"||((r.type==="text"||r.type==="output_text"||r.type==="input_text")&&r.text?e.push({text:r.text,...r.cache_control?{cache_control:r.cache_control}:{}}):(r.type==="image_url"||r.type==="input_image"||r.type==="output_image")&&n.push(r));return{thinking:Rn(t),texts:e,images:n,toolCalls:Array.isArray(t?.tool_calls)?t.tool_calls:[]}}function Gi(t){return t.texts.some(e=>e.text.length>0)}function cs(t,e){if(!t||typeof t!="object")return null;let n=typeof t.content=="string"?t.content:"",r=rs(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_${PP("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 BP(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 UP(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=ss(e);r&&BP(t,r);return}if(e.type==="function_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("function_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="function_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("function_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("function_call requires name",400,"invalid_function_call","invalid_request_error");Dw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:typeof e.arguments=="string"?e.arguments:JSON.stringify(e.arguments??{})}});return}if(e.type==="custom_tool_call_output"){if(typeof e.call_id!="string"||!e.call_id)throw J("custom_tool_call_output requires call_id",400,"invalid_call_id","invalid_request_error");t.push({role:"tool",tool_call_id:bo(n,e.call_id)??e.call_id,content:typeof e.output=="string"?e.output:JSON.stringify(e.output??"")});return}if(e.type==="custom_tool_call"){let r=e.call_id||e.id;if(typeof r!="string"||!r)throw J("custom_tool_call requires call_id",400,"invalid_call_id","invalid_request_error");if(typeof e.name!="string"||!e.name)throw J("custom_tool_call requires name",400,"invalid_function_call","invalid_request_error");if(typeof e.input!="string")throw J("custom_tool_call requires string input",400,"invalid_custom_tool_input","invalid_request_error");Dw(t,{id:bo(n,r)??r,type:"function",function:{name:e.name,arguments:JSON.stringify({[xn]:e.input})}});return}if(e.type==="message"||e.role){let r=e.role==="assistant"?"assistant":e.role==="system"||e.role==="developer"?"system":e.role==="user"?"user":void 0;if(!r)throw J(`Unsupported Responses message role '${e.role}'`,400,"unsupported_role","invalid_request_error");if(typeof e.content!="string"&&!Array.isArray(e.content))throw J("Responses message items require string or array content",400,"invalid_content","invalid_request_error");t.push({role:r,content:jP(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 jP(t){if(typeof t=="string")return t;if(!Array.isArray(t))return t==null?"":JSON.stringify(t);let e=[];for(let n of t){if(typeof n=="string"){e.push({type:"text",text:n});continue}if(!(!n||typeof n!="object"))if(n.type==="input_text"||n.type==="output_text"||n.type==="text")e.push({type:"text",text:String(n.text??"")});else if(n.type==="input_image"||n.type==="image_url"){if(n.file_id)throw J("Provider-bound file_id inputs are not supported",400,"unsupported_file_id","invalid_request_error");let r=n.image_url?.url||n.image_url||n.url;if(typeof r!="string"||!r)throw J("input_image requires image_url",400,"invalid_image","invalid_request_error");e.push({type:"image_url",image_url:{url:r,...n.detail?{detail:n.detail}:{}}})}else throw J(`Unsupported Responses content part '${n.type||"unknown"}'`,400,"unsupported_content_part","invalid_request_error")}return e.length===1&&e[0].type==="text"?e[0].text:e.length>0?e:""}var xn="input";function Ow(t){let e=t.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return e?e[2]:t}function tu(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 Pw(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 Iw(t,e){if(t!=="exec")return e;let n=e.match(/^apply_patch\s*<<\s*['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return n?`await tools.apply_patch(${JSON.stringify(n[2])});`:e}function Th(t,e,n){if(!Fw(n)||t!=="exec")return e;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.input=="string")return r.input=Iw(t,Pw(t,r.input)),JSON.stringify(r)}catch{}return e}function xh(t){if(!t)return"";try{let n=JSON.parse(t)?.[xn];if(typeof n=="string")return Ow(n)}catch{}return Ow(t)}function Fw(t){return t?.codexIsolateConventions!==!1}function Rh(t,e,n){let r=xh(e);return Fw(n)&&(r=Iw(t,Pw(t,r))),tu(r)}function LP(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
134
|
|
|
133
|
-
Note: this tool takes freeform text, not JSON. Call it with a single "${xn}" argument whose value is the complete text described above, as a plain string \u2014 do not add markdown code fences, a shell heredoc (e.g. "<<EOF"), or any other wrapping around it.`,parameters:{type:"object",properties:{[xn]:{type:"string",description:"The complete freeform text/code input for this tool, exactly as described in the tool description \u2014 as a plain string, with no markdown code fences or shell heredoc wrapping."}},required:[xn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function MP(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 Rw(t,e){let n=e?.callIdMap??ns(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=cs(Rn(s),t?.id?`rs_${t.id}`:void 0);a&&i.push(a);let u=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(f=>f?.type==="text").map(f=>f.text).join(""):"";if(u||!s.tool_calls?.length){let f=`msg_${t.id||Date.now()}`;i.push({type:"message",id:f,status:"completed",role:"assistant",content:[{type:"output_text",text:u||"",annotations:[],logprobs:s?.logprobs?.content||[]}]})}if(Array.isArray(s.tool_calls))for(let f of s.tool_calls){if(!f?.function)continue;let p=bo(n,f.id,"unified_to_client")??f.id,h=typeof f.function.arguments=="string"?f.function.arguments:JSON.stringify(f.function.arguments??{});if(e?.customToolNames?.has(f.function.name)){i.push({type:"custom_tool_call",id:p,call_id:p,name:f.function.name,input:Ch(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:Xc(_h(f.function.name,h,r)),status:"completed"})}let d=Mw(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 Dw(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??ns(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function Ow(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function Pw(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:Nw(t,"in_progress")}))}function Iw(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 Fw(t,e){if(!t||typeof t!="object")return[];if(e.finished)return[];let n=[],r=t.choices?.[0],o=r?.delta||{};!e.model&&t.model&&(e.model=t.model),t.id&&(e.responseId=t.id.startsWith("resp_")?t.id:`resp_${t.id}`),t.usage&&(e.usage=t.usage);let s=Rn(o);!e.textStarted&&e.toolCalls.size===0&&(typeof o.content=="string"||Array.isArray(o.tool_calls)||s?.content||s?.encrypted_content||s?.id||r?.finish_reason)&&Pw(e,n),s?.content&&(e.thinkingContent+=s.content);let i=rs(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:ur(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&&Iw(e,n),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let u=typeof a.index=="number"?a.index:0,d=e.toolCalls.get(u);if(!d){let f=bo(e.callIdMap,a.id||`call_${e.responseId}_${u}`,"unified_to_client")||`call_${u}`,p=a.function?.name||"";d={id:f,name:p,arguments:"",added:!1,outputIndex:e.nextOutputIndex++,emittedArgumentsLength:0,isCustom:e.customToolNames.has(p)},e.toolCalls.set(u,d)}if(a.id&&!d.added&&(d.id=bo(e.callIdMap,a.id,"unified_to_client")||d.id),a.function?.name&&(d.name=a.function.name,d.isCustom=e.customToolNames.has(d.name)),typeof a.function?.arguments=="string"&&(d.arguments+=a.function.arguments),!d.added&&d.name&&(d.added=!0,n.push({type:"response.output_item.added",output_index:d.outputIndex,item:d.isCustom?{type:"custom_tool_call",id:d.id,call_id:d.id,name:d.name,input:""}:{type:"function_call",id:d.id,call_id:d.id,name:d.name,arguments:"",status:"in_progress"}})),d.added&&d.arguments.length>d.emittedArgumentsLength){if(!d.isCustom){let f=d.arguments.slice(d.emittedArgumentsLength);n.push({type:"response.function_call_arguments.delta",item_id:d.id,output_index:d.outputIndex,delta:f})}d.emittedArgumentsLength=d.arguments.length}}return r?.finish_reason&&(e.finishReasonSeen=!0),Ow(e,n)}function wh(t,e){if(t.finished)return[];t.finished=!0;let n=[];Pw(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};Iw(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=Ch(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=Xc(_h(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=Nw(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),Ow(t,n)}function Nw(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:Ch(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:Xc(_h(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=cs({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:Mw(n)}}function Mw(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 Ji(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 Bw(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=_w(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function jw(t,e,n,r){if(typeof n.transformRequestOut=="function"){let o=await n.transformRequestOut(e,r);return o&&typeof o=="object"&&"body"in o&&o.body?o.body:o}if(t==="openai_chat_completions")return BP(e);if(t==="openai_responses")return Kc(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 BP(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 jP=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"]),UP=["proxy-","x-forwarded-","x-real-ip"];function Uw(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(jP.has(s)||UP.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 Lw(t,e,n,r){let o=t.transformer?.use;if(!Array.isArray(o)||o.length!==1||o[0]?.name!==e.name)return!1;let s=r?t.transformer?.[r]?.use:void 0;if(Array.isArray(s)&&s.length>0&&(s.length!==1||s[0]?.name!==e.name))return!1;let i={anthropic_messages:"Anthropic",openai_chat_completions:"OpenAI",openai_responses:"openai-responses"};return e.name===i[n]}import{get_encoding as LP}from"tiktoken";var kh=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())}},Sh=new kh(100);import{readFile as $w}from"fs/promises";import{opendir as $P,stat as qw}from"fs/promises";import{join as Eh,resolve as Qc,relative as Ww,basename as Zc}from"path";import{CLAUDE_PROJECTS_DIR as Ah,HOME_DIR as qP}from"@caeliq/ccr-shared";import{LRUCache as HP}from"lru-cache";var zP=LP("cl100k_base"),lr=t=>zP.encode(t,void 0,[]),Hw="<CCR-SUBAGENT-MODEL>",zw="</CCR-SUBAGENT-MODEL>",us="x-anthropic-billing-header",ls=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Gw(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 WP(t){let e=`${us}:`;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 ls(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 eu(t,e){let n=t.indexOf(Hw);if(n<0)return;let r=n+Hw.length,o=t.indexOf(zw,r);if(o<0)return;let s=Gw(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+zw.length)}`),s}function Jw(t,e){if(typeof t=="string")return eu(t,e);if(!(!ls(t)||typeof t.text!="string"))return eu(t.text,e)}function GP(t){let e=t?.system;if(typeof e=="string")return eu(e,n=>{t.system=n});if(Array.isArray(e))for(let n=0;n<e.length;n+=1){let r=e[n],o=Jw(r,s=>{typeof r=="string"?e[n]=s:ls(r)&&(r.text=s)});if(o)return o}}function JP(t){if(typeof t.content=="string")return eu(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=Jw(r,s=>{typeof r=="string"?e[n]=s:ls(r)&&(r.text=s)});if(o)return o}}function KP(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(!ls(r)||r.role!=="user")continue;let o=JP(r);if(o)return o}}function Kw(t){return GP(t)||KP(t)}function Vw(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:ls(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(us)?{present:!0,isSubagent:WP(r)}:{present:!1,isSubagent:!1}}var Yw=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=lr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=lr(s.text).length:s.type==="tool_use"?r+=lr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=lr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=lr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=lr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=lr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=lr(o.name+o.description).length),o.input_schema&&(r+=lr(JSON.stringify(o.input_schema)).length)}),r},VP=async(t,e)=>{if(t.sessionId){let n=await Qw(t.sessionId);if(n){let r=Qc(qP),o=Qc(r,Zc(n)),s=Ww(r,o);if(!s||s.startsWith(".."))return;let i=`${Zc(String(t.sessionId))}.json`,a=Eh(o,"config.json"),u=Eh(o,i);try{let d=JSON.parse(await $w(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await $w(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function Xw(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function YP(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function XP(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 QP(t){if(Ot(t?.reasoning,t?.thinking))return!1;if(t?.thinking)return!0;let e=t?.reasoning;return!!(e&&typeof e=="object"&&(e.enabled===!0||typeof e.effort=="string"&&e.effort.trim().length>0))}var ZP=async(t,e,n,r)=>{let o=await VP(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=Xw(t),u=typeof a?.model=="string"?a.model:String(a?.model??"");if(u.includes(",")){let[h,g]=u.split(","),C=s.find(k=>k.name.toLowerCase()===h.toLowerCase()),_=C?.models?.find(k=>k.toLowerCase()===g.toLowerCase());return C&&_?{model:`${C.name},${_}`,scenarioType:"default"}:{model:u,scenarioType:"default"}}let d=i?.longContextThreshold||6e4,f=r&&r.input_tokens>d&&e>2e4,p=e>d;if(YP(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 _=Gw(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(_)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${_}`),{model:_,scenarioType:"subagent"}}let C=n.get("Router");if(u?.includes("claude")&&u?.includes("haiku")&&C?.background)return t.log.info(`Using background model for ${u}`),{model:C.background,scenarioType:"background"}}return XP(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:QP(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"}},e1=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{}},vh=async(t,e,n)=>{let{configService:r,event:o}=n,s=Xw(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=e1(i);let a=Sh.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(","),C=n.tokenizerService?.getTokenizerConfigForModel(h,g),_;n.tokenizerService?_=(await n.tokenizerService.countTokens({messages:u,system:d,tools:f},C)).tokenCount:_=Yw(u,d,f),t.tokenCount=_;let k,b=r.get("CUSTOM_ROUTER_PATH");if(b)try{k=await re(b)(t,r.getAll(),{event:o})}catch(A){t.log.error(`failed to load custom router: ${A.message}`)}if(k)t.scenarioType="default";else{let A=await ZP(t,_,r,a);k=A.model,t.scenarioType=A.scenarioType}s.model=k,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=k)}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"}},Ur=new HP({max:1e3}),Qw=async(t,e)=>{if(Ur.has(t)){let n=Ur.get(t);return!n||n===""?null:n}try{if(!(await qw(Ah)).isDirectory())return Ur.set(t,""),null}catch(n){return n?.code==="ENOENT"?(Ur.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),Ur.set(t,""),null)}try{let n=await $P(Ah),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=Qc(Ah),s=`${Zc(String(t))}.jsonl`,i=r.map(async u=>{let d=Qc(o,Zc(u)),f=Ww(o,d);if(!f||f.startsWith(".."))return null;let p=Eh(d,s);try{return(await qw(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return Ur.set(t,u),u;return Ur.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),Ur.set(t,""),null}};import{readFile as d1}from"fs/promises";import{createHash as t1}from"crypto";var n1="59cf53e54c78",Th=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",r1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",Zw=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Co="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 s1(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 t1("sha256").update(n1+n+e).digest("hex").slice(0,3)}function a1(){return"00000"}function c1(t,e=Th,n=r1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=i1(s1(t),e);return`${us}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${a1()};`}function tu(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 nu(t,e){for(let r=t.length-1;r>=0;r--)t[r].text.startsWith(us)&&t.splice(r,1);let n=c1(e);n&&t.unshift({type:"text",text:n})}function ru(t){let e=t.findIndex(o=>o.text.startsWith(us)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Co){if(r?.text.startsWith(Co)&&r.text.length>Co.length){let o={type:"text",text:r.text.slice(Co.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Co},o);return}t.splice(n,0,{type:"text",text:Co})}}function ou(t,e){let n=t.findIndex(i=>i.text===Co);if(n<0||t.length<=n+1||!Array.isArray(e))return;let r=e.find(i=>i.role==="user");if(!r)return;let s=t.splice(n+1).map(i=>i.text).filter(i=>i.length>0).join(`
|
|
135
|
+
Note: this tool takes freeform text, not JSON. Call it with a single "${xn}" argument whose value is the complete text described above, as a plain string \u2014 do not add markdown code fences, a shell heredoc (e.g. "<<EOF"), or any other wrapping around it.`,parameters:{type:"object",properties:{[xn]:{type:"string",description:"The complete freeform text/code input for this tool, exactly as described in the tool description \u2014 as a plain string, with no markdown code fences or shell heredoc wrapping."}},required:[xn]}}}}return{type:"function",function:{name:o,description:n.description||n.function?.description,parameters:n.parameters||n.schema||n.function?.parameters||{type:"object",properties:{}}}}})}}function $P(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 Nw(t,e){let n=e?.callIdMap??ns(),r={codexIsolateConventions:e?.codexIsolateConventions},s=t?.choices?.[0]?.message||{},i=[],a=cs(Rn(s),t?.id?`rs_${t.id}`:void 0);a&&i.push(a);let u=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.filter(f=>f?.type==="text").map(f=>f.text).join(""):"";if(u||!s.tool_calls?.length){let f=`msg_${t.id||Date.now()}`;i.push({type:"message",id:f,status:"completed",role:"assistant",content:[{type:"output_text",text:u||"",annotations:[],logprobs:s?.logprobs?.content||[]}]})}if(Array.isArray(s.tool_calls))for(let f of s.tool_calls){if(!f?.function)continue;let p=bo(n,f.id,"unified_to_client")??f.id,h=typeof f.function.arguments=="string"?f.function.arguments:JSON.stringify(f.function.arguments??{});if(e?.customToolNames?.has(f.function.name)){i.push({type:"custom_tool_call",id:p,call_id:p,name:f.function.name,input:Rh(f.function.name,h,r)});continue}i.push({type:"function_call",id:p,call_id:p,name:f.function.name,arguments:tu(Th(f.function.name,h,r)),status:"completed"})}let d=qw(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 Mw(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??ns(),customToolNames:t?.customToolNames??new Set,thinkingContent:"",codexIsolateConventions:t?.codexIsolateConventions!==!1}}function Bw(t,e){return e.map(n=>({...n,sequence_number:t.sequenceNumber++}))}function Uw(t,e){t.created||(t.created=!0,e.push({type:"response.created",response:$w(t,"in_progress")}))}function jw(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 Lw(t,e){if(!t||typeof t!="object")return[];if(e.finished)return[];let n=[],r=t.choices?.[0],o=r?.delta||{};!e.model&&t.model&&(e.model=t.model),t.id&&(e.responseId=t.id.startsWith("resp_")?t.id:`resp_${t.id}`),t.usage&&(e.usage=t.usage);let s=Rn(o);!e.textStarted&&e.toolCalls.size===0&&(typeof o.content=="string"||Array.isArray(o.tool_calls)||s?.content||s?.encrypted_content||s?.id||r?.finish_reason)&&Uw(e,n),s?.content&&(e.thinkingContent+=s.content);let i=rs(s?.encrypted_content);if(i&&(e.thinkingEncryptedContent=i),typeof s?.id=="string"&&s.id?e.thinkingId=s.id:ur(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&&jw(e,n),Array.isArray(o.tool_calls))for(let a of o.tool_calls){let u=typeof a.index=="number"?a.index:0,d=e.toolCalls.get(u);if(!d){let f=bo(e.callIdMap,a.id||`call_${e.responseId}_${u}`,"unified_to_client")||`call_${u}`,p=a.function?.name||"";d={id:f,name:p,arguments:"",added:!1,outputIndex:e.nextOutputIndex++,emittedArgumentsLength:0,isCustom:e.customToolNames.has(p)},e.toolCalls.set(u,d)}if(a.id&&!d.added&&(d.id=bo(e.callIdMap,a.id,"unified_to_client")||d.id),a.function?.name&&(d.name=a.function.name,d.isCustom=e.customToolNames.has(d.name)),typeof a.function?.arguments=="string"&&(d.arguments+=a.function.arguments),!d.added&&d.name&&(d.added=!0,n.push({type:"response.output_item.added",output_index:d.outputIndex,item:d.isCustom?{type:"custom_tool_call",id:d.id,call_id:d.id,name:d.name,input:""}:{type:"function_call",id:d.id,call_id:d.id,name:d.name,arguments:"",status:"in_progress"}})),d.added&&d.arguments.length>d.emittedArgumentsLength){if(!d.isCustom){let f=d.arguments.slice(d.emittedArgumentsLength);n.push({type:"response.function_call_arguments.delta",item_id:d.id,output_index:d.outputIndex,delta:f})}d.emittedArgumentsLength=d.arguments.length}}return r?.finish_reason&&(e.finishReasonSeen=!0),Bw(e,n)}function Dh(t,e){if(t.finished)return[];t.finished=!0;let n=[];Uw(t,n);let r={codexIsolateConventions:t.codexIsolateConventions};jw(t,n);for(let s of t.toolCalls.values()){if(s.isCustom){let a=Rh(s.name,s.arguments,r);n.push({type:"response.custom_tool_call_input.delta",item_id:s.id,output_index:s.outputIndex,delta:a}),n.push({type:"response.custom_tool_call_input.done",item_id:s.id,output_index:s.outputIndex,input:a}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"custom_tool_call",id:s.id,call_id:s.id,name:s.name,input:a}});continue}let i=tu(Th(s.name,s.arguments,r));n.push({type:"response.function_call_arguments.done",item_id:s.id,output_index:s.outputIndex,name:s.name,arguments:i}),n.push({type:"response.output_item.done",output_index:s.outputIndex,item:{type:"function_call",id:s.id,call_id:s.id,name:s.name,arguments:i,status:"completed"}})}let o=$w(t,"completed",e||t.usage);return n.push({type:"response.completed",response:o}),Bw(t,n)}function $w(t,e,n){let r=[];for(let i of t.closedTextItems)r.push({index:i.outputIndex,item:{type:"message",id:i.id,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:i.content,annotations:[],logprobs:[]}]}});(t.textStarted||t.textContent)&&!t.closedTextItems.some(i=>i.id===t.textItemId)&&r.push({index:t.textOutputIndex??0,item:{type:"message",id:t.textItemId,status:e==="completed"?"completed":"in_progress",role:"assistant",content:[{type:"output_text",text:t.textContent,annotations:[],logprobs:[]}]}});for(let i of t.toolCalls.values()){let a={codexIsolateConventions:t.codexIsolateConventions};r.push({index:i.outputIndex,item:i.isCustom?{type:"custom_tool_call",id:i.id,call_id:i.id,name:i.name,input:Rh(i.name,i.arguments,a)}:{type:"function_call",id:i.id,call_id:i.id,name:i.name,arguments:tu(Th(i.name,i.arguments,a)),status:e==="completed"?"completed":"in_progress"}})}let o=r.sort((i,a)=>i.index-a.index).map(({item:i})=>i),s=cs({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:qw(n)}}function qw(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 Ji(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 Hw(t,e,n){let r=e&&typeof e=="object"?Ur(e):{},o=t.stream,s=typeof r.model=="string"?r.model:void 0;(t.protocol==="openai_chat_completions"||t.protocol==="openai_responses"||t.protocol==="anthropic_messages")&&(o=r.stream===!0);let i=Aw(t,{originalModel:s,stream:o});return{normalizationInput:r,context:i}}async function zw(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 qP(e);if(t==="openai_responses")return Qc(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 qP(t){if(!t||typeof t!="object")throw J("Invalid Chat Completions body",400,"invalid_body");if(!Array.isArray(t.messages))throw J("Chat Completions requires messages[]",400,"invalid_body","invalid_request_error");if(typeof t.model!="string"||!t.model)throw J("Chat Completions requires model",400,"invalid_body","invalid_request_error");return t}function Ur(t){return typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t))}var HP=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"]),zP=["proxy-","x-forwarded-","x-real-ip"];function Ww(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(HP.has(s)||zP.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 Gw(t,e,n,r){let o=t.transformer?.use;if(!Array.isArray(o)||o.length!==1||o[0]?.name!==e.name)return!1;let s=r?t.transformer?.[r]?.use:void 0;if(Array.isArray(s)&&s.length>0&&(s.length!==1||s[0]?.name!==e.name))return!1;let i={anthropic_messages:"Anthropic",openai_chat_completions:"OpenAI",openai_responses:"openai-responses"};return e.name===i[n]}import{get_encoding as WP}from"tiktoken";var Oh=class{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){if(!this.cache.has(e))return;let n=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,n),n}put(e,n){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(e,n)}values(){return Array.from(this.cache.values())}},Ph=new Oh(100);import{readFile as Jw}from"fs/promises";import{opendir as GP,stat as Kw}from"fs/promises";import{join as Fh,resolve as nu,relative as Xw,basename as ru}from"path";import{CLAUDE_PROJECTS_DIR as Ih,HOME_DIR as JP}from"@caeliq/ccr-shared";import{LRUCache as KP}from"lru-cache";var VP=WP("cl100k_base"),lr=t=>VP.encode(t,void 0,[]),Vw="<CCR-SUBAGENT-MODEL>",Yw="</CCR-SUBAGENT-MODEL>",us="x-anthropic-billing-header",ls=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Qw(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 YP(t){let e=`${us}:`;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 ls(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(Vw);if(n<0)return;let r=n+Vw.length,o=t.indexOf(Yw,r);if(o<0)return;let s=Qw(t.slice(r,o));if(s)return e(`${t.slice(0,n)}${t.slice(o+Yw.length)}`),s}function Zw(t,e){if(typeof t=="string")return ou(t,e);if(!(!ls(t)||typeof t.text!="string"))return ou(t.text,e)}function XP(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=Zw(r,s=>{typeof r=="string"?e[n]=s:ls(r)&&(r.text=s)});if(o)return o}}function QP(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=Zw(r,s=>{typeof r=="string"?e[n]=s:ls(r)&&(r.text=s)});if(o)return o}}function ZP(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(!ls(r)||r.role!=="user")continue;let o=QP(r);if(o)return o}}function ek(t){return XP(t)||ZP(t)}function tk(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:ls(n)&&n.type==="text"&&typeof n.text=="string"?n.text:void 0;return r?.startsWith(us)?{present:!0,isSubagent:YP(r)}:{present:!1,isSubagent:!1}}var nk=(t,e,n)=>{let r=0;return Array.isArray(t)&&t.forEach(o=>{typeof o.content=="string"?r+=lr(o.content).length:Array.isArray(o.content)&&o.content.forEach(s=>{s.type==="text"?r+=lr(s.text).length:s.type==="tool_use"?r+=lr(JSON.stringify(s.input)).length:s.type==="tool_result"&&(r+=lr(typeof s.content=="string"?s.content:JSON.stringify(s.content)).length)})}),typeof e=="string"?r+=lr(e).length:Array.isArray(e)&&e.forEach(o=>{o.type==="text"&&(typeof o.text=="string"?r+=lr(o.text).length:Array.isArray(o.text)&&o.text.forEach(s=>{r+=lr(s||"").length}))}),n&&n.forEach(o=>{o.description&&(r+=lr(o.name+o.description).length),o.input_schema&&(r+=lr(JSON.stringify(o.input_schema)).length)}),r},e1=async(t,e)=>{if(t.sessionId){let n=await ok(t.sessionId);if(n){let r=nu(JP),o=nu(r,ru(n)),s=Xw(r,o);if(!s||s.startsWith(".."))return;let i=`${ru(String(t.sessionId))}.json`,a=Fh(o,"config.json"),u=Fh(o,i);try{let d=JSON.parse(await Jw(u,"utf8"));if(d&&d.Router)return d.Router}catch{}try{let d=JSON.parse(await Jw(a,"utf8"));if(d&&d.Router)return d.Router}catch{}}}};function rk(t){return t.unifiedBody&&typeof t.unifiedBody=="object"?t.unifiedBody:t.body}function t1(t){return!t.clientProtocol||t.clientProtocol==="anthropic_messages"}function n1(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 r1(t){if(Ot(t?.reasoning,t?.thinking))return!1;if(t?.thinking)return!0;let e=t?.reasoning;return!!(e&&typeof e=="object"&&(e.enabled===!0||typeof e.effort=="string"&&e.effort.trim().length>0))}var o1=async(t,e,n,r)=>{let o=await e1(t,n),s=n.get("providers")||[],i=o||n.get("Router"),a=rk(t),u=typeof a?.model=="string"?a.model:String(a?.model??"");if(u.includes(",")){let[h,g]=u.split(","),C=s.find(k=>k.name.toLowerCase()===h.toLowerCase()),y=C?.models?.find(k=>k.toLowerCase()===g.toLowerCase());return C&&y?{model:`${C.name},${y}`,scenarioType:"default"}:{model:u,scenarioType:"default"}}let d=i?.longContextThreshold||6e4,f=r&&r.input_tokens>d&&e>2e4,p=e>d;if(t1(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 y=Qw(process.env.CLAUDE_CODE_SUBAGENT_MODEL);if(y)return t.log.info(`Using CLAUDE_CODE_SUBAGENT_MODEL for Claude Code subagent: ${y}`),{model:y,scenarioType:"subagent"}}let C=n.get("Router");if(u?.includes("claude")&&u?.includes("haiku")&&C?.background)return t.log.info(`Using background model for ${u}`),{model:C.background,scenarioType:"background"}}return n1(a?.tools)&&i?.webSearch?{model:i.webSearch,scenarioType:"webSearch"}:r1(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"}},s1=t=>{if(typeof t!="string"||!t)return;let e=t.split("_session_");if(e.length>1&&e[1])return e[1];try{let n=JSON.parse(t);if(n&&typeof n.session_id=="string"&&n.session_id)return n.session_id}catch{}},Nh=async(t,e,n)=>{let{configService:r,event:o}=n,s=rk(t),i=t.body?.metadata?.user_id??s?.metadata?.user_id;t.sessionId=s1(i);let a=Ph.get(t.sessionId),u=s.messages||[],d=s.system??[],f=s.tools||[];try{let p=typeof s.model=="string"?s.model:String(s.model??""),[h,g]=p.split(","),C=n.tokenizerService?.getTokenizerConfigForModel(h,g),y;n.tokenizerService?y=(await n.tokenizerService.countTokens({messages:u,system:d,tools:f},C)).tokenCount:y=nk(u,d,f),t.tokenCount=y;let k,b=r.get("CUSTOM_ROUTER_PATH");if(b)try{k=await re(b)(t,r.getAll(),{event:o})}catch(A){t.log.error(`failed to load custom router: ${A.message}`)}if(k)t.scenarioType="default";else{let A=await o1(t,y,r,a);k=A.model,t.scenarioType=A.scenarioType}s.model=k,t.unifiedBody&&typeof t.unifiedBody=="object"&&(t.unifiedBody.model=k)}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"}},jr=new KP({max:1e3}),ok=async(t,e)=>{if(jr.has(t)){let n=jr.get(t);return!n||n===""?null:n}try{if(!(await Kw(Ih)).isDirectory())return jr.set(t,""),null}catch(n){return n?.code==="ENOENT"?(jr.set(t,""),null):((e?.error??console.error)("Error checking Claude projects directory:",n),jr.set(t,""),null)}try{let n=await GP(Ih),r=[];for await(let u of n)u.isDirectory()&&r.push(u.name);let o=nu(Ih),s=`${ru(String(t))}.jsonl`,i=r.map(async u=>{let d=nu(o,ru(u)),f=Xw(o,d);if(!f||f.startsWith(".."))return null;let p=Fh(d,s);try{return(await Kw(p)).isFile()?u:null}catch{return null}}),a=await Promise.all(i);for(let u of a)if(u)return jr.set(t,u),u;return jr.set(t,""),null}catch(n){return(e?.error??console.error)("Error searching for project by session:",n),jr.set(t,""),null}};import{readFile as m1}from"fs/promises";import{createHash as i1}from"crypto";var a1="59cf53e54c78",Mh=process.env.ANTHROPIC_CLI_VERSION||"2.1.226",c1=process.env.CLAUDE_CODE_ENTRYPOINT??"unknown",sk=process.env.CLAUDE_CODE_ENTRYPOINT??"cli",Co="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 l1(t){let e=t?.find(n=>n.role==="user");return e?u1(e.content):""}function d1(t,e){let n=[4,7,20].map(r=>t[r]||"0").join("");return i1("sha256").update(a1+n+e).digest("hex").slice(0,3)}function f1(){return"00000"}function p1(t,e=Mh,n=c1){let r=process.env.CLAUDE_CODE_ATTRIBUTION_HEADER?.trim().toLowerCase();if(["0","false","no","off"].includes(r||""))return"";let o=d1(l1(t),e);return`${us}: cc_version=${e}.${o}; cc_entrypoint=${n}; cch=${f1()};`}function su(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(us)&&t.splice(r,1);let n=p1(e);n&&t.unshift({type:"text",text:n})}function au(t){let e=t.findIndex(o=>o.text.startsWith(us)),n=e>=0?e+1:0,r=t[n];if(r?.text!==Co){if(r?.text.startsWith(Co)&&r.text.length>Co.length){let o={type:"text",text:r.text.slice(Co.length)};r.cache_control!==void 0&&(o.cache_control=r.cache_control),t.splice(n,1,{type:"text",text:Co},o);return}t.splice(n,0,{type:"text",text:Co})}}function cu(t,e){let n=t.findIndex(i=>i.text===Co);if(n<0||t.length<=n+1||!Array.isArray(e))return;let r=e.find(i=>i.role==="user");if(!r)return;let s=t.splice(n+1).map(i=>i.text).filter(i=>i.length>0).join(`
|
|
134
136
|
|
|
135
137
|
`);s&&(typeof r.content=="string"?r.content=r.content?`${s}
|
|
136
138
|
|
|
137
|
-
${r.content}`:s:Array.isArray(r.content)?r.content.unshift({type:"text",text:s}):r.content=s)}function u1(t){return/^mcp_[A-Z]/.test(t)?t:`mcp_${t.charAt(0).toUpperCase()}${t.slice(1)}`}function l1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function su(t,e){let n=r=>{let o=u1(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 ds(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??l1(o))};for(let r of t?.choices??[]){for(let o of r?.message?.tool_calls??[])n(o);for(let o of r?.delta?.tool_calls??[])n(o)}}function wo(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n||o==null)continue;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a));return i.length?i.map(String).join(", "):void 0}return String(o)||void 0}}function f1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function p1(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 ek(t,e){let n=xh(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 xh(t,e){let n=wo(t,"user-agent")||"",r=wo(t,"anthropic-desktop-topbar"),s=(/^claude-cli\/[^\s()]+\s+\(([^)]*)\)$/i.exec(n)?.[1]||"").split(",").map(a=>a.trim().toLowerCase()),i=s.some(a=>["claude-desktop","claude-desktop-3p"].includes(a))&&s.some(a=>/^agent-sdk\/[^\s,]+$/.test(a));return{desktopMarker:r==="1",desktopUserAgent:/^Anthropic\/JS\s+/i.test(n),desktopAgentSdkUserAgent:i,cliUserAgent:/^claude-cli\//i.test(n),cliApp:["cli","cli-bg"].includes(wo(t,"x-app")||""),cliSession:!!wo(t,"x-claude-code-session-id"),stainlessPackage:!!wo(t,"x-stainless-package-version"),billingSystem:f1(e),identitySystem:p1(e)}}function iu(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 au(t){return t==="claude_desktop"||t==="claude_code"}async function cu(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=tu(t);nu(r,t.messages),ru(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 d1(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}ou(r,t.messages);let s=new Map;su(t,s),h1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function h1(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 g1={"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:[]}},tk=/\[1m\]$/i;function Dn(t){let e=t||"",n=tk.test(e);return{modelId:e.replace(tk,""),requestedOneMillion:n}}function m1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=Dn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function fs(t){let e=m1(t);if(e)return g1[e]}function Rh(t,e){return t?.capabilities.includes(e)??!1}function nk(t){return(t?.capabilities.length??0)>0}import{decodeClaudeModelAlias as y1}from"@caeliq/ccr-shared";async function ok(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||ar(t.method,s)||ar("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}=Bw(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=ek(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:xh(t.headers,d)},"classified Anthropic client"),await _1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await jw(i.protocol,d,r,p);h.model=rk(h.model,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"";let g=t;t.protocolContext=f,t.unifiedBody=h,t.originalClientBody=a;let C=n.configService.get("CUSTOM_ROUTER_PATH"),_=g.body;g.body=i.protocol==="anthropic_messages"&&C?a:h;try{await vh(g,e,{configService:n.configService,tokenizerService:n.tokenizerService})}finally{g.body=_??a}let k=typeof h.model=="string"?h.model:f.originalModel;h.model=rk(k,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 b=b1(h.model,i.protocol),A=Dn(b.modelName);b.modelName=A.modelId,f.requestedOneMillion=A.requestedOneMillion;let w=n.providerService.getProvider(b.providerName);w||Ki(i.protocol,`Provider '${b.providerName}' not found`,404,"provider_not_found"),h.model=b.modelName,g.provider=b.providerName,g.model=b.modelName;let E=jr(h),x=iu(w);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&au(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await cu(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:b.providerName,modelName:b.modelName}}async function _1(t,e){let n=Vw(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=Kw(t)}function b1(t,e){let n=typeof t=="string"?t.trim():"";n||Ki(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||Ki(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)&&Ki(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function rk(t,e,n){if(typeof t!="string")return t;let r=y1(t);if(!r)return t;let o=Dn(r).modelId;return e(o)||Ki(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function Ki(t,e,n,r,o="api_error"){let s=qi(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function uu(t,e,n,r){return n?Lw(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 Vi(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function ko(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function w1(t,e,n,r,o){let s=HC(t,e),i=s.signal;s.arm();let a;try{a=await ok(t,e,n,r,o)}catch(d){throw Xe(d)||i.aborted?typeof d=="string"?vn(d):vn(i.reason??d):d}let u=n.providerService.getProvider(a.providerName);if(!u)throw J(`Provider '${a.providerName}' not found`,404,"provider_not_found");t._preparedInbound=a;try{let d=uu(u,r,a.protocolContext,a.modelName)&&!ko(a.protocolContext),f=!ko(a.protocolContext)&&Vi(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);ik(t,n,u,h);let{requestBody:g,config:C,bypass:_}=await sk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),k=await ak(g,C,u,n,_,r,{req:t,signal:i,protocolContext:a.protocolContext}),b=await ck(g,k,u,r,_,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:_});return await uk(b,e,a.originalBody,i,a.protocolContext.stream)}catch(d){if(Xe(d))throw typeof d=="string"?vn(d):d;if(i.aborted)throw vn(i.reason??d);if(rh(d)){let f=await k1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw vn(i.reason??St)}throw d}}async function k1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=zC(a,i);if(!u?.length||s?.aborted||Xe(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:En(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=nh(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 th(f,s)}catch(p){if(Xe(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,[C,..._]=h.split(","),k=_.join(","),b=n.providerService.getProvider(C);if(!b){t.log.warn(`Fallback provider '${C}' not found, skipping`);continue}let A=iu(b),w=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:A,anthropicDestinationInScope:A!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&A!=="out_of_scope"&&au(g.protocolContext.anthropicClientKind||"other")),anthropicPolicyApplied:!1,anthropicSystemTransformed:!1,claudeAuthToolNameMap:new Map}:g?.protocolContext,E={...jr(g?.prePolicyUnifiedBody||g?.unifiedBody||t.unifiedBody||t.body),model:k};w?.anthropicDestinationInScope&&w.anthropicClientKind==="other"&&await cu(E,w,n.configService);let x={...t,provider:C,model:k,body:g?.originalBody??t.body,unifiedBody:E,protocolContext:w,clientProtocol:w?.protocol,scenarioType:i},O=uu(b,r,w,k)&&!ko(w),q=!ko(w)&&Vi(b,r,w),V=w?.anthropicNativeWire?g?.originalBody:g?.clientWireBody??g?.originalBody,U=w?.anthropicNativeWire||O||q?{...typeof V=="object"&&V?jr(V):{},model:k}:E;ik(x,n,b,U);let{requestBody:ee,config:z,bypass:te}=await sk(U,b,r,t.headers,{req:x,provider:b,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:w,skipClientNormalization:!0}),Q=await ak(ee,z,b,n,te,r,{req:x,signal:s,protocolContext:w}),_e=await ck(ee,Q,b,r,te,{req:x,signal:s,protocolContext:w});return t.log.info(`Fallback model ${h} succeeded`),await uk(_e,e,g?.originalBody??t.body,s,w?.stream)}catch(g){if(Xe(g))throw g;if(s?.aborted)throw vn(s.reason??St);if(!rh(g))throw t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed`),p<u.length-1){let _=nh(d,g?.headers?.["Retry-After"]??g?.headers?.["retry-after"]);if(d+=1,_>0){t.log.info(`Waiting ${_}ms before next fallback attempt`);try{await th(_,s)}catch(k){if(Xe(k)||s?.aborted)return null;throw k}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function sk(t,e,n,r,o){let s=t,i={},a=uu(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!ko(o?.protocolContext)),d=ko(o?.protocolContext),f=!d&&Vi(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Uw(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 C=g.config||{};i={...i,...C,headers:zc(i.headers,C.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 C=g.config||{};i={...i,...C,headers:zc(i.headers,C.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=Hc(s),s=qc(s,e,o)),{requestBody:s,config:i,bypass:u}}function ik(t,e,n,r){t&&(t._cachePrefixClientDiff=hh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function ak(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 k=>{let b=hh(t,{...a,stage:"wire",responseStatus:k?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheAffinity:{sessionId:e?.headers?.["session-id"],threadId:e?.headers?.["thread-id"],clientRequestId:e?.headers?.["x-client-request-id"]}});return gw(k,{...a,responseStatus:k?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheDiff:b})};if(e?.__providerResponse)return u(e.__providerResponse);let d=n.transformer?.use?.find(k=>typeof k?.auth=="function")||s;if((o||n.transformer?.passthrough)&&typeof d.auth=="function"){let k=await d.auth(t,n,i);if(k.body){t=k.body;let b=e.headers||{};k.config?.headers&&(b=zc(b,k.config.headers),delete b.host,delete k.config.headers),e={...e,...k.config,headers:b}}else t=k}let f=e.url||new URL(n.baseUrl),p=nw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},_=await mw(k=>es(f,t,{httpsProxy:r.configService.getHttpsProxy(),...g,headers:JSON.parse(JSON.stringify(k)),signal:i?.signal??g.signal},i,r.log),p,h);if(!_.ok){let k=await _.text(),b=Je(k)||k.slice(0,240),A;try{A=JSON.parse(k)}catch{A=void 0}let w=A&&typeof A=="object"?A.error:void 0,E=ah(_.headers),x=Object.keys(E).length>0?E:void 0;if(!x?.["retry-after"]&&_.status===429){let U=w?.details||A?.details;if(Array.isArray(U)){let ee=U.find(z=>z["@type"]==="type.googleapis.com/google.rpc.RetryInfo");if(ee?.retryDelay){let z=parseInt(ee.retryDelay,10);isNaN(z)||(x={...x||{},"retry-after":z.toString()})}}}let O=typeof w?.message=="string"?w.message:void 0,q=Je(O||k)||b;r.log.error({status:_.status,provider:n.name,model:t.model,errorMessage:q,upstreamType:typeof w?.type=="string"?w.type:void 0,upstreamCode:typeof w?.code=="string"?w.code:void 0},`[provider_response_error] ${n.name},${t.model}: ${q}`);let V=J(`Error from provider(${n.name},${t.model}: ${_.status}): ${q}`,_.status,typeof w?.code=="string"?w.code:"provider_response_error","api_error",x);throw V.upstream={status:_.status,statusText:_.statusText,headers:x??{},body:A!==void 0?Zo(A):void 0,provider:n.name,model:t.model},V}return u(_)}async function ck(t,e,n,r,o,s){let i=e,a=ko(s?.protocolContext),u=o||!a&&Vi(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&Vi(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 uk(t,e,n,r,o){t.ok||e.code(t.status);let s=ah(t.headers);for(let[a,u]of Object.entries(s))e.header(a,u);if((typeof o=="boolean"?o:n?.stream===!0)&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let a=gh(t.body),u=C1.fromWeb(a),d=!1,f=()=>{if(!d){d=!0;try{u.destroyed||u.destroy()}catch{}}},p=()=>{r&&r.removeEventListener("abort",f)};return GC(e)?(f(),!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",f,{once:!0}),e.raw.on("error",g=>{(g?.code==="EPIPE"||g?.code==="ECONNRESET"||g?.code==="ERR_STREAM_PREMATURE_CLOSE"||Xe(g))&&f()}),e.raw.on("close",()=>{e.raw.writableEnded||f()}),u.on("error",g=>{g?.code==="ERR_STREAM_PREMATURE_CLOSE"||g?.code==="ABORT_ERR"||Xe(g)||e.log?.error?.(En(g),"upstream stream error")}),u.once("end",p),u.once("close",p),e.send(u))}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 a=await t.json();return e.send(a)}}var Dh=async t=>{let e={config:{rateLimit:{...ps}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=ar(s.method,i);s.pathname=i,a&&(s.protocolMatch=a,s.clientProtocol=a.protocol)}),t.get("/",e,async()=>({message:"LLMs API",version:YC})),t.get("/health",e,async()=>{let s=VC();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 mh()){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:{...ps}},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||!S1(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:{...ps}},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:{...ps}},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:{...ps}},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:{...ps}},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 S1(t){try{return new URL(t),!0}catch{return!1}}var hs=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}configService;transformerService;logger;providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let i=`${r.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let i=`${r.name},${s}`,a={provider:r.name,model:s,fullModel:i};this.modelRoutes.set(i,a),this.modelRoutes.has(s)||this.modelRoutes.set(s,a)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var ut=[];for(let t=0;t<256;++t)ut.push((t+256).toString(16).slice(1));function lk(t,e=0){return(ut[t[e+0]]+ut[t[e+1]]+ut[t[e+2]]+ut[t[e+3]]+"-"+ut[t[e+4]]+ut[t[e+5]]+"-"+ut[t[e+6]]+ut[t[e+7]]+"-"+ut[t[e+8]]+ut[t[e+9]]+"-"+ut[t[e+10]]+ut[t[e+11]]+ut[t[e+12]]+ut[t[e+13]]+ut[t[e+14]]+ut[t[e+15]]).toLowerCase()}var A1=new Uint8Array(16);function Oh(){return crypto.getRandomValues(A1)}function E1(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():v1(t,e,n)}function v1(t,e,n){t=t||{};let r=t.random??t.rng?.()??Oh();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 lk(r)}var On=E1;var dk=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var Ph=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function T1(t){if(typeof t!="string")return!1;let e=t.trim();return Ph.some(n=>e===n)}function x1(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(`
|
|
138
|
-
`);if(e)return e}return JSON.stringify(t)??""}function
|
|
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 g1(t){return!t.startsWith("mcp_")||t.length<=4?t:`${t.charAt(4).toLowerCase()}${t.slice(5)}`}function uu(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 ds(t,e){let n=r=>{let o=r?.function?.name;typeof o=="string"&&(r.function.name=e?.get(o)??g1(o))};for(let r of t?.choices??[]){for(let o of r?.message?.tool_calls??[])n(o);for(let o of r?.delta?.tool_calls??[])n(o)}}function wo(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n||o==null)continue;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a));return i.length?i.map(String).join(", "):void 0}return String(o)||void 0}}function y1(t){return(Array.isArray(t?.system)?t.system:[]).some(n=>typeof n?.text=="string"&&n.text.startsWith("x-anthropic-billing-header"))}function _1(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 ik(t,e){let n=Bh(t,e),r=n.desktopMarker&&n.desktopUserAgent&&Array.isArray(e?.messages),o=n.cliUserAgent&&n.cliApp&&n.cliSession&&n.stainlessPackage&&n.billingSystem&&n.identitySystem&&Array.isArray(e?.messages),s=n.cliUserAgent||n.cliApp||n.cliSession;return r&&s?"other":r||n.desktopAgentSdkUserAgent&&o?"claude_desktop":o?"claude_code":"other"}function Bh(t,e){let n=wo(t,"user-agent")||"",r=wo(t,"anthropic-desktop-topbar"),s=(/^claude-cli\/[^\s()]+\s+\(([^)]*)\)$/i.exec(n)?.[1]||"").split(",").map(a=>a.trim().toLowerCase()),i=s.some(a=>["claude-desktop","claude-desktop-3p"].includes(a))&&s.some(a=>/^agent-sdk\/[^\s,]+$/.test(a));return{desktopMarker:r==="1",desktopUserAgent:/^Anthropic\/JS\s+/i.test(n),desktopAgentSdkUserAgent:i,cliUserAgent:/^claude-cli\//i.test(n),cliApp:["cli","cli-bg"].includes(wo(t,"x-app")||""),cliSession:!!wo(t,"x-claude-code-session-id"),stainlessPackage:!!wo(t,"x-stainless-package-version"),billingSystem:y1(e),identitySystem:_1(e)}}function lu(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 du(t){return t==="claude_desktop"||t==="claude_code"}async function fu(t,e,n){if(e.anthropicClientKind!=="other"||e.anthropicDestinationInScope!==!0)return;let r=su(t);iu(r,t.messages),au(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 m1(o,"utf-8");i.text=`${a}<env>${i.text.split("<env>").pop()}`}cu(r,t.messages);let s=new Map;uu(t,s),b1(t,e.anthropicProviderMode),e.claudeAuthToolNameMap=s,e.anthropicPolicyApplied=!0,e.anthropicSystemTransformed=!0}function b1(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 C1={"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:[]}},ak=/\[1m\]$/i;function Dn(t){let e=t||"",n=ak.test(e);return{modelId:e.replace(ak,""),requestedOneMillion:n}}function w1(t){if(!t)return"";let e=t.trim(),n=e.indexOf(",");return n>=0&&(e=e.slice(n+1)),e=Dn(e).modelId.trim(),e=e.replace(/[-@]\d{8}$/,""),e.toLowerCase()}function fs(t){let e=w1(t);if(e)return C1[e]}function Uh(t,e){return t?.capabilities.includes(e)??!1}function ck(t){return(t?.capabilities.length??0)>0}import{decodeClaudeModelAlias as k1}from"@caeliq/ccr-shared";async function lk(t,e,n,r,o){let s=t.pathname||String(t.url||o).split("?")[0]||o,i=t.protocolMatch||ar(t.method,s)||ar("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}=Hw(i,a,u);i.protocol==="anthropic_messages"?(f.anthropicClientKind=ik(t.headers,d),t.log?.debug?.({anthropicClientKind:f.anthropicClientKind,anthropicClientSignals:Bh(t.headers,d)},"classified Anthropic client"),await S1(d,f)):f.anthropicClientKind="other";let p={req:t,signal:void 0,clientProtocol:i.protocol,protocolContext:f},h=await zw(i.protocol,d,r,p);h.model=uk(h.model,O=>n.providerService.resolveModelRoute(O)!==null,i.protocol)||"";let g=t;t.protocolContext=f,t.unifiedBody=h,t.originalClientBody=a;let C=n.configService.get("CUSTOM_ROUTER_PATH"),y=g.body;g.body=i.protocol==="anthropic_messages"&&C?a:h;try{await Nh(g,e,{configService:n.configService,tokenizerService:n.tokenizerService})}finally{g.body=y??a}let k=typeof h.model=="string"?h.model:f.originalModel;h.model=uk(k,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 b=A1(h.model,i.protocol),A=Dn(b.modelName);b.modelName=A.modelId,f.requestedOneMillion=A.requestedOneMillion;let w=n.providerService.getProvider(b.providerName);w||Ki(i.protocol,`Provider '${b.providerName}' not found`,404,"provider_not_found"),h.model=b.modelName,g.provider=b.providerName,g.model=b.modelName;let E=Ur(h),x=lu(w);return f.anthropicProviderMode=x,f.anthropicDestinationInScope=x!=="out_of_scope",f.anthropicNativeWire=i.protocol==="anthropic_messages"&&f.anthropicDestinationInScope&&du(f.anthropicClientKind||"other"),f.anthropicDestinationInScope&&f.anthropicClientKind==="other"&&await fu(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:b.providerName,modelName:b.modelName}}async function S1(t,e){let n=tk(t);e.claudeCodeSubagent=n.isSubagent,e.taggedSubagentModel=ek(t)}function A1(t,e){let n=typeof t=="string"?t.trim():"";n||Ki(e,"Missing model. Configure Router.default or send provider,model.",400,"missing_model","invalid_request_error"),n.includes(",")||Ki(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)&&Ki(e,`Invalid model '${n}'. Expected provider,model.`,400,"invalid_model","invalid_request_error"),{providerName:r,modelName:s}}function uk(t,e,n){if(typeof t!="string")return t;let r=k1(t);if(!r)return t;let o=Dn(r).modelId;return e(o)||Ki(n,`Encoded model alias resolves to an unconfigured model '${o}'.`,404,"model_not_found","invalid_request_error"),r}function Ki(t,e,n,r,o="api_error"){let s=qi(t,e,n,r,o),i=J(e,s.statusCode,r,o);throw i.protocolBody=s.body,i}function pu(t,e,n,r){return n?Gw(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 Vi(t,e,n){return!!(n&&t.transformer?.passthrough===!0&&t.transformer?.use?.some(r=>r?.name===e.name))}function ko(t){return t?.anthropicDestinationInScope===!0&&t?.anthropicClientKind==="other"}async function v1(t,e,n,r,o){let s=VC(t,e),i=s.signal;s.arm();let a;try{a=await lk(t,e,n,r,o)}catch(d){throw Xe(d)||i.aborted?typeof d=="string"?vn(d):vn(i.reason??d):d}let u=n.providerService.getProvider(a.providerName);if(!u)throw J(`Provider '${a.providerName}' not found`,404,"provider_not_found");t._preparedInbound=a;try{let d=pu(u,r,a.protocolContext,a.modelName)&&!ko(a.protocolContext),f=!ko(a.protocolContext)&&Vi(u,r,a.protocolContext),p=a.protocolContext.anthropicNativeWire?a.originalBody:a.clientWireBody??a.originalBody,h=a.protocolContext.anthropicNativeWire||d||f?{...typeof p=="object"&&p?Ur(p):{},model:a.modelName}:Ur(a.unifiedBody);fk(t,n,u,h);let{requestBody:g,config:C,bypass:y}=await dk(h,u,r,t.headers,{req:t,provider:u,signal:i,clientProtocol:a.protocolContext.protocol,protocolContext:a.protocolContext,skipClientNormalization:!0}),k=await pk(g,C,u,n,y,r,{req:t,signal:i,protocolContext:a.protocolContext}),b=await hk(g,k,u,r,y,{req:t,signal:i,protocolContext:a.protocolContext,skipClientNormalization:y});return await gk(b,e,a.originalBody,i,a.protocolContext.stream,a.protocolContext.protocol)}catch(d){if(Xe(d))throw typeof d=="string"?vn(d):d;if(i.aborted)throw vn(i.reason??d);if(dh(d)){let f=await T1(t,e,n,r,d,i);if(f)return f;if(i.aborted)throw vn(i.reason??St)}throw d}}async function T1(t,e,n,r,o,s){let i=t.scenarioType||"default",a=n.configService.get("fallback"),u=YC(a,i);if(!u?.length||s?.aborted||Xe(o))return null;t.log.warn({scenarioType:i,fallbackCount:u.length,error:En(o)},`Request failed for ${i}, trying ${u.length} fallback models`);let d=0,f=lh(d,o?.headers?.["Retry-After"]??o?.headers?.["retry-after"]);if(d+=1,f>0){t.log.info(`Waiting ${f}ms before first fallback attempt`);try{await uh(f,s)}catch(p){if(Xe(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,[C,...y]=h.split(","),k=y.join(","),b=n.providerService.getProvider(C);if(!b){t.log.warn(`Fallback provider '${C}' not found, skipping`);continue}let A=lu(b),w=g?.protocolContext?{...g.protocolContext,anthropicProviderMode:A,anthropicDestinationInScope:A!=="out_of_scope",anthropicNativeWire:!!(g.protocolContext.protocol==="anthropic_messages"&&A!=="out_of_scope"&&du(g.protocolContext.anthropicClientKind||"other")),anthropicPolicyApplied:!1,anthropicSystemTransformed:!1,claudeAuthToolNameMap:new Map}:g?.protocolContext,E={...Ur(g?.prePolicyUnifiedBody||g?.unifiedBody||t.unifiedBody||t.body),model:k};w?.anthropicDestinationInScope&&w.anthropicClientKind==="other"&&await fu(E,w,n.configService);let x={...t,provider:C,model:k,body:g?.originalBody??t.body,unifiedBody:E,protocolContext:w,clientProtocol:w?.protocol,scenarioType:i},O=pu(b,r,w,k)&&!ko(w),q=!ko(w)&&Vi(b,r,w),V=w?.anthropicNativeWire?g?.originalBody:g?.clientWireBody??g?.originalBody,j=w?.anthropicNativeWire||O||q?{...typeof V=="object"&&V?Ur(V):{},model:k}:E;fk(x,n,b,j);let{requestBody:ee,config:z,bypass:te}=await dk(j,b,r,t.headers,{req:x,provider:b,signal:s,clientProtocol:g?.protocolContext?.protocol,protocolContext:w,skipClientNormalization:!0}),Q=await pk(ee,z,b,n,te,r,{req:x,signal:s,protocolContext:w}),_e=await hk(ee,Q,b,r,te,{req:x,signal:s,protocolContext:w});return t.log.info(`Fallback model ${h} succeeded`),await gk(_e,e,g?.originalBody??t.body,s,w?.stream,w?.protocol)}catch(g){if(Xe(g))throw g;if(s?.aborted)throw vn(s.reason??St);if(!dh(g))throw t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed with a terminal error`),g;if(t.log.warn({fallbackModel:h,error:En(g)},`Fallback model ${h} failed`),p<u.length-1){let y=lh(d,g?.headers?.["Retry-After"]??g?.headers?.["retry-after"]);if(d+=1,y>0){t.log.info(`Waiting ${y}ms before next fallback attempt`);try{await uh(y,s)}catch(k){if(Xe(k)||s?.aborted)return null;throw k}}}continue}}return t.log.error(`All fallback models failed for ${i}`),null}async function dk(t,e,n,r,o){let s=t,i={},a=pu(e,n,o?.protocolContext,t?.model),u=!!(o?.protocolContext?.anthropicNativeWire===!0||a&&!ko(o?.protocolContext)),d=ko(o?.protocolContext),f=!d&&Vi(e,n,o?.protocolContext),p=u||!d&&e.transformer?.passthrough||o?.skipClientNormalization===!0;if(u&&(i.headers=Ww(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 C=g.config||{};i={...i,...C,headers:Wc(i.headers,C.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 C=g.config||{};i={...i,...C,headers:Wc(i.headers,C.headers)}}else s=g}return!u&&!e.transformer?.use?.length&&Array.isArray(s?.messages)&&(s=zc(s),s=Hc(s,e,o)),{requestBody:s,config:i,bypass:u}}function fk(t,e,n,r){t&&(t._cachePrefixClientDiff=kh(r,{logger:t.log??e.log,reqId:t.id,provider:n?.name,model:r?.model,conversationId:t.sessionId,stage:"client"}))}async function pk(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 k=>{let b=kh(t,{...a,stage:"wire",responseStatus:k?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheAffinity:{sessionId:e?.headers?.["session-id"],threadId:e?.headers?.["thread-id"],clientRequestId:e?.headers?.["x-client-request-id"]}});return ww(k,{...a,responseStatus:k?.status,clientStageDiff:i?.req?._cachePrefixClientDiff,cacheDiff:b})};if(e?.__providerResponse)return u(e.__providerResponse);let d=n.transformer?.use?.find(k=>typeof k?.auth=="function")||s;if((o||n.transformer?.passthrough)&&typeof d.auth=="function"){let k=await d.auth(t,n,i);if(k.body){t=k.body;let b=e.headers||{};k.config?.headers&&(b=Wc(b,k.config.headers),delete b.host,delete k.config.headers),e={...e,...k.config,headers:b}}else t=k}let f=e.url||new URL(n.baseUrl),p=cw(e?.headers,n.apiKey),{__authRecovery:h,...g}=e||{},y=await kw(k=>es(f,t,{httpsProxy:r.configService.getHttpsProxy(),...g,headers:JSON.parse(JSON.stringify(k)),signal:i?.signal??g.signal},i,r.log),p,h);if(!y.ok){let k=await y.text(),b=Je(k)||k.slice(0,240),A;try{A=JSON.parse(k)}catch{A=void 0}let w=A&&typeof A=="object"?A.error:void 0,E=gh(y.headers),x=Object.keys(E).length>0?E:void 0;if(!x?.["retry-after"]&&y.status===429){let j=w?.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 w?.message=="string"?w.message:void 0,q=Je(O||k)||b;r.log.error({status:y.status,provider:n.name,model:t.model,errorMessage:q,upstreamType:typeof w?.type=="string"?w.type:void 0,upstreamCode:typeof w?.code=="string"?w.code:void 0},`[provider_response_error] ${n.name},${t.model}: ${q}`);let V=J(`Error from provider(${n.name},${t.model}: ${y.status}): ${q}`,y.status,typeof w?.code=="string"?w.code:"provider_response_error","api_error",x);throw V.upstream={status:y.status,statusText:y.statusText,headers:x??{},body:A!==void 0?Zo(A):void 0,provider:n.name,model:t.model},V}return u(y)}async function hk(t,e,n,r,o,s){let i=e,a=ko(s?.protocolContext),u=o||!a&&Vi(n,r,s?.protocolContext)||n.transformer?.passthrough&&!s?.protocolContext,d=!a&&Vi(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 gk(t,e,n,r,o,s){t.ok||e.code(t.status);let i=gh(t.headers);for(let[u,d]of Object.entries(i))e.header(u,d);if((typeof o=="boolean"?o:n?.stream===!0)&&t.ok){if(t.body&&typeof t.body.getReader=="function"){let u=s==="openai_chat_completions"?Ah(t.body):t.body,d=Sh(u),f=E1.fromWeb(d),p=!1,h=()=>{if(!p){p=!0;try{f.destroyed||f.destroy()}catch{}}},g=()=>{r&&r.removeEventListener("abort",h)};return QC(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",y=>{(y?.code==="EPIPE"||y?.code==="ECONNRESET"||y?.code==="ERR_STREAM_PREMATURE_CLOSE"||Xe(y))&&h()}),e.raw.on("close",()=>{e.raw.writableEnded||h()}),f.on("error",y=>{y?.code==="ERR_STREAM_PREMATURE_CLOSE"||y?.code==="ABORT_ERR"||Xe(y)||e.log?.error?.(En(y),"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 jh=async t=>{let e={config:{rateLimit:{...ps}}};t.addHook("onRequest",async s=>{let i=String(s.url||"").split("?")[0]||"/",a=ar(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=tw();return{status:"ok",timestamp:new Date().toISOString(),...s?{vitals:s}:{}}});let n=t.transformerService.getAllTransformers(),r=s=>{let i=n.get(s);if(i){if(typeof i=="object")return i;try{let a=new i;return a&&typeof a=="object"&&(a.logger=t.log),a}catch{return}}},o=new Set;for(let s of Eh()){let i=r(s.ownerTransformerName);if(!i){t.log.warn(`protocol route ${s.path}: owner transformer '${s.ownerTransformerName}' not found`);continue}for(let a of[s.path,`${s.path}/`])o.has(a)||(o.add(a),t.post(a,e,async(u,d)=>v1(u,d,t,i,a)))}t.post("/providers",{config:{rateLimit:{...ps}},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||!x1(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:{...ps}},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:{...ps}},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:{...ps}},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:{...ps}},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 x1(t){try{return new URL(t),!0}catch{return!1}}var hs=class{constructor(e,n,r){this.configService=e;this.transformerService=n;this.logger=r;this.initializeCustomProviders()}configService;transformerService;logger;providers=new Map;modelRoutes=new Map;initializeCustomProviders(){let e=this.configService.get("providers");if(e&&Array.isArray(e)){this.initializeFromProvidersArray(e);return}}initializeFromProvidersArray(e){e.forEach(n=>{try{if(!n.name||!n.api_base_url||!n.api_key)return;let r={};n.transformer&&Object.keys(n.transformer).forEach(o=>{o==="use"?Array.isArray(n.transformer.use)&&(r.use=n.transformer.use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")):o==="passthrough"?r.passthrough=n.transformer.passthrough:Array.isArray(n.transformer[o]?.use)&&(r[o]={use:n.transformer[o].use.map(s=>{if(Array.isArray(s)&&typeof s[0]=="string"){let i=this.transformerService.getTransformer(s[0]);if(i)return this.attachTransformerLogger(new i(s[1]))}if(typeof s=="string"){let i=this.transformerService.getTransformer(s);return typeof i=="function"?this.attachTransformerLogger(new i):this.attachTransformerLogger(i)}}).filter(s=>typeof s<"u")})}),this.registerProvider({name:n.name,baseUrl:n.api_base_url,apiKey:n.api_key,models:n.models||[],project_id:n.project_id,transformer:n.transformer?r:void 0}),this.logger.info(`${n.name} provider registered`)}catch(r){this.logger.error(`${n.name} provider registered error: ${r}`)}})}attachTransformerLogger(e){return e&&typeof e=="object"&&(e.logger=this.logger),e}registerProvider(e){let n={...e};return this.providers.set(n.name,n),e.models.forEach(r=>{let o=`${n.name},${r}`,s={provider:n.name,model:r,fullModel:o};this.modelRoutes.set(o,s),this.modelRoutes.has(r)||this.modelRoutes.set(r,s)}),n}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}updateProvider(e,n){let r=this.providers.get(e);if(!r)return null;let o={...r,...n,updatedAt:new Date};return this.providers.set(e,o),n.models&&(r.models.forEach(s=>{let i=`${r.name},${s}`;this.modelRoutes.delete(i),this.modelRoutes.delete(s)}),n.models.forEach(s=>{let i=`${r.name},${s}`,a={provider:r.name,model:s,fullModel:i};this.modelRoutes.set(i,a),this.modelRoutes.has(s)||this.modelRoutes.set(s,a)})),o}deleteProvider(e){let n=this.providers.get(e);return n?(n.models.forEach(r=>{let o=`${n.name},${r}`;this.modelRoutes.delete(o),this.modelRoutes.delete(r)}),this.providers.delete(e),!0):!1}toggleProvider(e,n){return!!this.providers.get(e)}resolveModelRoute(e){let n=this.modelRoutes.get(e);if(!n)return null;let r=this.providers.get(n.provider);return r?{provider:r,originalModel:e,targetModel:n.model}:null}getAvailableModelNames(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push(r),e.push(`${n.name},${r}`)})}),e}getModelRoutes(){return Array.from(this.modelRoutes.values())}parseTransformerConfig(e){return e?Array.isArray(e)?e.reduce((n,r)=>{if(Array.isArray(r)){let[o,s={}]=r;n[o]=s}else n[r]={};return n},{}):e:{}}async getAvailableModels(){let e=[];return this.providers.forEach(n=>{n.models.forEach(r=>{e.push({id:r,object:"model",owned_by:n.name,provider:n.name}),e.push({id:`${n.name},${r}`,object:"model",owned_by:n.name,provider:n.name})})}),{object:"list",data:e}}};var ut=[];for(let t=0;t<256;++t)ut.push((t+256).toString(16).slice(1));function mk(t,e=0){return(ut[t[e+0]]+ut[t[e+1]]+ut[t[e+2]]+ut[t[e+3]]+"-"+ut[t[e+4]]+ut[t[e+5]]+"-"+ut[t[e+6]]+ut[t[e+7]]+"-"+ut[t[e+8]]+ut[t[e+9]]+"-"+ut[t[e+10]]+ut[t[e+11]]+ut[t[e+12]]+ut[t[e+13]]+ut[t[e+14]]+ut[t[e+15]]).toLowerCase()}var R1=new Uint8Array(16);function Lh(){return crypto.getRandomValues(R1)}function D1(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():O1(t,e,n)}function O1(t,e,n){t=t||{};let r=t.random??t.rng?.()??Lh();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return mk(r)}var On=D1;var yk=(t,e)=>(t.includes("base64")&&(t=t.split("base64").pop(),t.startsWith(",")&&(t=t.slice(1))),`data:${e};base64,${t}`);var $h=["[Request interrupted by user]","[Request interrupted by user for tool use]"];function P1(t){if(typeof t!="string")return!1;let e=t.trim();return $h.some(n=>e===n)}function I1(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 F1(t){return!t||typeof t!="object"?!1:t.type==="image"?!!t.source:t.type!=="tool_result"&&t.type!=="text"}function N1(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:I1(o.content),isError:o.is_error===!0});continue}if(o?.type==="text"&&typeof o.text=="string"){r&&P1(o.text)?e.interruption="synthetic_client_interrupt":o.text.trim()&&(e.steering="meaningful");continue}F1(o)&&(e.steering="meaningful")}return e}function M1(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 _k(t){return{source:"anthropic",sourceSessionIdentity:M1(t.metadata),turnIntent:N1(t.messages)}}var gs=class extends TransformStream{constructor(){super({transform:(e,n)=>{let r="";e.event&&(r+=`event: ${e.event}
|
|
139
141
|
`),e.id&&(r+=`id: ${e.id}
|
|
140
142
|
`),e.retry&&(r+=`retry: ${e.retry}
|
|
141
143
|
`),e.data&&(e.data.type==="done"?r+=`data: [DONE]
|
|
142
144
|
`:r+=`data: ${JSON.stringify(e.data)}
|
|
143
145
|
`),r+=`
|
|
144
|
-
`,n.enqueue(r)}})}};var
|
|
145
|
-
`);for(let C of g)if(C.trim())try{e(C,d)}catch(
|
|
146
|
-
`))}}}catch(f){if(!i){let p=
|
|
146
|
+
`,n.enqueue(r)}})}};var bk=(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 hu(t,e,n,r){let o={...r,...En(n)};t?.error?t.error(o,e):console.error(e,o)}function B1(t){if(Xe(t)||!mo(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 Ne(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 Tn).pipeThrough(new gs).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 C of g)if(C.trim())try{e(C,d)}catch(y){hu(n?.logger,"Error processing line",y,{line:Je(C)}),u.enqueue(r.encode(C+`
|
|
148
|
+
`))}}}catch(f){if(!i){let p=B1(f);hu(n?.logger,"Stream error",p);let h=!1;try{h=n?.onError?.(p,d)===!0}catch(g){hu(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(hu(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:{...Gc(t.headers),"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function ve(t,e){return e.encode(`data: ${t}
|
|
147
149
|
|
|
148
150
|
`)}function Pe(t,e){return e.encode(t+`
|
|
149
|
-
`)}var
|
|
150
|
-
`):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}:{}})}),
|
|
151
|
+
`)}var gu=nr(Pk(),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"},qh="\u26A0\uFE0F Upstream ended the turn without a reply";function Yi(t){return t?tI[t.toUpperCase()]||t.toLowerCase():null}function Hh(t){let e=t?.finishReason;if(!e||String(e).toUpperCase()==="STOP")return null;let n=String(t?.finishMessage||"").trim();return`${qh} (${String(e).toUpperCase()})`+(n?`: ${n}`:"")}var mu=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:Yi(n?.finishReason)}});return}this.flushBufferedContent({chunk:e,candidate:n,mode:n?.finishReason?"finish":"buffered",finishReason:Yi(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 yu(t,e){return e[t]||t}function _u(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 bu(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 ms(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 Cu(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 Xi(t){if(!t||!t.includes("\\")&&!t.includes("$"))return t;try{let e=typeof gu.default=="function"?gu.default:gu.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 Ik(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 $r(t){let e=t?.input_tokens||0,n=t?.cache_read_input_tokens||0,r=t?.cache_creation_input_tokens||0,o=t?.output_tokens||0;return{completion_tokens:o,prompt_tokens:e+n+r,prompt_tokens_details:{cached_tokens:n,cache_write_tokens:r},total_tokens:e+n+r+o}}function zh(t){switch(t){case"tool_use":return"tool_calls";case"max_tokens":case"model_context_window_exceeded":return"length";case"refusal":return"content_filter";case"end_turn":case"stop_sequence":case"pause_turn":return"stop";default:return typeof t=="string"&&t?"stop":null}}function Fk(t){let e=[];for(let o=0;o<t.messages.length;o++){let s=t.messages[o],i=yu(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}:{}})}),_u(s.content).forEach(d=>{a.push(Cu(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:bu(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=ms(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})),Lc(r)}function Nk(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 wu(t,e,n){if(t.headers.get("Content-Type")?.includes("application/json")){let r=await t.json(),o=Array.isArray(r.content)?r.content:[],s=o.filter(h=>h?.type==="text"&&typeof h.text=="string").map(h=>h.text),i=o.find(h=>h?.type==="thinking"&&typeof h.thinking=="string"),a,u=o.filter(h=>h?.type==="tool_use");u.length>0?a=u.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})):Array.isArray(r.tool_use)&&r.tool_use.length>0&&(a=r.tool_use.map(h=>({id:h.id,type:"function",function:{name:h.name,arguments:JSON.stringify(h.input??{})}})));let d=zh(r.stop_reason),f={role:"assistant",content:s.length>0?s.join(""):null,...a&&{tool_calls:a}};i&&(f.thinking={content:i.thinking,signature:i.signature});let p={id:r.id,choices:[{finish_reason:d,index:0,message:f}],created:parseInt(new Date().getTime()/1e3+"",10),model:r.model,object:"chat.completion",usage:$r(r.usage)};return new Response(JSON.stringify(p),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(t.headers.get("Content-Type")?.includes("stream")){if(!t.body)return t;let r={},o="",s="",i=new Map;return Ne(t,(u,d)=>{let{controller:f,encoder:p}=d;if(u.startsWith("data: ")){let h=u.slice(6).trim();if(h){n?.debug({chunkStr:h},`${e} chunk:`);try{let g=JSON.parse(h);if(g.type==="message_start"){r=g.message?.usage||g.usage||{},o=g.message?.id||g.id||o,s=g.message?.model||g.model||s;let C={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(C)}
|
|
151
153
|
|
|
152
154
|
`))}else if(g.type==="content_block_delta"&&g.delta?.type==="text_delta"){let C={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:$r(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(C)}
|
|
153
155
|
|
|
@@ -157,25 +159,25 @@ ${r.content}`:s:Array.isArray(r.content)?r.content.unshift({type:"text",text:s})
|
|
|
157
159
|
|
|
158
160
|
`))}else if(g.type==="content_block_delta"&&g.delta?.type==="signature_delta"){let C={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:$r(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(C)}
|
|
159
161
|
|
|
160
|
-
`))}else if(g.type==="content_block_start"&&g.content_block?.type==="tool_use"){let C=Number(g.index||0),
|
|
162
|
+
`))}else if(g.type==="content_block_start"&&g.content_block?.type==="tool_use"){let C=Number(g.index||0),y=i.size;i.set(C,y);let k={choices:[{delta:{tool_calls:[{index:y,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:$r(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(k)}
|
|
161
163
|
|
|
162
|
-
`))}else if(g.type==="message_delta"){let C={choices:[{delta:{},finish_reason:
|
|
164
|
+
`))}else if(g.type==="message_delta"){let C={choices:[{delta:{},finish_reason:zh(g.delta?.stop_reason)||"stop",index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:$r({...r,...g.usage})};f.enqueue(p.encode(`data: ${JSON.stringify(C)}
|
|
163
165
|
|
|
164
166
|
`))}else if(g.type==="message_stop")f.enqueue(p.encode(`data: [DONE]
|
|
165
167
|
|
|
166
|
-
`));else{if(g.type==="content_block_start"||g.type==="content_block_stop"||g.type==="ping")return;{let C={choices:[{delta:{role:"assistant",content:g.content?.[0]?.text||""},finish_reason:
|
|
168
|
+
`));else{if(g.type==="content_block_start"||g.type==="content_block_stop"||g.type==="ping")return;{let C={choices:[{delta:{role:"assistant",content:g.content?.[0]?.text||""},finish_reason:zh(g.stop_reason),index:0,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:g.id||o,model:g.model||s,object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",...g.usage?{usage:$r(g.usage)}:{}};f.enqueue(p.encode(`data: ${JSON.stringify(C)}
|
|
167
169
|
|
|
168
|
-
`))}}}catch(g){n?.error(`Error parsing ${e} stream chunk`,h,g.message)}}}})}return t}import{randomUUID as
|
|
170
|
+
`))}}}catch(g){n?.error(`Error parsing ${e} stream chunk`,h,g.message)}}}})}return t}import{randomUUID as Gk}from"crypto";import{existsSync as Su,readFileSync as Bk,writeFileSync as Uk,mkdirSync as jk}from"fs";import{dirname as Lk,join as $k}from"path";import{homedir as qk}from"os";import{randomBytes as nI}from"crypto";var rI=$k(qk(),".claude-code-router","claude_auth.json"),oI=$k(qk(),".claude-code-router","claude_device.json"),sI=/^[0-9a-f]{64}$/;function Hk(){return process.env.CCR_CLAUDE_AUTH_FILE||rI}function iI(){return process.env.CCR_CLAUDE_DEVICE_FILE||oI}var Mk={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"},ku=null;function Wh(){try{let t=Hk();if(!Su(t))return null;let e=Bk(t,"utf-8"),n=JSON.parse(e);return n.access_token?n:null}catch{return null}}function Gh(t){let e=Hk(),n=Lk(e);Su(n)||jk(n,{recursive:!0}),Uk(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function aI(t,e=60){return t.expires_at?Date.now()/1e3+e>=t.expires_at:!1}async function Jh(t){let e=await fetch(Mk.token_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:"refresh_token",client_id:Mk.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 Au(t){let e=Wh();if(!e)throw new Error("No Claude OAuth tokens found. Run `ccr claude-auth` to authenticate.");if(t?.force||aI(e)){if(!e.refresh_token)throw new Error("Claude OAuth token expired and no refresh token available. Run `ccr claude-auth` to re-authenticate.");ku||(ku=Jh(e.refresh_token).then(n=>(Gh(n),n)).finally(()=>{ku=null})),e=await ku}return e}function zk(){let t=iI();try{if(Su(t)){let r=JSON.parse(Bk(t,"utf-8"));if(typeof r.device_id=="string"&&sI.test(r.device_id))return r.device_id}}catch{}let e=nI(32).toString("hex"),n=Lk(t);return Su(n)||jk(n,{recursive:!0}),Uk(t,JSON.stringify({device_id:e},null,2),{mode:384,encoding:"utf-8"}),e}function Qi(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 Wk="oauth-2025-04-20";function cI(...t){let e=new Set,n=[];for(let r of t)if(r)for(let o of r.split(",")){let s=o.trim();if(!s)continue;let i=s.toLowerCase();e.has(i)||(e.add(i),n.push(s))}return n.join(",")}function Kh(t,e){if(!t)return;let n=e.toLowerCase();for(let[r,o]of Object.entries(t)){if(r.toLowerCase()!==n)continue;if(o==null)return;if(Array.isArray(o)){let i=o.filter(a=>a!=null&&String(a).length>0);return i.length?i.map(String).join(", "):void 0}let s=String(o);return s.length?s:void 0}}function uI(t){return t?.startsWith("claude-cli/")??!1}function Vh(t){return t.clientBeta?.trim()?cI(t.clientBeta,Wk):Wk}function Xh(t,e){let{requestedOneMillion:n}=Dn(t),r=fs(t),o=u=>Uh(r,u),i=Dn(t).modelId.toLowerCase().includes("haiku")?[]:["claude-code-20250219"];e?.includeOAuthBeta!==!1&&i.push("oauth-2025-04-20"),n&&i.push("context-1m-2025-08-07"),ck(r)&&i.push("interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13"),o("context_management")&&i.push("context-management-2025-06-27"),i.push("prompt-caching-scope-2026-01-05"),o("mid_conv_system")&&i.push("mid-conversation-system-2026-04-07"),e?.includeToolSearch&&i.push("advanced-tool-use-2025-11-20"),e?.includeEffort&&o("effort")&&i.push("effort-2025-11-24"),e?.includeFallbackCredit&&i.push("fallback-credit-2026-06-01");let a=e?.envBeta??process.env.ANTHROPIC_BETAS;for(let u of a?.split(",")||[]){let d=u.trim();d&&!i.includes(d)&&i.push(d)}return i.join(",")}function Qh(t,e){if(!t||!e)return t;let n=Dn(t).modelId;return fs(n)?.nativeOneMillion?n:`${n}[1m]`}function Zh(t,e){let n=o=>Uh(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 lI="0.94.0";function dI(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";default:return process.arch}}function fI(){switch(process.platform){case"darwin":return"MacOS";case"linux":return"Linux";case"win32":return"Windows";default:return process.platform}}var Yh;function Jk(){return Yh||(Yh=Gk()),Yh}var pI=new Set(["authorization","x-api-key","anthropic-beta","cookie","set-cookie","host","content-length","content-encoding","connection","transfer-encoding","upgrade","te","trailer"]);function hI(){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||pI.has(r.toLowerCase())||(t[r]=o)}return t}function eg(){let t=[sk,process.env.CLAUDE_AGENT_SDK_VERSION?`agent-sdk/${process.env.CLAUDE_AGENT_SDK_VERSION}`:void 0,process.env.CLAUDE_AGENT_SDK_CLIENT_APP?`client-app/${process.env.CLAUDE_AGENT_SDK_CLIENT_APP}`:void 0].filter(Boolean).join(", ");return{"User-Agent":process.env.ANTHROPIC_USER_AGENT||`claude-cli/${Mh} (external, ${t})`,"x-app":"cli","anthropic-dangerous-direct-browser-access":"true","X-Claude-Code-Session-Id":Jk(),"x-client-request-id":Gk(),"x-stainless-arch":dI(),"x-stainless-lang":"js","x-stainless-os":fI(),"x-stainless-package-version":lI,"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"}:{},...hI()}}function tg(){return{user_id:JSON.stringify({device_id:zk(),account_uuid:"",session_id:Jk()})}}var Eu=class{name="claude-auth";logger;async transformRequestIn(e,n,r){let o=await Au(),s=r?.req?.headers||{},i=Kh(s,"user-agent"),a=r?.protocolContext?.anthropicClientKind||(uI(i)?"claude_code":"other"),u=a==="claude_code",d=!r?.protocolContext||r.protocolContext.anthropicDestinationInScope===!0;if(a==="other"&&d&&!r?.protocolContext?.anthropicPolicyApplied){let g=su(e);iu(g,e.messages),au(g),cu(g,e.messages);let C=new Map;uu(e,C),r&&(r.claudeAuthToolNameMap=C,r.protocolContext&&(r.protocolContext.claudeAuthToolNameMap=C))}else if(a==="other"){let g=r?.protocolContext?.claudeAuthToolNameMap;g&&r&&(r.claudeAuthToolNameMap=g)}let f=u?Kh(s,"anthropic-beta"):void 0,p=Vh(u?{clientBeta:f}:{clientBeta:Xh(Qh(e.model,r?.protocolContext?.requestedOneMillion))}),h={Authorization:`Bearer ${o.access_token}`,"anthropic-beta":p};if(u)for(let g of["user-agent","x-app","x-claude-code-session-id","anthropic-dangerous-direct-browser-access","x-client-request-id","x-stainless-arch","x-stainless-lang","x-stainless-os","x-stainless-package-version","x-stainless-retry-count","x-stainless-runtime","x-stainless-runtime-version","x-stainless-timeout"]){let C=Kh(s,g);C&&(h[g]=C)}else{Object.assign(h,eg());let g=fs(e.model);r&&(r.claudeAuthPostBuildHook=C=>{Zh(C,g),C.metadata={...C.metadata||{},...tg()}})}return{body:e,config:{headers:h,__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async auth(e,n,r){let o=await Au(),s=r?.req?.headers||{},i=wo(s,"anthropic-beta");return{body:e,config:{url:Qi(n?.baseUrl),headers:{Authorization:`Bearer ${o.access_token}`,"anthropic-beta":Vh({clientBeta:i})},__authRecovery:()=>this.recoverUnauthorizedAuth(o.access_token)}}}async transformResponseOut(e,n){let r=n?.claudeAuthToolNameMap??n?.protocolContext?.claudeAuthToolNameMap;if(r?.size&&e.ok){let s=e.headers.get("Content-Type")||"";if(s.includes("application/json")){let i=await e.json();return ds(i,r),new Response(JSON.stringify(i),{status:e.status,statusText:e.statusText,headers:e.headers})}if(s.includes("text/event-stream")&&e.body)return Ne(e,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
|
|
169
171
|
`));return}try{let u=JSON.parse(i.slice(6));ds(u,r),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
|
|
170
172
|
|
|
171
173
|
`))}catch{a.controller.enqueue(a.encoder.encode(i+`
|
|
172
|
-
`))}},{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=
|
|
174
|
+
`))}},{logger:this.logger})}let o=e.headers.get("anthropic-ratelimit-unified-overage-in-use");return o&&this.logger?.debug?.({overageInUse:o,overageStatus:e.headers.get("anthropic-ratelimit-unified-overage-status")},"claude-auth: subscription overage in use for this request"),e}async recoverUnauthorizedAuth(e){let n=Wh();if(n?.access_token&&n.access_token!==e)return{Authorization:`Bearer ${n.access_token}`};if(!n?.refresh_token)return null;let r=await Jh(n.refresh_token);return Gh(r),{Authorization:`Bearer ${r.access_token}`}}};function vu(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 gI(t,e){if(!t||typeof t!="object")return;let n=structuredClone(t);if(n.effort!==void 0){let r=e?void 0:iw(n.effort);r?n.effort=r:delete n.effort}return Object.keys(n).length?n:void 0}var Tu=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:Qi(n.baseUrl),headers:o}}}async transformRequestIn(e,n,r){let o=t.buildAnthropicBody(e,this.logger,r);o.model=Dn(o.model).modelId;let s=r?.protocolContext,a=s?.anthropicDestinationInScope===!0&&s.anthropicClientKind==="other"&&s.anthropicPolicyApplied===!0&&s?.anthropicProviderMode==="api_key";a&&(Zh(o,fs(o.model)),o.metadata={...o.metadata||{},...tg()}),r?.claudeAuthPostBuildHook?.(o);let u=Qi(n?.baseUrl),d={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return a&&Object.assign(d,eg(),{"anthropic-beta":Xh(Qh(o.model,s?.requestedOneMillion),{includeOAuthBeta:!1})}),!n?.transformer?.use?.some(p=>p?.name==="claude-auth")&&(this.useBearer?(d.Authorization=`Bearer ${n.apiKey}`,d["x-api-key"]=void 0):(d["x-api-key"]=n.apiKey,d.Authorization=void 0)),{body:o,config:{url:u,headers:d}}}async transformResponseOut(e,n){let r=await wu(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 ds(i,o),new Response(JSON.stringify(i),{status:r.status,statusText:r.statusText,headers:r.headers})}return s.includes("text/event-stream")&&r.body?Ne(r,(i,a)=>{if(!i.startsWith("data: ")||i.trim()==="data: [DONE]"){a.controller.enqueue(a.encoder.encode(i+`
|
|
173
175
|
`));return}try{let u=JSON.parse(i.slice(6));ds(u,o),a.controller.enqueue(a.encoder.encode(`data: ${JSON.stringify(u)}
|
|
174
176
|
|
|
175
177
|
`))}catch{a.controller.enqueue(a.encoder.encode(i+`
|
|
176
|
-
`))}},{logger:this.logger}):r}async transformRequestOut(e,n){n&&(n.unifiedRequest=
|
|
177
|
-
`)||JSON.stringify(g.content),tool_call_id:cr(g.tool_use_id)??g.tool_use_id,cache_control:g.cache_control};r.push(C)});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"?
|
|
178
|
-
`));let g=f.content.filter(
|
|
178
|
+
`))}},{logger:this.logger}):r}async transformRequestOut(e,n){n&&(n.unifiedRequest=_k(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 C={role:"tool",content:typeof g.content=="string"?g.content:Array.isArray(g.content)&&g.content.filter(y=>y.type==="text"&&y.text).map(y=>y.text).join(`
|
|
179
|
+
`)||JSON.stringify(g.content),tool_call_id:cr(g.tool_use_id)??g.tool_use_id,cache_control:g.cache_control};r.push(C)});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"?yk(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(y=>y.type==="text"&&y.text);h.length&&(p.content=h.some(y=>y.cache_control)?h.map(y=>({type:"text",text:y.text,cache_control:y.cache_control})):h.map(y=>y.text).join(`
|
|
180
|
+
`));let g=f.content.filter(y=>y.type==="tool_use"&&y.id);g.length&&(p.tool_calls=g.map(y=>({id:cr(y.id)??y.id,type:"function",function:{name:y.name,arguments:JSON.stringify(y.input||{})},cache_control:y.cache_control})));let C=f.content.find(y=>y.type==="thinking"&&y.signature);C&&(p.thinking={content:C.thinking,signature:C.signature}),r.push(p)}return}}});let s={messages:r,model:e.model,max_tokens:e.max_tokens,temperature:e.temperature,stream:e.stream,tools:e.tools?.length?this.convertAnthropicToolsToUnified(e.tools):void 0,tool_choice:e.tool_choice,...e.cache_control?{cache_control:e.cache_control}:{}},i=Dt(e.output_config?.effort??e.effort);if(e.thinking||i){let f=e.thinking?e.thinking.type==="enabled"||e.thinking.type==="adaptive":!0;s.reasoning={...ts(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=k=>{if(typeof k=="string"){k&&o.push({type:"text",text:k});return}if(Array.isArray(k))for(let b of k)b?.type==="text"&&b.text&&o.push({type:"text",text:b.text,...b.cache_control?{cache_control:b.cache_control}:{}})};e.system&&s(e.system);let i=[];for(let k of e.messages){if(k.role==="system"||k.role==="developer"){s(k.content);continue}if(k.role==="tool"){let b={type:"tool_result",tool_use_id:cr(k.tool_call_id)??k.tool_call_id,content:typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.filter(w=>w?.type==="text").map(w=>({type:"text",text:w.text||"",...w.cache_control?{cache_control:w.cache_control}:{}})):JSON.stringify(k.content),...k.cache_control?{cache_control:k.cache_control}:{}},A=i[i.length-1];A?.role==="user"&&Array.isArray(A.content)?A.content.push(b):i.push({role:"user",content:[b]});continue}if(k.role==="assistant"){let b=[],A=as(k);if(A.thinking){let w=os(A.thinking);b.push({type:"thinking",thinking:A.thinking.content,...w?{signature:w}:{}})}for(let w of A.texts)b.push({type:"text",text:w.text,...w.cache_control?{cache_control:w.cache_control}:{}});for(let w of A.images){let E=w.image_url?.url;if(typeof E=="string"&&E.startsWith("data:")){let[x,O]=E.split(","),q=x.split(":")[1]?.split(";")[0]??"image/jpeg";b.push({type:"image",source:{type:"base64",media_type:q,data:O}})}else typeof E=="string"&&b.push({type:"image",source:{type:"url",url:E}})}if(A.toolCalls.length)for(let w of A.toolCalls){let E={};try{E=JSON.parse(w.function.arguments||"{}")}catch(x){(n?.error??console.error)("Failed to parse tool_call arguments for tool '%s': %s",w.function.name,x)}b.push({type:"tool_use",id:cr(w.id)??w.id,name:w.function.name,input:E,...w.cache_control?{cache_control:w.cache_control}:{}})}b.length>0&&i.push({role:"assistant",content:b});continue}if(k.role==="user"){let b=[];if(typeof k.content=="string")b.push({type:"text",text:k.content});else if(Array.isArray(k.content)){for(let A of k.content)if(A.type==="text"&&A.text)b.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 w=A.image_url.url;if(w.startsWith("data:")){let[E,x]=w.split(","),O=E.split(":")[1]?.split(";")[0]??"image/jpeg";b.push({type:"image",source:{type:"base64",media_type:O,data:x},...A.cache_control?{cache_control:A.cache_control}:{}})}else b.push({type:"image",source:{type:"url",url:w},...A.cache_control?{cache_control:A.cache_control}:{}})}}b.length>0&&i.push({role:"user",content:b});continue}}let a;if(e.tools?.length){let k=e.tools.find(b=>b?.type!=="function"||!b?.function);if(k)throw J(`Tool type '${k?.type||"unknown"}' cannot be represented by Anthropic Messages`,400,"unsupported_hosted_tool","invalid_request_error");a=e.tools.map(b=>({name:b.function.name,description:b.function.description||"",input_schema:b.function.parameters,...b.cache_control?{cache_control:b.cache_control}:{}}))}let u;if(e.tool_choice){let k=e.tool_choice;k==="auto"?u={type:"auto"}:k==="required"?u={type:"any"}:typeof k=="string"?u={type:"tool",name:k}:k.type==="function"&&(u={type:"tool",name:k.function?.name})}e.parallel_tool_calls===!1&&e.tool_choice!=="none"&&(!u&&a?.length&&(u={type:"auto"}),u&&typeof u=="object"&&(u.disable_parallel_tool_use=!0));let d=o.length===1&&!o[0].cache_control?o[0].text:o.length>0?o:void 0,f={model:e.model,max_tokens:e.max_tokens??8192,messages:i,stream:e.stream??!0};d!==void 0&&(f.system=d),e.temperature!==void 0&&(f.temperature=e.temperature),e.top_p!==void 0&&(f.top_p=e.top_p),e.stop!==void 0&&(f.stop_sequences=Array.isArray(e.stop)?e.stop:[e.stop]),e.tool_choice!=="none"&&a?.length&&(f.tools=a),e.tool_choice!=="none"&&u&&(f.tool_choice=u);let p=r?.protocolContext?.anthropicSource,h=Ot(e.reasoning,e.thinking);h?f.thinking={type:"disabled"}:p?.thinking?f.thinking=p.thinking:e.anthropic_thinking?f.thinking=e.anthropic_thinking:(e.reasoning?.enabled||e.reasoning?.effort)&&(f.thinking={type:"adaptive"});let g=p?.outputConfig?p.outputConfig:e.anthropic_output_config?e.anthropic_output_config:e.reasoning?.effort?{effort:e.reasoning.effort}:void 0,C=gI(g,h)||{},y=e.response_format;return y?.type==="json_schema"&&y.json_schema?.schema&&typeof y.json_schema.schema=="object"&&(C.format={type:"json_schema",schema:y.json_schema.schema}),Object.keys(C).length&&(f.output_config=C),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,C=new Map,y=new Map,k=0,b=0,A=!1;o=()=>{A=!0};let w=!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
|
|
179
181
|
data: ${JSON.stringify(Q)}
|
|
180
182
|
|
|
181
183
|
`)),x=-1}if(d)O>0&&(d.usage.server_tool_use={web_search_requests:O}),V(a.encode(`event: message_delta
|
|
@@ -200,7 +202,7 @@ data: ${JSON.stringify(we)}
|
|
|
200
202
|
`));continue}if(f=Z.model||f,!p&&!A&&!g){p=!0;let we={type:"message_start",message:{id:u,type:"message",role:"assistant",content:[],model:f,stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}};V(a.encode(`event: message_start
|
|
201
203
|
data: ${JSON.stringify(we)}
|
|
202
204
|
|
|
203
|
-
`))}let ae=Z.choices?.[0];if(Z.usage&&(d?d.usage=
|
|
205
|
+
`))}let ae=Z.choices?.[0];if(Z.usage&&(d?d.usage=vu(Z.usage):d={type:"message_delta",delta:{stop_reason:"end_turn",stop_sequence:null},usage:vu(Z.usage)}),!ae)continue;let Ie=Rn(ae?.delta);if(Ie&&!A&&!g){let we=typeof Ie.content=="string"?Ie.content:"",H=os(Ie);if(we||H){if(x>=0&&!w){let Ee={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
|
|
204
206
|
data: ${JSON.stringify(Ee)}
|
|
205
207
|
|
|
206
208
|
`)),x=-1,h=!1}if(!w){let Ee=q(),Ze={type:"content_block_start",index:Ee,content_block:{type:"thinking",thinking:""}};V(a.encode(`event: content_block_start
|
|
@@ -233,13 +235,13 @@ data: ${JSON.stringify(Ee)}
|
|
|
233
235
|
`));let Ze={type:"content_block_stop",index:H};V(a.encode(`event: content_block_stop
|
|
234
236
|
data: ${JSON.stringify(Ze)}
|
|
235
237
|
|
|
236
|
-
`))})}if(ae?.delta?.tool_calls&&!A&&!g){b++;let we=new Set;for(let H of ae.delta.tool_calls){if(A)break;let Ee=H.index??0;if(we.has(Ee))continue;if(we.add(Ee),!
|
|
238
|
+
`))})}if(ae?.delta?.tool_calls&&!A&&!g){b++;let we=new Set;for(let H of ae.delta.tool_calls){if(A)break;let Ee=H.index??0;if(we.has(Ee))continue;if(we.add(Ee),!y.has(Ee)){if(x>=0){let R={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
|
|
237
239
|
data: ${JSON.stringify(R)}
|
|
238
240
|
|
|
239
|
-
`)),x=-1}h=!1,w=!1;let X=q();
|
|
241
|
+
`)),x=-1}h=!1,w=!1;let X=q();y.set(Ee,X);let de=cr(H.id)||`call_${Date.now()}_${Ee}`,ce=H.function?.name||`tool_${Ee}`,S={type:"content_block_start",index:X,content_block:{type:"tool_use",id:de,name:ce,input:{}}};V(a.encode(`event: content_block_start
|
|
240
242
|
data: ${JSON.stringify(S)}
|
|
241
243
|
|
|
242
|
-
`)),x=X;let T={id:de,name:ce,arguments:"",contentBlockIndex:X};C.set(Ee,T)}else if(H.id&&H.function?.name){let X=C.get(Ee);X.id.startsWith("call_")&&X.name.startsWith("tool_")&&(X.id=H.id,X.name=H.function.name)}if(H.function?.arguments&&!A&&!g){let X=
|
|
244
|
+
`)),x=X;let T={id:de,name:ce,arguments:"",contentBlockIndex:X};C.set(Ee,T)}else if(H.id&&H.function?.name){let X=C.get(Ee);X.id.startsWith("call_")&&X.name.startsWith("tool_")&&(X.id=H.id,X.name=H.function.name)}if(H.function?.arguments&&!A&&!g){let X=y.get(Ee);if(X===void 0)continue;let de=C.get(Ee);de&&(de.arguments+=H.function.arguments);try{let ce={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:H.function.arguments}};V(a.encode(`event: content_block_delta
|
|
243
245
|
data: ${JSON.stringify(ce)}
|
|
244
246
|
|
|
245
247
|
`))}catch{try{let ce=H.function.arguments.replace(new RegExp("\\p{Cc}","gu"),"").replace(/\\/g,"\\\\").replace(/"/g,'\\"'),S={type:"content_block_delta",index:X,delta:{type:"input_json_delta",partial_json:ce}};V(a.encode(`event: content_block_delta
|
|
@@ -248,17 +250,17 @@ data: ${JSON.stringify(S)}
|
|
|
248
250
|
`))}catch(ce){this.logger?.error(ce)}}}}}if(ae?.finish_reason&&!A&&!g){if(k===0&&b===0&&this.logger?.warn("No content in the stream response!"),x>=0){let we={type:"content_block_stop",index:x};V(a.encode(`event: content_block_stop
|
|
249
251
|
data: ${JSON.stringify(we)}
|
|
250
252
|
|
|
251
|
-
`)),x=-1}if(!A){let H={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[ae.finish_reason]||"end_turn";_.size>0&&H==="end_turn"&&(H="tool_use"),d={type:"message_delta",delta:{stop_reason:H,stop_sequence:null},usage:Cu(Z.usage)}}break}}catch(Z){this.logger?.error(`parseError: ${Z.name} message: ${Z.message} stack: ${Z.stack} data: ${ne}`)}}}U()}catch(te){ee(te)}finally{if(r===z&&(r=null),z)try{z.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:async i=>{o?.();let a=r;r=null,a&&await a.cancel(i).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${i}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[],s=Rn(r.message);if(s?.content){let u=os(s);o.push({type:"thinking",thinking:s.content,...u?{signature:u}:{}})}if(r.message.content&&o.push({type:"text",text:r.message.content}),r.message.annotations){let u=`srvtoolu_${On()}`;o.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:u,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(u=>{if(!("function"in u)||!u.function)return;let d={};try{let f=u.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:u.function.arguments||""}}o.push({type:"tool_use",id:cr(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:{...Cu(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 dI=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"&&!dI.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 ys(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(ys);let e={};for(let h in t){let g=t[h];if(h==="properties"&&g&&typeof g=="object"){let C={};for(let _ in g)C[_]=ys(g[_]);e[h]=C}else h==="items"?e[h]=ys(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(ys):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 ku(t){return!t||typeof t!="object"?t:qr(t)}var Zi=["minimal","low","medium","high"];function fI(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function pI(t){let e=fI(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:Zi}:{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 hI(t,e){let n=t.toLowerCase(),r=Zi.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=Zi.indexOf(n);return o<0?r[r.length-1]:r.find(s=>Zi.indexOf(s)>=o)??r[r.length-1]}function gI(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function mI(t,e,n){return Math.min(Math.max(t,e),n)}function qk(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=pI(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=Zi.filter(f=>r.levels.includes(f));return s?{includeThoughts:!1,thinkingLevel:d[0]}:o?{includeThoughts:!0,thinkingLevel:hI(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?gI(o,r.max):void 0;if(typeof a!="number")return{includeThoughts:!0};let u=mI(a,r.min,r.max);if(t.max_tokens&&u>=t.max_tokens&&(u=t.max_tokens-1),u<r.min){if(r.requireMin)return;u=r.min}return{includeThoughts:!0,thinkingBudget:u}}var So=new Map,Hk=(t,e)=>`${t||"default"}${e}`;function zk(t,e,n){if(!e||!n)return;let r=Hk(t,e);for(So.delete(r),So.set(r,{signature:n,expiresAt:Date.now()+216e5});So.size>4096;){let o=So.keys().next();if(o.done)break;So.delete(o.value)}}function Wk(t,e){if(!e)return;let n=Hk(t,e),r=So.get(n);if(r){if(r.expiresAt<=Date.now()){So.delete(n);return}return r.signature}}function yI(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var _s={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(_s).includes(r)?r:_s.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(_s).includes(o)?o:_s.TYPE_UNSPECIFIED})}}}function ea(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(_s).includes(u)?u:_s.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=ea(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(ea(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=ea(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 bI(t,e){let n=r=>e?.collapseUnions?ys(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(ea(o))}if(r.response){let o=qr(r.response);r.response=n(ea(o))}}return t}var Jk="skip_thought_signature_validator";function Su(t,e){let n=[],r=t.tools||[],o=r.filter(b=>ms(b).name!=="web_search").map(b=>{let{name:A,description:w,parameters:E}=ms(b);return{name:Tk(A),description:w,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(bI({functionDeclarations:o},{collapseUnions:yI(t.model)})),r.find(b=>ms(b).name==="web_search")&&n.push({googleSearch:{}});let i=[],a=t.messages||[],u=[],d=b=>{if(typeof b=="string")b&&u.push(b);else if(Array.isArray(b))for(let A of b)A?.type==="text"&&A.text?u.push(A.text):typeof A=="string"&&A&&u.push(A)};t.system&&d(t.system);for(let b of a)b.role==="system"&&d(b.content);let f=a.filter(b=>b.role==="tool"),p=a.filter(b=>b.role!=="tool"&&b.role!=="system"),h=e?.thoughtSignatureFallback!=="none";p.forEach(b=>{let A=pu(b.role,{assistant:"model"}),w=[],E=Rn(b),x=os(E),O=x?.startsWith("ccr_")?void 0:x,q=U=>A==="model"&&(U==="(no content)"||U.startsWith(Ih));if(O&&A==="model"&&w.push({thought:!0,text:E?.content||"",thoughtSignature:O}),typeof b.content=="string")b.content&&!q(b.content)&&w.push({text:b.content});else if(Array.isArray(b.content))b.content.forEach(ee=>{if(ee.type==="text"){let z=ee.text||"";z&&!q(z)&&w.push({text:z})}}),hu(b.content).forEach(ee=>{w.push(mu(ee,"gemini"))});else if(b.content&&typeof b.content=="object")if(b.content.text){let U=b.content.text;q(U)||w.push({text:U})}else w.push({text:JSON.stringify(b.content)});let V=Array.isArray(b.tool_calls)?b.tool_calls.map((U,ee)=>{let z=U.id||`tool_${Math.random().toString(36).substring(2,15)}`,te=U.thought_signature||Wk(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?Jk:void 0)),{toolCall:U,id:z,signature:te}}):[];if(V.length>0&&w.push(...V.map(({toolCall:U,id:ee,signature:z})=>({functionCall:{id:ee,name:U.function.name,args:JSON.parse(U.function.arguments||"{}")},...z&&{thoughtSignature:z}}))),w.length===0&&w.push({text:""}),i.push({role:A,parts:w}),A==="model"&&V.length>0){let U=V.map(({toolCall:ee,id:z})=>{let Q=f.find(_e=>_e.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(_e=>_e.type==="text").map(_e=>_e.text).join(`
|
|
252
|
-
`):typeof Q=="object"&&Q!==null&&(Q=JSON.stringify(Q)),{functionResponse:{id:z,name:ee?.function?.name,response:{result:Q}}}});i.push({role:"user",parts:
|
|
253
|
+
`)),x=-1}if(!A){let H={stop:"end_turn",length:"max_tokens",tool_calls:"tool_use",content_filter:"stop_sequence",model_context_window_exceeded:"model_context_window_exceeded"}[ae.finish_reason]||"end_turn";y.size>0&&H==="end_turn"&&(H="tool_use"),d={type:"message_delta",delta:{stop_reason:H,stop_sequence:null},usage:vu(Z.usage)}}break}}catch(Z){this.logger?.error(`parseError: ${Z.name} message: ${Z.message} stack: ${Z.stack} data: ${ne}`)}}}j()}catch(te){ee(te)}finally{if(r===z&&(r=null),z)try{z.releaseLock()}catch(te){this.logger?.error(te)}}},cancel:async i=>{o?.();let a=r;r=null,a&&await a.cancel(i).catch(()=>{}),this.logger.debug({reqId:n.req.id},`cancel stream: ${i}`)}})}convertOpenAIResponseToAnthropic(e,n){this.logger.debug({reqId:n.req.id,response:e},"Original OpenAI response");try{let r=e.choices[0];if(!r)throw new Error("No choices found in OpenAI response");let o=[],s=Rn(r.message);if(s?.content){let u=os(s);o.push({type:"thinking",thinking:s.content,...u?{signature:u}:{}})}if(r.message.content&&o.push({type:"text",text:r.message.content}),r.message.annotations){let u=`srvtoolu_${On()}`;o.push({type:"server_tool_use",id:u,name:"web_search",input:{query:""}}),o.push({type:"web_search_tool_result",tool_use_id:u,content:r.message.annotations.map(d=>({type:"web_search_result",url:d.url_citation.url,title:d.url_citation.title}))})}r.message.tool_calls&&r.message.tool_calls.length>0&&r.message.tool_calls.forEach(u=>{if(!("function"in u)||!u.function)return;let d={};try{let f=u.function.arguments||"{}";typeof f=="object"?d=f:typeof f=="string"&&(d=JSON.parse(f))}catch{d={text:u.function.arguments||""}}o.push({type:"tool_use",id:cr(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:{...vu(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 mI=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"&&!mI.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 ys(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(ys);let e={};for(let h in t){let g=t[h];if(h==="properties"&&g&&typeof g=="object"){let C={};for(let y in g)C[y]=ys(g[y]);e[h]=C}else h==="items"?e[h]=ys(g):["anyOf","allOf","oneOf"].includes(h)&&Array.isArray(g)?e[h]=g.map(ys):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 xu(t){return!t||typeof t!="object"?t:qr(t)}var Zi=["minimal","low","medium","high"];function yI(t){return String(t||"").toLowerCase().replace(/^models\//,"")}function _I(t){let e=yI(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:Zi}:{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=Zi.filter(s=>e.includes(s));if(!r.length)return"high";if(n==="xhigh"||n==="max"||n==="ultra")return r[r.length-1];let o=Zi.indexOf(n);return o<0?r[r.length-1]:r.find(s=>Zi.indexOf(s)>=o)??r[r.length-1]}function CI(t,e){return Math.round(e*(t==="minimal"?.1:t==="low"?.25:t==="medium"?.5:1))}function wI(t,e,n){return Math.min(Math.max(t,e),n)}function Kk(t){let e=t.reasoning,n=t.thinking?.type==="disabled";if(!e||n)return;let r=_I(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=Zi.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?CI(o,r.max):void 0;if(typeof a!="number")return{includeThoughts:!0};let u=wI(a,r.min,r.max);if(t.max_tokens&&u>=t.max_tokens&&(u=t.max_tokens-1),u<r.min){if(r.requireMin)return;u=r.min}return{includeThoughts:!0,thinkingBudget:u}}var So=new Map,Vk=(t,e)=>`${t||"default"}${e}`;function Yk(t,e,n){if(!e||!n)return;let r=Vk(t,e);for(So.delete(r),So.set(r,{signature:n,expiresAt:Date.now()+216e5});So.size>4096;){let o=So.keys().next();if(o.done)break;So.delete(o.value)}}function Xk(t,e){if(!e)return;let n=Vk(t,e),r=So.get(n);if(r){if(r.expiresAt<=Date.now()){So.delete(n);return}return r.signature}}function kI(t){return String(t||"").toLowerCase().replace(/^models\//,"").startsWith("claude")}var _s={TYPE_UNSPECIFIED:"TYPE_UNSPECIFIED",STRING:"STRING",NUMBER:"NUMBER",INTEGER:"INTEGER",BOOLEAN:"BOOLEAN",ARRAY:"ARRAY",OBJECT:"OBJECT",NULL:"NULL"};function SI(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(_s).includes(r)?r:_s.TYPE_UNSPECIFIED}else{e.anyOf=[];for(let r of n){let o=r.toUpperCase();e.anyOf.push({type:Object.values(_s).includes(o)?o:_s.TYPE_UNSPECIFIED})}}}function ea(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)&&SI(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(_s).includes(u)?u:_s.TYPE_UNSPECIFIED}else if(n.includes(i))e[i]=ea(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(ea(d))}e[i]=u}else if(o.includes(i)){let u={};for(let[d,f]of Object.entries(a))u[d]=ea(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 AI(t,e){let n=r=>e?.collapseUnions?ys(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(ea(o))}if(r.response){let o=qr(r.response);r.response=n(ea(o))}}return t}var Zk="skip_thought_signature_validator";function Ru(t,e){let n=[],r=t.tools||[],o=r.filter(b=>ms(b).name!=="web_search").map(b=>{let{name:A,description:w,parameters:E}=ms(b);return{name:Ik(A),description:w,parameters:E??{type:"object",properties:{}}}});o?.length&&n.push(AI({functionDeclarations:o},{collapseUnions:kI(t.model)})),r.find(b=>ms(b).name==="web_search")&&n.push({googleSearch:{}});let i=[],a=t.messages||[],u=[],d=b=>{if(typeof b=="string")b&&u.push(b);else if(Array.isArray(b))for(let A of b)A?.type==="text"&&A.text?u.push(A.text):typeof A=="string"&&A&&u.push(A)};t.system&&d(t.system);for(let b of a)b.role==="system"&&d(b.content);let f=a.filter(b=>b.role==="tool"),p=a.filter(b=>b.role!=="tool"&&b.role!=="system"),h=e?.thoughtSignatureFallback!=="none";p.forEach(b=>{let A=yu(b.role,{assistant:"model"}),w=[],E=Rn(b),x=os(E),O=x?.startsWith("ccr_")?void 0:x,q=j=>A==="model"&&(j==="(no content)"||j.startsWith(qh));if(O&&A==="model"&&w.push({thought:!0,text:E?.content||"",thoughtSignature:O}),typeof b.content=="string")b.content&&!q(b.content)&&w.push({text:b.content});else if(Array.isArray(b.content))b.content.forEach(ee=>{if(ee.type==="text"){let z=ee.text||"";z&&!q(z)&&w.push({text:z})}}),_u(b.content).forEach(ee=>{w.push(Cu(ee,"gemini"))});else if(b.content&&typeof b.content=="object")if(b.content.text){let j=b.content.text;q(j)||w.push({text:j})}else w.push({text:JSON.stringify(b.content)});let V=Array.isArray(b.tool_calls)?b.tool_calls.map((j,ee)=>{let z=j.id||`tool_${Math.random().toString(36).substring(2,15)}`,te=j.thought_signature||Xk(e?.signatureScope,z);return!te&&ee===0&&(te=O||(h?Zk:void 0)),{toolCall:j,id:z,signature:te}}):[];if(V.length>0&&w.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}}))),w.length===0&&w.push({text:""}),i.push({role:A,parts:w}),A==="model"&&V.length>0){let j=V.map(({toolCall:ee,id:z})=>{let Q=f.find(_e=>_e.tool_call_id===ee.id)?.content;return Array.isArray(Q)?Q=Q.filter(_e=>_e.type==="text").map(_e=>_e.text).join(`
|
|
254
|
+
`):typeof Q=="object"&&Q!==null&&(Q=JSON.stringify(Q)),{functionResponse:{id:z,name:ee?.function?.name,response:{result:Q}}}});i.push({role:"user",parts:j})}});let g=bu(i,"parts"),C={},y=Kk(t);y&&(C.thinkingConfig=y),t.max_tokens&&(C.maxOutputTokens=t.max_tokens),t.temperature!==void 0&&(C.temperature=t.temperature);let k={contents:g.length?g:[{role:"user",parts:[{text:""}]}],tools:n.length?n:void 0,generationConfig:C};if(u.length&&(k.systemInstruction={parts:[{text:u.join(`
|
|
253
255
|
|
|
254
|
-
`)}]}),t.tool_choice){let b={functionCallingConfig:{}};t.tool_choice==="auto"?b.functionCallingConfig.mode="auto":t.tool_choice==="none"?b.functionCallingConfig.mode="none":t.tool_choice==="required"?b.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(b.functionCallingConfig.mode="any",b.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),k.toolConfig=b}return k}function
|
|
255
|
-
`)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",C=!g&&f.length===0?
|
|
256
|
+
`)}]}),t.tool_choice){let b={functionCallingConfig:{}};t.tool_choice==="auto"?b.functionCallingConfig.mode="auto":t.tool_choice==="none"?b.functionCallingConfig.mode="none":t.tool_choice==="required"?b.functionCallingConfig.mode="any":typeof t.tool_choice=="object"&&t.tool_choice.function?.name&&(b.functionCallingConfig.mode="any",b.functionCallingConfig.allowedFunctionNames=[t.tool_choice.function.name]),k.toolConfig=b}return k}function Du(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 Qk(t,e){e.forEach(n=>{let r=n.thought_signature;!r||r===Zk||r.startsWith("ccr_")||Yk(t,n.id,r)})}async function Ou(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 b of u)b.text&&b.thought===!0?i+=Xi(b.text):d.push(b);a=u.find(b=>b.thoughtSignature)?.thoughtSignature,i&&!a&&(a=`ccr_${+new Date}`);let f=d?.filter(b=>b.functionCall)?.map(b=>({id:b.functionCall?.id||`tool_${Math.random().toString(36).substring(2,15)}`,type:"function",function:{name:b.functionCall?.name,arguments:JSON.stringify(b.functionCall?.args||{})},thought_signature:b.thoughtSignature||b.thought_signature||void 0}))||[];a&&f.length>0&&!f[0].thought_signature&&(f[0].thought_signature=a),Qk(o,f);let p=d?.filter(b=>b.text)?.map(b=>Xi(b.text||""))?.join(`
|
|
257
|
+
`)||"",h=s.candidates[0],g=p&&p!=="(no content)"?p:"",C=!g&&f.length===0?Hh(h):null,y=Yi(h?.finishReason),k={id:s.responseId,choices:[{finish_reason:f.length>0?"tool_calls":y,index:0,message:{content:C||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(k),{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=(k,b)=>{k.controller.enqueue(k.encoder.encode(`data: ${JSON.stringify(b)}
|
|
256
258
|
|
|
257
|
-
`))},p=k=>({completion_tokens:k?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:k?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:k?.usageMetadata?.cachedContentTokenCount||0},total_tokens:k?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:k?.usageMetadata?.thoughtsTokenCount||0}}),h=k=>k?.groundingMetadata?.groundingChunks?.map((b,A)=>{let w=k?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:b?.web?.uri||"",title:b?.web?.title||"",content:w?.[0]?.segment?.text||"",start_index:w?.[0]?.segment?.startIndex||0,end_index:w?.[0]?.segment?.endIndex||0}}})||[],g=(k,b,A)=>{let w=A?.mode||"direct";w==="direct"&&s++;let E={choices:[{delta:{role:"assistant",content:b},finish_reason:A?.finishReason??(w==="direct"||w==="finish"?Yi(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(w==="direct"||w==="finish"){E.usage=p(A?.chunk);let x=h(A?.candidate);x.length>0&&(E.choices[0].delta.annotations=x)}f(k,E)},C=new
|
|
258
|
-
`),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),
|
|
259
|
+
`))},p=k=>({completion_tokens:k?.usageMetadata?.candidatesTokenCount||0,prompt_tokens:k?.usageMetadata?.promptTokenCount||0,prompt_tokens_details:{cached_tokens:k?.usageMetadata?.cachedContentTokenCount||0},total_tokens:k?.usageMetadata?.totalTokenCount||0,output_tokens_details:{reasoning_tokens:k?.usageMetadata?.thoughtsTokenCount||0}}),h=k=>k?.groundingMetadata?.groundingChunks?.map((b,A)=>{let w=k?.groundingMetadata?.groundingSupports?.filter(E=>E.groundingChunkIndices?.includes(A));return{type:"url_citation",url_citation:{url:b?.web?.uri||"",title:b?.web?.title||"",content:w?.[0]?.segment?.text||"",start_index:w?.[0]?.segment?.startIndex||0,end_index:w?.[0]?.segment?.endIndex||0}}})||[],g=(k,b,A)=>{let w=A?.mode||"direct";w==="direct"&&s++;let E={choices:[{delta:{role:"assistant",content:b},finish_reason:A?.finishReason??(w==="direct"||w==="finish"?Yi(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(w==="direct"||w==="finish"){E.usage=p(A?.chunk);let x=h(A?.candidate);x.length>0&&(E.choices[0].delta.annotations=x)}f(k,E)},C=new mu({thinking:(k,b)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{content:k}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b?.responseId||"",model:b?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},signature:(k,b)=>{a&&f(a,{choices:[{delta:{role:"assistant",content:null,thinking:{signature:k}},finish_reason:null,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:b?.responseId||"",model:b?.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1"})},content:(k,b)=>{a&&g(a,k,b)}});return Ne(t,(k,b)=>{if(a=b,k.startsWith("data: ")){let A=k.slice(6).trim();if(A){n?.debug({chunkStr:A},`${e} chunk:`);try{let w=JSON.parse(A);if(!w.candidates||!w.candidates[0]){n?.debug({chunkStr:A},"Invalid chunk structure");return}let E=w.candidates[0];u=w,d=E;let x=E.content?.parts||[];x.filter(z=>z.text&&z.thought===!0).forEach(z=>{C.processThinking(Xi(z.text),w)});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=>Xi(z.text||"")).join(`
|
|
260
|
+
`),V=x.find(z=>z.thoughtSignature)?.thoughtSignature;V&&O.length>0&&!O[0].thought_signature&&(O[0].thought_signature=V),Qk(o,O);let j=!!(q&&q!=="(no content)")||O.length>0||!!E.finishReason;if(q&&q!=="(no content)"&&w.modelVersion?.includes("3")&&C.shouldDeferContent(!!E.finishReason,O.length>0))C.bufferContent(q);else if(q&&q!=="(no content)"){if(C.hasThinkingContent&&!C.signatureSent&&j&&!V){let z=C.hasBufferedContent;C.processSignatureWithMeta(`ccr_${+new Date}`,w,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:w,candidate:E,mode:"buffered",finishReason:null}:void 0})}C.processContent(q,w,E)}V&&(O.length>0&&!C.hasThinkingContent&&!q&&!C.contentSent?C.acknowledgeSignature():C.processSignatureWithMeta(V,w,{beforeFlush:()=>{s++},flushMeta:{chunk:w,candidate:E,mode:"buffered"}}));let ee=i<0&&O.length===0&&!q?Hh(E):null;if(!q&&O.length===0&&i<0&&E.finishReason&&!ee&&C.needsContentPlaceholder&&C.emitContentPlaceholder("(no content)",{chunk:w,candidate:E}),!V&&!q&&C.hasThinkingContent&&!C.signatureSent&&j){let z=C.hasBufferedContent;C.processSignatureWithMeta(`ccr_${+new Date}`,w,{beforeFlush:z?()=>{s++}:void 0,flushMeta:z?{chunk:w,candidate:E,mode:"buffered",finishReason:null}:void 0})}if(q&&w.modelVersion?.includes("3")&&C.hasBufferedContent&&!V&&O.length===0&&!E.finishReason)return;O.length>0&&O.forEach((z,te)=>{s++,i++;let Q=E.finishReason!=null&&te===O.length-1?"tool_calls":null,_e={choices:[{delta:{role:"assistant",tool_calls:[{...z,index:i}]},finish_reason:Q,index:s,logprobs:null}],created:parseInt(new Date().getTime()/1e3+"",10),id:w.responseId||"",model:w.modelVersion||"",object:"chat.completion.chunk",system_fingerprint:"fp_a49d71b8a1",usage:p(w)},Oe=h(E);Oe.length>0&&(_e.choices[0].delta.annotations=Oe),f(b,_e)}),E.finishReason&&(C.hasBufferedContent?C.finalize(w,E,{beforeFlush:()=>{C.signatureSent||s++}}):!q&&O.length===0&&(s++,g(b,ee||"",{chunk:w,candidate:E,mode:"finish",...i>=0?{finishReason:"tool_calls"}:{}})))}catch(w){n?.error(`Error parsing ${e} stream chunk`,A,w.message)}}}},{onComplete:k=>{a=k,(C.hasBufferedContent||C.hasThinkingContent&&!C.signatureSent)&&C.finalize(u||void 0,d||void 0,{beforeFlush:()=>{C.signatureSent||s++}})}})}return t}import{createHash as EI}from"crypto";var vI=15e3,TI=256,dr=new Map,ng=new Map;function eS(t){return EI("sha256").update(JSON.stringify(t)).digest("hex").slice(0,48)}function xI(t){return t.toLowerCase().includes("gemini-2.5")?2048:4096}function RI(t){return Math.floor(JSON.stringify(t).length/4)}function DI(t){return Object.fromEntries(["systemInstruction","tools","toolConfig"].filter(e=>t[e]!==void 0).map(e=>[e,t[e]]))}function tS(t,e){let n={...t,cachedContent:e};return delete n.systemInstruction,delete n.tools,delete n.toolConfig,n}function Pu(t,e){let n=Date.now();for(let[r,o]of dr)o.expiresAt<=n&&dr.delete(r);for(dr.delete(t),dr.set(t,e);dr.size>TI;){let r=dr.keys().next().value;if(r===void 0)break;dr.delete(r)}}async function Iu(t){let{body:e,modelResource:n,createUrl:r,headers:o}=t,s=DI(e);if(Object.keys(s).length===0||RI(s)<xI(n))return e;let i=eS(o),a=[String(r),i,n,eS(s)].join(":"),u=Date.now(),d=dr.get(a);if(d&&d.expiresAt>u)return d.name?tS(e,d.name):e;d&&dr.delete(a);let f=3600,p={model:n,...s,ttl:`${f}s`},h=ng.get(a);h||(h=(async()=>{try{let C=await fetch(r,{method:"POST",headers:Object.fromEntries(Object.entries({"Content-Type":"application/json",...o}).filter(([,k])=>k!==void 0)),body:JSON.stringify(p),signal:AbortSignal.timeout(vI)});if(!C.ok){t.logger?.debug?.({status:C.status},"Gemini cached-content create failed; using implicit cache"),Pu(a,{expiresAt:Date.now()+300*1e3});return}let y=await C.json();if(!y?.name){t.logger?.debug?.("Gemini cached-content response had no resource name; using implicit cache"),Pu(a,{expiresAt:Date.now()+300*1e3});return}return Pu(a,{name:y.name,expiresAt:Date.now()+(f-30)*1e3}),y.name}catch(C){t.logger?.debug?.({error:C?.message||String(C)},"Gemini cached-content create errored; using implicit cache"),Pu(a,{expiresAt:Date.now()+300*1e3});return}finally{ng.delete(a)}})(),ng.set(a,h));let g=await h;return g?tS(e,g):e}var Fu=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=Ru(e,{thoughtSignatureFallback:this.thoughtSignatureFallback,signatureScope:n?.name||this.name});return{body:this.cachedContent?await Iu({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 Du(e)}async transformResponseOut(e,n){return Ou(e,this.name,this.logger,n?.provider?.name||this.name)}};async function Uj(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(hd(),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
261
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
260
262
|
2. Run "gcloud auth application-default login"
|
|
261
|
-
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 IU(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 Tu({body:Su(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 Au(e)}async transformResponseOut(e,n){return Eu(e,this.name,this.logger,n?.provider?.name||this.name)}};function ld(){return{content:"",isComplete:!1,hasContent:!1}}function dd(t,e){t.content+=e,t.hasContent=!0}function fd(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Qr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function Vs(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 Zr(t){delete t.reasoning_content,delete t.reasoning}import{createHash as FU}from"node:crypto";var yT=360*60*1e3,NU=4096,Ry="__ccrDeepseekReasoning",Dy=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>yT){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>yT&&this.cache.delete(e);for(;this.cache.size>NU;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},pd=new Dy;function Oy(t){return Array.isArray(t)?t.map(Oy):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=Oy(t[n]),e),{}):t}function Mo(t){return JSON.stringify(Oy(t))}function hd(t){return FU("sha256").update(t).digest("hex")}function bT(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):Mo(e)).join(""):Mo(t)}function Py(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Mo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function CT(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function wT(t){let e=Py(t);return hd(Mo({...e,id:void 0}))}function kT(t){return hd(Mo({content:bT(t.content),tool_calls:(t.tool_calls||[]).map(e=>Py(e))}))}function MU(t){let e={role:t.role,content:bT(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=>Py(n))),e}function _T(t,e){let n=t.filter(r=>r.role!=="system").map(r=>MU(r));return hd(Mo({namespace:e,messages:n}))}function BU(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 ST(t,e){if(t.role!=="assistant")return 0;let n=BU(t);if(!n)return 0;let r=[`scope:${e}:signature:${kT(t)}`];return r.push(...CT(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${wT(o)}`)),r.forEach(o=>pd.put(o,n)),r.length}function jU(t,e){let n=pd.get(`scope:${e}:signature:${kT(t)}`);if(n)return n;for(let r of CT(t)){let o=pd.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=pd.get(`scope:${e}:tool_call_signature:${wT(r)}`);if(o)return o}}function UU(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 LU(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek");if(t.enable_thinking===!1||Ot(t.reasoning,t.thinking))return!1;let i=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&i}function $U(t,e){return hd(Mo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function gd(t,e,n){if(!LU(t,e))return n?.req&&delete n.req[Ry],{restoredFromCache:0,restoredFromThinking:0};let r=$U(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=_T(o,r);if(UU(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=jU(a,u);h&&(a.reasoning_content=h,s++)}}ST(a,u)}o.push(a)}return n?.req&&(n.req[Ry]={enabled:!0,namespace:r,requestScope:_T(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function AT(t){return t?.req?.[Ry]}function md(t){return AT(t)?.enabled===!0}function Ys(t,e){if(!t)return 0;let n=AT(e);return n?ST(t,n.requestScope):0}function yd(){return{content:"",reasoning:"",toolCalls:new Map}}function Xs(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 _d(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 ET(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 bd=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Ke(e.messages),e.tools=Ve(e.tools),gd(e,n,r),e}async transformResponseOut(e,n){let r=md(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return ET(o),r&&Ys({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=ld(),s=r?yd():null;return Ne(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Pe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Pe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);ET(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(ve(JSON.stringify(d),a.encoder));return}let p=Vs(f);if(p){s&&Xs(s,f),dd(o,p);let h=Qr(d,{content:p});Zr(h.choices[0].delta),a.controller.enqueue(ve(JSON.stringify(h),a.encoder));return}if(s&&Xs(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=fd(o),C=Qr(d,{content:h,signature:g});Zr(C.choices[0].delta),C.choices[0].delta.content=null,a.controller.enqueue(ve(JSON.stringify(C),a.encoder))}f.reasoning_content&&delete f.reasoning_content,d.choices?.[0]?.delta&&Object.keys(d.choices[0].delta).length>0&&(o.isComplete&&d.choices[0].index++,a.controller.enqueue(ve(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Pe(i,a.encoder))}},{onComplete:()=>{s&&Ys(_d(s),n)}})}return e}};var Cd=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 gd=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 Uj(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 Iu({body:Ru(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 Du(e)}async transformResponseOut(e,n){return Ou(e,this.name,this.logger,n?.provider?.name||this.name)}};function md(){return{content:"",isComplete:!1,hasContent:!1}}function yd(t,e){t.content+=e,t.hasContent=!0}function _d(t){return t.isComplete=!0,{content:t.content,signature:Date.now().toString()}}function Qr(t,e){return{...t,choices:[{...t.choices?.[0]||{},delta:{...t.choices?.[0]?.delta||{},content:null,thinking:e}}]}}function Vs(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 Zr(t){delete t.reasoning_content,delete t.reasoning}import{createHash as jj}from"node:crypto";var ST=360*60*1e3,Lj=4096,By="__ccrDeepseekReasoning",Uy=class{cache=new Map;get(e){let n=this.cache.get(e);if(n){if(Date.now()-n.createdAt>ST){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>ST&&this.cache.delete(e);for(;this.cache.size>Lj;){let e=this.cache.keys().next().value;if(!e)break;this.cache.delete(e)}}},bd=new Uy;function jy(t){return Array.isArray(t)?t.map(jy):t&&typeof t=="object"?Object.keys(t).sort().reduce((e,n)=>(e[n]=jy(t[n]),e),{}):t}function Mo(t){return JSON.stringify(jy(t))}function Cd(t){return jj("sha256").update(t).digest("hex")}function ET(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):Mo(e)).join(""):Mo(t)}function Ly(t){let e=t.function??{},n=typeof e.arguments=="string"?e.arguments:Mo(e.arguments??"");return{id:t.id||"",type:t.type||"function",function:{name:e.name||"",arguments:n}}}function vT(t){return(t.tool_calls||[]).map(e=>e.id).filter(e=>typeof e=="string"&&e.length>0)}function TT(t){let e=Ly(t);return Cd(Mo({...e,id:void 0}))}function xT(t){return Cd(Mo({content:ET(t.content),tool_calls:(t.tool_calls||[]).map(e=>Ly(e))}))}function $j(t){let e={role:t.role,content:ET(t.content)};return t.name&&(e.name=t.name),t.tool_call_id&&(e.tool_call_id=t.tool_call_id),t.tool_calls?.length&&(e.tool_calls=t.tool_calls.map(n=>Ly(n))),e}function AT(t,e){let n=t.filter(r=>r.role!=="system").map(r=>$j(r));return Cd(Mo({namespace:e,messages:n}))}function qj(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 RT(t,e){if(t.role!=="assistant")return 0;let n=qj(t);if(!n)return 0;let r=[`scope:${e}:signature:${xT(t)}`];return r.push(...vT(t).map(o=>`scope:${e}:tool_call:${o}`)),r.push(...(t.tool_calls||[]).map(o=>`scope:${e}:tool_call_signature:${TT(o)}`)),r.forEach(o=>bd.put(o,n)),r.length}function Hj(t,e){let n=bd.get(`scope:${e}:signature:${xT(t)}`);if(n)return n;for(let r of vT(t)){let o=bd.get(`scope:${e}:tool_call:${r}`);if(o)return o}for(let r of t.tool_calls||[]){let o=bd.get(`scope:${e}:tool_call_signature:${TT(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 Wj(t,e){let n=String(t.model||"").toLowerCase(),r=String(e?.name||"").toLowerCase(),o=String(e?.baseUrl||"").toLowerCase(),s=n.includes("deepseek")||r.includes("deepseek")||o.includes("deepseek");if(t.enable_thinking===!1||Ot(t.reasoning,t.thinking))return!1;let i=t.enable_thinking===!0||t.thinking?.type==="enabled"||t.reasoning?.enabled===!0||typeof t.reasoning?.effort=="string"||typeof t.reasoning?.max_tokens=="number";return s&&i}function Gj(t,e){return Cd(Mo({provider:e?.name||"",baseUrl:e?.baseUrl||"",model:t.model||"",thinking:t.thinking||null,enable_thinking:t.enable_thinking||!1,reasoning:t.reasoning||null}))}function wd(t,e,n){if(!Wj(t,e))return n?.req&&delete n.req[By],{restoredFromCache:0,restoredFromThinking:0};let r=Gj(t,e),o=[],s=0,i=0;for(let a of t.messages){if(a.role==="assistant"){let u=AT(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=Hj(a,u);h&&(a.reasoning_content=h,s++)}}RT(a,u)}o.push(a)}return n?.req&&(n.req[By]={enabled:!0,namespace:r,requestScope:AT(t.messages,r)}),{restoredFromCache:s,restoredFromThinking:i}}function DT(t){return t?.req?.[By]}function kd(t){return DT(t)?.enabled===!0}function Ys(t,e){if(!t)return 0;let n=DT(e);return n?RT(t,n.requestScope):0}function Sd(){return{content:"",reasoning:"",toolCalls:new Map}}function Xs(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 Ad(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 OT(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 Ed=class{name="deepseek";async transformRequestIn(e,n,r){return e.max_tokens&&e.max_tokens>8192&&(e.max_tokens=8192),e.messages=Ke(e.messages),e.tools=Ve(e.tools),wd(e,n,r),e}async transformResponseOut(e,n){let r=kd(n);if(e.headers.get("Content-Type")?.includes("application/json")){let o=await e.json();return OT(o),r&&Ys({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=md(),s=r?Sd():null;return Ne(e,(i,a)=>{if(!i.trim()){a.controller.enqueue(Pe(i,a.encoder));return}if(!i.startsWith("data:")||i.trim()==="data: [DONE]"){a.controller.enqueue(Pe(i,a.encoder));return}try{let u=i.slice(5).trim(),d=JSON.parse(u);OT(d);let f=d.choices?.[0]?.delta;if(!f){a.controller.enqueue(ve(JSON.stringify(d),a.encoder));return}let p=Vs(f);if(p){s&&Xs(s,f),yd(o,p);let h=Qr(d,{content:p});Zr(h.choices[0].delta),a.controller.enqueue(ve(JSON.stringify(h),a.encoder));return}if(s&&Xs(s,f),f.content&&o.hasContent&&!o.isComplete){let{content:h,signature:g}=_d(o),C=Qr(d,{content:h,signature:g});Zr(C.choices[0].delta),C.choices[0].delta.content=null,a.controller.enqueue(ve(JSON.stringify(C),a.encoder))}f.reasoning_content&&delete f.reasoning_content,d.choices?.[0]?.delta&&Object.keys(d.choices[0].delta).length>0&&(o.isComplete&&d.choices[0].index++,a.controller.enqueue(ve(JSON.stringify(d),a.encoder)))}catch{a.controller.enqueue(Pe(i,a.encoder))}},{onComplete:()=>{s&&Ys(Ad(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.
|
|
262
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.
|
|
263
265
|
Examples:
|
|
264
266
|
1. Task: "Use a tool to summarize this document" \u2014 Do not use ExitTool if a summarization tool is available.
|
|
@@ -268,124 +270,126 @@ Examples:
|
|
|
268
270
|
|
|
269
271
|
`;a.enqueue(u.encode(f))}}catch{a.enqueue(u.encode(s+`
|
|
270
272
|
`))}else a.enqueue(u.encode(s+`
|
|
271
|
-
`))})}return e}};var
|
|
272
|
-
+`.includes(t)}function
|
|
273
|
-
+`.includes(t)}function
|
|
274
|
-
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function br(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function
|
|
275
|
-
`,r:"\r",t:" "};function
|
|
276
|
-
`;)e++;return!0}return!1}function d(ne){if(f(ne)){if(
|
|
273
|
+
`))})}return e}};var Td=class{constructor(e){this.options=e}options;static TransformerName="openrouter";logger;async transformRequestIn(e,n,r){let o=en(r,e),s=(e.model||"").toLowerCase();return s.includes("anthropic/")||s.includes("claude")?e=Lc(e):s.startsWith("openai/")||s.startsWith("gpt-")?e=Hi(e,n,r):s.includes("qwen")||s.includes("alibaba")?e=yo(e):s.includes("gemini")?e=yo(e):e={...e,messages:Ke(e.messages),tools:Ve(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=md(),r=!1,o=!1;return Ne(e,(s,i)=>{if(!s.trim()){i.controller.enqueue(Pe(s,i.encoder));return}if(!s.startsWith("data: ")||s.trim()==="data: [DONE]"){i.controller.enqueue(Pe(s,i.encoder));return}try{let a=s.slice(6),u=JSON.parse(a);u.usage&&(this.logger?.debug({usage:u.usage,hasToolCall:o},"usage"),u.choices[0].finish_reason=o?"tool_calls":"stop"),u.choices?.[0]?.finish_reason==="error"&&i.controller.enqueue(ve(JSON.stringify({error:u.choices?.[0]?.error}),i.encoder)),u.choices?.[0]?.delta?.content&&!r&&(r=!0);let d=u.choices?.[0]?.delta,f=d?Vs(d):null;if(f){yd(n,f);let p=Qr(u,{content:f});Zr(p.choices[0].delta),i.controller.enqueue(ve(JSON.stringify(p),i.encoder));return}if(d?.content&&n.hasContent&&!n.isComplete){let{content:p,signature:h}=_d(n),g=Qr(u,{content:p,signature:h});Zr(g.choices[0].delta),g.choices[0].delta.content=null,i.controller.enqueue(ve(JSON.stringify(g),i.encoder))}d?.reasoning&&delete d.reasoning,d?.tool_calls?.length&&!Number.isNaN(parseInt(d.tool_calls[0].id,10))&&d.tool_calls.forEach(p=>{p.id=`call_${On()}`}),d?.tool_calls?.length&&!o&&(o=!0),d?.tool_calls?.length&&r&&(typeof u.choices[0].index=="number"?u.choices[0].index+=1:u.choices[0].index=1),i.controller.enqueue(ve(JSON.stringify(u),i.encoder))}catch{i.controller.enqueue(Pe(s,i.encoder))}})}return e}};var 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 Rd=class{name="groq";async transformRequestIn(e){return e.messages=Ke(e.messages),e.tools=Ve(e.tools),Array.isArray(e.tools)&&e.tools.forEach(n=>{n?.function?.parameters&&(n.function.parameters=xu(n.function.parameters))}),e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=!1;return Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(!r.startsWith("data:")||r.trim()==="data: [DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}try{let s=r.slice(5).trim(),i=JSON.parse(s);if(i.error)throw new Error(JSON.stringify(i));i.choices?.[0]?.delta?.content&&!n&&(n=!0),i.choices?.[0]?.delta?.tool_calls?.length&&i.choices[0].delta.tool_calls.forEach(a=>{a.id=`call_${On()}`}),i.choices?.[0]?.delta?.tool_calls?.length&&n&&(typeof i.choices[0].index=="number"?i.choices[0].index+=1:i.choices[0].index=1),o.controller.enqueue(ve(JSON.stringify(i),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}})}return e}};var Dd=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 qT=nr(oh());var _r=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};function PT(t){return/^[0-9A-Fa-f]$/.test(t)}function Cr(t){return t>="0"&&t<="9"}function IT(t){return t>=" "}function Zs(t){return`,:[]/{}()
|
|
274
|
+
+`.includes(t)}function $y(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function Od(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var qy=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,Hy=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function zy(t){return`,[]/{}
|
|
275
|
+
+`.includes(t)}function Wy(t){return ei(t)||Jj.test(t)}var Jj=/^[[{\w-]$/;function Gy(t){return t===`
|
|
276
|
+
`||t==="\r"||t===" "||t==="\b"||t==="\f"}function br(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function FT(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function NT(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 ei(t){return Jy(t)||Pd(t)}function Jy(t){return t==='"'||t==="\u201C"||t==="\u201D"}function Ky(t){return t==='"'}function Pd(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function Vy(t){return t==="'"}function ti(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,r=t.lastIndexOf(e);return r!==-1?t.substring(0,r)+(n?"":t.substring(r+1)):t}function Yt(t,e){let n=t.length;if(!br(t,n-1))return t+e;for(;br(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function MT(t,e,n){return t.substring(0,e)+t.substring(e+n)}function BT(t){return/[,\n][ \t\r]*$/.test(t)}var Kj={""":'"',"&":"&","<":"<",">":">","'":"'"},Yy=12;function Xy(t){if(t.charAt(0)!=="&")return null;let e=t.indexOf(";");if(e===-1)return null;let n=t.substring(0,e+1),r=Kj[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 UT(t){return t!==null&&t.char==='"'}function jT(t){return t!==null&&t.char==="'"}function Qs(t,e){let n=0;for(let r=0;r<t.length;r++)t.charAt(r)===e&&n++;return n}function LT(t,e){switch(e){case")":return Qs(t,"(")>Qs(t,")");case"]":return Qs(t,"[")>Qs(t,"]");case"}":return Qs(t,"{")>Qs(t,"}");default:return!1}}var $T={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Vj={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
277
|
+
`,r:"\r",t:" "};function Qy(t){let e=0,n="";d(["```","[```","{```"]),s()||_e(),d(["```","```]","```}"]);let o=p(",");for(o&&i(),Wy(t[e])&&BT(n)?(o||(n=Yt(n,",")),b()):o&&(n=ti(n,","));t[e]==="}"||t[e]==="]";)e++,i();if(e>=t.length)return n;Q();function s(){i();let ne=y()||k()||A()||E()||x()||q(!1)||V();return i(),ne}function i(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,Z=e,ae=a(ne);do ae=u(),ae&&(ae=a(ne));while(ae);return e>Z}function a(ne){let Z=ne?br:FT,ae="";for(;;)if(Z(t,e))ae+=t[e],e++;else if(NT(t,e))ae+=" ",e++;else break;return ae.length>0?(n+=ae,!0):!1}function u(){if(t[e]==="/"&&t[e+1]==="*"){for(;e<t.length&&!Yj(t,e);)e++;return e+=2,!0}if(t[e]==="/"&&t[e+1]==="/"){for(;e<t.length&&t[e]!==`
|
|
278
|
+
`;)e++;return!0}return!1}function d(ne){if(f(ne)){if($y(t[e]))for(;e<t.length&&Od(t[e]);)e++;return i(),!0}return!1}function f(ne){a(!0);for(let Z of ne){let ae=e+Z.length;if(t.slice(e,ae)===Z)return e=ae,!0}return!1}function p(ne){return t[e]===ne?(n+=t[e],e++,!0):!1}function h(ne){return t[e]===ne?(e++,!0):!1}function g(){return h("\\")}function C(){return i(),t[e]==="."&&t[e+1]==="."&&t[e+2]==="."?(e+=3,i(),h(","),!0):!1}function y(){if(t[e]==="{"){n+="{",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="}";){let Z;if(ne?Z=!0:(Z=p(","),Z||(n=Yt(n,",")),i()),C(),!(A()||q(!0))){t[e]==="}"||t[e]==="{"||t[e]==="]"||t[e]==="["||t[e]===void 0?ne||(n=ti(n,",")):Oe();break}i();let Ie=p(":"),we=e>=t.length;Ie||(Wy(t[e])||we?n=Yt(n,":"):Te()),s()||(Ie||we?n+="null":Te()),ne=!1}return t[e]==="}"?(n+="}",e++):n=Yt(n,"}"),!0}return!1}function k(){if(t[e]==="["){n+="[",e++,i(),h(",")&&i();let ne=!0;for(;e<t.length&&t[e]!=="]";){if(ne||p(",")||(n=Yt(n,",")),C(),!s()){ne||(n=ti(n,","));break}ne=!1}return t[e]==="]"?(n+="]",e++):n=Yt(n,"]"),!0}return!1}function b(){let ne=!0,Z=!0;for(;Z;)ne?ne=!1:p(",")||(n=Yt(n,",")),Z=s();Z||(n=ti(n,",")),n=`[
|
|
277
279
|
${n}
|
|
278
|
-
]`}function A(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";ae&&(e++,ei(t[e])||Q());let Ie=t[e]==="&"?
|
|
279
|
-
`?(X+="\\n",e+=2):(X+=S,e+=2)}else{let S=t.charAt(e);S==='"'&&t[e-1]!=="\\"?(X+=`\\${S}`,e++):
|
|
280
|
+
]`}function A(){let ne=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,Z=arguments.length>1&&arguments[1]!==void 0?arguments[1]:-1,ae=t[e]==="\\";ae&&(e++,ei(t[e])||Q());let Ie=t[e]==="&"?Xy(t.slice(e,e+Yy)):null,we=UT(Ie)||jT(Ie);if(ei(t[e])||we){let H=Ky(t[e])?Ky:Vy(t[e])?Vy:Pd(t[e])?Pd:Jy,Ee=e,Ze=n.length,X='"';for(e+=we&&Ie?Ie.length:1;;){if(e>=t.length){let S=j(e-1);return!ne&&Zs(t.charAt(S))?(e=Ee,n=n.substring(0,Ze),A(!0)):(X=Yt(X,'"'),n+=X,!0)}if(e===Z)return X=Yt(X,'"'),n+=X,!0;let de=we&&t[e]==="&"?Xy(t.slice(e,e+Yy)):null;if(de&&Ie?de.char===Ie.char:H(t[e])){let S=e,T=X.length;if(X+='"',e+=de?de.length:1,n+=X,i(!1),ne||e>=t.length||Zs(t[e])&&!LT(X,t[e])||ei(t[e])&&!ee(e)||Cr(t[e]))return w(),!0;t[e]==="\\"&&Q();let R=j(S-1),M=t.charAt(R);if(M===",")return e=Ee,n=n.substring(0,Ze),A(!1,R);if(Zs(M))return e=Ee,n=n.substring(0,Ze),A(!0);n=n.substring(0,Ze),e=S+(de?de.length:1),X=`${X.substring(0,T)}\\${X.substring(T)}`}else if(ne&&zy(t[e])){if(t[e-1]===":"&&qy.test(t.substring(Ee+1,e+2)))for(;e<t.length&&Hy.test(t[e]);)X+=t[e],e++;return X=Yt(X,'"'),n+=X,w(),!0}else if(de){let S=de.char;S==='"'?X+='\\"':Gy(S)?X+=$T[S]:X+=S,e+=de.length}else if(t[e]==="\\"){let S=t.charAt(e+1);if(Vj[S]!==void 0)X+=t.slice(e,e+2),e+=2;else if(S==="u"){let R=2;for(;R<6&&PT(t[e+R]);)R++;R===6?(X+=t.slice(e,e+6),e+=6):e+R>=t.length?e=t.length:Ge()}else S===`
|
|
281
|
+
`?(X+="\\n",e+=2):(X+=S,e+=2)}else{let S=t.charAt(e);S==='"'&&t[e-1]!=="\\"?(X+=`\\${S}`,e++):Gy(S)?(X+=$T[S],e++):(IT(S)||te(S),X+=S,e++)}ae&&g()}}return!1}function w(){let ne=!1;for(i();t[e]==="+";){ne=!0,e++,i(),n=ti(n,'"',!0);let Z=n.length;A()?n=MT(n,Z,1):n=Yt(n,'"')}return ne}function E(){let ne=e,Z="",ae=!1;for(t[e]==="-"&&(Z+=t[e],e++,!Cr(t[e])&&z()&&(Z+="0")),t[e]==="0"&&Cr(t[e+1])&&(ae=!0);Cr(t[e]);)Z+=t[e],e++;if(t[e]===".")for((Z===""||Z==="-")&&(Z+="0"),Z+=t[e],e++,Cr(t[e])||(Z+="0");Cr(t[e]);)Z+=t[e],e++;if(e>ne){if(t[e]==="e"||t[e]==="E")for(Z==="-"&&(ae=!0),Z+=t[e],e++,(t[e]==="-"||t[e]==="+")&&(Z+=t[e],e++),Cr(t[e])||(Z+="0");Cr(t[e]);)Z+=t[e],e++;return z()?(n+=ae?`"${t.substring(ne,e)}"`:Z,!0):(e=ne,!1)}return!1}function x(){return O("true","true")||O("false","false")||O("null","null")||O("True","true")||O("False","false")||O("None","null")}function O(ne,Z){return t.slice(e,e+ne.length)===ne&&!Od(t[e+ne.length])?(n+=Z,e+=ne.length,!0):!1}function q(ne){let Z=e;if($y(t[e])){for(;e<t.length&&Od(t[e]);)e++;let ae=e;for(;br(t,ae);)ae++;if(t[ae]==="(")return e=ae+1,s(),t[e]===")"&&(e++,t[e]===";"&&e++),!0}for(;e<t.length&&!zy(t[e])&&!ei(t[e])&&(!ne||t[e]!==":");)e++;if(t[e-1]===":"&&qy.test(t.substring(Z,e+2)))for(;e<t.length&&Hy.test(t[e]);)e++;if(e>Z){for(;br(t,e-1)&&e>0;)e--;let ae=t.slice(Z,e);return n+=ae==="undefined"?"null":JSON.stringify(ae),t[e]==='"'&&e++,!0}}function V(){if(t[e]==="/"){let ne=e;for(e++;e<t.length&&(t[e]!=="/"||t[e-1]==="\\");)e++;return e++,n+=JSON.stringify(t.substring(ne,e)),!0}}function j(ne){let Z=ne;for(;Z>0&&br(t,Z);)Z--;return Z}function ee(ne){let Z=ne+1;for(;Z<t.length&&br(t,Z);)Z++;return Z>=t.length||Zs(t[Z])}function z(){return e>=t.length||Zs(t[e])||br(t,e)}function te(ne){throw new _r(`Invalid character ${JSON.stringify(ne)}`,e)}function Q(){throw new _r(`Unexpected character ${JSON.stringify(t[e])}`,e)}function _e(){throw new _r("Unexpected end of json string",t.length)}function Oe(){throw new _r("Object key expected",e)}function Te(){throw new _r("Colon expected",e)}function Ge(){let ne=t.slice(e,e+6);throw new _r(`Invalid unicode character "${ne}"`,e)}}function Yj(t,e){return t[e]==="*"&&t[e+1]==="/"}function Zy(t,e){if(!t||t.trim()===""||t==="{}")return"{}";try{return JSON.parse(t),e?.debug("Tool arguments standard JSON parsing successful"),t}catch(n){try{let r=qT.default.parse(t);return e?.debug("Tool arguments JSON5 parsing successful"),JSON.stringify(r)}catch(r){try{let o=Qy(t);return e?.debug("Tool arguments safely repaired"),o}catch(o){return e?.error(`JSON parsing failed: ${n.message}. JSON5 parsing failed: ${r.message}. JSON repair failed: ${o.message}. Input data: ${JSON.stringify(t)}`),e?.debug("Returning safe empty object as fallback"),"{}"}}}}var Id=class{logger;name="enhancetool";async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();if(n?.choices?.[0]?.message?.tool_calls?.length)for(let r of n.choices[0].message.tool_calls)r.function?.arguments&&(r.function.arguments=Zy(r.function.arguments,this.logger));return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o={},s=!1,i="",a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(y,k,b)=>{let A=y.split(`
|
|
280
282
|
`);for(let w of A)w.trim()&&k.enqueue(b.encode(w+`
|
|
281
|
-
`))},g=(
|
|
283
|
+
`))},g=(y,k,b)=>{let A;try{A=Zy(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 w={role:"assistant",tool_calls:[{function:{name:o.name,arguments:A},id:o.id,index:o.index,type:"function"}]},E={...y,choices:[{...y.choices[0],delta:w}]};E.choices[0].delta.content!==void 0&&delete E.choices[0].delta.content;let x=`data: ${JSON.stringify(E)}
|
|
282
284
|
|
|
283
|
-
`;k.enqueue(b.encode(x))},C=(
|
|
285
|
+
`;k.enqueue(b.encode(x))},C=(y,k)=>{let{controller:b,encoder:A}=k;if(y.startsWith("data: ")&&y.trim()!=="data: [DONE]"){let w=y.slice(6);try{let E=JSON.parse(w);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)}
|
|
284
286
|
|
|
285
287
|
`;b.enqueue(A.encode(q));return}else if(o.index===O.index){O.function?.arguments&&(o.arguments+=O.function.arguments);return}else{g(E,b,A),o={index:O.index,name:O.function?.name||"",id:O.id||"",arguments:O.function?.arguments||""};return}}if(E.choices?.[0]?.finish_reason==="tool_calls"&&o.index!==void 0){g(E,b,A),o={};return}E.choices?.[0]?.delta?.tool_calls?.length&&k.hasTextContent()&&(typeof E.choices[0].index=="number"?E.choices[0].index+=1:E.choices[0].index=1);let x=`data: ${JSON.stringify(E)}
|
|
286
288
|
|
|
287
|
-
`;b.enqueue(A.encode(x))}catch{b.enqueue(A.encode(
|
|
288
|
-
`))}}else b.enqueue(A.encode(
|
|
289
|
-
`))};try{for(;;){let{done:
|
|
289
|
+
`;b.enqueue(A.encode(x))}catch{b.enqueue(A.encode(y+`
|
|
290
|
+
`))}}else b.enqueue(A.encode(y+`
|
|
291
|
+
`))};try{for(;;){let{done:y,value:k}=await p.read();if(y){u.trim()&&h(u,f,r);break}if(!k||k.length===0)continue;let b;try{b=n.decode(k,{stream:!0})}catch(w){this.logger?.warn("Failed to decode chunk",w);continue}if(b.length===0)continue;if(u+=b,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let w=u.split(`
|
|
290
292
|
`);u=w.pop()||"";for(let E of w)if(E.trim())try{C(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+`
|
|
291
293
|
`))}continue}let A=u.split(`
|
|
292
294
|
`);u=A.pop()||"";for(let w of A)if(w.trim())try{C(w,{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:",w,E),f.enqueue(r.encode(w+`
|
|
293
|
-
`))}}}catch(
|
|
294
|
-
`));return}if(g.reasoning_content){o+=typeof g.reasoning_content=="string"?g.reasoning_content:JSON.stringify(g.reasoning_content),i&&Xs(i,g);let C={...h,choices:[{...h.choices[0],delta:{...g,thinking:{content:g.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let
|
|
295
|
+
`))}}}catch(y){this.logger?.error("Stream error:",y),f.error(y)}finally{try{p.releaseLock()}catch(y){this.logger?.error("Error releasing reader lock:",y)}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 Fd=class{constructor(e){this.options=e;this.enable=this.options?.enable??!0}options;static TransformerName="reasoning";enable;async transformRequestIn(e,n,r){return this.enable?Ot(e.reasoning,e.thinking)?(e.thinking={type:"disabled",budget_tokens:-1},e.enable_thinking=!1,e):(e.reasoning?(e.thinking={type:"enabled",budget_tokens:e.reasoning.max_tokens},e.enable_thinking=!0):e.model&&String(e.model).startsWith("deepseek")&&(e.enable_thinking=!0),wd(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=kd(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&&Ys({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?Sd():null;return Ne(e,(u,d)=>{let{controller:f,encoder:p}=d;if(u.startsWith("data: ")&&u.trim()!=="data: [DONE]")try{let h=JSON.parse(u.slice(6)),g=h.choices?.[0]?.delta;if(!g){f.enqueue(p.encode(u+`
|
|
296
|
+
`));return}if(g.reasoning_content){o+=typeof g.reasoning_content=="string"?g.reasoning_content:JSON.stringify(g.reasoning_content),i&&Xs(i,g);let C={...h,choices:[{...h.choices[0],delta:{...g,thinking:{content:g.reasoning_content}}}]};delete C.choices[0].delta.reasoning_content;let y=`data: ${JSON.stringify(C)}
|
|
295
297
|
|
|
296
|
-
`;f.enqueue(p.encode(
|
|
298
|
+
`;f.enqueue(p.encode(y));return}if(i&&Xs(i,g),(g.content||g.tool_calls)&&o&&!s){s=!0;let C=Date.now().toString(),y={...h,choices:[{...h.choices[0],delta:{...h.choices[0].delta,content:null,thinking:{content:o,signature:C}}}]};delete y.choices[0].delta.reasoning_content;let k=`data: ${JSON.stringify(y)}
|
|
297
299
|
|
|
298
300
|
`;f.enqueue(p.encode(k))}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 C=`data: ${JSON.stringify(h)}
|
|
299
301
|
|
|
300
302
|
`;f.enqueue(p.encode(C))}}catch{f.enqueue(p.encode(u+`
|
|
301
303
|
`))}else f.enqueue(p.encode(u+`
|
|
302
|
-
`))},{onComplete:()=>{i&&Ys(
|
|
304
|
+
`))},{onComplete:()=>{i&&Ys(Ad(i),n)}})}return e}};var Nd=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 Md=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 Xj(t){try{let{GoogleAuth:e}=await Promise.resolve().then(()=>nr(hd(),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:
|
|
303
305
|
1. Set GOOGLE_APPLICATION_CREDENTIALS to point to service account key file
|
|
304
306
|
2. Run "gcloud auth application-default login"
|
|
305
|
-
3. Use Google Cloud environment with default service account`,{cause:e})}}var
|
|
306
|
-
`)}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 BT.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:Ke(e.messages),tools:Ve(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var Id=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Ke(o.messages),o.tools=Ve(o.tools);let s=en(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Fd=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var Nd=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return JU(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),Hc(e),e.messages=VU(e.messages),qc(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return XU(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json();return new Response(JSON.stringify(jT(o)),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function JU(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(YU(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=>KU(i)),o={model:t.model,messages:r,stream:t.stream===!0};if(t.stream_options&&(o.stream_options=t.stream_options),e&&(o.max_tokens=Number(t.max_tokens)),n&&(o.max_completion_tokens=Number(t.max_completion_tokens),e||(o.max_tokens=Number(t.max_completion_tokens))),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.stop!==void 0&&(o.stop=t.stop),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),t.parallel_tool_calls!==void 0&&(o.parallel_tool_calls=t.parallel_tool_calls),t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;(a==="json_schema"||a==="json_object")&&(o.response_format=i)}let s=Dt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...ts(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function KU(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"&&Md(n),n}function Md(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 VU(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),Md(n),delete n.thinking,n})}function jT(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0]?.message;e&&Md(e);let n=t.choices?.[0]?.delta;return n&&Md(n),t}function YU(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 XU(t,e){if(!t.body)return t;let n=t.body.getReader(),r=new TextDecoder,o=new TextEncoder,s="",i=!1,a=e?.aliasThinking===!0,u=p=>{if(!a||!p.startsWith("data:"))return p;let h=p.slice(5).trim();if(!h||h==="[DONE]")return p;try{return`data: ${JSON.stringify(jT(JSON.parse(h)))}`}catch{return p}},d=(p,h=!1)=>{s+=p;let g=s.split(/\r?\n/);s=h?"":g.pop()||"";let C=[];for(let _ of g)/^data:\s*\[DONE\]\s*$/.test(_)&&(i=!0),C.push(u(_));return h&&s&&(/^data:\s*\[DONE\]\s*$/.test(s)&&(i=!0),C.push(u(s)),s=""),C.length?`${C.join(`
|
|
307
|
+
3. Use Google Cloud environment with default service account`,{cause:e})}}var Bd=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 Xj(this.logger);return{body:Fk(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 Nk(e)}async transformResponseOut(e){return wu(e,this.name,this.logger)}};var HT=nr(hd(),1);var Ud=class{static TransformerName="vertex-openai";client;client_email;private_key;constructor(e={}){this.client_email=e.client_email,this.private_key=e.private_key?.replace(/\\n/g,`
|
|
308
|
+
`)}async getClient(){if(this.client)return this.client;if(!this.client_email||!this.private_key)throw new Error("vertex-openai requires client_email and private_key in transformer options");let e=new HT.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:Ke(e.messages),tools:Ve(e.tools)},config:{headers:{Authorization:`Bearer ${r}`}}}}};var jd=class{name="cerebras";async transformRequestIn(e,n,r){let o=JSON.parse(JSON.stringify(e));o.messages=Ke(o.messages),o.tools=Ve(o.tools);let s=en(r,e);return s&&(o.prompt_cache_key=s),o.reasoning?delete o.reasoning:o.disable_reasoning=!1,{body:o,config:{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json"}}}}async transformResponseOut(e){return e}};var Ld=class{name="streamoptions";async transformRequestIn(e){return e.stream&&(e.stream_options={include_usage:!0}),e}};var $d=class{name="OpenAI";endPoint="/v1/chat/completions";async transformRequestOut(e,n){return Qj(e)}async transformRequestIn(e,n,r){return e=structuredClone(e),zc(e),e.messages=eL(e.messages),Hc(e,n,r)}async transformResponseIn(e,n){let r=e.headers.get("Content-Type")||"";if(r.includes("text/event-stream"))return nL(e,{aliasThinking:!0});if(r.includes("application/json")){let o=await e.json();return new Response(JSON.stringify(zT(o)),{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};function Qj(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(tL(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=>Zj(i)),o={model:t.model,messages:r,stream:t.stream===!0};if(t.stream_options&&(o.stream_options=t.stream_options),e&&(o.max_tokens=Number(t.max_tokens)),n&&(o.max_completion_tokens=Number(t.max_completion_tokens),e||(o.max_tokens=Number(t.max_completion_tokens))),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.stop!==void 0&&(o.stop=t.stop),t.tools!==void 0&&(o.tools=t.tools),t.tool_choice!==void 0&&(o.tool_choice=t.tool_choice),t.parallel_tool_calls!==void 0&&(o.parallel_tool_calls=t.parallel_tool_calls),t.response_format!==void 0){let i=t.response_format,a=typeof i=="object"&&i?i.type:i;(a==="json_schema"||a==="json_object")&&(o.response_format=i)}let s=Dt(t.reasoning_effort??t.reasoning?.effort);return(t.reasoning!==void 0||s)&&(o.reasoning={...t.reasoning&&typeof t.reasoning=="object"?t.reasoning:{},...ts(s,t.reasoning?.enabled)||{}}),t.thinking!==void 0&&(o.thinking=t.thinking),o}function Zj(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"&&qd(n),n}function qd(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 eL(t){return(t||[]).map(e=>{if(e?.role!=="assistant")return e;let n={...e};return n.thinking&&(n.thinking={...n.thinking}),qd(n),delete n.thinking,n})}function zT(t){if(!t||typeof t!="object")return t;let e=t.choices?.[0]?.message;e&&qd(e);let n=t.choices?.[0]?.delta;return n&&qd(n),t}function tL(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 nL(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(zT(JSON.parse(h)))}`}catch{return p}},d=(p,h=!1)=>{s+=p;let g=s.split(/\r?\n/);s=h?"":g.pop()||"";let C=[],y=k=>{if(!i)for(let b of Vc(k)){if(i)return;if(Yc(b)){i=!0,Xc(C);return}C.push(u(b))}};for(let k of g)y(k);return h&&s&&(y(s),s=""),C.length?`${C.join(`
|
|
307
309
|
`)}
|
|
308
|
-
`:""},f=new ReadableStream({async pull(p){try{let{done:h,value:g}=await n.read();if(h){let
|
|
310
|
+
`:""},f=new ReadableStream({async pull(p){try{let{done:h,value:g}=await n.read();if(h){let y=d(r.decode(),!0);y&&p.enqueue(o.encode(y)),i||p.enqueue(o.encode(`
|
|
311
|
+
data: [DONE]
|
|
309
312
|
|
|
310
313
|
`)),p.close();return}let C=d(r.decode(g,{stream:!0}));C&&p.enqueue(o.encode(C))}catch{i||(p.enqueue(o.encode(`data: ${JSON.stringify({error:{message:"Upstream stream failed",type:"api_error",param:null,code:"provider_response_error"}})}
|
|
311
314
|
|
|
312
|
-
`)),p.enqueue(o.encode(`
|
|
315
|
+
`)),p.enqueue(o.encode(`
|
|
316
|
+
data: [DONE]
|
|
313
317
|
|
|
314
|
-
`))),p.close()}},cancel(p){return n.cancel(p)}});return new Response(f,{status:t.status,statusText:t.statusText,headers:t.headers})}var
|
|
315
|
-
`);for(let A of b)A.trim()&&
|
|
316
|
-
`))},g=(C,
|
|
318
|
+
`))),p.close()}},cancel(p){return n.cancel(p)}});return new Response(f,{status:t.status,statusText:t.statusText,headers:t.headers})}var Hd=class{static TransformerName="customparams";options;constructor(e={}){this.options=e}async transformRequestIn(e){let n={...e},r=Object.entries(this.options);for(let[o,s]of r)if(o in n)if(typeof n[o]=="object"&&typeof s=="object"&&!Array.isArray(n[o])&&!Array.isArray(s)&&n[o]!==null&&s!==null)n[o]=this.deepMergeObjects(n[o],s);else continue;else n[o]=this.cloneValue(s);return n}async transformResponseOut(e){return e}deepMergeObjects(e,n){let r={...e};for(let[o,s]of Object.entries(n))o in r&&typeof r[o]=="object"&&typeof s=="object"&&!Array.isArray(r[o])&&!Array.isArray(s)&&r[o]!==null&&s!==null?r[o]=this.deepMergeObjects(r[o],s):r[o]=this.cloneValue(s);return r}cloneValue(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>this.cloneValue(r));let n={};for(let[r,o]of Object.entries(e))n[r]=this.cloneValue(o);return n}};var zd=class{constructor(e){this.options=e}options;static TransformerName="vercel";logger;endPoint="/v1/chat/completions";async transformRequestIn(e,n,r){e={...e,messages:Ke(e.messages),tools:Ve(e.tools)},e.messages.forEach(s=>{Array.isArray(s.content)&&s.content.forEach(i=>{i.type==="image_url"&&(i.image_url.url.startsWith("http")||(i.image_url.url=`data:${i.media_type};base64,${i.image_url.url}`),delete i.media_type)})}),Object.assign(e,this.options||{});let o=e.providerOptions||{};return e.providerOptions={...o,gateway:{...o.gateway||{},caching:"auto"}},e}async transformResponseOut(e){if(e.headers.get("Content-Type")?.includes("application/json")){let n=await e.json();return new Response(JSON.stringify(n),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(e.headers.get("Content-Type")?.includes("stream")){if(!e.body)return e;let n=new TextDecoder,r=new TextEncoder,o=!1,s="",i=!1,a=!1,u="",d=new ReadableStream({start:async f=>{let p=e.body.getReader(),h=(C,y,k)=>{let b=C.split(`
|
|
319
|
+
`);for(let A of b)A.trim()&&y.enqueue(k.encode(A+`
|
|
320
|
+
`))},g=(C,y)=>{let{controller:k,encoder:b}=y;if(C.startsWith("data: ")&&C.trim()!=="data: [DONE]"){let A=C.slice(6);try{let w=JSON.parse(A);if(w.usage&&(this.logger?.debug({usage:w.usage,hasToolCall:a},"usage"),w.choices[0].finish_reason=a?"tool_calls":"stop"),w.choices?.[0]?.finish_reason==="error"&&k.enqueue(b.encode(`data: ${JSON.stringify({error:w.choices?.[0].error})}
|
|
317
321
|
|
|
318
|
-
`)),w.choices?.[0]?.delta?.content&&!
|
|
322
|
+
`)),w.choices?.[0]?.delta?.content&&!y.hasTextContent()&&y.setHasTextContent(!0),w.choices?.[0]?.delta?.reasoning){y.appendReasoningContent(w.choices[0].delta.reasoning);let x={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,thinking:{content:w.choices[0].delta.reasoning}}}]};x.choices?.[0]?.delta&&delete x.choices[0].delta.reasoning;let O=`data: ${JSON.stringify(x)}
|
|
319
323
|
|
|
320
|
-
`;k.enqueue(b.encode(O));return}if(w.choices?.[0]?.delta?.content&&
|
|
324
|
+
`;k.enqueue(b.encode(O));return}if(w.choices?.[0]?.delta?.content&&y.reasoningContent()&&!y.isReasoningComplete()){y.setReasoningComplete(!0);let x=Date.now().toString(),O={...w,choices:[{...w.choices?.[0],delta:{...w.choices[0].delta,content:null,thinking:{content:y.reasoningContent(),signature:x}}}]};O.choices?.[0]?.delta&&delete O.choices[0].delta.reasoning;let q=`data: ${JSON.stringify(O)}
|
|
321
325
|
|
|
322
|
-
`;k.enqueue(b.encode(q))}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(x=>{x.id=`call_${On()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!a&&(a=!0),w.choices?.[0]?.delta?.tool_calls?.length&&
|
|
326
|
+
`;k.enqueue(b.encode(q))}w.choices?.[0]?.delta?.reasoning&&delete w.choices[0].delta.reasoning,w.choices?.[0]?.delta?.tool_calls?.length&&!Number.isNaN(parseInt(w.choices?.[0]?.delta?.tool_calls[0].id,10))&&w.choices?.[0]?.delta?.tool_calls.forEach(x=>{x.id=`call_${On()}`}),w.choices?.[0]?.delta?.tool_calls?.length&&!a&&(a=!0),w.choices?.[0]?.delta?.tool_calls?.length&&y.hasTextContent()&&(typeof w.choices[0].index=="number"?w.choices[0].index+=1:w.choices[0].index=1);let E=`data: ${JSON.stringify(w)}
|
|
323
327
|
|
|
324
328
|
`;k.enqueue(b.encode(E))}catch{k.enqueue(b.encode(C+`
|
|
325
329
|
`))}}else k.enqueue(b.encode(C+`
|
|
326
|
-
`))};try{for(;;){let{done:C,value:
|
|
330
|
+
`))};try{for(;;){let{done:C,value:y}=await p.read();if(C){u.trim()&&h(u,f,r);break}if(!y||y.length===0)continue;let k;try{k=n.decode(y,{stream:!0})}catch(A){this.logger?.warn("Failed to decode chunk",A);continue}if(k.length===0)continue;if(u+=k,u.length>1e6){this.logger?.warn("Buffer size exceeds limit, processing partial data");let A=u.split(`
|
|
327
331
|
`);u=A.pop()||"";for(let w of A)if(w.trim())try{g(w,{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:",w,E),f.enqueue(r.encode(w+`
|
|
328
332
|
`))}continue}let b=u.split(`
|
|
329
333
|
`);u=b.pop()||"";for(let A of b)if(A.trim())try{g(A,{controller:f,encoder:r,hasTextContent:()=>o,setHasTextContent:w=>o=w,reasoningContent:()=>s,appendReasoningContent:w=>s+=w,isReasoningComplete:()=>i,setReasoningComplete:w=>i=w})}catch(w){this.logger?.error("Error processing line:",A,w),f.enqueue(r.encode(A+`
|
|
330
|
-
`))}}}catch(C){this.logger?.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){this.logger?.error("Error releasing reader lock:",C)}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 Ud=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=ns(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),Kc(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||ns(),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=Rw(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=Dw({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Ne(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=Ji("Malformed upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return}let i=o.slice(5).trim();if(i==="[DONE]"){if(!r.finished)for(let a of wh(r))s.controller.enqueue(ve(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=Ji(Je(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=Fw(a,r);for(let d of u)s.controller.enqueue(ve(JSON.stringify(d),s.encoder))}catch{let a=Ji("Malformed JSON in upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of wh(r))o.controller.enqueue(ve(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=Ji(Je(i)||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return!0},logger:this.logger})}async transformRequestIn(e,n,r){e=structuredClone(e);let o=e.max_tokens??e.max_completion_tokens;if(o!=null&&(e.max_output_tokens=o),delete e.max_tokens,delete e.max_completion_tokens,e.reasoning){let h=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning.effort);e.reasoning={...h?{effort:h}:{},...h!=="none"&&e.reasoning.summary?{summary:e.reasoning.summary}:{}}}delete e.stop,delete e.stream_options;let s=Yc(e.response_format);s&&(e.text={...e.text,format:s}),delete e.response_format;let i=e.model||"";e=Hi(e,n,r);let a=Lc(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(C=>{let _="";typeof C=="string"?_=C:C&&typeof C=="object"&&"text"in C&&(_=C.text),u.push({role:"system",content:[{type:"input_text",text:_,...$c(C,i)}]})}):g===0?e.instructions=h.content:u.push({role:"system",content:[{type:"input_text",text:String(h.content||"")}]})});let p=h=>{let g=cs(Rn(h));g&&u.push(g)};if(e.messages.forEach(h=>{if(h.role!=="system"){if(Array.isArray(h.content)){let g=h.content.map(C=>this.normalizeRequestContent(C,h.role,i)).filter(C=>C!==null);g.length>0?h.content=g:delete h.content}if(h.role==="tool"){let g={...h};g.type="function_call_output",g.call_id=_t(h.tool_call_id)??h.tool_call_id,g.output=h.content,delete g.cache_control,delete g.role,delete g.tool_call_id,delete g.content,u.push(g),d=!0;return}if(h.role==="assistant"){let g=as(h);if(g.thinking||g.toolCalls.length||Gi(g)||g.images.length){if(d=!1,g.thinking&&p(h),Gi(g)||g.images.length){let C={...h};delete C.tool_calls,delete C.thinking,delete C.reasoning_content,g.texts.length===1&&g.images.length===0&&(C.content=g.texts[0].text),u.push(C)}for(let C of g.toolCalls)u.push({type:"function_call",arguments:C.function.arguments,name:C.function.name,call_id:_t(C.id)??C.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=C=>C?.type==="web_search"||C?.function?.name==="web_search",g=e.tools.find(h);e.tools=e.tools.filter(C=>!h(C)).map(C=>(C.function.name==="WebSearch"&&C.function.parameters?.properties&&delete C.function.parameters.properties.allowed_domains,C.function.name==="Edit"?{type:C.type,name:C.function.name,description:C.function.description,parameters:{...C.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:C.type,name:C.function.name,description:C.function.description,parameters:C.function.parameters})),g&&e.tools.push({type:"web_search"})}return e.tool_choice&&typeof e.tool_choice=="object"&&e.tool_choice.type==="function"?e.tool_choice={type:"function",name:e.tool_choice.function?.name}:e.tool_choice==="required"?e.tool_choice="required":e.tool_choice==="none"?e.tool_choice="none":e.tool_choice==="auto"&&(e.tool_choice="auto"),e.parallel_tool_calls!==void 0&&(e.parallel_tool_calls=e.parallel_tool_calls),e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new Map,o=new Map,s=new Map,i=0,a=!1,u=f=>{let p=f.item_id||f.item?.id||(typeof f.output_index=="number"?`output:${f.output_index}`:void 0);if(p!==void 0){let h=r.get(p);if(h!==void 0)return h;let g=i++;return r.set(p,g),g}return i++},d=()=>{a=!0,r.clear()};return Ne(e,(f,p)=>{if(!a&&f.trim()&&!f.startsWith("event: "))if(f.startsWith("data: ")){let h=f.slice(5).trim();if(h==="[DONE]"){p.controller.enqueue(ve("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let _=g.response?.error??{},k=Je(String(_.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(ve(JSON.stringify({error:{message:k,type:typeof _.type=="string"?_.type:"api_error",code:typeof _.code=="string"?_.code:null}}),p.encoder)),p.controller.enqueue(ve("[DONE]",p.encoder));return}let C=this.convertStreamEvent(g,u,o,s);for(let _ of C)p.controller.enqueue(ve(JSON.stringify(_),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(ve("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Pe(f,p.encoder))}}else p.controller.enqueue(Pe(f,p.encoder))})}return e}convertStreamEvent(e,n,r,o){let s=d=>(d?.content||[]).filter(f=>f?.type==="output_text").map(f=>f.text||"").join(""),i=d=>d?[d]:[],a=d=>d?.id||e.item?.id||e.item_id||"text",u=d=>{let f=a();r.set(f,(r.get(f)||"")+(typeof d=="string"?d:""))};if(e.type==="response.output_text.delta"&&typeof e.delta=="string"?u(e.delta):e.type==="response.output_item.added"&&e.item?.type==="message"&&u(s(e.item)),e.type==="response.reasoning_summary_text.delta"&&typeof e.delta=="string"&&Vc(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=is(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",C=s(h),_=r.get(g)||"",k=C.startsWith(_)?C.slice(_.length):C;r.set(g,C),k&&d.push({id:g,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:k},finish_reason:null}]})}for(let h of e.response?.output||[]){if(h.type!=="reasoning")continue;let g=is(h,o);g&&d.push({id:h.id||e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:g},finish_reason:null}]})}let p=this.convertStreamEventCore(e,n);return p&&d.push(p),d}return i(this.convertStreamEventCore(e,n))}convertStreamEventCore(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:n(e),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:0,delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{tool_calls:[{index:n(e),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call"||s.type==="custom_tool_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{id:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...$c(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,...$c(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=ss(r)||null;if(!u&&n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let h=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});h&&f.push(h)}else if(p.type==="output_image_base64"){let h=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});h&&f.push(h)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),i=p}else i=d.join("")}return o.length>0&&(a=o.map(d=>({id:_t(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[xn]:d.input||""}):d.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:a,thinking:u,annotations:s},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{randomUUID as wL}from"crypto";import{execFileSync as kL}from"child_process";import{arch as zT,platform as r_,release as SL}from"os";import{resolveCodexPat as WT}from"@caeliq/ccr-shared";import{closeSync as QU,existsSync as UT,fstatSync as ZU,mkdirSync as eL,openSync as tL,readFileSync as nL,renameSync as rL,statSync as LT,unlinkSync as Vy,writeFileSync as oL}from"fs";import{dirname as sL,join as iL}from"path";import{homedir as aL}from"os";var cL=iL(aL(),".claude-code-router","codex_auth.json"),uL=300,lL=11520*60,dL=2*6e4,fL=35e3,$T={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Ld=null;function Yy(){return process.env.CCR_CODEX_AUTH_FILE||cL}function Jy(){return`${Yy()}.refresh.lock`}function pL(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||$T.token_endpoint}function Xy(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 $d(t){let e=t.account_id?.trim();return e||Xy(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function hL(t){return Xy(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function qT(t){let e=Xy(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function qd(t){let e=$d(t),n=qT(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function Ky(){try{let t=Yy();if(!UT(t))return null;let e=JSON.parse(nL(t,"utf8"));return e.access_token?qd(e):null}catch{return null}}function gL(t){let e=Yy();eL(sL(e),{recursive:!0});let n=qd(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{oL(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),rL(r,e)}finally{try{UT(r)&&Vy(r)}catch{}}}function HT(t,e=uL){let n=qT(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+lL)}function Gy(t,e){let n=$d(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function mL(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 yL(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(pL(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:$T.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}): ${mL(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 qd({...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 _L(){let t=Jy();try{return tL(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-LT(t).mtimeMs>dL&&Vy(t)}catch{}return null}}async function bL(t){let e=Date.now()+fL,n=null;for(;n===null&&(n=_L(),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=ZU(n).ino;QU(n);try{LT(Jy()).ino===r&&Vy(Jy())}catch{}}}async function CL(t,e){return bL(async()=>{let n=Ky();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");Gy(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!HT(n))return n;let o=await yL(n);Gy(e.expectedAccountId,o);let s=Ky();return s&&s.access_token!==n.access_token?(Gy(e.expectedAccountId,s),s):(gL(o),o)})}async function Qy(t={}){let e=Ky();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!HT(e)?e:(Ld||(Ld=CL(e,{...t,expectedAccountId:t.expectedAccountId||$d(e)}).finally(()=>{Ld=null})),Ld)}function Zy(t){let e=qd(t);return{mode:"oauth",token:e.access_token,accountId:$d(e),isFedramp:hL(e)}}var AL=300*1e3,Hd=new Map,e_=new Map,JT="0.145.0",KT="codex_cli_rs",VT="x-codex-turn-metadata",EL="x-codex-window-id",vL="x-codex-parent-thread-id",TL="session_id",xL="thread_id",RL="turn_id",DL="window_id";function t_(){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 n_(t){return t.item_id||t.item?.id||t.item?.call_id||""}function OL(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function PL(){switch(r_()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return r_()||"unknown"}}function IL(){switch(zT()){case"x64":return"x86_64";case"arm64":return"arm64";default:return zT()||"unknown"}}function FL(){if(r_()==="darwin")try{return kL("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return SL()||"unknown"}function NL(){return`${KT}/${JT} (${PL()} ${FL()}; ${IL()})`}function GT(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",JT),e.toString()}function ML(t){return{session_id:t,thread_id:t,turn_id:wL(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function BL(t){return{[TL]:t.session_id,[xL]:t.thread_id,[RL]:t.turn_id,[DL]:t.window_id,[VT]:JSON.stringify(t)}}function jL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function UL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[EL]:t.window_id,[VT]:JSON.stringify(t),[vL]:t.thread_id}}function LL(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 $L(t,e){return t?.req?.sessionId||LL(e)}function qL(t,e,n){if(!n)return;let r=ML(n);t.client_metadata=jL(t.client_metadata,BL(r)),Object.assign(e,UL(r))}var zd=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let a=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning?.effort)||Dt(n?.reasoningEffort);if(a){let A={effort:a},w=["auto","detailed","none"],E=n?.reasoningSummary;a!=="none"&&(E&&w.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=Yc(e.response_format);d&&(e.text={...e.text,format:d}),delete e.response_format,e=ih(e,r);let f=Lc(e.messages);e.messages=f;let p=[],h=!1,g=OL(r),C=new Set,_=e.messages.filter(A=>A.role==="system");if(_.length>0){let A=_[0],w;Array.isArray(A.content)?w=A.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
|
|
331
|
-
`):w=A.content,w&&(e.instructions=w)}for(let A of
|
|
334
|
+
`))}}}catch(C){this.logger?.error("Stream error:",C),f.error(C)}finally{try{p.releaseLock()}catch(C){this.logger?.error("Error releasing reader lock:",C)}f.close()}}});return new Response(d,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var Wd=class{logger;name="openai-responses";endPoint="/v1/responses";async transformRequestOut(e,n){let r=ns(),o=new Set;return n&&(n.responsesCallIdMap=r,n.responsesCustomToolNames=o,n.protocolContext&&(n.protocolContext.responsesCallIdMap=r,n.protocolContext.responsesCustomToolNames=o)),Qc(e,r,o)}async transformResponseIn(e,n){let r=n?.responsesCallIdMap||n?.protocolContext?.responsesCallIdMap||n?.req?.protocolContext?.responsesCallIdMap||ns(),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=Nw(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=Mw({model:n.originalModel,callIdMap:n.callIdMap,customToolNames:n.customToolNames,codexIsolateConventions:n.codexIsolateConventions});return Ne(e,(o,s)=>{if(r.finished||!o.trim()||o.startsWith("event: "))return;if(!o.startsWith("data: ")){if(!o.startsWith(":")){let a=Ji("Malformed upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return}let i=o.slice(5).trim();if(i==="[DONE]"){if(!r.finished)for(let a of Dh(r))s.controller.enqueue(ve(JSON.stringify(a),s.encoder));return}try{let a=JSON.parse(i);if(typeof a?.type=="string"&&a.type.startsWith("response.")){s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),(a.type==="response.completed"||a.type==="response.failed")&&(r.finished=!0);return}if(a?.error&&!a?.choices){let d=Ji(Je(String(a.error.message||a.error))||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(d),s.encoder)),r.finished=!0;return}let u=Lw(a,r);for(let d of u)s.controller.enqueue(ve(JSON.stringify(d),s.encoder))}catch{let a=Ji("Malformed JSON in upstream SSE event",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}},{onComplete:o=>{if(!r.finished)for(let s of Dh(r))o.controller.enqueue(ve(JSON.stringify(s),o.encoder))},onError:(o,s)=>{if(!r.finished){let i=o instanceof Error?o.message:String(o),a=Ji(Je(i)||"Upstream stream failed",r);s.controller.enqueue(ve(JSON.stringify(a),s.encoder)),r.finished=!0}return!0},logger:this.logger})}async transformRequestIn(e,n,r){e=structuredClone(e);let o=e.max_tokens??e.max_completion_tokens;if(o!=null&&(e.max_output_tokens=o),delete e.max_tokens,delete e.max_completion_tokens,e.reasoning){let h=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning.effort);e.reasoning={...h?{effort:h}:{},...h!=="none"&&e.reasoning.summary?{summary:e.reasoning.summary}:{}}}delete e.stop,delete e.stream_options;let s=eu(e.response_format);s&&(e.text={...e.text,format:s}),delete e.response_format;let i=e.model||"";e=Hi(e,n,r);let a=$c(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(C=>{let y="";typeof C=="string"?y=C:C&&typeof C=="object"&&"text"in C&&(y=C.text),u.push({role:"system",content:[{type:"input_text",text:y,...qc(C,i)}]})}):g===0?e.instructions=h.content:u.push({role:"system",content:[{type:"input_text",text:String(h.content||"")}]})});let p=h=>{let g=cs(Rn(h));g&&u.push(g)};if(e.messages.forEach(h=>{if(h.role!=="system"){if(Array.isArray(h.content)){let g=h.content.map(C=>this.normalizeRequestContent(C,h.role,i)).filter(C=>C!==null);g.length>0?h.content=g:delete h.content}if(h.role==="tool"){let g={...h};g.type="function_call_output",g.call_id=_t(h.tool_call_id)??h.tool_call_id,g.output=h.content,delete g.cache_control,delete g.role,delete g.tool_call_id,delete g.content,u.push(g),d=!0;return}if(h.role==="assistant"){let g=as(h);if(g.thinking||g.toolCalls.length||Gi(g)||g.images.length){if(d=!1,g.thinking&&p(h),Gi(g)||g.images.length){let C={...h};delete C.tool_calls,delete C.thinking,delete C.reasoning_content,g.texts.length===1&&g.images.length===0&&(C.content=g.texts[0].text),u.push(C)}for(let C of g.toolCalls)u.push({type:"function_call",arguments:C.function.arguments,name:C.function.name,call_id:_t(C.id)??C.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=C=>C?.type==="web_search"||C?.function?.name==="web_search",g=e.tools.find(h);e.tools=e.tools.filter(C=>!h(C)).map(C=>(C.function.name==="WebSearch"&&C.function.parameters?.properties&&delete C.function.parameters.properties.allowed_domains,C.function.name==="Edit"?{type:C.type,name:C.function.name,description:C.function.description,parameters:{...C.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:C.type,name:C.function.name,description:C.function.description,parameters:C.function.parameters})),g&&e.tools.push({type:"web_search"})}return e.tool_choice&&typeof e.tool_choice=="object"&&e.tool_choice.type==="function"?e.tool_choice={type:"function",name:e.tool_choice.function?.name}:e.tool_choice==="required"?e.tool_choice="required":e.tool_choice==="none"?e.tool_choice="none":e.tool_choice==="auto"&&(e.tool_choice="auto"),e.parallel_tool_calls!==void 0&&(e.parallel_tool_calls=e.parallel_tool_calls),e}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(n.includes("application/json")){let r=await e.json();if(r.object==="response"&&r.output){let o=this.convertResponseToChat(r);return new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(JSON.stringify(r),{status:e.status,statusText:e.statusText,headers:e.headers})}else if(n.includes("text/event-stream")){if(!e.body)return e;let r=new Map,o=new Map,s=new Map,i=0,a=!1,u=f=>{let p=f.item_id||f.item?.id||(typeof f.output_index=="number"?`output:${f.output_index}`:void 0);if(p!==void 0){let h=r.get(p);if(h!==void 0)return h;let g=i++;return r.set(p,g),g}return i++},d=()=>{a=!0,r.clear()};return Ne(e,(f,p)=>{if(!a&&f.trim()&&!f.startsWith("event: "))if(f.startsWith("data: ")){let h=f.slice(5).trim();if(h==="[DONE]"){p.controller.enqueue(ve("[DONE]",p.encoder)),d();return}try{let g=JSON.parse(h);if(g.type==="response.failed"){d();let y=g.response?.error??{},k=Je(String(y.message||"Upstream response failed"))||"Upstream response failed";p.controller.enqueue(ve(JSON.stringify({error:{message:k,type:typeof y.type=="string"?y.type:"api_error",code:typeof y.code=="string"?y.code:null}}),p.encoder)),p.controller.enqueue(ve("[DONE]",p.encoder));return}let C=this.convertStreamEvent(g,u,o,s);for(let y of C)p.controller.enqueue(ve(JSON.stringify(y),p.encoder));g.type==="response.completed"&&(p.controller.enqueue(ve("[DONE]",p.encoder)),d())}catch{p.controller.enqueue(Pe(f,p.encoder))}}else p.controller.enqueue(Pe(f,p.encoder))})}return e}convertStreamEvent(e,n,r,o){let s=d=>(d?.content||[]).filter(f=>f?.type==="output_text").map(f=>f.text||"").join(""),i=d=>d?[d]:[],a=d=>d?.id||e.item?.id||e.item_id||"text",u=d=>{let f=a();r.set(f,(r.get(f)||"")+(typeof d=="string"?d:""))};if(e.type==="response.output_text.delta"&&typeof e.delta=="string"?u(e.delta):e.type==="response.output_item.added"&&e.item?.type==="message"&&u(s(e.item)),e.type==="response.reasoning_summary_text.delta"&&typeof e.delta=="string"&&Zc(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=is(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",C=s(h),y=r.get(g)||"",k=C.startsWith(y)?C.slice(y.length):C;r.set(g,C),k&&d.push({id:g,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:k},finish_reason:null}]})}for(let h of e.response?.output||[]){if(h.type!=="reasoning")continue;let g=is(h,o);g&&d.push({id:h.id||e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:g},finish_reason:null}]})}let p=this.convertStreamEventCore(e,n);return p&&d.push(p),d}return i(this.convertStreamEventCore(e,n))}convertStreamEventCore(e,n){if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:n(e),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="message"){let r=[];(e.item.content||[]).forEach(s=>{s.type==="output_text"&&r.push({type:"text",text:s.text||""})});let o={role:"assistant"};return r.length===1&&r[0].type==="text"?o.content=r[0].text:r.length>0&&(o.content=r),o.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:o,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex",choices:[{index:0,delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{tool_calls:[{index:n(e),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let r=e.response?.output?.some(s=>s.type==="function_call"||s.type==="custom_tool_call")?"tool_calls":"stop",o={id:e.response?.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model||"gpt-5-codex-",choices:[{index:0,delta:{},finish_reason:r}]};return e.response?.usage&&(o.usage={prompt_tokens:e.response.usage.input_tokens||0,completion_tokens:e.response.usage.output_tokens||0,total_tokens:e.response.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.response.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.response.usage.input_tokens_details?.cache_write_tokens||0}}),o}return e.type==="response.reasoning_summary_text.delta"?{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{content:e.delta||""}},finish_reason:null}]}:e.type==="response.reasoning_summary_part.done"&&e.part?typeof e.item_id!="string"||!e.item_id?null:{id:e.item_id,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e.response?.model,choices:[{index:0,delta:{thinking:{id:e.item_id}},finish_reason:null}]}:null}normalizeRequestContent(e,n,r){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text,...qc(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,...qc(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=ss(r)||null;if(!u&&n&&n.reasoning&&(u={content:n.reasoning}),n&&n.content){let d=[],f=[];if(n.content.forEach(p=>{if(p.type==="output_text")d.push(p.text||"");else if(p.type==="output_image"){let h=this.buildImageContent({url:p.image_url,mime_type:p.mime_type});h&&f.push(h)}else if(p.type==="output_image_base64"){let h=this.buildImageContent({b64_json:p.image_base64,mime_type:p.mime_type});h&&f.push(h)}}),f.length>0){let p=[];d.length>0&&p.push({type:"text",text:d.join("")}),p.push(...f),i=p}else i=d.join("")}return o.length>0&&(a=o.map(d=>({id:_t(d.call_id||d.id)||d.call_id||d.id,function:{name:d.name,arguments:d.type==="custom_tool_call"?JSON.stringify({[xn]:d.input||""}):d.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:i||null,tool_calls:a,thinking:u,annotations:s},logprobs:null,finish_reason:a?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{randomUUID as vL}from"crypto";import{execFileSync as TL}from"child_process";import{arch as YT,platform as l_,release as xL}from"os";import{resolveCodexPat as XT}from"@caeliq/ccr-shared";import{closeSync as rL,existsSync as WT,fstatSync as oL,mkdirSync as sL,openSync as iL,readFileSync as aL,renameSync as cL,statSync as GT,unlinkSync as r_,writeFileSync as uL}from"fs";import{dirname as lL,join as dL}from"path";import{homedir as fL}from"os";var pL=dL(fL(),".claude-code-router","codex_auth.json"),hL=300,gL=11520*60,mL=2*6e4,yL=35e3,JT={client_id:"app_EMoamEEZ73f0CkXaXp7hrann",token_endpoint:"https://auth.openai.com/oauth/token"},Gd=null;function o_(){return process.env.CCR_CODEX_AUTH_FILE||pL}function t_(){return`${o_()}.refresh.lock`}function _L(){return process.env.CODEX_OAUTH_TOKEN_ENDPOINT||JT.token_endpoint}function s_(t){if(!t)return null;let e=t.split(".");if(e.length!==3||!e[1])return null;try{return JSON.parse(Buffer.from(e[1],"base64url").toString("utf8"))}catch{return null}}function Jd(t){let e=t.account_id?.trim();return e||s_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_id}function bL(t){return s_(t.id_token)?.["https://api.openai.com/auth"]?.chatgpt_account_is_fedramp===!0}function KT(t){let e=s_(t.access_token)?.exp;return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Kd(t){let e=Jd(t),n=KT(t);return{...t,...e?{account_id:e}:{},...n?{expires_at:n}:{}}}function n_(){try{let t=o_();if(!WT(t))return null;let e=JSON.parse(aL(t,"utf8"));return e.access_token?Kd(e):null}catch{return null}}function CL(t){let e=o_();sL(lL(e),{recursive:!0});let n=Kd(t),r=`${e}.${process.pid}.${Date.now()}.tmp`;try{uL(r,JSON.stringify(n,null,2),{mode:384,encoding:"utf8"}),cL(r,e)}finally{try{WT(r)&&r_(r)}catch{}}}function VT(t,e=hL){let n=KT(t);return n?Date.now()/1e3+e>=n:!!(t.last_refresh&&Date.now()/1e3>=t.last_refresh+gL)}function e_(t,e){let n=Jd(e);if(t&&t!==n)throw new Error("Codex OAuth account changed while credentials were being refreshed. Retry the request.")}function wL(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 kL(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(_L(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:JT.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}): ${wL(n)}`);let r=JSON.parse(n);if(typeof r.access_token!="string"||!r.access_token)throw new Error("Codex OAuth token refresh response did not include an access token.");let o=Date.now()/1e3;return Kd({...t,access_token:r.access_token,refresh_token:r.refresh_token||t.refresh_token,id_token:r.id_token||t.id_token,token_type:r.token_type||t.token_type||"Bearer",scope:r.scope||t.scope,expires_at:r.expires_at||o+(typeof r.expires_in=="number"?r.expires_in:3600),account_id:r.account_id||t.account_id,last_refresh:o})}function SL(){let t=t_();try{return iL(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-GT(t).mtimeMs>mL&&r_(t)}catch{}return null}}async function AL(t){let e=Date.now()+yL,n=null;for(;n===null&&(n=SL(),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=oL(n).ino;rL(n);try{GT(t_()).ino===r&&r_(t_())}catch{}}}async function EL(t,e){return AL(async()=>{let n=n_();if(!n)throw new Error("Codex OAuth credentials disappeared while refreshing. Run `ccr codex-auth` again.");e_(e.expectedAccountId,n);let r=e.previousAccessToken||t.access_token;if(n.access_token!==r||!e.force&&!VT(n))return n;let o=await kL(n);e_(e.expectedAccountId,o);let s=n_();return s&&s.access_token!==n.access_token?(e_(e.expectedAccountId,s),s):(CL(o),o)})}async function Vd(t={}){let e=n_();if(!e)throw new Error("No Codex OAuth tokens found. Run `ccr codex-auth` to authenticate.");return!t.force&&!VT(e)?e:(Gd||(Gd=EL(e,{...t,expectedAccountId:t.expectedAccountId||Jd(e)}).finally(()=>{Gd=null})),Gd)}function i_(t){let e=Kd(t);return{mode:"oauth",token:e.access_token,accountId:Jd(e),isFedramp:bL(e)}}var RL=300*1e3,Yd=new Map,a_=new Map,ZT="0.145.0",ex="codex_cli_rs",tx="x-codex-turn-metadata",DL="x-codex-window-id",OL="x-codex-parent-thread-id",PL="session_id",IL="thread_id",FL="turn_id",NL="window_id";function c_(){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 ML(t){return t?.responsesCustomToolNames||t?.protocolContext?.responsesCustomToolNames||t?.req?.protocolContext?.responsesCustomToolNames||new Set}function BL(){switch(l_()){case"darwin":return"Mac OS";case"linux":return"Linux";case"win32":return"Windows";default:return l_()||"unknown"}}function UL(){switch(YT()){case"x64":return"x86_64";case"arm64":return"arm64";default:return YT()||"unknown"}}function jL(){if(l_()==="darwin")try{return TL("sw_vers",["-productVersion"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{}return xL()||"unknown"}function LL(){return`${ex}/${ZT} (${BL()} ${jL()}; ${UL()})`}function QT(t){let e=new URL(t);return e.searchParams.has("client_version")||e.searchParams.set("client_version",ZT),e.toString()}function $L(t){return{session_id:t,thread_id:t,turn_id:vL(),window_id:`${t}:0`,request_kind:"turn",turn_started_at_unix_ms:Date.now()}}function qL(t){return{[PL]:t.session_id,[IL]:t.thread_id,[FL]:t.turn_id,[NL]:t.window_id,[tx]:JSON.stringify(t)}}function HL(t,e){return!t||typeof t!="object"||Array.isArray(t)?{...e}:{...t,...e}}function zL(t){return{"session-id":t.session_id,"thread-id":t.thread_id,"x-client-request-id":t.thread_id,[DL]:t.window_id,[tx]:JSON.stringify(t),[OL]:t.thread_id}}function WL(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 GL(t,e){return t?.req?.sessionId||WL(e)}function JL(t,e,n){if(!n)return;let r=$L(n);t.client_metadata=HL(t.client_metadata,qL(r)),Object.assign(e,zL(r))}var Xd=class{name="codex";logger;streamIntent=new Map;async transformRequestIn(e,n,r){let o=r?.req?.id;o&&this.streamIntent.set(o,e.stream===!0);let s=await this.resolveAuth(n);delete e.temperature,delete e.max_tokens;let a=Ot(e.reasoning,e.thinking)?"none":Dt(e.reasoning?.effort)||Dt(n?.reasoningEffort);if(a){let A={effort:a},w=["auto","detailed","none"],E=n?.reasoningSummary;a!=="none"&&(E&&w.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=eu(e.response_format);d&&(e.text={...e.text,format:d}),delete e.response_format,e=hh(e,r);let f=$c(e.messages);e.messages=f;let p=[],h=!1,g=ML(r),C=new Set,y=e.messages.filter(A=>A.role==="system");if(y.length>0){let A=y[0],w;Array.isArray(A.content)?w=A.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
|
|
335
|
+
`):w=A.content,w&&(e.instructions=w)}for(let A of y.slice(1)){let w=Array.isArray(A.content)?A.content.map(E=>typeof E=="string"?E:E&&typeof E=="object"&&"text"in E?E.text:"").filter(Boolean).join(`
|
|
332
336
|
`):String(A.content||"");w&&p.push({type:"message",role:"system",content:[{type:"input_text",text:w}]})}if(e.instructions||(e.instructions=""),e.messages.forEach(A=>{if(A.role!=="system"){if(Array.isArray(A.content)){let w=A.content.map(E=>this.normalizeRequestContent(E,A.role)).filter(E=>E!==null);w.length>0?A.content=w:delete A.content}if(A.role==="tool"){let w=_t(A.tool_call_id)??A.tool_call_id;if(w&&C.has(w)){p.push({type:"custom_tool_call_output",call_id:w,output:A.content}),h=!0;return}let E={...A};E.type="function_call_output",E.call_id=w,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 w=as(A);if(w.thinking||w.toolCalls.length){h=!1;let E=cs(w.thinking);E&&p.push(E),(Gi(w)||w.images.length)&&p.push({type:"message",role:"assistant",content:w.images.length>0?A.content:[{type:"output_text",text:w.texts.map(x=>x.text).join(`
|
|
333
|
-
`)}]});for(let x of w.toolCalls){let O=_t(x.id)??x.id;if(g.has(x.function.name)){C.add(O),p.push({type:"custom_tool_call",name:x.function.name,call_id:O,input:
|
|
337
|
+
`)}]});for(let x of w.toolCalls){let O=_t(x.id)??x.id;if(g.has(x.function.name)){C.add(O),p.push({type:"custom_tool_call",name:x.function.name,call_id:O,input:xh(x.function.arguments)});continue}p.push({type:"function_call",arguments:x.function.arguments,name:x.function.name,call_id:O})}if(w.toolCalls.length||w.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(w=>w.function.name==="web_search");e.tools=e.tools.filter(w=>w.function.name!=="web_search").map(w=>g.has(w.function.name)?{type:"custom",name:w.function.name,description:w.function.description}:(w.function.name==="WebSearch"&&delete w.function.parameters.properties.allowed_domains,w.function.name==="Edit"?{type:w.type,name:w.function.name,description:w.function.description,parameters:{...w.function.parameters,required:["file_path","old_string","new_string","replace_all"]},strict:!0}:{type:w.type,name:w.function.name,description:w.function.description,parameters:w.function.parameters})),A&&e.tools.push({type:"web_search"})}e.parallel_tool_calls=n?.parallelToolCalls===!0,e.stream=!0;let k=this.buildAuthHeaders(s);JL(e,k,e.prompt_cache_key||GL(r,e));let b=n?.baseUrl||"https://chatgpt.com/backend-api/codex";return{body:e,config:{url:QT(`${b}/responses`),headers:k,__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:QT(`${s}/responses`),headers:o,__authRecovery:()=>this.recoverUnauthorizedAuth(n,r)}}}async resolveAuth(e){let n=XT(e?.apiKey,{allowBareEnvName:!0});return n?this.resolvePatAuth(n):i_(await Vd())}buildAuthHeaders(e){let n={Authorization:`Bearer ${e.token}`,originator:ex,"User-Agent":LL()};return e.accountId&&(n["ChatGPT-Account-ID"]=e.accountId),e.isFedramp&&(n["X-OpenAI-Fedramp"]="true"),n}async recoverUnauthorizedAuth(e,n){if(n.mode==="pat")return Yd.delete(n.token),null;if(XT(e?.apiKey,{allowBareEnvName:!0}))return null;let r=await Vd({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=Yd.get(e);if(n&&n.expiresAt>Date.now())return n.value;Yd.delete(e);let r=a_.get(e);if(r)return r;let o=this.requestPatAuth(e).finally(()=>{a_.delete(e)});return a_.set(e,o),o}async requestPatAuth(e){let n=(process.env.CODEX_AUTHAPI_BASE_URL||"https://auth.openai.com/api/accounts").replace(/\/+$/,""),r=await fetch(`${n}/v1/user-auth-credential/whoami`,{headers:{Authorization:`Bearer ${e}`},signal:AbortSignal.timeout(15e3)});if(!r.ok)throw new Error(`Codex PAT metadata request failed (${r.status}). Verify that the configured at- token is valid and has Codex access.`);let o=await r.json();if(!o.chatgpt_account_id||!o.chatgpt_user_id||!o.chatgpt_plan_type)throw new Error("Codex PAT metadata response is missing required account, user, or plan information.");let s={mode:"pat",token:e,accountId:o.chatgpt_account_id,isFedramp:o.chatgpt_account_is_fedramp===!0};return Yd.set(e,{value:s,expiresAt:Date.now()+RL}),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,C=c_(),y=x=>(x!==p&&(f++,p=x),f),b=Ne(e,(x,O)=>{if(x.trim()&&!x.startsWith("event: "))if(x.startsWith("data: ")){let q=x.slice(5).trim();if(q==="[DONE]"){O.controller.enqueue(ve("[DONE]",O.encoder));return}try{let V=JSON.parse(q);V.response?.model&&(a=V.response.model);let j=r.convertStreamEvent(V,y,u,h,C,g);j&&O.controller.enqueue(ve(JSON.stringify(j),O.encoder))}catch{O.controller.enqueue(Pe(x,O.encoder))}}else O.controller.enqueue(Pe(x,O.encoder))}).body,A=!1,w=null,E=new ReadableStream({start(x){w=b.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||!w||w.read().then(({done:ee,value:z})=>{if(ee){q();return}z&&O(z),j()}).catch(ee=>{A||V(ee)})};j()},cancel(){if(A=!0,w)try{w.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="",C=new Map,y=new Map,k=c_(),b=w=>(w!==g&&(h++,g=w),h),A=new ReadableStream({start(w){for(let E of d){E?.response?.model&&(a=E.response.model);let x=r.convertStreamEvent(E,b,u,C,k,y);x&&w.enqueue(p.encode(`data: ${JSON.stringify(x)}
|
|
334
338
|
|
|
335
339
|
`))}w.enqueue(p.encode(`data: [DONE]
|
|
336
340
|
|
|
337
|
-
`)),w.close()}});return new Response(A,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(d.object==="response"&&d.output){let p=this.convertResponseToChat(d),h=JSON.stringify(p);return o&&i?new Response(this.jsonToSseStream(h),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(h,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let f=JSON.stringify(d);return o&&i?new Response(this.jsonToSseStream(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r,o,s,i){let a=()=>s?s(e):0,u=i??new Map,d=p=>r?r(p):p,f=p=>p||d(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="custom_tool_call"){let p=
|
|
341
|
+
`)),w.close()}});return new Response(A,{status:e.status,statusText:e.statusText,headers:{"Content-Type":"text/event-stream"}})}if(d.object==="response"&&d.output){let p=this.convertResponseToChat(d),h=JSON.stringify(p);return o&&i?new Response(this.jsonToSseStream(h),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(h,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}let f=JSON.stringify(d);return o&&i?new Response(this.jsonToSseStream(f),{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"text/event-stream"})}):new Response(f,{status:e.status,statusText:e.statusText,headers:new Headers({"Content-Type":"application/json"})})}return e}convertStreamEvent(e,n,r,o,s,i){let a=()=>s?s(e):0,u=i??new Map,d=p=>r?r(p):p,f=p=>p||d(void 0);if(e.type==="response.output_text.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{content:e.delta||""},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="function_call")return{id:e.item.call_id||e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{role:"assistant",tool_calls:[{index:a(),id:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]};if(e.type==="response.output_item.added"&&e.item?.type==="custom_tool_call"){let p=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:_t(e.item.call_id||e.item.id)||e.item.call_id||e.item.id,function:{name:e.item.name||"",arguments:""},type:"function"}]},finish_reason:null}]}}if(e.type==="response.custom_tool_call_input.delta"){let p=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({[xn]:h})}}]},finish_reason:null}]}}if(e.type==="response.output_item.added"&&e.item?.type==="message"){let p=[];(e.item.content||[]).forEach(g=>{g.type==="output_text"&&p.push({type:"text",text:g.text||""})});let h={role:"assistant"};return p.length===1&&p[0].type==="text"?h.content=p[0].text:p.length>0&&(h.content=p),h.content?{id:e.item.id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:h,finish_reason:null}]}:null}if(e.type==="response.output_text.annotation.added")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{annotations:[{type:"url_citation",url_citation:{url:e.annotation?.url||"",title:e.annotation?.title||"",content:"",start_index:e.annotation?.start_index||0,end_index:e.annotation?.end_index||0}}]},finish_reason:null}]};if(e.type==="response.function_call_arguments.delta")return{id:e.item_id||"chatcmpl-"+Date.now(),object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:f(e.response?.model),choices:[{index:n(e.type),delta:{tool_calls:[{index:a(),function:{arguments:e.delta||""}}]},finish_reason:null}]};if(e.type==="response.completed"){let p=e.response?.output?.some(C=>C.type==="function_call"||C.type==="custom_tool_call")?"tool_calls":"stop",h=is(e.response?.output?.find(C=>C.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 Zc(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=is(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)}
|
|
338
342
|
|
|
339
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]
|
|
340
344
|
|
|
341
|
-
`)),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=[],C=new Map,
|
|
342
|
-
`);s=z.pop()||"";for(let te of z){if(!te.startsWith("data: "))continue;let Q=te.slice(5).trim();if(!(!Q||Q==="[DONE]"))try{let _e=JSON.parse(Q);if(_e.response?.model){let Te=n(_e.response.model);Te&&(i=Te)}let Oe=this.convertStreamEvent(_e,O,n,w,x,E);V(Oe)}catch{}}}return q()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=(e.output??[]).filter(u=>u.type==="function_call"||u.type==="custom_tool_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,i=null,a=ss(e.output?.find(u=>u.type==="reasoning"))||null;if(!a&&n&&n.reasoning&&(a={content:n.reasoning}),n&&n.content){let u=[],d=[];if(n.content.forEach(f=>{if(f.type==="output_text")u.push(f.text||"");else if(f.type==="output_image"){let p=this.buildImageContent({url:f.image_url,mime_type:f.mime_type});p&&d.push(p)}else if(f.type==="output_image_base64"){let p=this.buildImageContent({b64_json:f.image_base64,mime_type:f.mime_type});p&&d.push(p)}}),d.length>0){let f=[];u.length>0&&f.push({type:"text",text:u.join("")}),f.push(...d),s=f}else s=u.join("")}return r.length>0&&(i=r.map(u=>({id:_t(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[xn]:u.input||""}):u.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:a,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{existsSync as
|
|
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=[],C=new Map,y=null,k,b=-1,A="",w=new Map,E=new Map,x=c_(),O=j=>(j!==A&&(b++,A=j),b),q=()=>{let j={role:"assistant"};(f||p||h)&&(j.thinking={content:f,...p?{encrypted_content:p}:{},...h?{id:h}:{}});let ee=Array.from(C.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":y||"stop"};return{id:a,object:"chat.completion",created:u,model:i||"unknown",choices:[z],usage:k||null}},V=j=>{if(!j)return;j.id&&(a=j.id),j.model&&(i=j.model),j.created&&(u=j.created),j.usage&&(k=j.usage);let ee=j.choices?.[0];if(!ee)return;ee.finish_reason&&(y=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=rs(z.thinking?.encrypted_content);if(te&&(p=te),typeof z.thinking?.id=="string"&&z.thinking.id?h=z.thinking.id:ur(z.thinking?.signature)&&(h=z.thinking.signature),Array.isArray(z.annotations))for(let Q of z.annotations)g.push(Q);if(Array.isArray(z.tool_calls))for(let Q of z.tool_calls){let _e=Q.index??0,Oe=C.get(_e)||{index:_e,id:Q.id,type:"function",function:{name:Q.function?.name||"",arguments:""}};Q.id&&(Oe.id=Q.id),Q.function?.name&&(Oe.function.name=Q.function.name),typeof Q.function?.arguments=="string"&&(Oe.function.arguments=(Oe.function.arguments||"")+Q.function.arguments),C.set(_e,Oe)}};for(;;){let{done:j,value:ee}=await r.read();if(j)break;s+=o.decode(ee,{stream:!0});let z=s.split(`
|
|
346
|
+
`);s=z.pop()||"";for(let te of z){if(!te.startsWith("data: "))continue;let Q=te.slice(5).trim();if(!(!Q||Q==="[DONE]"))try{let _e=JSON.parse(Q);if(_e.response?.model){let Te=n(_e.response.model);Te&&(i=Te)}let Oe=this.convertStreamEvent(_e,O,n,w,x,E);V(Oe)}catch{}}}return q()}normalizeRequestContent(e,n){if(e.type==="text")return{type:n==="assistant"?"output_text":"input_text",text:e.text};if(e.type==="image_url"){this.logger?.debug(e);let r={type:n==="assistant"?"output_image":"input_image"};return typeof e.image_url?.url=="string"&&(r.image_url=e.image_url.url),r}return null}convertResponseToChat(e){let n=e.output?.find(u=>u.type==="message"),r=(e.output??[]).filter(u=>u.type==="function_call"||u.type==="custom_tool_call"),o;n?.content?.length&&n?.content[0].annotations&&(o=n.content[0].annotations.map(u=>({type:"url_citation",url_citation:{url:u.url||"",title:u.title||"",content:"",start_index:u.start_index||0,end_index:u.end_index||0}}))),this.logger.debug({data:o,type:"url_citation"});let s=null,i=null,a=ss(e.output?.find(u=>u.type==="reasoning"))||null;if(!a&&n&&n.reasoning&&(a={content:n.reasoning}),n&&n.content){let u=[],d=[];if(n.content.forEach(f=>{if(f.type==="output_text")u.push(f.text||"");else if(f.type==="output_image"){let p=this.buildImageContent({url:f.image_url,mime_type:f.mime_type});p&&d.push(p)}else if(f.type==="output_image_base64"){let p=this.buildImageContent({b64_json:f.image_base64,mime_type:f.mime_type});p&&d.push(p)}}),d.length>0){let f=[];u.length>0&&f.push({type:"text",text:u.join("")}),f.push(...d),s=f}else s=u.join("")}return r.length>0&&(i=r.map(u=>({id:_t(u.call_id||u.id)||u.call_id||u.id,function:{name:u.name,arguments:u.type==="custom_tool_call"?JSON.stringify({[xn]:u.input||""}):u.arguments},type:"function"}))),{id:e.id||"chatcmpl-"+Date.now(),object:"chat.completion",created:e.created_at,model:e.model,choices:[{index:0,message:{role:"assistant",content:s||null,tool_calls:i,thinking:a,annotations:o},logprobs:null,finish_reason:i?"tool_calls":"stop"}],usage:e.usage?{prompt_tokens:e.usage.input_tokens||0,completion_tokens:e.usage.output_tokens||0,total_tokens:e.usage.total_tokens||0,prompt_tokens_details:{cached_tokens:e.usage.input_tokens_details?.cached_tokens||0,cache_write_tokens:e.usage.input_tokens_details?.cache_write_tokens||0}}:null}}buildImageContent(e){return e&&(e.url||e.b64_json)?{type:"image_url",image_url:{url:e.url||"",b64_json:e.b64_json},media_type:e.mime_type}:null}};import{existsSync as nx,readFileSync as KL,writeFileSync as VL,mkdirSync as YL}from"fs";import{dirname as XL,join as QL}from"path";import{homedir as ZL}from"os";var e2=QL(ZL(),".claude-code-router","qwen_auth.json"),t2="https://qwen.aikit.club",n2=1e4,r2=120,Qd=null;function rx(){return process.env.CCR_QWEN_AUTH_FILE||e2}function o2(){try{let t=rx();if(!nx(t))return null;let e=JSON.parse(KL(t,"utf-8"));return e.token?e:null}catch{return null}}function s2(t){let e=rx(),n=XL(e);nx(n)||YL(n,{recursive:!0}),VL(e,JSON.stringify(t,null,2),{mode:384,encoding:"utf-8"})}function i2(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 a2(t){try{let e=await fetch(`${t2}/v1/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t}),signal:AbortSignal.timeout(n2)});return e.ok&&(await e.json()).access_token||null}catch{return null}}async function d_(t){let e=o2();if(!e)throw new Error("No Qwen token found. Run `ccr qwen-auth` to authenticate.");return(t?.force||e.expiresAt!=null&&Date.now()+r2*1e3>=e.expiresAt)&&(Qd||(Qd=(async()=>{let r=await a2(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:i2(r),updatedAt:Date.now()};return s2(o),o})().finally(()=>{Qd=null})),e=await Qd),e}var c2="https://qwen.aikit.club",ox=/(?:\\n|\n)?<details>[\s\S]*?<\/details>\s*/g,Zd=class{name="qwen-auth";logger;async buildAuthConfig(e){let n=await d_();return{url:e?.api_base_url||e?.baseUrl||c2,headers:{Authorization:`Bearer ${n.token}`}}}async transformRequestIn(e,n){return{body:yo(e),config:await this.buildAuthConfig(n)}}async auth(e,n){return{config:await this.buildAuthConfig(n)}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(5);if(s.trim()==="[DONE]"){o.controller.enqueue(Pe(r,o.encoder));return}let i=s.replace(ox,"");o.controller.enqueue(Pe(`data: ${i}`,o.encoder));return}o.controller.enqueue(Pe(r,o.encoder))}):e;if(n.includes("application/json")){let o=(await e.text()).replace(ox,"");return new Response(o,{status:e.status,statusText:e.statusText,headers:e.headers})}return e}};var f_=`Always think before answering. Even if the problem seems simple, always write down your reasoning process explicitly.
|
|
343
347
|
|
|
344
348
|
Output format:
|
|
345
349
|
<reasoning_content>
|
|
346
350
|
Your detailed thinking process goes here
|
|
347
351
|
</reasoning_content>
|
|
348
|
-
Your final answer must follow after the closing tag above.`,
|
|
349
|
-
${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:
|
|
352
|
+
Your final answer must follow after the closing tag above.`,u2=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<u2)&&(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:f_}):r.content=[{type:"text",text:f_},{type:"text",text:r.content||""}]),r.role==="tool"&&e.messages.push({role:"user",content:[{type:"text",text:f_}]}),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="",C=(y,k)=>{if(typeof k!="string"){y.choices?.[0]?.delta&&Object.keys(y.choices[0].delta).length>0&&!y.choices[0].delta.content&&(y.choices[0].index=o,u.enqueue(i.encode(`data: ${JSON.stringify(y)}
|
|
350
354
|
|
|
351
|
-
`)));return}let b=h+k;for(h="";b.length>0;)if(p==="SEARCHING"){let A=b.indexOf(n);if(A!==-1)b=b.substring(A+n.length),p="REASONING";else{for(let w=n.length-1;w>0;w--)if(b.endsWith(n.substring(0,w))){h=b.substring(b.length-w);break}b=""}}else if(p==="REASONING"){let A=b.indexOf(r);if(A!==-1){let w=b.substring(0,A);if(w.length>0){let O={...
|
|
355
|
+
`)));return}let b=h+k;for(h="";b.length>0;)if(p==="SEARCHING"){let A=b.indexOf(n);if(A!==-1)b=b.substring(A+n.length),p="REASONING";else{for(let w=n.length-1;w>0;w--)if(b.endsWith(n.substring(0,w))){h=b.substring(b.length-w);break}b=""}}else if(p==="REASONING"){let A=b.indexOf(r);if(A!==-1){let w=b.substring(0,A);if(w.length>0){let O={...y.choices[0].delta,thinking:{content:w}};delete O.content;let q={...y,choices:[{...y.choices[0],delta:O,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(q)}
|
|
352
356
|
|
|
353
|
-
`))}let E={...
|
|
357
|
+
`))}let E={...y.choices[0].delta,thinking:{signature:new Date().getTime().toString()}};delete E.content;let x={...y,choices:[{...y.choices[0],delta:E,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
|
|
354
358
|
|
|
355
|
-
`)),o++,b=b.substring(A+r.length),p="FINAL"}else{let w=b;for(let E=r.length-1;E>0;E--)if(b.endsWith(r.substring(0,E))){h=b.substring(b.length-E),w=b.substring(0,b.length-E);break}if(w.length>0){let E={...
|
|
359
|
+
`)),o++,b=b.substring(A+r.length),p="FINAL"}else{let w=b;for(let E=r.length-1;E>0;E--)if(b.endsWith(r.substring(0,E))){h=b.substring(b.length-E),w=b.substring(0,b.length-E);break}if(w.length>0){let E={...y.choices[0].delta,thinking:{content:w}};delete E.content;let x={...y,choices:[{...y.choices[0],delta:E,index:o}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
|
|
356
360
|
|
|
357
|
-
`))}b=""}}else if(p==="FINAL"){if(b.length>0)if(/^\s*$/.test(b))g+=b;else{let w=g+b,E={...
|
|
361
|
+
`))}b=""}}else if(p==="FINAL"){if(b.length>0)if(/^\s*$/.test(b))g+=b;else{let w=g+b,E={...y.choices[0].delta,content:w};E.thinking&&delete E.thinking;let x={...y,choices:[{...y.choices[0],delta:E}]};u.enqueue(i.encode(`data: ${JSON.stringify(x)}
|
|
358
362
|
|
|
359
|
-
`)),g=""}o++,b=""}};try{for(;;){let{done:
|
|
363
|
+
`)),g=""}o++,b=""}};try{for(;;){let{done:y,value:k}=await d.read();if(y)break;let b=s.decode(k,{stream:!0});f+=b;let A=f.split(`
|
|
360
364
|
`);f=A.pop()||"";for(let w of A)if(w.trim()){if(w.trim()==="data: [DONE]"){u.enqueue(i.encode(w+`
|
|
361
365
|
|
|
362
366
|
`));break}if(w.startsWith("data:"))try{let E=JSON.parse(w.slice(5));C(E,E.choices?.[0]?.delta?.content)}catch{u.enqueue(i.encode(w+`
|
|
363
367
|
`))}else u.enqueue(i.encode(w+`
|
|
364
|
-
`))}}}catch(
|
|
368
|
+
`))}}}catch(y){this.logger?.error("Stream error:",y),u.error(y)}finally{try{d.releaseLock()}catch(y){this.logger?.error("Error releasing reader lock:",y)}if(p==="REASONING"){let k={choices:[{delta:{thinking:{signature:new Date().getTime().toString()}}}]};u.enqueue(i.encode(`data: ${JSON.stringify(k)}
|
|
365
369
|
|
|
366
|
-
`))}u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var
|
|
370
|
+
`))}u.close()}}});return new Response(a,{status:e.status,statusText:e.statusText,headers:{"Content-Type":e.headers.get("Content-Type")||"text/plain","Cache-Control":"no-cache",Connection:"keep-alive"}})}return e}};var tf=class{name="extrathinktag";async transformRequestIn(e){return e}async transformResponseOut(e){let n="<think>",r="</think>";if(e.headers.get("Content-Type")?.includes("application/json"))try{let u=await e.json(),d=u?.choices?.[0]?.message?.content;if(typeof d=="string"){let f=d.match(/<think>([\s\S]*?)<\/think>/);f?.[1]&&(u.thinking={content:f[1]})}return new Response(JSON.stringify(u),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return e}if(!e.headers.get("Content-Type")?.includes("stream")||!e.body)return e;let o=new TextDecoder,s=new TextEncoder,i=0,a=new ReadableStream({async start(u){let d=e.body.getReader(),f="",p="SEARCHING",h="",g="",C=k=>{u.enqueue(s.encode(`data: ${JSON.stringify(k)}
|
|
367
371
|
|
|
368
|
-
`))},
|
|
372
|
+
`))},y=(k,b)=>{if(typeof b!="string"&&k?.choices?.[0]?.delta&&Object.keys(k.choices[0].delta).length>0&&!k.choices[0].delta.content){k.choices[0].index=i,C(k);return}if(typeof b!="string")return;let A=h+b;for(h="";A.length>0;){if(p==="SEARCHING"){let w=A.indexOf(n);if(w!==-1){A=A.substring(w+n.length),p="THINKING";continue}for(let E=n.length-1;E>0;E--)if(A.endsWith(n.substring(0,E))){h=A.substring(A.length-E);break}A="";continue}if(p==="THINKING"){let w=A.indexOf(r);if(w!==-1){let x=A.substring(0,w);if(x.length>0){let q={...k.choices[0].delta,thinking:{content:x}};delete q.content,C({...k,choices:[{...k.choices[0],delta:q,index:i}]})}let O={...k.choices[0].delta,thinking:{signature:Date.now().toString()}};delete O.content,C({...k,choices:[{...k.choices[0],delta:O,index:i}]}),i++,A=A.substring(w+r.length),p="FINAL";continue}let E=A;for(let x=r.length-1;x>0;x--)if(A.endsWith(r.substring(0,x))){h=A.substring(A.length-x),E=A.substring(0,A.length-x);break}if(E.length>0){let x={...k.choices[0].delta,thinking:{content:E}};delete x.content,C({...k,choices:[{...k.choices[0],delta:x,index:i}]})}A="";continue}if(A.length>0)if(/^\s*$/.test(A))g+=A;else{let w=g+A,E={...k.choices[0].delta,content:w};E.thinking&&delete E.thinking,C({...k,choices:[{...k.choices[0],delta:E}]}),g=""}i++,A=""}};try{for(;;){let{done:k,value:b}=await d.read();if(k)break;f+=o.decode(b,{stream:!0});let A=f.split(`
|
|
369
373
|
`);f=A.pop()||"";for(let w of A)if(w.trim()){if(w.trim()==="data: [DONE]"){u.enqueue(s.encode(w+`
|
|
370
374
|
|
|
371
|
-
`));continue}if(w.startsWith("data:"))try{let E=JSON.parse(w.slice(5));
|
|
375
|
+
`));continue}if(w.startsWith("data:"))try{let E=JSON.parse(w.slice(5));y(E,E?.choices?.[0]?.delta?.content)}catch{u.enqueue(s.encode(w+`
|
|
372
376
|
`))}else u.enqueue(s.encode(w+`
|
|
373
|
-
`))}}}catch(k){console.error("Stream error:",k),u.error(k)}finally{try{d.releaseLock()}catch(k){console.error("Error releasing reader lock:",k)}p==="THINKING"&&C({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
|
|
374
|
-
`):typeof e.content=="string"?e.content:"";if(e.role==="assistant"&&n){let i=[];i.push(
|
|
375
|
-
`):String(t)}function ni(t){return
|
|
376
|
-
`)).digest("hex").slice(0,32)}function ri(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
|
|
377
|
-
`)}function
|
|
378
|
-
`)}function
|
|
379
|
-
`)}function
|
|
380
|
-
`)}function
|
|
381
|
-
`)}function
|
|
382
|
-
${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,
|
|
377
|
+
`))}}}catch(k){console.error("Stream error:",k),u.error(k)}finally{try{d.releaseLock()}catch(k){console.error("Error releasing reader lock:",k)}p==="THINKING"&&C({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 l2(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 d2(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+=l2(o);return e||n||r}function f2(t){return{type:"thinking",thinking:[{type:"text",text:t}]}}function sx(t){if(!t||typeof t!="object"||!("cache_control"in t))return t;let{cache_control:e,...n}=t;return n}function p2(t){let e={...t},n=d2(e),r=Array.isArray(e.content)?e.content:void 0,o=(r||[]).filter(i=>i?.type==="image_url").map(sx),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(f2(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(sx):e.content=s);return delete e.thinking,delete e.reasoning_content,delete e.cache_control,e}function h2(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 g2(t){let e=t.effort?.toLowerCase();if(!(!e||e==="none"))return e==="minimal"?"low":e==="low"||e==="medium"||e==="high"?e:"high"}var ix=new Set(["mistral-small-2506","mistral-medium-2505","mistral-medium-2508"]);function ax(t,e,n){let r={...t};Array.isArray(r.messages)&&(r.messages=r.messages.map(s=>p2(s))),r.stream===void 0&&(r.stream=!0);let o=en(e,t);if(o&&(r.prompt_cache_key=o),r.tool_choice&&(r.tool_choice=h2(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:xu(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-")&&!ix.has(s)||s.startsWith("mistral-medium-")&&!ix.has(s))&&(r.reasoning_effort=g2(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 cx(t,e,n){let r=t.headers.get("Content-Type")??"";if(r.includes("application/json")){let o=await t.json();n?.debug({response:o},`${e} response:`);let s=o.choices?.[0];if(s?.message){let i=s.message,a="";if(i.reasoning_content){let u=i.reasoning_content;a+=typeof u=="string"?u:typeof u?.text=="string"?u.text:JSON.stringify(u),delete i.reasoning_content}if(Array.isArray(i.content)){let u="";for(let d of i.content)if(d.type==="thinking"){let f=Array.isArray(d.thinking)?d.thinking:[d.thinking];a+=f.map(p=>typeof p=="string"?p:p&&typeof p.text=="string"?p.text:JSON.stringify(p)).join("")}else d.type==="text"&&(u+=typeof d.text=="string"?d.text:JSON.stringify(d.text??""));i.content=u}a&&(o.thinking={content:a},i.thinking={content:a})}return new Response(JSON.stringify(o),{status:t.status,statusText:t.statusText,headers:t.headers})}else if(r.includes("stream"))return t.body?Ne(t,(o,s)=>{if(!o.trim()){s.controller.enqueue(Pe(o,s.encoder));return}if(!o.startsWith("data:")||o.trim()==="data: [DONE]"){s.controller.enqueue(Pe(o,s.encoder));return}try{let i=o.slice(5).trim(),a=JSON.parse(i),u=a.choices?.[0]?.delta;if(!u){s.controller.enqueue(Pe(o,s.encoder));return}let d=Vs(u);if(d){let f=Qr(a,{content:d});Zr(f.choices[0].delta);let p=u.content;if(Array.isArray(p)){let h="",g=p.filter(C=>C.type==="text").map(C=>typeof C.text=="string"?C.text:JSON.stringify(C.text??"")).join("");for(let C of p)if(C.type==="thinking"){let y=Array.isArray(C.thinking)?C.thinking:[C.thinking];h+=y.map(k=>typeof k=="string"?k:k&&typeof k.text=="string"?k.text:JSON.stringify(k)).join("")}delete f.choices[0].delta.content,(h||d)&&(f.choices[0].delta.thinking={content:h||d}),g&&(f.choices[0].delta.content=g)}s.controller.enqueue(ve(JSON.stringify(f),s.encoder));return}if(Array.isArray(u.content)){let f="",p=u.content.filter(h=>h.type==="text").map(h=>typeof h.text=="string"?h.text:JSON.stringify(h.text??"")).join("");for(let h of u.content)if(h.type==="thinking"){let g=Array.isArray(h.thinking)?h.thinking:[h.thinking];f+=g.map(C=>typeof C=="string"?C:C&&typeof C.text=="string"?C.text:JSON.stringify(C)).join("")}delete u.content,f&&(u.thinking={content:f}),p&&(u.content=p)}s.controller.enqueue(ve(JSON.stringify(a),s.encoder))}catch{s.controller.enqueue(Pe(o,s.encoder))}}):t;return t}var nf=class{name="mistral";logger;async transformRequestIn(e,n,r){return{body:ax(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 cx(e,this.name,this.logger)}catch(r){throw this.logger?.error({error:r.message,response:e},"Mistral transformResponseOut error:"),r}}};var m2="http://127.0.0.1:3457",rf=class{name="chrome-on-device";async transformRequestIn(e,n,r){let o=process.env.CHROME_BRIDGE_URL||n?.baseUrl||m2;r?.req?.body&&(r.req.body.stream=!0);let s=en(r,e);return{body:{...e,messages:Ke(e.messages),tools:Ve(e.tools),stream:!0},config:{url:`${o}/v1/chat/completions`,headers:{"Content-Type":"application/json",...s?{"x-ccr-session-id":s}:{}}}}}async transformResponseOut(e){return(e.headers.get("Content-Type")||"").includes("text/event-stream")||!e.body,e}};import{randomBytes as y2,createHash as _2}from"crypto";var b2="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ux=3,of=class{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=await this.sendWithSessionRetry(s,i,n,r,o);return{body:s,config:{...i,url:n?.baseUrl||n?.api_base_url,__providerResponse:a}}}async sendWithSessionRetry(e,n,r,o,s){let i=r?.baseUrl||r?.api_base_url,a=o?.req?.server?.configService?.getHttpsProxy?.(),u=o?.req?.log??o?.req?.server?.log,d=e?.model;for(let f=0;f<ux;f++){let p=this.buildHeaders(n,r,s),h=await es(i,e,{httpsProxy:a,...n,headers:p,signal:o?.signal??n?.signal},o,u);if(h.ok)return h;let g=await h.text();if(!(f===ux-1)&&this.isZenRoutingFailure(h.status,g)){this.invalidateSession(s),u?.warn?.({provider:r?.name,model:d,status:h.status,attempt:f+1},"opencode: Zen provider-routing failure \u2014 re-rolling session and retrying");continue}let y=Je(g)||g.slice(0,240);throw J(`Error from provider(${r?.name},${d}: ${h.status}): ${y}`,h.status,"provider_response_error","api_error",this.retryAfterHeaders(h))}throw J(`Error from provider(${r?.name},${d}): Zen provider-routing retries exhausted`,503,"provider_response_error")}buildHeaders(e,n,r){let o=this.getOrCreateSessionId(r),s=this.generateId("msg");return{...e?.headers,"x-api-key":n.apiKey||"","x-opencode-project":"global","x-opencode-session":o,"x-opencode-request":s,"x-opencode-client":"cli","user-agent":"opencode/1.18.4",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))}retryAfterHeaders(e){let n=e.headers.get("retry-after");return n?{"Retry-After":n}:void 0}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 _2("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=y2(1)[0];i>=248||(s+=b2[i%62])}return`${e}_${o.toString("hex")}${s}`}};import{Cursor as _$}from"@cursor/sdk";var C2=/^\$\{?[A-Z_][A-Z0-9_]*\}?$/;function lx(t){let e=typeof t?.apiKey=="string"?t.apiKey.trim():"";if(e&&e.startsWith("crsr_")&&!C2.test(e)&&!e.includes("$CURSOR_API_KEY")&&!e.includes("${"))return e;let n=process.env.CURSOR_API_KEY?.trim();if(n)return n;throw Object.assign(new Error("Cursor API key not found. Set Providers[].api_key to a crsr_ key, or export CURSOR_API_KEY."),{statusCode:401,code:"provider_response_error",type:"api_error"})}import{createHash as w2}from"crypto";import{homedir as k2}from"os";import{basename as S2,dirname as A2,join as dx}from"path";var p_="cursor-sdk",sf="bridge",E2=dx(k2(),".claude-code-router"),zn=dx(E2,"cursor-sdk-workspaces"),fx=900*1e3,h_=32,px=1440*60*1e3,hx=3600*1e3,v2=/^[0-9a-f]{32}$/;function g_(t,e=zn){let n=t.replace(/[\\/]+$/,"");return A2(n)!==e.replace(/[\\/]+$/,"")?!1:v2.test(S2(n))}var gx=["Shell","Read","Write","Delete","Grep","Glob","Edit","ApplyPatch","Task","SemanticSearch","SemSearch","ReadLints","LS","CreatePlan","UpdateTodos","Await","WebFetch","WebSearch","GenerateImage"],Ta="custom-user-tools";function dn(t){return t==null?"":typeof t=="string"?t:Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&"text"in e?String(e.text||""):"").filter(Boolean).join(`
|
|
379
|
+
`):String(t)}function ni(t){return w2("sha256").update(t.filter(Boolean).join(`
|
|
380
|
+
`)).digest("hex").slice(0,32)}function ri(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 m_(t){return t?.output_config?.effort||t?.reasoning?.effort||t?.effort||void 0}function mx(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:ri(s)}},finish_reason:null}]}},thinkingSignature(s=`ccr_cursor_${Date.now()}`){return{...o(),choices:[{index:0,delta:{thinking:{signature:s}},finish_reason:null}]}},toolCall(s,i=0){return{...o(),choices:[{index:0,delta:{role:"assistant",tool_calls:[{index:i,id:s.id,type:"function",function:{name:s.name,arguments:JSON.stringify(s.args??{})}}]},finish_reason:null}]}},finish(s,i){let a=Number(i?.prompt_tokens)||0,u=Number(i?.completion_tokens)||0,d=Number(i?.total_tokens)||a+u;return{...o(),choices:[{index:0,delta:{},finish_reason:s}],usage:{prompt_tokens:a,completion_tokens:u,total_tokens:d,prompt_tokens_details:{cached_tokens:Number(i?.prompt_tokens_details?.cached_tokens)||0}}}},encode(s){return ve(JSON.stringify(s),e)},encodeDone(){return ve("[DONE]",e)}}}function y_(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+=ri(g.thinking.content)),typeof g.thinking?.signature=="string"&&g.thinking.signature&&(o=g.thinking.signature),Array.isArray(g.tool_calls))for(let C of g.tool_calls){let y=C.index??s.length;s[y]||(s[y]={id:C.id,type:"function",function:{name:C.function?.name||"",arguments:""}}),C.id&&(s[y].id=C.id),C.function?.name&&(s[y].function.name=C.function.name),typeof C.function?.arguments=="string"&&(s[y].function.arguments+=C.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 eo={additionalRoots:[],facts:[],known:!1,fingerprint:"none"},yx=/<(env|environment|system-info|system_info)>([\s\S]*?)<\/\1>/gi,T2=/^\s*[-*]?\s*([A-Za-z][A-Za-z0-9 _/'-]{2,48}?)\s*:\s*(\S.*?)\s*$/,x2=/working director|workspace root|project root|platform|os version|operating system|git repo/i,_x=[/^primary working director/i,/^current working director/i,/^working director/i,/^project root/i,/^workspace root/i,/^cwd$/i],bx=[/^additional working director/i,/^additional director/i,/^extra working director/i],Cx=[/^platform$/i,/^operating system$/i,/^os$/i],wx=[/^os version$/i,/^system version$/i],R2=[..._x,...bx,...Cx,...wx],D2=2e5,O2=16,P2=400;function I2(t){let e=[],n=D2,r=!1;for(let o of t.messages||[]){if(o.role!=="system"&&o.role!=="user")continue;if(o.role==="user"&&r)break;o.role==="user"&&(r=!0);let s=dn(o.content);if(s&&(e.push(s.slice(0,n)),n-=Math.min(s.length,n),n<=0))break}return e.join(`
|
|
381
|
+
`)}function F2(t){let e=[],n=new Set,r=i=>{if(e.length>=O2)return;let a=i.match(T2);if(!a)return;let u=a[1].trim(),d=a[2].trim().slice(0,P2);if(!u||!d)return;let f=u.toLowerCase();n.has(f)||(n.add(f),e.push({key:u,value:d}))},o=!1;yx.lastIndex=0;let s;for(;s=yx.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/))x2.test(i)&&r(i);return e}function af(t,e){for(let n of e){let r=t.find(o=>n.test(o.key));if(r)return r.value}}function kx(t){return/^(?:\/|[A-Za-z]:[\\/]|\\\\)/.test(t)}function N2(t){return t?t.split(/[,\n]/).map(e=>e.trim()).filter(e=>kx(e)):[]}function xa(t){let e=F2(I2(t)),n=af(e,_x),r=n&&kx(n)?n:void 0,o=N2(af(e,bx)).filter(u=>u!==r),s=af(e,Cx),i=af(e,wx),a=!!(r||s||i||e.length);return a?{projectRoot:r,additionalRoots:o,platform:s,osVersion:i,facts:e,known:a,fingerprint:ni([r||"",o.join("|"),s||"",i||"",e.map(u=>`${u.key}=${u.value}`).join("|")])}:eo}function Sx(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)R2.some(r=>r.test(n.key))||e.push(`- ${n.key}: ${n.value}`);return e}function Bo(t){return t.projectRoot?`Every path you pass to a host tool must be an absolute path on the host, normally under ${t.projectRoot}.`:"Every path you pass to a host tool must be an absolute host path taken from this conversation \u2014 never invent one and never derive one from your local filesystem."}function M2(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 B2(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(`
|
|
382
|
+
`)}function Ex(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=Sx(e);return r.length&&(n.push("The user's project lives on the host machine, which is where every tool call lands:"),n.push(...r)),n.push(Bo(e)),n.push(`Host tools are exposed via MCP server "${Ta}" 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 U2(t,e,n=xa(t)){return[...Ex(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:",B2(t)].join(`
|
|
383
|
+
`)}function j2(t,e){return["[bridge reminder]",`Tools run on the host machine, not here. ${t} is empty scratch space \u2014 never treat it as the project, and never build a tool path from it.`,Bo(e)].join(`
|
|
384
|
+
`)}function vx(t,e){return["# Agent rules","",...Ex(t,e).map(n=>n.startsWith("- ")?n:`- ${n}`),""].join(`
|
|
385
|
+
`)}function Tx(t){return["Your local filesystem is empty scratch space on a different machine from the user's project.","The project is reachable only through the host tools, and it is not restricted.",Bo(t)].join(" ")}var L2=[/^(?: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 $2(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:L2.some(o=>o.test(n))}function xx(t){return t.mode==="bridge"&&t.emittedHostTools===0&&t.continuationAttempts<1&&$2(t.assistantText)}function Rx(t){let e=["Continue the same turn now.","Your previous assistant message was only progress narration and ended without a host tool call or a complete answer.","Do not repeat the progress update.","If evidence is still needed, call an available host tool immediately; otherwise provide the complete user-facing answer now.","Do not finish until the requested work or answer is complete."];return t?.known&&e.push(Bo(t)),{text:e.join(" ")}}function Ax(t){let e=t.trim();return $h.some(n=>e===n)}function q2(t){if(!Array.isArray(t)){let e=dn(t);return e.trim().length>0&&!Ax(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&&!Ax(n)}return!0})}function Dx(t,e){let n=t.messages||[],r=[],o=e.hostEnv||xa(t);e.mode==="bridge"?(r.push(U2(t,e.workspaceDir,o)),r.push("")):e.mode==="plan"&&(r.push("You are a planning/chat assistant. Respond with text and reasoning only. Do not execute tools."),r.push(""));let s=n.filter(f=>f.role==="system");for(let f of s){let p=dn(f.content);p&&r.push(`[system]
|
|
386
|
+
${p}`)}let i=n.filter(f=>f.role!=="system"),a=e.followUpOnly?i.slice(-Math.max(1,H2(i,e.turnIntent)+1)):i,u=[];for(let f of a){if(f.role==="assistant"){let p=dn(f.content);if(p&&r.push(`[assistant]
|
|
383
387
|
${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}]
|
|
384
388
|
${h.function.arguments||"{}"}`);continue}if(f.role==="tool"){r.push(`[tool_result id=${f.tool_call_id||"unknown"}]
|
|
385
|
-
${dn(f.content)}`);continue}if(f.role==="user"){let p=dn(f.content);u=[...u,...
|
|
386
|
-
${p}`)}}e.mode==="bridge"&&r.push(
|
|
389
|
+
${dn(f.content)}`);continue}if(f.role==="user"){let p=dn(f.content);u=[...u,...M2(f.content)],p&&r.push(`[user]
|
|
390
|
+
${p}`)}}e.mode==="bridge"&&r.push(j2(e.workspaceDir,o));let d=r.join(`
|
|
387
391
|
|
|
388
|
-
`).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function
|
|
392
|
+
`).trim()||"Continue.";return u.length?{text:d,images:u}:{text:d}}function H2(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 Ox(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||q2(r[o].content),o-=1;for(;o>=0;o--){let i=r[o];if(i.role!=="tool")break;n.unshift({toolCallId:String(i.tool_call_id||""),content:dn(i.content)})}return{toolResults:n,hasTrailingUserInput:s}}import{createHash as b_}from"crypto";import{existsSync as Mx,mkdirSync as Px,readdirSync as Y2,rmSync as X2,statSync as Q2}from"fs";import{join as Bx}from"path";import{Agent as Ix}from"@cursor/sdk";import{chmodSync as z2,mkdirSync as W2,readFileSync as G2,writeFileSync as J2}from"fs";import{join as Ra}from"path";function K2(t){return`#!/usr/bin/env node
|
|
389
393
|
const chunks = [];
|
|
390
394
|
process.stdin.on("data", (c) => chunks.push(c));
|
|
391
395
|
process.stdin.on("end", () => {
|
|
@@ -424,17 +428,17 @@ process.stdin.on("end", () => {
|
|
|
424
428
|
})
|
|
425
429
|
);
|
|
426
430
|
});
|
|
427
|
-
`}function L2(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${Ta}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,Sx(t)].join(" ")}function d_(t,e,n){try{if(B2(t,"utf-8")===e)return}catch{}j2(t,e,{encoding:"utf-8",mode:n})}function Da(t,e=eo){let n=Ra(t,".cursor"),r=Ra(n,"hooks");M2(r,{recursive:!0});let o=Ra(r,"deny-builtin.cjs");d_(o,U2(L2(e)),448);try{N2(o,448)}catch{}let s=dx.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};d_(Ra(n,"hooks.json"),JSON.stringify(a,null,2),384),d_(Ra(t,"AGENTS.md"),kx(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 oi(t,e){t.poisoned=!0,t.poisonReason=e}async function h_(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 ef(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&&oi(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function ef(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 tf(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 Oa(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")||Px("/.dockerenv")||process.env.container==="docker")}function G2(t,e){Px(zn)||xx(zn,{recursive:!0});let n=Ix(zn,t);return xx(n,{recursive:!0}),Da(n,e),n}function g_(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 Da(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function Dx(t,e,n=zn){if(!c_(t,n))return!1;try{return q2(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function Fx(t){if(t.headerSession)return f_("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?f_("sha256").update(e[1]).digest("hex").slice(0,32):f_("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return ni([t.model||"",t.systemAndFirstUser||""])}function Ox(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function Zd(t){t.lastActiveAt=Date.now()}var p_=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&&Zd(n),n}async retireSession(e,n,r){oi(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||eo,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:G2(e.key,o);e.mode==="bridge"&&Da(s,o);let i=e.mode==="plan"?"plan":"agent",a=Oa(e.sandboxEnabled),u=await Rx.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=Oa(e.sandboxEnabled),r=e.hostEnv||eo;e.mode==="bridge"&&Da(e.workspaceDir,r);let o=await Rx.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"),Zd(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 h_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),Dx(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(oi(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 ef(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>=a_;){let e,n=1/0;for(let[r,o]of this.sessions)Ox(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:a_},"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)Ox(r)||e-r.lastActiveAt>cx&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=zn){if(e-this.lastSweepAt<lx)return 0;this.lastSweepAt=e;let r;try{r=$2(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=Ix(n,i);if(!(o.has(a)||!c_(a,n))){try{let u=H2(a);if(!u.isDirectory()||e-u.mtimeMs<=ux)continue}catch{continue}Dx(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},to=new p_;var J2="Cursor SDK agent.send timed out";function m_(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 y_(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 ef(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 __(t,e,n,r={}){return V2(t,e,n,r.abortSignal)}import{randomUUID as t$}from"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(zn)}function Nx(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 Mx(t){return t.projectRoot?!t.projectRoot.startsWith(zn):!0}function Bx(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
|
|
431
|
+
`}function V2(t){return["CCR Cursor SDK bridge: do not use Cursor built-in tools.",`Call host tools via MCP server '${Ta}' using the bare Claude Code tool names (Read, Bash, Edit, \u2026).`,Tx(t)].join(" ")}function __(t,e,n){try{if(G2(t,"utf-8")===e)return}catch{}J2(t,e,{encoding:"utf-8",mode:n})}function Da(t,e=eo){let n=Ra(t,".cursor"),r=Ra(n,"hooks");W2(r,{recursive:!0});let o=Ra(r,"deny-builtin.cjs");__(o,K2(V2(e)),448);try{z2(o,448)}catch{}let s=gx.join("|"),i=`node "${o}"`,a={version:1,hooks:{preToolUse:[{matcher:s,command:i}],beforeShellExecution:[{command:i}],beforeReadFile:[{command:i}],beforeMCPExecution:[{command:i}]}};__(Ra(n,"hooks.json"),JSON.stringify(a,null,2),384),__(Ra(t,"AGENTS.md"),vx(t,e),384)}var Z2=2e3;function e$(t){let e=t;return e?.name==="AbortError"||String(e?.message||t).toLowerCase()==="this operation was aborted"}function oi(t,e){t.poisoned=!0,t.poisonReason=e}async function w_(t,e={}){let n={skipped:!1,hadRun:!!t.run,hadIterator:!!t.streamIterator,runCancelFailed:!1,iteratorReturnFailed:!1,failed:!1,timedOut:!1};if(e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken)return{...n,skipped:!0};let r=t.run,o=t.streamIterator,s=t.streamNext;if(t.run=void 0,t.streamIterator=void 0,t.streamNext=void 0,t.streamNextRunToken=void 0,t.activeRunToken=void 0,t.pendingEmit=[],t.pendingSdkMessages=[],t.notifyEmit(),t.notifySdkMessage?.(),s?.catch(()=>{}),e.rejectParked&&t.parked.length){let u=e.reason||"cursor-sdk run cancelled";for(let d of t.parked.splice(0,t.parked.length))try{d.reject(new Error(u))}catch{}}let i=async(u,d,f)=>{try{await uf(Promise.resolve().then(u),e.timeoutMs??2e3,d)}catch(p){n.failed=!0,f==="run"&&(n.runCancelFailed=!0),f==="iterator"&&(n.iteratorReturnFailed=!0),n.timedOut=n.timedOut||String(p?.message||p).toLowerCase().includes("timed out")}},a=[];return r?.status==="running"&&a.push(i(()=>r.cancel(),"cursor-sdk run cancel timed out","run")),o&&typeof o.return=="function"&&a.push(i(()=>o.return(void 0),"cursor-sdk stream iterator return timed out","iterator")),await Promise.all(a),n.failed&&e.poisonOnFailure&&oi(t,e.reason||"cursor-sdk run cancellation did not complete"),n}async function uf(t,e,n){let r;try{return await Promise.race([t,new Promise((o,s)=>{r=setTimeout(()=>s(new Error(n)),e)})])}finally{r&&clearTimeout(r)}}async function lf(t,e){let n=t.sendChain,r,o=new Promise(s=>{r=s});t.sendChain=n.then(()=>o).catch(()=>o),await n.catch(()=>{});try{return await e()}finally{r()}}function Oa(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")||Mx("/.dockerenv")||process.env.container==="docker")}function t$(t,e){Mx(zn)||Px(zn,{recursive:!0});let n=Bx(zn,t);return Px(n,{recursive:!0}),Da(n,e),n}function k_(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 Da(t.workspaceDir,e),t.guidanceFingerprint=e.fingerprint,!0}catch{return!1}}function Fx(t,e,n=zn){if(!g_(t,n))return!1;try{return X2(t,{recursive:!0,force:!0}),!0}catch(r){return e?.debug?.({err:r,dir:t},"cursor-sdk workspace cleanup failed"),!1}}function Ux(t){if(t.headerSession)return b_("sha256").update(t.headerSession).digest("hex").slice(0,32);if(t.metadataUserId){let e=t.metadataUserId.split("_session_");return e.length>1&&e[1]?b_("sha256").update(e[1]).digest("hex").slice(0,32):b_("sha256").update(t.metadataUserId).digest("hex").slice(0,32)}return ni([t.model||"",t.systemAndFirstUser||""])}function Nx(t){return!!(t.streamIterator||t.streamNext||t.activeRunToken||t.parked.length>0||t.pendingSdkMessages.length>0||t.run?.status==="running")}function cf(t){t.lastActiveAt=Date.now()}var C_=class{constructor(e){this.logger=e;this.cleanupTimer=setInterval(()=>this.evictIdle(),6e4),typeof this.cleanupTimer.unref=="function"&&this.cleanupTimer.unref()}logger;sessions=new Map;retirements=new Map;creations=new Map;cleanupTimer;lastSweepAt=0;setLogger(e){this.logger=e}get(e){let n=this.sessions.get(e);if(n?.poisoned){let r=n.poisonReason||"cursor-sdk session poisoned";this.retireSession(n,r,async()=>(await this.invalidate(n,r),!0)).catch(o=>{this.logger?.warn?.({err:o,sessionKey:n.key,agentId:n.agentId,reason:r},"cursor-sdk poisoned session retirement failed")});return}return n&&cf(n),n}async retireSession(e,n,r){oi(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||eo,s=e.mode==="agent"&&e.cursorCwd?e.cursorCwd:t$(e.key,o);e.mode==="bridge"&&Da(s,o);let i=e.mode==="plan"?"plan":"agent",a=Oa(e.sandboxEnabled),u=await Ix.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=Oa(e.sandboxEnabled),r=e.hostEnv||eo;e.mode==="bridge"&&Da(e.workspaceDir,r);let o=await Ix.resume(e.agentId,{apiKey:e.apiKey,model:e.model,local:{cwd:e.workspaceDir,settingSources:[],sandboxOptions:{enabled:n}}}),s=this.createSessionRecord({key:e.key,agent:o,mode:e.mode,workspaceDir:e.workspaceDir,hostEnv:r,guidanceFingerprint:r.fingerprint});return this.sessions.set(e.key,s),s}resolveParkedTools(e,n){let r=0,o=[],s=e.parked.map(i=>i.id).filter((i,a,u)=>i&&u.indexOf(i)!==a);s.length&&this.logger?.warn?.({sessionKey:e.key,duplicates:[...new Set(s)]},"cursor-sdk parked tools share an id; results may mispair");for(let i of n){let a=-1;if(i.toolCallId?a=e.parked.findIndex(d=>d.id===i.toolCallId):n.length===1&&e.parked.length===1&&(a=0),a===-1){o.push(i.toolCallId||"(empty)");continue}let[u]=e.parked.splice(a,1);u.resolve(i.content),r++}return o.length&&this.logger?.warn?.({unmatched:o,parkedRemaining:e.parked.map(i=>i.id),resolved:r},"cursor-sdk tool results did not match parked tools"),cf(e),r}async dispose(e){let n=this.sessions.get(e);if(!n)return;let r="cursor-sdk session disposed";await this.retireSession(n,r,async()=>(await w_(n,{rejectParked:!0,reason:r}),await this.disposeAgent(n,r),Fx(n.workspaceDir,this.logger),!0))}invalidate(e,n){let r=typeof e=="string"?this.sessions.get(e):e;if(!r)return Promise.resolve();if(oi(r,n),r.run=void 0,r.streamIterator=void 0,r.streamNext?.catch(()=>{}),r.streamNext=void 0,r.streamNextRunToken=void 0,r.activeRunToken=void 0,r.pendingEmit=[],r.pendingSdkMessages=[],r.parked.length)for(let o of r.parked.splice(0,r.parked.length))try{o.reject(new Error(n))}catch{}return r.notifyEmit(),r.notifySdkMessage(),this.sessions.get(r.key)===r&&this.sessions.delete(r.key),this.logger?.warn?.({sessionKey:r.key,agentId:r.agentId,reason:n},"cursor-sdk session invalidated"),this.disposeAgent(r,n)}async disposeAgent(e,n){try{let r=e.agent[Symbol.asyncDispose]();r.catch(()=>{}),await uf(r,Z2,"cursor-sdk agent disposal timed out")}catch(r){let o={err:r,sessionKey:e.key,agentId:e.agentId,reason:n};e$(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>=h_;){let e,n=1/0;for(let[r,o]of this.sessions)Nx(o)||o.lastActiveAt<n&&(n=o.lastActiveAt,e=r);if(!e){this.logger?.warn?.({size:this.sessions.size,max:h_},"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)Nx(r)||e-r.lastActiveAt>fx&&(this.logger?.info?.({sessionKey:n},"cursor-sdk idle session evicted"),this.dispose(n));this.sweepOrphanWorkspaces(e)}sweepOrphanWorkspaces(e=Date.now(),n=zn){if(e-this.lastSweepAt<hx)return 0;this.lastSweepAt=e;let r;try{r=Y2(n)}catch{return 0}let o=new Set([...this.sessions.values()].map(i=>i.workspaceDir)),s=0;for(let i of r){let a=Bx(n,i);if(!(o.has(a)||!g_(a,n))){try{let u=Q2(a);if(!u.isDirectory()||e-u.mtimeMs<=px)continue}catch{continue}Fx(a,this.logger,n)&&s++}}return s&&this.logger?.info?.({removed:s,root:n},"cursor-sdk orphan workspaces swept"),s}},to=new C_;var n$="Cursor SDK agent.send timed out";function S_(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 A_(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 r$(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 o$(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=r$(r),await uf(s?Promise.race([o,s.promise]):o,15e3,n$)}catch(i){throw o&&o.then(a=>a.cancel()).catch(()=>{}),i}finally{s?.cleanup()}}async function E_(t,e,n,r={}){return o$(t,e,n,r.abortSignal)}import{randomUUID as l$}from"crypto";var s$=6,i$=512,a$=4;function c$(t){return t.length>200?`${t.slice(0,200)}\u2026`:t}function u$(t,e){return t.length<8?!1:t.includes(e)||t.includes(zn)}function jx(t,e){let n=[],r=0,o=(s,i,a)=>{if(!(n.length>=a$||r>=i$||a>s$)){if(r++,typeof s=="string"){u$(s,e)&&n.push({argPath:i||"(argument)",value:c$(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 Lx(t){return t.projectRoot?!t.projectRoot.startsWith(zn):!0}function $x(t,e,n,r){let o=t.map(s=>` - ${s.argPath}: ${s.value}`).join(`
|
|
428
432
|
`);return[`Error: this ${e} call was not executed because it points at your local scratch container, not at the user's machine.`,"Offending arguments:",o,`${n} is disposable scratch space on the machine running the model bridge. It is empty and contains none of the user's files.`,"Host tools execute on the user's machine, where that path does not exist.",Bo(r),"Retry the call with a host path."].join(`
|
|
429
|
-
`)}var
|
|
430
|
-
`).length)}function qx(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=Lx(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 nf(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Hx(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=nf(t.prompt_tokens),s=nf(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=nf(e?.prompt_tokens),a=nf(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 zx(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,i=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:i}}}import{createHash as o$}from"crypto";var s$=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Wn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="bigint")return String(t);if(Array.isArray(t))return t.map(n=>Wn(n)).filter(n=>n!==void 0);if(typeof t!="object")return;let e={};for(let n of Object.keys(t).sort()){if(n==="cache_control")continue;let r=Wn(t[n]);r!==void 0&&(e[n]=r)}return e}function w_(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Wn(t);return e===void 0?[]:[e]}return t.map(e=>{if(typeof e=="string")return{text:e,type:"text"};if(!e||typeof e!="object")return Wn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Wn(n)}).filter(e=>e!==void 0)}function i$(t){if(typeof t!="string")return Wn(t)??null;try{return Wn(JSON.parse(t))??null}catch{return t}}function k_(t){let e=t,n={content:w_(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:i$(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function Wx(t){return Array.isArray(t)?t.map(e=>Wn(e)).filter(e=>e!==void 0).sort((e,n)=>C_(e).localeCompare(C_(n))):[]}function C_(t){return JSON.stringify(t)}function S_(t){return o$("sha256").update(C_(t)).digest("hex")}function Gx(t){return{system:w_(t.system),messages:(t.messages||[]).map(k_)}}function a$(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(s$.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(k_):r==="system"?o=w_(t.system):r==="tools"?o=Wx(t.tools):o=Wn(e[r]),o!==void 0&&(n[r]=o)}return n}function Jx(t,e={}){return S_({compatibilityStamp:e.compatibilityStamp||"",request:a$(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 A_(t){return S_({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Wn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:Wx(t.tools),workspaceDir:t.workspaceDir})}function Kx(t,e){return S_({messages:e,system:t})}function Vx(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=Gx(t);return e&&n.messages.push(k_(e)),Object.freeze({transcriptHash:Kx(n.system,n.messages),messageCount:n.messages.length})}function Yx(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=Gx(e);if(!(n.messages.length<=t.messageCount)&&Kx(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function c$(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 wr=t=>({action:"retire-and-replay-full",reason:t});function Xx(t){let{session:e,turn:n}=t;if(e.poisoned)return wr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:wr("inconsistent-unused-session");if(e.alignment==="unknown")return wr("unknown-context-alignment");if(e.alignment==="divergent")return wr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return wr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return wr("dead-parked-run");if(n.hasMeaningfulSteering)return wr("parked-turn-has-steering");let r=c$(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:wr("parked-tool-results-mismatch")}return n.toolResults.length>0?wr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function fn(t){let e=t instanceof Error?t.message:typeof t=="string"&&t?t:"Cursor turn subscriber aborted";return Object.assign(new Error(e),{name:"AbortError"})}async function E_(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var v_=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 T_(this,r,e,n)}releaseInterest(e){if(this.interests.delete(e))return this.abortIfUnobserved("Cursor turn has no remaining subscribers")}async attach(e,n,r){if(this.phase==="aborting"||this.phase==="failed"||this.abortController.signal.aborted){try{await e.body?.cancel(this.abortController.signal.reason)}catch{}this.finishFailed(fn(this.abortController.signal.reason??"Cursor turn superseded"));return}let o=[];e.headers.forEach((i,a)=>{o.push([a,i])}),this.responseMetadata={status:e.status,statusText:e.statusText,headers:o},this.phase="streaming";let s=this.interests.has(n)?this.responseForReadyInterest(n,r):void 0;return this.readySettled=!0,this.readyResolve(),e.body?(this.sourceReader=e.body.getReader(),s&&this.ensurePumpStarted(),s):(this.finishCompleted(),s)}fail(e){this.finishFailed(e instanceof Error?e:new Error(String(e)))}async supersede(e){if(this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"){await E_(this.settled,3e3);return}this.phase="aborting";let n=fn(e);this.readySettled||(this.readySettled=!0,this.readyReject(n)),this.abortController.abort(n),this.errorSubscribers(n);let r=this.sourceReader;if(r){let o=Promise.resolve(r.cancel(n)).catch(()=>{}).then(()=>{});await E_(o,3e3),this.finishFailed(n)}await E_(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw fn(n?.reason);if(!this.responseMetadata)throw this.failure||new Error("Cursor turn response metadata is missing");if(!this.replayable&&this.phase!=="streaming")throw this.releaseInterest(e),Object.assign(new Error("Cursor turn result exceeded the bounded replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});let r=this.responseForReadyInterest(e,n);return this.ensurePumpStarted(),r}responseForReadyInterest(e,n){let r=this.openStream(e,n);return new Response(r,{status:this.responseMetadata.status,statusText:this.responseMetadata.statusText,headers:this.responseMetadata.headers})}openStream(e,n){let r;return new ReadableStream({start:o=>{if(!this.interests.has(e)){o.error(fn(n?.reason));return}r=this.nextSubscriberId++;let s={controller:o};if(this.subscribers.set(r,s),this.interests.delete(e),n){let i=()=>{r!==void 0&&this.removeSubscriber(r,fn(n.reason))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0}),s.removeAbortListener=()=>n.removeEventListener("abort",i)}if(!this.replayable){this.removeSubscriber(r,Object.assign(new Error("Cursor turn cannot replay an oversized active result"),{statusCode:409,code:"cursor_turn_not_replayable"}));return}for(let i of this.chunks)o.enqueue(i);this.phase==="completed"?this.closeSubscriber(r):(this.phase==="failed"||this.phase==="aborting")&&this.removeSubscriber(r,this.failure||fn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,fn(o),!1):this.releaseInterest(e)})}pumpStarted=!1;ensurePumpStarted(){this.pumpStarted||!this.sourceReader||this.phase!=="streaming"||(this.pumpStarted=!0,this.pump())}async pump(){let e=this.sourceReader;if(e)try{for(;this.phase==="streaming";){let{done:n,value:r}=await e.read();if(n){this.finishCompleted();return}if(r){if(this.replayable)if(this.bufferedBytes+r.byteLength<=8388608){let o=r.slice();this.chunks.push(o),this.bufferedBytes+=o.byteLength}else this.replayable=!1,this.chunks=[];for(let o of this.subscribers.values())o.controller.enqueue(r)}}}catch(n){this.finishFailed(n instanceof Error?n:new Error(String(n)))}}abortIfUnobserved(e){if(!(this.interests.size>0||this.subscribers.size>0||this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"))return this.supersede(e)}removeSubscriber(e,n,r=!0){let o=this.subscribers.get(e);if(o){if(this.subscribers.delete(e),o.removeAbortListener?.(),r)try{o.controller.error(n)}catch{}return this.abortIfUnobserved(n.message)}}closeSubscriber(e){let n=this.subscribers.get(e);if(n){this.subscribers.delete(e),n.removeAbortListener?.();try{n.controller.close()}catch{}}}errorSubscribers(e){for(let n of[...this.subscribers.keys()])this.removeSubscriber(n,e)}releaseSourceReader(){let e=this.sourceReader;if(this.sourceReader=void 0,!!e)try{e.releaseLock()}catch{}}finishCompleted(){if(!(this.phase==="completed"||this.phase==="failed")){if(this.phase==="aborting"){this.finishFailed(fn(this.abortController.signal.reason));return}this.phase="completed",this.completedAt=Date.now(),this.releaseSourceReader();for(let e of[...this.subscribers.keys()])this.closeSubscriber(e);this.settledResolve(),this.onTerminal(this,"completed")}}finishFailed(e){this.phase==="completed"||this.phase==="failed"||(this.phase="failed",this.failure=e,this.releaseSourceReader(),this.readySettled||(this.readySettled=!0,this.readyReject(e)),this.errorSubscribers(e),this.interests.clear(),this.settledResolve(),this.onTerminal(this,"failed"))}},T_=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}}},x_=class{sessions=new Map;admissionGates=new Map;forgetExpiredSuperseded(e,n,r=!0){let o=Date.now();for(let[s,i]of n.superseded)i<=o&&n.superseded.delete(s);r&&!n.active&&!n.completed&&n.superseded.size===0&&this.sessions.delete(e)}rememberSuperseded(e,n,r){for(n.superseded.delete(r),n.superseded.set(r,Date.now()+9e5);n.superseded.size>16;){let s=n.superseded.keys().next().value;if(typeof s!="string")break;n.superseded.delete(s)}let o=setTimeout(()=>{let s=this.sessions.get(e);s&&this.forgetExpiredSuperseded(e,s)},9e5);typeof o.unref=="function"&&o.unref()}async admit(e){if(e.signal?.aborted)throw fn(e.signal.reason);let n=this.admissionGates.get(e.sessionKey),r,o=new Promise(s=>{r=s});this.admissionGates.set(e.sessionKey,o),n&&await n;try{if(e.signal?.aborted)throw fn(e.signal.reason);for(;;){if(e.signal?.aborted)throw fn(e.signal.reason);let s=this.sessions.get(e.sessionKey)||{superseded:new Map};if(this.sessions.set(e.sessionKey,s),this.forgetExpiredSuperseded(e.sessionKey,s,!1),s.superseded.has(e.fingerprint))throw Object.assign(new Error("This Cursor turn was superseded by a newer request"),{statusCode:409,code:"cursor_turn_superseded"});let i=s.active;if(i){if(i.fingerprint===e.fingerprint){if(i.responseKind!==e.responseKind)throw Object.assign(new Error("An identical Cursor turn is already using a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});if(i.isJoinable)return i.reserve(e.signal,"join");if(i.isProducing)throw Object.assign(new Error("The active Cursor turn exceeded the bounded duplicate replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});await i.supersede("Waiting for the aborted Cursor turn to finish cleanup"),s.active===i&&(s.active=void 0);continue}this.rememberSuperseded(e.sessionKey,s,i.fingerprint),await i.supersede("Cursor turn superseded by a newer request"),s.active===i&&(s.active=void 0);continue}let a=s.completed;if(a&&a.replayAgeMs<=6e4&&a.fingerprint===e.fingerprint&&a.canReplay){if(a.responseKind!==e.responseKind)throw Object.assign(new Error("The cached Cursor turn uses a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});return a.reserve(e.signal,"replay")}a&&a.fingerprint!==e.fingerprint&&this.rememberSuperseded(e.sessionKey,s,a.fingerprint),s.completed=void 0;let u=new v_(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()}},Qx=new x_;var l$=900*1e3,Pa=null;function R_(t){return ni([t])}async function d$(t){let e=R_(t);if(Pa&&Pa.apiKeyFingerprint===e&&Date.now()-Pa.fetchedAt<l$)return Pa.models;let n=await u$.models.list({apiKey:t})||[];return Pa={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function f$(t,e,n){let r;try{r=await d$(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 p$(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(`
|
|
431
|
-
`)}function h$(t){return t.length===1&&t[0]?.role==="user"}function g$(t,e,n){if(e.hasTrailingUserInput)return!1;let r=n?.interruption==="synthetic_client_interrupt"&&n.steering==="none",o=e.toolResults.length+(r?1:0);if(t.length!==o)return!1;for(let s=0;s<e.toolResults.length;s+=1){let i=t[s],a=e.toolResults[s];if(i?.role!=="tool"||i.tool_call_id!==a.toolCallId||dn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function pn(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*m$(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(C=>({type:C})),i.then(C=>({type:"msg",r:C})),a.then(C=>({type:C}))]);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 C=d();if(!C)break;yield{kind:"sdk",message:C.message,source:C.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 y$(t,e){if(!e||e.type!=="thinking-delta")return;let n=ri(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function Ia(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:to.retireSession(t,e.reason,()=>tf(t,async()=>(await h_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await to.invalidate(t,e.reason),!0)))}function _$(t,e,n,r){let o=r.cursorMode||Xd,s=t.model||"composer-2",i;try{i=ix(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=Fx({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:p$(t)});return{apiKey:i,hostEnv:xa(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function Zx(t,e,n,r={}){let o=_$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=A_({credentialFingerprint:R_(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:u_(t)||""},sandboxEnabled:Oa(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=Jx(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await Qx.admit({sessionKey:o.sessionKey,fingerprint:a,responseKind:t.stream===!0?"stream":"json",signal:r.abortSignal});if(u.kind!=="leader")return u.response();try{let d=await b$(t,e,n,{...r,abortSignal:u.producerSignal,turnIntent:o.turnIntent},o);await u.attach(d)}catch(d){throw u.fail(d),d}return u.response()}async function b$(t,e,n,r,o){pn(r.abortSignal);let s=r.logger||e?.logger;s&&to.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=u_(t),h=await f$(d,u,p);pn(r.abortSignal);let g=o.hostEnv,C={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};pn(r.abortSignal);let _=await to.getOrCreate(C);pn(r.abortSignal);let k=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,b=X=>A_({credentialFingerprint:R_(d),guidanceFingerprint:k(X).fingerprint,mode:i,model:h,sandboxEnabled:Oa(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),A=k(_),w=b(_),E=Tx(t,r.turnIntent),x=E.toolResults,O=_.parked.length>0?{kind:"parked",live:!!(_.run&&_.streamIterator&&_.activeRunToken&&!_.poisoned),tools:_.parked}:_.run||_.streamIterator||_.streamNext||_.activeRunToken?{kind:"active-different-turn"}:{kind:"idle"},q=_.transcriptCommit&&_.compatibilityStamp===w?Yx(_.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?g$(q,E,r.turnIntent):O.kind==="idle"?h$(q):!0,U=!_.hasSentPrompt||!_.transcriptCommit?"unknown":V?"strict":"divergent",ee=Xx({session:{alignment:U,hasSentPrompt:_.hasSentPrompt,poisoned:_.poisoned===!0,run:O},turn:{hasMeaningfulSteering:E.hasTrailingUserInput,toolResults:x}});if(ee.action==="retire-and-replay-full"&&(s?.info?.({sessionKey:_.key,agentId:_.agentId,alignment:U,lifecycleReason:ee.reason,toolResultCount:x.length},"cursor-sdk retiring session before full transcript replay"),await Ia(_,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:_.activeRunToken}),pn(r.abortSignal),_=await to.getOrCreate(C),pn(r.abortSignal),A=k(_),w=b(_),ee={action:"send-full",reason:"unused-session"}),pn(r.abortSignal),g_(_,A),ee.action==="resume-parked"&&(pn(r.abortSignal),to.resolveParkedTools(_,x)!==x.length||_.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=_.activeRunToken,_e=(X,de)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ce=>ce.runToken!==de),X.notifySdkMessage()},Oe=(X,de)=>{let ce=i==="bridge"?jx(t,X,s,Te):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ce?{customTools:ce}:void 0,onDelta:({update:S})=>{let T=y$(X,S);T&&X.enqueueSdkMessage(T,de)}}},Te=b_(),Ge=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,de)=>de.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||m_(X)||y_(X)),Z=async(X,de)=>{let ce;if(await tf(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 oi(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=vx(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:de,hostEnv:A,turnIntent:r.turnIntent});ce=Symbol("cursor-sdk-run"),X.activeRunToken=ce;try{let T=await __(X,S,Oe(X,ce),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ce,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,pn(r.abortSignal)}catch(T){throw ce&&X.activeRunToken===ce&&(X.activeRunToken=void 0,_e(X,ce)),(r.abortSignal?.aborted||y_(T)||m_(T))&&oi(X,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),s?.error?.({err:T},"cursor-sdk agent.send failed"),T}}),!ce)throw new Error("cursor-sdk agent.send did not produce a run token");return ce};if(z)try{Q=await Z(_,te)}catch(X){let de=ne(X,_);if(await Ia(_,{reason:"cursor-sdk prompt send failed before streaming"}),!de)throw Ge(X);pn(r.abortSignal),s?.warn?.({err:X,sessionKey:_.key,agentId:_.agentId},"cursor-sdk retrying failed resumed send with fresh session"),_=await to.getOrCreate(C),pn(r.abortSignal),A=k(_),w=b(_),g_(_,A);try{Q=await Z(_,!1)}catch(ce){throw await Ia(_,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ge(ce)}}Q||(Q=Symbol("cursor-sdk-run"),_.activeRunToken=Q);let ae=fx(u,new TextEncoder),Ie=[],we=$x(t),H=0,Ee,Ze=new ReadableStream({async start(X){let de=()=>{Te.scratchViolations<=0||s?.warn?.({sessionKey:_.key,model:u,scratchViolations:Te.scratchViolations,scratchCorrections:Te.scratchCorrections,metrics:_.metrics,hostProjectRoot:A.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ce=D=>{Ie.push(D),a&&X.enqueue(ae.encode(D))},S=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=Hx(Ee,_.lastSdkUsageRaw,we),F=qx(we,H,D);return Ee&&(_.lastSdkUsageRaw=Ee),F},R=()=>{if(_.activeRunToken!==Q)return;let F=l_(u,Ie)?.choices?.[0]?.message;!F||F.role!=="assistant"||(_.transcriptCommit=Vx(t,F),_.compatibilityStamp=w)},M=D=>{let F=T();s?.debug?.({reason:D,promptTokens:F.prompt_tokens,completionTokens:F.completion_tokens,outputChars:H,sdkUsageRaw:Ee,runUsage:_.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ce(ae.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,j,B="",K=0,ie=()=>{!P||N||(ce(ae.thinkingSignature()),N=!0,L=!1)};for(;;){let ue=!1;for await(let be of m$(_,i,Q,r.abortSignal)){if(Zd(_),be.kind==="host_tool"){if(i!=="bridge")continue;for(ie(),L=!1,S(be.tool.name),S(JSON.stringify(be.tool.args??{})),ce(ae.toolCall(be.tool,D)),D+=1;_.pendingEmit.length;){let he=_.pendingEmit.shift();S(he.name),S(JSON.stringify(he.args??{})),ce(ae.toolCall(he,D)),D+=1}M("tool_calls"),a&&X.enqueue(ae.encodeDone()),X.close();return}if(be.kind==="end"){if(be.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(Ax({mode:i,assistantText:B,emittedHostTools:D,continuationAttempts:K})){_.activeRunToken===Q&&(_.streamIterator=void 0,_.streamNext=void 0,_.streamNextRunToken=void 0,_.run=void 0,_.activeRunToken=void 0),K+=1,s?.warn?.({assistantText:B,attempt:K},"cursor-sdk continuing progress-only terminal turn");let he=Symbol("cursor-sdk-run");Q=he,_.activeRunToken=he,await tf(_,async()=>{if(_.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let ye=await __(_,Ex(A),Oe(_,he),{abortSignal:r.abortSignal,logger:s});if(_.run=ye,_.activeRunToken=he,_.streamIterator=ye.stream()[Symbol.asyncIterator](),_.streamNext=void 0,_.streamNextRunToken=void 0,_.hasSentPrompt=!0,_.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation retired during send")}),B="",ue=!0;break}ie(),M("stop"),_.activeRunToken===Q&&(_.streamIterator=void 0,_.streamNext=void 0,_.streamNextRunToken=void 0,_.run=void 0,_.activeRunToken=void 0),a&&X.enqueue(ae.encodeDone()),X.close();return}let me=be.message;if(me){if(me.type==="assistant")for(let he of me.message?.content||[])he.type==="text"&&he.text&&(ie(),L=!1,F=!0,B+=he.text,S(he.text),ce(ae.content(he.text)));else if(me.type==="thinking"){if(!L)continue;let he=be.source||"stream";if(j&&j!==he)continue;j=he;let ye=ri(me.text);ye&&(P=!0,S(ye),ce(ae.thinking(ye)))}else if(me.type==="usage")Ee=zx(me);else if(me.type==="status"){if(me.status==="ERROR"||me.status==="CANCELLED")throw Object.assign(new Error(me.message||`Cursor run ${me.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(me.type==="tool_call"&&i!=="bridge"&&i==="agent"&&me.name){ie(),L=!1;let he=`
|
|
433
|
+
`)}var d$=3;function f$(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 v_(){return{scratchViolations:0,scratchCorrections:0}}function qx(t,e,n,r=v_()){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:f$(s.function.parameters),async execute(a,u){let d=cr(u.toolCallId)||l$(),f=a||{},p=e.hostEnv||eo,h=Lx(p)?jx(f,e.workspaceDir):[];if(h.length){e.metrics.scratchPathViolations+=1,r.scratchViolations+=1;let g=e.metrics.scratchPathCorrections<d$;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,$x(h,i,e.workspaceDir,p)}return e.metrics.customToolCalls+=1,e.parkHostTool({id:d,name:i,args:f})}})}return o}function zx(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function Hx(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)??""}catch{return String(t)}}function Wx(t){let e=[];t.system&&e.push(Hx(t.system));for(let n of t.messages||[])e.push(Hx(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)),zx(e.join(`
|
|
434
|
+
`).length)}function Gx(t,e,n=0){let r=Math.max(0,Math.trunc(t)||0),o=zx(e),s=Math.min(r,Math.max(0,Math.trunc(n)||0));return{prompt_tokens:r,completion_tokens:o,total_tokens:r+o,prompt_tokens_details:{cached_tokens:s}}}function df(t){let e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Jx(t,e,n){let r=Math.max(0,Math.trunc(n)||0);if(!r||!t)return 0;let o=df(t.prompt_tokens),s=df(t.prompt_tokens_details?.cached_tokens);if(!o||!s)return 0;let i=df(e?.prompt_tokens),a=df(e?.prompt_tokens_details?.cached_tokens),u=o-i,d=s-a,f=u>0&&d>0?d/u:s/o,p=Math.min(1,Math.max(0,f));return Math.min(r,Math.floor(r*p))}function Kx(t){let e=t?.usage??t;if(!e||typeof e!="object")return;let n=e.inputTokens??e.input_tokens??e.prompt_tokens,r=e.outputTokens??e.output_tokens??e.completion_tokens;if(n==null&&r==null)return;let o=Number(n)||0,s=Number(r)||0,i=Number(e.cacheReadTokens??e.cache_read_input_tokens??0)||0;return{prompt_tokens:o,completion_tokens:s,total_tokens:Number(e.totalTokens??e.total_tokens??o+s)||0,prompt_tokens_details:{cached_tokens:i}}}import{createHash as p$}from"crypto";var h$=new Set(["id","idempotency_key","metadata","anthropic_metadata","request_id","req_id","stream","stream_options","trace_id","user"]);function Wn(t){if(t===null)return null;if(typeof t=="string"||typeof t=="boolean"||typeof t=="number")return t;if(typeof t=="bigint")return String(t);if(Array.isArray(t))return t.map(n=>Wn(n)).filter(n=>n!==void 0);if(typeof t!="object")return;let e={};for(let n of Object.keys(t).sort()){if(n==="cache_control")continue;let r=Wn(t[n]);r!==void 0&&(e[n]=r)}return e}function x_(t){if(t==null)return[];if(typeof t=="string")return[{text:t,type:"text"}];if(!Array.isArray(t)){let e=Wn(t);return e===void 0?[]:[e]}return t.map(e=>{if(typeof e=="string")return{text:e,type:"text"};if(!e||typeof e!="object")return Wn(e);let n=e;return n.type==="text"?{text:String(n.text||""),type:"text"}:Wn(n)}).filter(e=>e!==void 0)}function g$(t){if(typeof t!="string")return Wn(t)??null;try{return Wn(JSON.parse(t))??null}catch{return t}}function R_(t){let e=t,n={content:x_(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:g$(r.function.arguments),name:r.function.name},id:r.id,type:r.type}))),n}function Vx(t){return Array.isArray(t)?t.map(e=>Wn(e)).filter(e=>e!==void 0).sort((e,n)=>T_(e).localeCompare(T_(n))):[]}function T_(t){return JSON.stringify(t)}function D_(t){return p$("sha256").update(T_(t)).digest("hex")}function Yx(t){return{system:x_(t.system),messages:(t.messages||[]).map(R_)}}function m$(t){let e=t,n={};for(let r of Object.keys(e).sort()){if(h$.has(r)||r==="cache_control")continue;let o;r==="messages"?o=(t.messages||[]).map(R_):r==="system"?o=x_(t.system):r==="tools"?o=Vx(t.tools):o=Wn(e[r]),o!==void 0&&(n[r]=o)}return n}function Xx(t,e={}){return D_({compatibilityStamp:e.compatibilityStamp||"",request:m$(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 O_(t){return D_({credentialFingerprint:t.credentialFingerprint||"",guidanceFingerprint:t.guidanceFingerprint||"",mode:t.mode,model:Wn(t.model)??null,sandboxEnabled:t.sandboxEnabled===!0,tools:Vx(t.tools),workspaceDir:t.workspaceDir})}function Qx(t,e){return D_({messages:e,system:t})}function Zx(t,e){if(e&&e.role!=="assistant")throw new TypeError("Cursor transcript commits require an assistant message");let n=Yx(t);return e&&n.messages.push(R_(e)),Object.freeze({transcriptHash:Qx(n.system,n.messages),messageCount:n.messages.length})}function eR(t,e){if(!Number.isInteger(t.messageCount)||t.messageCount<0||typeof t.transcriptHash!="string")return;let n=Yx(e);if(!(n.messages.length<=t.messageCount)&&Qx(n.system,n.messages.slice(0,t.messageCount))===t.transcriptHash)return(e.messages||[]).slice(t.messageCount)}function y$(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 wr=t=>({action:"retire-and-replay-full",reason:t});function tR(t){let{session:e,turn:n}=t;if(e.poisoned)return wr("poisoned-session");if(!e.hasSentPrompt)return e.run.kind==="idle"?{action:"send-full",reason:"unused-session"}:wr("inconsistent-unused-session");if(e.alignment==="unknown")return wr("unknown-context-alignment");if(e.alignment==="divergent")return wr("divergent-context-alignment");if(e.run.kind==="active-different-turn")return wr("active-different-turn");if(e.run.kind==="parked"){if(!e.run.live)return wr("dead-parked-run");if(n.hasMeaningfulSteering)return wr("parked-turn-has-steering");let r=y$(e.run.tools,n.toolResults);return r?{action:"resume-parked",reason:"exact-parked-tool-results",matches:r}:wr("parked-tool-results-mismatch")}return n.toolResults.length>0?wr("orphaned-tool-results"):{action:"send-incremental",reason:"strictly-aligned-idle-session"}}function fn(t){let e=t instanceof Error?t.message:typeof t=="string"&&t?t:"Cursor turn subscriber aborted";return Object.assign(new Error(e),{name:"AbortError"})}async function P_(t,e){let n;try{await Promise.race([t,new Promise(r=>{n=setTimeout(r,e)})])}finally{n&&clearTimeout(n)}}var I_=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 F_(this,r,e,n)}releaseInterest(e){if(this.interests.delete(e))return this.abortIfUnobserved("Cursor turn has no remaining subscribers")}async attach(e,n,r){if(this.phase==="aborting"||this.phase==="failed"||this.abortController.signal.aborted){try{await e.body?.cancel(this.abortController.signal.reason)}catch{}this.finishFailed(fn(this.abortController.signal.reason??"Cursor turn superseded"));return}let o=[];e.headers.forEach((i,a)=>{o.push([a,i])}),this.responseMetadata={status:e.status,statusText:e.statusText,headers:o},this.phase="streaming";let s=this.interests.has(n)?this.responseForReadyInterest(n,r):void 0;return this.readySettled=!0,this.readyResolve(),e.body?(this.sourceReader=e.body.getReader(),s&&this.ensurePumpStarted(),s):(this.finishCompleted(),s)}fail(e){this.finishFailed(e instanceof Error?e:new Error(String(e)))}async supersede(e){if(this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"){await P_(this.settled,3e3);return}this.phase="aborting";let n=fn(e);this.readySettled||(this.readySettled=!0,this.readyReject(n)),this.abortController.abort(n),this.errorSubscribers(n);let r=this.sourceReader;if(r){let o=Promise.resolve(r.cancel(n)).catch(()=>{}).then(()=>{});await P_(o,3e3),this.finishFailed(n)}await P_(this.settled,3e3)}async responseFor(e,n){if(await this.ready,!this.interests.has(e))throw fn(n?.reason);if(!this.responseMetadata)throw this.failure||new Error("Cursor turn response metadata is missing");if(!this.replayable&&this.phase!=="streaming")throw this.releaseInterest(e),Object.assign(new Error("Cursor turn result exceeded the bounded replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});let r=this.responseForReadyInterest(e,n);return this.ensurePumpStarted(),r}responseForReadyInterest(e,n){let r=this.openStream(e,n);return new Response(r,{status:this.responseMetadata.status,statusText:this.responseMetadata.statusText,headers:this.responseMetadata.headers})}openStream(e,n){let r;return new ReadableStream({start:o=>{if(!this.interests.has(e)){o.error(fn(n?.reason));return}r=this.nextSubscriberId++;let s={controller:o};if(this.subscribers.set(r,s),this.interests.delete(e),n){let i=()=>{r!==void 0&&this.removeSubscriber(r,fn(n.reason))};if(n.aborted){i();return}n.addEventListener("abort",i,{once:!0}),s.removeAbortListener=()=>n.removeEventListener("abort",i)}if(!this.replayable){this.removeSubscriber(r,Object.assign(new Error("Cursor turn cannot replay an oversized active result"),{statusCode:409,code:"cursor_turn_not_replayable"}));return}for(let i of this.chunks)o.enqueue(i);this.phase==="completed"?this.closeSubscriber(r):(this.phase==="failed"||this.phase==="aborting")&&this.removeSubscriber(r,this.failure||fn("Cursor turn ended before subscription"))},cancel:o=>r!==void 0?this.removeSubscriber(r,fn(o),!1):this.releaseInterest(e)})}pumpStarted=!1;ensurePumpStarted(){this.pumpStarted||!this.sourceReader||this.phase!=="streaming"||(this.pumpStarted=!0,this.pump())}async pump(){let e=this.sourceReader;if(e)try{for(;this.phase==="streaming";){let{done:n,value:r}=await e.read();if(n){this.finishCompleted();return}if(r){if(this.replayable)if(this.bufferedBytes+r.byteLength<=8388608){let o=r.slice();this.chunks.push(o),this.bufferedBytes+=o.byteLength}else this.replayable=!1,this.chunks=[];for(let o of this.subscribers.values())o.controller.enqueue(r)}}}catch(n){this.finishFailed(n instanceof Error?n:new Error(String(n)))}}abortIfUnobserved(e){if(!(this.interests.size>0||this.subscribers.size>0||this.phase==="completed"||this.phase==="failed"||this.phase==="aborting"))return this.supersede(e)}removeSubscriber(e,n,r=!0){let o=this.subscribers.get(e);if(o){if(this.subscribers.delete(e),o.removeAbortListener?.(),r)try{o.controller.error(n)}catch{}return this.abortIfUnobserved(n.message)}}closeSubscriber(e){let n=this.subscribers.get(e);if(n){this.subscribers.delete(e),n.removeAbortListener?.();try{n.controller.close()}catch{}}}errorSubscribers(e){for(let n of[...this.subscribers.keys()])this.removeSubscriber(n,e)}releaseSourceReader(){let e=this.sourceReader;if(this.sourceReader=void 0,!!e)try{e.releaseLock()}catch{}}finishCompleted(){if(!(this.phase==="completed"||this.phase==="failed")){if(this.phase==="aborting"){this.finishFailed(fn(this.abortController.signal.reason));return}this.phase="completed",this.completedAt=Date.now(),this.releaseSourceReader();for(let e of[...this.subscribers.keys()])this.closeSubscriber(e);this.settledResolve(),this.onTerminal(this,"completed")}}finishFailed(e){this.phase==="completed"||this.phase==="failed"||(this.phase="failed",this.failure=e,this.releaseSourceReader(),this.readySettled||(this.readySettled=!0,this.readyReject(e)),this.errorSubscribers(e),this.interests.clear(),this.settledResolve(),this.onTerminal(this,"failed"))}},F_=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}}},N_=class{sessions=new Map;admissionGates=new Map;forgetExpiredSuperseded(e,n,r=!0){let o=Date.now();for(let[s,i]of n.superseded)i<=o&&n.superseded.delete(s);r&&!n.active&&!n.completed&&n.superseded.size===0&&this.sessions.delete(e)}rememberSuperseded(e,n,r){for(n.superseded.delete(r),n.superseded.set(r,Date.now()+9e5);n.superseded.size>16;){let s=n.superseded.keys().next().value;if(typeof s!="string")break;n.superseded.delete(s)}let o=setTimeout(()=>{let s=this.sessions.get(e);s&&this.forgetExpiredSuperseded(e,s)},9e5);typeof o.unref=="function"&&o.unref()}async admit(e){if(e.signal?.aborted)throw fn(e.signal.reason);let n=this.admissionGates.get(e.sessionKey),r,o=new Promise(s=>{r=s});this.admissionGates.set(e.sessionKey,o),n&&await n;try{if(e.signal?.aborted)throw fn(e.signal.reason);for(;;){if(e.signal?.aborted)throw fn(e.signal.reason);let s=this.sessions.get(e.sessionKey)||{superseded:new Map};if(this.sessions.set(e.sessionKey,s),this.forgetExpiredSuperseded(e.sessionKey,s,!1),s.superseded.has(e.fingerprint))throw Object.assign(new Error("This Cursor turn was superseded by a newer request"),{statusCode:409,code:"cursor_turn_superseded"});let i=s.active;if(i){if(i.fingerprint===e.fingerprint){if(i.responseKind!==e.responseKind)throw Object.assign(new Error("An identical Cursor turn is already using a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});if(i.isJoinable)return i.reserve(e.signal,"join");if(i.isProducing)throw Object.assign(new Error("The active Cursor turn exceeded the bounded duplicate replay buffer"),{statusCode:409,code:"cursor_turn_not_replayable"});await i.supersede("Waiting for the aborted Cursor turn to finish cleanup"),s.active===i&&(s.active=void 0);continue}this.rememberSuperseded(e.sessionKey,s,i.fingerprint),await i.supersede("Cursor turn superseded by a newer request"),s.active===i&&(s.active=void 0);continue}let a=s.completed;if(a&&a.replayAgeMs<=6e4&&a.fingerprint===e.fingerprint&&a.canReplay){if(a.responseKind!==e.responseKind)throw Object.assign(new Error("The cached Cursor turn uses a different response format"),{statusCode:409,code:"cursor_turn_response_format_conflict"});return a.reserve(e.signal,"replay")}a&&a.fingerprint!==e.fingerprint&&this.rememberSuperseded(e.sessionKey,s,a.fingerprint),s.completed=void 0;let u=new I_(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()}},nR=new N_;var b$=900*1e3,Pa=null;function M_(t){return ni([t])}async function C$(t){let e=M_(t);if(Pa&&Pa.apiKeyFingerprint===e&&Date.now()-Pa.fetchedAt<b$)return Pa.models;let n=await _$.models.list({apiKey:t})||[];return Pa={fetchedAt:Date.now(),apiKeyFingerprint:e,models:n},n}async function w$(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 k$(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(`
|
|
435
|
+
`)}function S$(t){return t.length===1&&t[0]?.role==="user"}function A$(t,e,n){if(e.hasTrailingUserInput)return!1;let r=n?.interruption==="synthetic_client_interrupt"&&n.steering==="none",o=e.toolResults.length+(r?1:0);if(t.length!==o)return!1;for(let s=0;s<e.toolResults.length;s+=1){let i=t[s],a=e.toolResults[s];if(i?.role!=="tool"||i.tool_call_id!==a.toolCallId||dn(i.content)!==a.content)return!1}return!r||t[t.length-1]?.role==="user"}function pn(t){if(t?.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted before lifecycle mutation"),{name:"AbortError"})}async function*E$(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(C=>({type:C})),i.then(C=>({type:"msg",r:C})),a.then(C=>({type:C}))]);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 C=d();if(!C)break;yield{kind:"sdk",message:C.message,source:C.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 v$(t,e){if(!e||e.type!=="thinking-delta")return;let n=ri(e.text);if(n)return{type:"thinking",agent_id:t.agentId,run_id:t.run?.id||"",text:n}}async function Ia(t,e){return e.onlyRunToken&&t.activeRunToken!==e.onlyRunToken?!1:to.retireSession(t,e.reason,()=>lf(t,async()=>(await w_(t,{rejectParked:!0,reason:e.reason,timeoutMs:2e3,poisonOnFailure:!0}),await to.invalidate(t,e.reason),!0)))}function T$(t,e,n,r){let o=r.cursorMode||sf,s=t.model||"composer-2",i;try{i=lx(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=Ux({headerSession:typeof a=="string"?a:void 0,metadataUserId:typeof u=="string"?u:void 0,model:s,systemAndFirstUser:k$(t)});return{apiKey:i,hostEnv:xa(t),mode:o,modelId:s,sessionKey:d,turnIntent:r.turnIntent||n?.unifiedRequest?.turnIntent}}async function rR(t,e,n,r={}){let o=T$(t,e,n,r),s=r.cursorCwd||`managed-session:${o.sessionKey}`,i=O_({credentialFingerprint:M_(o.apiKey),guidanceFingerprint:o.hostEnv.fingerprint,mode:o.mode,model:{id:o.modelId,effort:m_(t)||""},sandboxEnabled:Oa(r.sandboxEnabled),tools:t.tools,workspaceDir:s}),a=Xx(t,{compatibilityStamp:i,turnIntent:o.turnIntent}),u=await nR.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 x$(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 x$(t,e,n,r,o){pn(r.abortSignal);let s=r.logger||e?.logger;s&&to.setLogger(s);let i=o.mode,a=t.stream===!0,u=o.modelId,d=o.apiKey,f=o.sessionKey,p=m_(t),h=await w$(d,u,p);pn(r.abortSignal);let g=o.hostEnv,C={key:f,apiKey:d,model:h,mode:i,cursorCwd:r.cursorCwd,sandboxEnabled:r.sandboxEnabled,hostEnv:g};pn(r.abortSignal);let y=await to.getOrCreate(C);pn(r.abortSignal);let k=X=>!g.known&&X.hostEnv?.known?X.hostEnv:g,b=X=>O_({credentialFingerprint:M_(d),guidanceFingerprint:k(X).fingerprint,mode:i,model:h,sandboxEnabled:Oa(r.sandboxEnabled),tools:t.tools,workspaceDir:X.workspaceDir}),A=k(y),w=b(y),E=Ox(t,r.turnIntent),x=E.toolResults,O=y.parked.length>0?{kind:"parked",live:!!(y.run&&y.streamIterator&&y.activeRunToken&&!y.poisoned),tools:y.parked}:y.run||y.streamIterator||y.streamNext||y.activeRunToken?{kind:"active-different-turn"}:{kind:"idle"},q=y.transcriptCommit&&y.compatibilityStamp===w?eR(y.transcriptCommit,t):void 0,V=q===void 0?!1:O.kind==="parked"?A$(q,E,r.turnIntent):O.kind==="idle"?S$(q):!0,j=!y.hasSentPrompt||!y.transcriptCommit?"unknown":V?"strict":"divergent",ee=tR({session:{alignment:j,hasSentPrompt:y.hasSentPrompt,poisoned:y.poisoned===!0,run:O},turn:{hasMeaningfulSteering:E.hasTrailingUserInput,toolResults:x}});if(ee.action==="retire-and-replay-full"&&(s?.info?.({sessionKey:y.key,agentId:y.agentId,alignment:j,lifecycleReason:ee.reason,toolResultCount:x.length},"cursor-sdk retiring session before full transcript replay"),await Ia(y,{reason:`cursor-sdk lifecycle: ${ee.reason}`,onlyRunToken:y.activeRunToken}),pn(r.abortSignal),y=await to.getOrCreate(C),pn(r.abortSignal),A=k(y),w=b(y),ee={action:"send-full",reason:"unused-session"}),pn(r.abortSignal),k_(y,A),ee.action==="resume-parked"&&(pn(r.abortSignal),to.resolveParkedTools(y,x)!==x.length||y.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=y.activeRunToken,_e=(X,de)=>{X.pendingSdkMessages=X.pendingSdkMessages.filter(ce=>ce.runToken!==de),X.notifySdkMessage()},Oe=(X,de)=>{let ce=i==="bridge"?qx(t,X,s,Te):void 0;return{model:h,mode:i==="plan"?"plan":"agent",local:ce?{customTools:ce}:void 0,onDelta:({update:S})=>{let T=v$(X,S);T&&X.enqueueSdkMessage(T,de)}}},Te=v_(),Ge=X=>Object.assign(new Error(`Cursor SDK error: ${X?.message||X}`),{statusCode:502,code:"provider_response_error",type:"api_error"}),ne=(X,de)=>de.hasSentPrompt&&!r.abortSignal?.aborted&&(X?.retryFreshCursorSession===!0||S_(X)||A_(X)),Z=async(X,de)=>{let ce;if(await lf(X,async()=>{if(X.poisoned)throw Object.assign(new Error("cursor-sdk session is no longer safe for sends"),{retryFreshCursorSession:!0});if(X.run||X.streamIterator||X.streamNext||X.activeRunToken||X.parked.length>0)throw oi(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=Dx(t,{mode:i,workspaceDir:X.workspaceDir,followUpOnly:de,hostEnv:A,turnIntent:r.turnIntent});ce=Symbol("cursor-sdk-run"),X.activeRunToken=ce;try{let T=await E_(X,S,Oe(X,ce),{abortSignal:r.abortSignal,logger:s});X.run=T,X.activeRunToken=ce,X.streamIterator=T.stream()[Symbol.asyncIterator](),X.streamNext=void 0,X.streamNextRunToken=void 0,X.hasSentPrompt=!0,pn(r.abortSignal)}catch(T){throw ce&&X.activeRunToken===ce&&(X.activeRunToken=void 0,_e(X,ce)),(r.abortSignal?.aborted||A_(T)||S_(T))&&oi(X,r.abortSignal?.aborted?"cursor-sdk send aborted":"cursor-sdk send left session state unsafe"),s?.error?.({err:T},"cursor-sdk agent.send failed"),T}}),!ce)throw new Error("cursor-sdk agent.send did not produce a run token");return ce};if(z)try{Q=await Z(y,te)}catch(X){let de=ne(X,y);if(await Ia(y,{reason:"cursor-sdk prompt send failed before streaming"}),!de)throw Ge(X);pn(r.abortSignal),s?.warn?.({err:X,sessionKey:y.key,agentId:y.agentId},"cursor-sdk retrying failed resumed send with fresh session"),y=await to.getOrCreate(C),pn(r.abortSignal),A=k(y),w=b(y),k_(y,A);try{Q=await Z(y,!1)}catch(ce){throw await Ia(y,{reason:"cursor-sdk fresh replay send failed before streaming"}),Ge(ce)}}Q||(Q=Symbol("cursor-sdk-run"),y.activeRunToken=Q);let ae=mx(u,new TextEncoder),Ie=[],we=Wx(t),H=0,Ee,Ze=new ReadableStream({async start(X){let de=()=>{Te.scratchViolations<=0||s?.warn?.({sessionKey:y.key,model:u,scratchViolations:Te.scratchViolations,scratchCorrections:Te.scratchCorrections,metrics:y.metrics,hostProjectRoot:A.projectRoot},"cursor-sdk turn produced scratch-workspace tool paths")},ce=D=>{Ie.push(D),a&&X.enqueue(ae.encode(D))},S=D=>{typeof D=="string"&&D.length&&(H+=D.length)},T=()=>{let D=Jx(Ee,y.lastSdkUsageRaw,we),F=Gx(we,H,D);return Ee&&(y.lastSdkUsageRaw=Ee),F},R=()=>{if(y.activeRunToken!==Q)return;let F=y_(u,Ie)?.choices?.[0]?.message;!F||F.role!=="assistant"||(y.transcriptCommit=Zx(t,F),y.compatibilityStamp=w)},M=D=>{let F=T();s?.debug?.({reason:D,promptTokens:F.prompt_tokens,completionTokens:F.completion_tokens,outputChars:H,sdkUsageRaw:Ee,runUsage:y.run?.usage},"cursor-sdk finish usage (request estimate; raw SDK is diagnostic only)"),ce(ae.finish(D,F)),R()};try{let D=0,F=!1,L=!0,P=!1,N=!1,U,B="",K=0,ie=()=>{!P||N||(ce(ae.thinkingSignature()),N=!0,L=!1)};for(;;){let ue=!1;for await(let be of E$(y,i,Q,r.abortSignal)){if(cf(y),be.kind==="host_tool"){if(i!=="bridge")continue;for(ie(),L=!1,S(be.tool.name),S(JSON.stringify(be.tool.args??{})),ce(ae.toolCall(be.tool,D)),D+=1;y.pendingEmit.length;){let he=y.pendingEmit.shift();S(he.name),S(JSON.stringify(he.args??{})),ce(ae.toolCall(he,D)),D+=1}M("tool_calls"),a&&X.enqueue(ae.encodeDone()),X.close();return}if(be.kind==="end"){if(be.aborted)throw Object.assign(new Error("cursor-sdk response producer aborted"),{name:"AbortError"});if(xx({mode:i,assistantText:B,emittedHostTools:D,continuationAttempts:K})){y.activeRunToken===Q&&(y.streamIterator=void 0,y.streamNext=void 0,y.streamNextRunToken=void 0,y.run=void 0,y.activeRunToken=void 0),K+=1,s?.warn?.({assistantText:B,attempt:K},"cursor-sdk continuing progress-only terminal turn");let he=Symbol("cursor-sdk-run");Q=he,y.activeRunToken=he,await lf(y,async()=>{if(y.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation aborted before send");let ye=await E_(y,Rx(A),Oe(y,he),{abortSignal:r.abortSignal,logger:s});if(y.run=ye,y.activeRunToken=he,y.streamIterator=ye.stream()[Symbol.asyncIterator](),y.streamNext=void 0,y.streamNextRunToken=void 0,y.hasSentPrompt=!0,y.poisoned||r.abortSignal?.aborted)throw new Error("cursor-sdk progress continuation retired during send")}),B="",ue=!0;break}ie(),M("stop"),y.activeRunToken===Q&&(y.streamIterator=void 0,y.streamNext=void 0,y.streamNextRunToken=void 0,y.run=void 0,y.activeRunToken=void 0),a&&X.enqueue(ae.encodeDone()),X.close();return}let me=be.message;if(me){if(me.type==="assistant")for(let he of me.message?.content||[])he.type==="text"&&he.text&&(ie(),L=!1,F=!0,B+=he.text,S(he.text),ce(ae.content(he.text)));else if(me.type==="thinking"){if(!L)continue;let he=be.source||"stream";if(U&&U!==he)continue;U=he;let ye=ri(me.text);ye&&(P=!0,S(ye),ce(ae.thinking(ye)))}else if(me.type==="usage")Ee=Kx(me);else if(me.type==="status"){if(me.status==="ERROR"||me.status==="CANCELLED")throw Object.assign(new Error(me.message||`Cursor run ${me.status.toLowerCase()}`),{statusCode:502,code:"provider_response_error",type:"api_error"})}else if(me.type==="tool_call"&&i!=="bridge"&&i==="agent"&&me.name){ie(),L=!1;let he=`
|
|
432
436
|
[cursor tool ${me.status||"running"}: ${me.name}]
|
|
433
|
-
`;S(he),ce(ae.content(he))}}}if(!ue)break}!F&&!D&&(ie(),M("stop")),a&&X.enqueue(ae.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:_.metrics},"cursor-sdk stream failed"),await Ia(_,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{de()}},async cancel(){await Ia(_,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=Ze.getReader();for(;;){let{done:ce}=await X.read();if(ce)break}let de=l_(u,Ie);return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(Ze,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function C$(t,e,n){return{cursorMode:t.cursorMode||Xd,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var rf=class{static TransformerName=i_;name=i_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=C$(this.options,r,this.logger),s={...e,messages:Ke(e.messages),tools:Ve(e.tools)},i=await Zx(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};import{randomUUID as G$}from"crypto";import{existsSync as tR,mkdirSync as w$,readFileSync as k$,renameSync as S$,unlinkSync as A$,writeFileSync as E$}from"fs";import{dirname as v$,join as T$}from"path";import{homedir as x$}from"os";import{randomUUID as R$}from"crypto";var O_="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",P_="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",nR="http://localhost:51121/oauth-callback",D$=["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"],I_="https://daily-cloudcode-pa.sandbox.googleapis.com",rR="https://autopush-cloudcode-pa.sandbox.googleapis.com",oR="https://cloudcode-pa.googleapis.com",O$=[I_,rR,oR],D_=[oR,I_,rR],P$="1.18.3",I$=T$(x$(),".claude-code-router","antigravity_auth.json"),F$=12e4,sR="https://oauth2.googleapis.com/token",N$="https://www.googleapis.com/oauth2/v2/userinfo",of=null,iR=null;function aR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||I$}function Fa(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${P$} 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 sf(){try{let t=aR();if(!tR(t))return null;let e=JSON.parse(k$(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function F_(t){let e=aR();w$(v$(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{E$(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),S$(n,e)}finally{try{tR(n)&&A$(n)}catch{}}}function M$(t){return Date.now()+F$>=t.expires_at}async function B$(t){let e=new URLSearchParams({client_id:O_,client_secret:P_,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(sR,{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 F_(o),o}async function af(t){let e=sf();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!M$(e)?e:(of||(of=B$(e).finally(()=>{of=null})),of)}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 j$(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 cR(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function eR(t){await new Promise(e=>setTimeout(e,t))}async function U$(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()};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 eR(2e3);continue}let a=await i.json();if(a?.done===!0)return si(a?.response)||si(a)||void 0}catch{}await eR(2e3)}}async function L$(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()},body:JSON.stringify({tierId:e,metadata:cR()}),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()?U$(t,n,o.name.trim()):void 0}catch{return}}function $$(t){let e=j$(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function q$(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()},n=JSON.stringify({metadata:cR()}),r;for(let o of D_)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 $$(r))for(let s of D_){let i=await L$(t,o,s);if(i)return i}for(let o of D_)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 N_(t,e){let n=t?.project_id?.trim();if(n)return n;let r=sf();if(r?.project_id?.trim())return r.project_id.trim();let o=await q$(e);if(o){let s=sf();return s&&F_({...s,project_id:o}),o}}function Na(){return iR||I_}function uR(t){iR=t}var lR=new Set;function dR(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function fR(t){lR.add(t.replace(/\/$/,""))}function H$(t){return lR.has(t.replace(/\/$/,""))}function pR(t,e){return e?t===404||t===403||t>=500:!1}function hR(t){let e=t?.replace(/\/$/,"")||Na(),n=[...new Set([e,...O$])],r=n.filter(o=>!H$(o));return r.length?r:n}function cf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function gR(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:R$()}}async function z$(t){try{let e=await fetch(N$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function W$(t,e){let n=new URLSearchParams({client_id:O_,client_secret:P_,code:t,grant_type:"authorization_code",redirect_uri:nR,code_verifier:e}),r=await fetch(sR,{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 mR(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 yR(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function J$(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 K$(t){return t?.req?.body?.stream===!0}function V$(t){return hR(t)}var uf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await af({force:o?.forceRefresh}),i=await N_(n,s.access_token),a=J$(r,n),u=K$(r),d=gR({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||G$(),{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,...Fa(),...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||Na(),f=V$(d),p;for(let h=0;h<f.length;h++){let g=f[h],C=cf(g,r),_=this.buildHeaders(n,r);try{let k=await es(C,e,{httpsProxy:a,headers:Object.fromEntries(Object.entries(_).filter(([,b])=>b!==void 0)),signal:s?.signal},s,u);if(k.status===401&&!i){let b=await af({force:!0});return this.sendWithFallback(e,b.access_token,r,o,s,!0)}if(k.status===429){let b=await k.clone().text().catch(()=>""),A=mR(b),w={};throw A!=null&&(w["Retry-After"]=String(Math.ceil(A/1e3))),J(Je(b)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",w)}if(!k.ok){let b=await k.clone().text().catch(()=>"");if(k.status===403&&dR(b)&&(fR(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),pR(k.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${k.status}`,k.status,"provider_error");continue}throw J(Je(b)||`Antigravity request failed with ${k.status}`,k.status,k.status===403?"permission_error":"provider_error")}return uR(g),k}catch(k){if(k?.statusCode===429||k?.status===429||!mo(k))throw k;if(p=k,h<f.length-1)continue;throw k}}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:cf(Na(),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:cf(n?.baseUrl||Na(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(ve("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=yR(i);o.controller.enqueue(ve(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}return}o.controller.enqueue(Pe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=yR(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};import{resolveXaiApiKey as Cq}from"@caeliq/ccr-shared";import{closeSync as Y$,existsSync as bR,fstatSync as X$,mkdirSync as Q$,openSync as Z$,readFileSync as eq,renameSync as tq,statSync as CR,unlinkSync as B_,writeFileSync as nq}from"fs";import{dirname as rq,join as oq}from"path";import{homedir as sq}from"os";var iq=oq(sq(),".claude-code-router","xai_auth.json"),aq=2*6e4,cq=35e3,_R={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 kK=300*1e3;var uq=120,lf=null;function j_(){return process.env.CCR_XAI_AUTH_FILE||iq}function M_(){return`${j_()}.refresh.lock`}function lq(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function dq(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 fq(t){let e=dq(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Ma(){try{let t=j_();if(!bR(t))return null;let e=JSON.parse(eq(t,"utf8"));return e.access_token?e:null}catch{return null}}function pq(t){let e=j_();Q$(rq(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{nq(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),tq(n,e)}finally{try{bR(n)&&B_(n)}catch{}}}function hq(t,e=uq){let n=fq(t);return n?Date.now()/1e3+e>=n:!1}function gq(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 mq(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(_R.token_endpoint,{method:"POST",headers:lq(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:_R.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${gq(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 yq(){let t=M_();try{return Z$(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-CR(t).mtimeMs>aq&&B_(t)}catch{}return null}}async function _q(t){let e=Date.now()+cq,n=null;for(;n===null&&(n=yq(),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=X$(n).ino;Y$(n);try{CR(M_()).ino===r&&B_(M_())}catch{}}}async function bq(t){return _q(async()=>{let e=Ma();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 mq(e),r=Ma();return r&&r.access_token!==e.access_token?r:(pq(n),n)})}async function wR(t){return U_({force:!0})}async function U_(t={}){let e=Ma();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!hq(e)?e:(lf||(lf=bq(e).finally(()=>{lf=null})),lf)}var df=class{name="xai-auth";logger;async resolveAuth(e){let n=Cq(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await U_()).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=Ma();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await wR(n.refresh_token)).access_token}`}:null}};var kR={AnthropicTransformer:wu,GeminiTransformer:xu,VertexGeminiTransformer:ud,VertexClaudeTransformer:Od,VertexOpenaiTransformer:Pd,DeepseekTransformer:bd,TooluseTransformer:Cd,OpenrouterTransformer:wd,OpenAITransformer:Nd,MaxTokenTransformer:kd,GroqTransformer:Sd,CleancacheTransformer:Ad,EnhanceToolTransformer:Td,ReasoningTransformer:xd,SamplingTransformer:Rd,MaxCompletionTokens:Dd,CerebrasTransformer:Id,StreamOptionsTransformer:Fd,CustomParamsTransformer:Bd,VercelTransformer:jd,OpenAIResponsesTransformer:Ud,CodexTransformer:zd,QwenAuthTransformer:Wd,ForceReasoningTransformer:Gd,ExtraThinkTagTransformer:Jd,MistralTransformer:Kd,ChromeOnDeviceTransformer:Vd,OpencodeHeadersTransformer:Yd,ClaudeAuthTransformer:bu,CursorSdkTransformer:rf,AntigravityAuthTransformer:uf,XaiAuthTransformer:df};var ii=class{constructor(e,n){this.configService=e;this.logger=n}configService;logger;transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let i=s.endPoint;if(!i)return;let a=n.get(i);if(a){this.logger?.debug?.(`transformer ${o} shares endpoint ${i} with ${a}; keeping ${a}`);return}n.set(i,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let i=new o;i&&typeof i=="object"&&(i.logger=this.logger),r(s,i)}catch(i){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${i?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=re(re.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
|
|
437
|
+
`;S(he),ce(ae.content(he))}}}if(!ue)break}!F&&!D&&(ie(),M("stop")),a&&X.enqueue(ae.encodeDone()),X.close()}catch(D){s?.error?.({err:D,metrics:y.metrics},"cursor-sdk stream failed"),await Ia(y,{reason:"cursor-sdk stream failed before terminal state",onlyRunToken:Q});try{X.error(D)}catch{}}finally{de()}},async cancel(){await Ia(y,{reason:"cursor-sdk client cancelled stream",onlyRunToken:Q})}});if(!a){let X=Ze.getReader();for(;;){let{done:ce}=await X.read();if(ce)break}let de=y_(u,Ie);return new Response(JSON.stringify(de),{status:200,headers:{"Content-Type":"application/json"}})}return new Response(Ze,{status:200,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}})}function R$(t,e,n){return{cursorMode:t.cursorMode||sf,cursorCwd:t.cursorCwd,sandboxEnabled:t.sandboxEnabled,abortSignal:e?.signal,logger:n,turnIntent:e?.unifiedRequest?.turnIntent,sourceSessionIdentity:e?.unifiedRequest?.sourceSessionIdentity}}var ff=class{static TransformerName=p_;name=p_;logger;options;constructor(e={}){this.options=e}async transformRequestIn(e,n,r){let o=R$(this.options,r,this.logger),s={...e,messages:Ke(e.messages),tools:Ve(e.tools)},i=await rR(s,n,r,o);return{body:s,config:{url:n?.baseUrl||"https://cursor.com",headers:{},__providerResponse:i}}}async transformResponseOut(e){return e}};import{randomUUID as tq}from"crypto";import{existsSync as sR,mkdirSync as D$,readFileSync as O$,renameSync as P$,unlinkSync as I$,writeFileSync as F$}from"fs";import{dirname as N$,join as M$}from"path";import{homedir as B$}from"os";import{randomUUID as U$}from"crypto";var U_="1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com",j_="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",iR="http://localhost:51121/oauth-callback",j$=["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"],L_="https://daily-cloudcode-pa.sandbox.googleapis.com",aR="https://autopush-cloudcode-pa.sandbox.googleapis.com",cR="https://cloudcode-pa.googleapis.com",L$=[L_,aR,cR],B_=[cR,L_,aR],$$="1.18.3",q$=M$(B$(),".claude-code-router","antigravity_auth.json"),H$=12e4,uR="https://oauth2.googleapis.com/token",z$="https://www.googleapis.com/oauth2/v2/userinfo",pf=null,lR=null;function dR(){return process.env.CCR_ANTIGRAVITY_AUTH_FILE||q$}function Fa(){return{"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Antigravity/${$$} Chrome/138.0.7204.235 Electron/37.3.1 Safari/537.36`,"X-Goog-Api-Client":"google-cloud-sdk vscode_cloudshelleditor/0.1","Client-Metadata":JSON.stringify({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})}}function hf(){try{let t=dR();if(!sR(t))return null;let e=JSON.parse(O$(t,"utf8"));return!e.access_token||!e.refresh_token?null:e}catch{return null}}function $_(t){let e=dR();D$(N$(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{F$(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),P$(n,e)}finally{try{sR(n)&&I$(n)}catch{}}}function W$(t){return Date.now()+H$>=t.expires_at}async function G$(t){let e=new URLSearchParams({client_id:U_,client_secret:j_,refresh_token:t.refresh_token,grant_type:"refresh_token"}),n=await fetch(uR,{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 $_(o),o}async function Na(t){let e=hf();if(!e)throw new Error("No Antigravity OAuth tokens found. Run `ccr antigravity-auth` to authenticate.");return!t?.force&&!W$(e)?e:(pf||(pf=G$(e).finally(()=>{pf=null})),pf)}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 J$(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 fR(){return{ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}}async function oR(t){await new Promise(e=>setTimeout(e,t))}async function K$(t,e,n){let r=n.startsWith("http")?n:`${e}/${n.replace(/^\//,"")}`,o={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()};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 oR(2e3);continue}let a=await i.json();if(a?.done===!0)return si(a?.response)||si(a)||void 0}catch{}await oR(2e3)}}async function V$(t,e,n){try{let r=await fetch(`${n}/v1internal:onboardUser`,{method:"POST",headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()},body:JSON.stringify({tierId:e,metadata:fR()}),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()?K$(t,n,o.name.trim()):void 0}catch{return}}function Y$(t){let e=J$(t),n=["free-tier","FREE"];return[...new Set([e,...n].filter(Boolean))]}async function X$(t){let e={Authorization:`Bearer ${t}`,"Content-Type":"application/json",...Fa()},n=JSON.stringify({metadata:fR()}),r;for(let o of B_)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 Y$(r))for(let s of B_){let i=await V$(t,o,s);if(i)return i}for(let o of B_)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 q_(t,e){let n=t?.project_id?.trim();if(n)return n;let r=hf();if(r?.project_id?.trim())return r.project_id.trim();let o=await X$(e);if(o){let s=hf();return s&&$_({...s,project_id:o}),o}}function Ma(){return lR||L_}function pR(t){lR=t}var hR=new Set;function gR(t){return t.includes("SERVICE_DISABLED")||t.includes("has not been used in project")}function mR(t){hR.add(t.replace(/\/$/,""))}function Q$(t){return hR.has(t.replace(/\/$/,""))}function yR(t,e){return e?t===404||t===403||t>=500:!1}function _R(t){let e=t?.replace(/\/$/,"")||Ma(),n=[...new Set([e,...L$])],r=n.filter(o=>!Q$(o));return r.length?r:n}function gf(t,e){return`${t}/v1internal:${e?"streamGenerateContent?alt=sse":"generateContent"}`}function bR(t){return{...t.project?{project:t.project}:{},model:t.model,request:t.request,userAgent:"antigravity",requestId:U$()}}async function Z$(t){try{let e=await fetch(z$,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});return e.ok?(await e.json()).email:void 0}catch{return}}async function eq(t,e){let n=new URLSearchParams({client_id:U_,client_secret:j_,code:t,grant_type:"authorization_code",redirect_uri:iR,code_verifier:e}),r=await fetch(uR,{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 CR(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 wR(t){return t&&typeof t=="object"&&"response"in t&&t.response!=null?t.response:t}function nq(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 rq(t){return t?.req?.body?.stream===!0}function oq(t){return _R(t)}var mf=class{name="antigravity-auth";logger;async buildAuthAndEnvelope(e,n,r,o){let s=await Na({force:o?.forceRefresh}),i=await q_(n,s.access_token),a=nq(r,n),u=rq(r),d=bR({...i?{project:i}:{},model:a,request:e});return d.requestId=d.requestId||tq(),{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,...Fa(),...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||Ma(),f=oq(d),p;for(let h=0;h<f.length;h++){let g=f[h],C=gf(g,r),y=this.buildHeaders(n,r);try{let k=await es(C,e,{httpsProxy:a,headers:Object.fromEntries(Object.entries(y).filter(([,b])=>b!==void 0)),signal:s?.signal},s,u);if(k.status===401&&!i){let b=await Na({force:!0});return this.sendWithFallback(e,b.access_token,r,o,s,!0)}if(k.status===429){let b=await k.clone().text().catch(()=>""),A=CR(b),w={};throw A!=null&&(w["Retry-After"]=String(Math.ceil(A/1e3))),J(Je(b)||"Antigravity rate limit exceeded",429,"rate_limit_error","api_error",w)}if(!k.ok){let b=await k.clone().text().catch(()=>"");if(k.status===403&&gR(b)&&(mR(g),u?.warn?.({endpoint:g},"Antigravity endpoint is not enabled for this project; skipping it")),yR(k.status,h<f.length-1)){p=J(`Antigravity endpoint ${g} returned ${k.status}`,k.status,"provider_error");continue}throw J(Je(b)||`Antigravity request failed with ${k.status}`,k.status,k.status===403?"permission_error":"provider_error")}return pR(g),k}catch(k){if(k?.statusCode===429||k?.status===429||!mo(k))throw k;if(p=k,h<f.length-1)continue;throw k}}throw p||J("All Antigravity endpoints failed",502,"provider_error")}async transformRequestIn(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r),s=await this.sendWithFallback(o.body,o.accessToken,o.stream,n,r);return{body:o.body,config:{url:gf(Ma(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream),__providerResponse:s}}}async auth(e,n,r){let o=await this.buildAuthAndEnvelope(e,n,r);return{config:{url:gf(n?.baseUrl||Ma(),o.stream),headers:this.buildHeaders(o.accessToken,o.stream)}}}async transformResponseOut(e){let n=e.headers.get("Content-Type")||"";if(!n||n.includes("text/event-stream"))return e.body?Ne(e,(r,o)=>{if(!r.trim()){o.controller.enqueue(Pe(r,o.encoder));return}if(r.startsWith("data: ")){let s=r.slice(6);if(s.trim()==="[DONE]"){o.controller.enqueue(ve("[DONE]",o.encoder));return}try{let i=JSON.parse(s),a=wR(i);o.controller.enqueue(ve(JSON.stringify(a),o.encoder))}catch{o.controller.enqueue(Pe(r,o.encoder))}return}o.controller.enqueue(Pe(r,o.encoder))},{logger:this.logger}):e;if(n.includes("application/json")){let r=await e.text();try{let o=JSON.parse(r),s=wR(o);return new Response(JSON.stringify(s),{status:e.status,statusText:e.statusText,headers:e.headers})}catch{return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}}return e}};import{resolveXaiApiKey as Rq}from"@caeliq/ccr-shared";import{closeSync as sq,existsSync as SR,fstatSync as iq,mkdirSync as aq,openSync as cq,readFileSync as uq,renameSync as lq,statSync as AR,unlinkSync as z_,writeFileSync as dq}from"fs";import{dirname as fq,join as pq}from"path";import{homedir as hq}from"os";var gq=pq(hq(),".claude-code-router","xai_auth.json"),mq=2*6e4,yq=35e3,kR={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 NK=300*1e3;var _q=120,yf=null;function W_(){return process.env.CCR_XAI_AUTH_FILE||gq}function H_(){return`${W_()}.refresh.lock`}function bq(){return{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}}function Cq(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 wq(t){let e=Cq(t.access_token);return Number.isFinite(e)?e:Number.isFinite(t.expires_at)?t.expires_at:void 0}function Ba(){try{let t=W_();if(!SR(t))return null;let e=JSON.parse(uq(t,"utf8"));return e.access_token?e:null}catch{return null}}function kq(t){let e=W_();aq(fq(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;try{dq(n,JSON.stringify(t,null,2),{mode:384,encoding:"utf8"}),lq(n,e)}finally{try{SR(n)&&z_(n)}catch{}}}function Sq(t,e=_q){let n=wq(t);return n?Date.now()/1e3+e>=n:!1}function Aq(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 Eq(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(kR.token_endpoint,{method:"POST",headers:bq(),body:new URLSearchParams({grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:kR.client_id}).toString()}),n=await e.text();if(!e.ok)throw new Error(`xAI OAuth token refresh failed (${e.status}): ${Aq(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 vq(){let t=H_();try{return cq(t,"wx",384)}catch(e){if(e?.code!=="EEXIST")throw e;try{Date.now()-AR(t).mtimeMs>mq&&z_(t)}catch{}return null}}async function Tq(t){let e=Date.now()+yq,n=null;for(;n===null&&(n=vq(),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=iq(n).ino;sq(n);try{AR(H_()).ino===r&&z_(H_())}catch{}}}async function xq(t){return Tq(async()=>{let e=Ba();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 Eq(e),r=Ba();return r&&r.access_token!==e.access_token?r:(kq(n),n)})}async function ER(t){return _f({force:!0})}async function _f(t={}){let e=Ba();if(!e)throw new Error("No xAI OAuth tokens found. Run `ccr xai-auth` to authenticate.");return!t.force&&!Sq(e)?e:(yf||(yf=xq(e).finally(()=>{yf=null})),yf)}var bf=class{name="xai-auth";logger;async resolveAuth(e){let n=Rq(e?.apiKey,{allowBareEnvName:!0});return n?{mode:"pat",token:n}:{mode:"oauth",token:(await _f()).access_token}}buildConfig(e,n){return{url:`${n?.baseUrl||"https://api.x.ai/v1"}/responses`,headers:{Authorization:`Bearer ${e.token}`},__authRecovery:()=>this.recoverUnauthorizedAuth(e)}}async transformRequestIn(e,n){let r=await this.resolveAuth(n);return{body:e,config:this.buildConfig(r,n)}}async auth(e,n){let r=await this.resolveAuth(n);return{config:this.buildConfig(r,n)}}async recoverUnauthorizedAuth(e){if(e.mode==="pat")return null;let n=Ba();return n?.access_token&&n.access_token!==e.token?{Authorization:`Bearer ${n.access_token}`}:n?.refresh_token?{Authorization:`Bearer ${(await ER(n.refresh_token)).access_token}`}:null}};var vR={AnthropicTransformer:Tu,GeminiTransformer:Fu,VertexGeminiTransformer:gd,VertexClaudeTransformer:Bd,VertexOpenaiTransformer:Ud,DeepseekTransformer:Ed,TooluseTransformer:vd,OpenrouterTransformer:Td,OpenAITransformer:$d,MaxTokenTransformer:xd,GroqTransformer:Rd,CleancacheTransformer:Dd,EnhanceToolTransformer:Id,ReasoningTransformer:Fd,SamplingTransformer:Nd,MaxCompletionTokens:Md,CerebrasTransformer:jd,StreamOptionsTransformer:Ld,CustomParamsTransformer:Hd,VercelTransformer:zd,OpenAIResponsesTransformer:Wd,CodexTransformer:Xd,QwenAuthTransformer:Zd,ForceReasoningTransformer:ef,ExtraThinkTagTransformer:tf,MistralTransformer:nf,ChromeOnDeviceTransformer:rf,OpencodeHeadersTransformer:of,ClaudeAuthTransformer:Eu,CursorSdkTransformer:ff,AntigravityAuthTransformer:mf,XaiAuthTransformer:bf};var ii=class{constructor(e,n){this.configService=e;this.logger=n}configService;logger;transformers=new Map;registerTransformer(e,n){this.transformers.set(e,n),this.logger.info(`register transformer: ${e}${n.endPoint?` (endpoint: ${n.endPoint})`:" (no endpoint)"}`)}getTransformer(e){return this.transformers.get(e)}getAllTransformers(){return new Map(this.transformers)}getTransformersWithEndpoint(){let e=[],n=new Map,r=(o,s)=>{let i=s.endPoint;if(!i)return;let a=n.get(i);if(a){this.logger?.debug?.(`transformer ${o} shares endpoint ${i} with ${a}; keeping ${a}`);return}n.set(i,o),e.push({name:o,transformer:s})};return this.transformers.forEach((o,s)=>{if(typeof o=="object"){r(s,o);return}if(typeof o=="function")try{let i=new o;i&&typeof i=="object"&&(i.logger=this.logger),r(s,i)}catch(i){this.logger?.warn?.(`transformer ${s} could not be instantiated for endpoint registration: ${i?.message}`)}}),e}getTransformersWithoutEndpoint(){let e=[];return this.transformers.forEach((n,r)=>{typeof n=="object"&&!n.endPoint&&e.push({name:r,transformer:n})}),e}removeTransformer(e){return this.transformers.delete(e)}hasTransformer(e){return this.transformers.has(e)}async registerTransformerFromConfig(e){try{if(e.path){let n=re(re.resolve(e.path));if(n){let r=new n(e.options);if(r&&typeof r=="object"&&(r.logger=this.logger),!r.name)throw new Error(`Transformer instance from ${e.path} does not have a name property.`);return this.registerTransformer(r.name,r),!0}}return!1}catch(n){return this.logger.error(`load transformer (${e.path})
|
|
434
438
|
error: ${n.message}
|
|
435
439
|
stack: ${n.stack}`),!1}}async initialize(){try{await this.registerDefaultTransformersInternal(),await this.loadFromConfig()}catch(e){this.logger.error(`TransformerService init error: ${e.message}
|
|
436
|
-
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(
|
|
437
|
-
`: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}},Uq=jq,Lq=class extends kr{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}},$q=Lq,qq=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>PR(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},Hq=qq,zq=class extends kr{normalize(t){let e=pf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},Wq=zq,Gq=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},hf=Gq,Jq=class extends hf{constructor(){super(...arguments),this.form="NFC"}},Kq=Jq,Vq=class extends hf{constructor(){super(...arguments),this.form="NFD"}},Yq=Vq,Xq=class extends hf{constructor(){super(...arguments),this.form="NFKC"}},Qq=Xq,Zq=class extends hf{constructor(){super(...arguments),this.form="NFKD"}},e4=Zq,t4=class extends kr{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}},n4=t4,r4=class extends kr{normalize(t){return OR(t)}},o4=r4,s4=class extends kr{normalize(t){return t.toLowerCase()}},i4=s4,a4=class extends kr{normalize(t){return t=this.config.prepend+t,t}},c4=a4;function u4(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Uq(t);case"Precompiled":return new $q(t);case"Sequence":return new Hq(t);case"Replace":return new Wq(t);case"NFC":return new Kq(t);case"NFD":return new Yq(t);case"NFKC":return new Qq(t);case"NFKD":return new e4(t);case"Strip":return new n4(t);case"StripAccents":return new o4(t);case"Lowercase":return new i4(t);case"Prepend":return new c4(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var PR=u4,l4=class extends ja{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},gn=l4,d4=class extends gn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=DR,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(""))}},f4=d4,p4=class extends gn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},h4=p4,g4=class extends gn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},m4=g4,y4=class extends gn{constructor(t){super(),this.config=t,this.pattern=pf(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):Fq(t,this.pattern)}},_4=y4,b4=class extends gn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${ff}]+|[${ff}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},C4=b4,w4=class extends gn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},k4=w4,S4=class extends gn{constructor(){super(),this.pattern=new RegExp(`[^\\s${ff}]+|[${ff}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},A4=S4,E4=class extends gn{constructor(t){super(),this.config=t,this.pattern=pf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},v4=E4,T4=class extends gn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>IR(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},x4=T4,R4=class extends gn{pre_tokenize_text(t){return Nq(t)}},D4=R4,O4=class extends gn{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let n=0;n<t.length;n+=this._length)e.push(t.slice(n,n+this._length));return e}},P4=O4;function I4(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new A4;case"Sequence":return new x4(t);case"Whitespace":return new h4;case"WhitespaceSplit":return new D4;case"Metaspace":return new m4(t);case"ByteLevel":return new f4(t);case"Split":return new _4(t);case"Punctuation":return new C4(t);case"Digits":return new k4(t);case"Replace":return new v4(t);case"FixedLength":return new P4(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var IR=I4,F4=class extends ja{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=Rq(e,this.tokens_to_ids,this.unk_token_id)),e}},gf=F4,N4=class extends gf{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=q_(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}},vR=N4,TR=class FR{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new FR(!1,new Map)}},M4=class{constructor(){this.root=TR.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=TR.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)}}},B4=M4,L_=class NR{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 NR(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},j4=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 L_(this.bos_token_id??0,0,0,0,0),o=new L_(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 L_(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)}},U4=j4;function L4(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 $4=class extends gf{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=L4(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new B4,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=Pq(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 U4(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}},xR=$4,q4=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}},H4=q4,z4=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()}},W4=z4,G4=class extends gf{constructor(t){super(t),this.tokens_to_ids=q_(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 W4(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 H4((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}},RR=G4,J4=class extends gf{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=q_(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}},K4=J4;function V4(t,e){switch(t.type){case"WordPiece":return new vR(t);case"Unigram":return new xR(t,e.eos_token);case"BPE":return new RR(t);default:if(t.vocab)return Array.isArray(t.vocab)?new xR(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new RR(t):new vR(t):new K4(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 Y4=V4,X4=class extends ja{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},Ua=X4,Q4=class extends Ua{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let i of r)"SpecialToken"in i?n&&(o.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(o=hn(o,t),s=hn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=hn(o,e),s=hn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},Z4=Q4,e6=class extends Ua{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},t6=e6,n6=class extends Ua{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},r6=n6,o6=class extends Ua{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},s6=o6,i6=class extends Ua{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>MR(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}},a6=i6;function c6(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new Z4(t);case"ByteLevel":return new t6(t);case"BertProcessing":return new r6(t);case"RobertaProcessing":return new s6(t);case"Sequence":return new a6(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var MR=c6,u6=class extends ja{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Gn=u6,l6=class extends Gn{constructor(t){super(t),this.byte_decoder=vq,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}},d6=l6,f6=class extends Gn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=$_(e)),e})}},p6=f6,h6=class extends Gn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},g6=h6,m6=class extends Gn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},y6=m6,_6=class extends Gn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let o=1;o<t.length;++o)t[o]!==e.at(-1)&&e.push(t[o]);let r=e.filter(o=>o!==this.pad_token).join("");return this.cleanup&&(r=$_(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},b6=_6,C6=class extends Gn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>BR(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},w6=C6,k6=class extends Gn{decode_chain(t){let e=pf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},S6=k6,A6=class extends Gn{decode_chain(t){return[t.join("")]}},E6=A6,v6=class extends Gn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o){n=o+1;continue}let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},T6=v6,x6=class extends Gn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},R6=x6;function D6(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new d6(t);case"WordPiece":return new p6(t);case"Metaspace":return new g6(t);case"BPEDecoder":return new y6(t);case"CTC":return new b6(t);case"Sequence":return new w6(t);case"Replace":return new S6(t);case"Fuse":return new E6(t);case"Strip":return new T6(t);case"ByteFallback":return new R6(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var BR=D6,O6=class{constructor(t,e){let n=ER(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=ER(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=PR(this.tokenizer.normalizer),this.pre_tokenizer=IR(this.tokenizer.pre_tokenizer),this.model=Y4(this.tokenizer.model,this.config),this.post_processor=MR(this.tokenizer.post_processor),this.decoder=BR(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 Aq(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 SR(o),this.splitter_normalized=new SR(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||!Oq(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=$_(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=Iq(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.splitter_normalized.split(n);return o.forEach((s,i)=>{let a=this.added_tokens_map.get(s);a&&(a.lstrip&&i>0&&(o[i-1]=o[i-1].trimEnd()),a.rstrip&&i<o.length-1&&(o[i+1]=o[i+1].trimStart()))}),o.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:r}):[s];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:hn(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(t||!this.added_tokens_map.has(r))&&e.set(r,n)}return e}},jR=O6;var _f=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||mf(P6(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=mf(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:mf(e,"tokenizer.json"),tokenizerConfig:mf(e,"tokenizer_config.json")}}ensureDir(e){H_(e)||I6(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!H_(e.tokenizerJson)||!H_(e.tokenizerConfig))return null;let[n,r]=await Promise.all([yf.readFile(e.tokenizerJson,"utf-8"),yf.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([yf.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),yf.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 jR(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 bf=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 ai=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 Ba("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 Ba(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new _f(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new bf(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var z_=class{plugins=new Map;pluginInstances=new Map;registerPlugin(e,n={}){this.pluginInstances.set(e.name,e),this.plugins.set(e.name,{name:e.name,enabled:n.enabled!==!1,options:n})}async enablePlugin(e,n){let r=this.plugins.get(e),o=this.pluginInstances.get(e);if(!r||!o)throw new Error(`Plugin ${e} not found`);r.enabled&&await n.register(o.register,r.options)}async enablePlugins(e){for(let[n,r]of this.plugins)if(r.enabled)try{await this.enablePlugin(n,e)}catch(o){let s=o instanceof Error?o.message:String(o);e.log?.error(`Failed to enable plugin ${n}: ${s}`)}}getPlugins(){return Array.from(this.plugins.values())}getPlugin(e){return this.pluginInstances.get(e)}hasPlugin(e){return this.pluginInstances.has(e)}isPluginEnabled(e){return this.plugins.get(e)?.enabled||!1}setPluginEnabled(e,n){let r=this.plugins.get(e);r&&(r.enabled=n)}removePlugin(e){this.plugins.delete(e),this.pluginInstances.delete(e)}clear(){this.plugins.clear(),this.pluginInstances.clear()}},UR=new z_;var HR=nr(Pp(),1);W_();G_();J_();$R();var jo=new Map;function zR(t){let e=jo.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function WR(){return Array.from(jo.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var V_=new Map,GR={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,HR.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)ci.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&&ci.registerHandlers(s)}n.outputOptions&&ci.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(V_.has(d))return V_.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 V_.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 C=s.body?.metadata?.user_id;if(C&&typeof C=="string"){let _=C.match(/_session_([a-f0-9-]+)/i);f=_?_[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(a instanceof ReadableStream){jo.set(d,{requestId:d,sessionId:f,startTime:u,lastTokenTime:u,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[C,_]=a.tee();return(async()=>{let b=null,A=async w=>{let E=jo.get(d);if(!E)return;let x=performance.now();if(w){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 qR(E,r,n.outputOptions,w,t.log).catch(O=>{t.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let E=_.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader();for(b=setInterval(async()=>{jo.get(d)&&await A(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=jo.get(d);if(!V)continue;let U=performance.now();if(!V.firstTokenTime&&(q.event==="content_block_start"||q.event==="content_block_delta"||q.event==="text_block"||q.event==="content_block")&&(V.firstTokenTime=U,V.timeToFirstToken=Math.round(U-V.startTime)),q.event==="content_block_delta"&&q.data?.delta){let ee=q.data.delta.type,z="";if(ee==="text_delta"?z=q.data.delta.text||"":ee==="input_json_delta"?z=q.data.delta.partial_json||"":ee==="thinking_delta"&&(z=q.data.delta.thinking||""),z){let te=p&&p.encodeText?p.encodeText(z).length:Ha(z);V.tokenCount+=te,V.lastTokenTime=U;for(let Q=0;Q<te;Q++)V.tokenTimestamps.push(U)}}q.event==="message_stop"&&(b&&(clearInterval(b),b=null),await A(!0),jo.delete(d))}}catch(w){b&&clearInterval(b),w.name!=="AbortError"&&w.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${w.message}`)}})().catch(b=>{t.log.error(b,"Background stats processing failed")}),C}let h=performance.now(),g=0;if(a&&typeof a=="string")try{let C=JSON.parse(a);if(C.usage?.output_tokens)g=C.usage.output_tokens;else{let _=C.content||C.message?.content||"";if(p)Array.isArray(_)?g=_.reduce((k,b)=>{if(b.type==="text"){let A=b.text||"";return k+(p.encodeText?p.encodeText(A).length:Ha(A))}return k},0):typeof _=="string"&&(g=p.encodeText?p.encodeText(_).length:Ha(_));else{let k=Array.isArray(_)?_.map(b=>b.text).join(""):_;g=Ha(k)}}}catch{}if(g>0){let C=(h-u)/1e3,_={requestId:d,sessionId:f,startTime:u,lastTokenTime:h,tokenCount:g,tokensPerSecond:C>0?Math.round(g/C):0,timeToFirstToken:Math.round(h-u),stream:!1,tokenTimestamps:[]};await qR(_,r,n.outputOptions,!0,t.log)}return a})})};function Ha(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function qR(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 ci.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function $6(t={}){let e=j6({bodyLimit:52428800,...t});return e.setErrorHandler(JC),e.register(U6),e.register(JR.default,{global:!0,...L6}),e}var Y_=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=$6({...r,logger:r.logger??!0}),this.configService=new Qo({...e,logger:this.app.log}),this.transformerService=new ii(this.configService,this.app.log),this.tokenizerService=new ai(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new hs(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 Dh(a)});return}if(!n)throw new Error("options is required");let r=new Qo({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ii(r,this.app.log);await o.initialize();let s=new hs(r,o,this.app.log),i=new ai(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 Dh(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=ar(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)}}},NY=Y_;export{O_ as ANTIGRAVITY_CLIENT_ID,P_ as ANTIGRAVITY_CLIENT_SECRET,nR as ANTIGRAVITY_REDIRECT_URI,D$ as ANTIGRAVITY_SCOPES,Qo as ConfigService,jc as DEFAULT_LOG_BODY_MAX_BYTES,hs as ProviderService,Tn as SSEParserTransform,gs as SSESerializerTransform,ai as TokenizerService,ii as TransformerService,Yw as calculateTokenCount,NY as default,DO as diffHeadersForLog,W$ as exchangeAuthorizationCode,z$ as fetchUserEmail,WR as getGlobalTokenSpeedStats,zR as getTokenSpeedStats,af as getValidAccessToken,Xe as isClientAbortError,kP as isRoutedLlmPost,mh as listClientRouteRegistrations,sf as loadTokens,ar as matchClientProtocol,UR as pluginManager,qi as protocolErrorBody,N_ as resolveProjectId,pk as rewriteStream,vh as router,Zp as sanitizeBodyForLog,Xp as sanitizeHeadersForLog,F_ as saveTokens,Qw as searchProjectBySession,Sh as sessionUsageCache,LO as setHealthReporter,GR as tokenSpeedPlugin};
|
|
440
|
+
Stack: ${e.stack}`)}}async registerDefaultTransformersInternal(){try{Object.values(vR).forEach(e=>{if("TransformerName"in e&&typeof e.TransformerName=="string")this.registerTransformer(e.TransformerName,e);else{let n=new e;n&&typeof n=="object"&&(n.logger=this.logger),this.registerTransformer(n.name,n)}})}catch(e){this.logger.error({error:e},"transformer regist error:")}}async loadFromConfig(){let e=this.configService.get("transformers",[]);for(let n of e)await this.registerTransformerFromConfig(n)}};import{get_encoding as Dq}from"tiktoken";var Ua=class{type="tiktoken";name;encoding;constructor(e="cl100k_base"){this.name=`tiktoken-${e}`;try{this.encoding=Dq(e)}catch(n){throw new Error(`Failed to initialize tiktoken encoding: ${e}`,{cause:n})}}async initialize(){if(!this.encoding)throw new Error("Tiktoken encoding not initialized")}async countTokens(e){if(!this.encoding)throw new Error("Encoding not initialized");let r=u=>this.encoding.encode(u,void 0,[]),o=0,{messages:s,system:i,tools:a}=e;return Array.isArray(s)&&s.forEach(u=>{typeof u.content=="string"?o+=r(u.content).length:Array.isArray(u.content)&&u.content.forEach(d=>{if(d.type==="text")o+=r(d.text).length;else if(d.type==="tool_use")o+=r(JSON.stringify(d.input)).length;else if(d.type==="tool_result"){let f=typeof d.content=="string"?d.content:JSON.stringify(d.content);o+=r(f).length}})}),typeof i=="string"?o+=r(i).length:Array.isArray(i)&&i.forEach(u=>{u.type==="text"&&(typeof u.text=="string"?o+=r(u.text).length:Array.isArray(u.text)&&u.text.forEach(d=>{o+=r(d||"").length}))}),a&&a.forEach(u=>{u.description&&(o+=r(u.name+u.description).length),u.input_schema&&(o+=r(JSON.stringify(u.input_schema)).length)}),o}isInitialized(){return this.encoding!==void 0}encodeText(e){let n=this.encoding;if(!n)throw new Error("Encoding not initialized");return Array.from(n.encode(e,void 0,[]))}dispose(){this.encoding&&(this.encoding.free(),this.encoding=void 0)}};import{join as Af}from"path";import{homedir as $6}from"os";import{existsSync as V_,mkdirSync as q6}from"fs";import{promises as Ef}from"fs";var Oq=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}},TR=Oq,Pq=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}},Iq=Pq,FR=(()=>{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]]))})(),Fq=t=>Object.fromEntries(Object.entries(t).map(([e,n])=>[n,e])),Nq=Fq(FR),xR=".,!?\u2026\u3002\uFF0C\u3001\u0964\u06D4\u060C",Mq=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|[${xR}])]+`,` ?[^\\s${xR}]+`]]),Cf="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",J_=t=>t.replace(/ \./g,".").replace(/ \?/g,"?").replace(/ \!/g,"!").replace(/ ,/g,",").replace(/ \' /g,"'").replace(/ n't/g,"n't").replace(/ 'm/g,"'m").replace(/ 's/g,"'s").replace(/ 've/g,"'ve").replace(/ 're/g,"'re"),wf=(t,e=!0)=>{if(t.Regex!==void 0){let n=t.Regex.replace(/\\([#&~])/g,"$1");n=n.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[r,o]of Mq)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=Bq(t.String);return new RegExp(e?n:`(${n})`,"gu")}else return console.warn("Unknown pattern type:",t),null},Bq=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Uq=(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},jq=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,Lq=t=>Number.isInteger(t)||typeof t=="bigint",$q=t=>{let e=0;for(let n of t)++e;return e},qq=t=>NR(t.toLowerCase()),hn=(...t)=>Array.prototype.concat.apply([],t),K_=t=>new Map(Object.entries(t)),Hq=(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},NR=t=>t.replace(new RegExp("\\p{M}","gu"),""),RR=(t,e,n=[])=>{if(!t||Array.isArray(t)||typeof t!="object")return`${e} must be a valid object`;for(let r of n)if(!(r in t))return`${e} must contain a "${r}" property`;return null},zq=t=>t.match(/\S+/g)||[],Wq=class{constructor(){let t=function(...e){return t._call(...e)};return Object.setPrototypeOf(t,new.target.prototype)}},ja=Wq,Gq=class extends ja{constructor(t){super(),this.config=t}_call(t){return this.normalize(t)}},kr=Gq,Jq=class extends kr{tokenize_chinese_chars(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n],o=r.charCodeAt(0);jq(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`
|
|
441
|
+
`: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}},Kq=Jq,Vq=class extends kr{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}},Yq=Vq,Xq=class extends kr{constructor(t){super(t),this.normalizers=(t.normalizers??[]).map(e=>MR(e))}normalize(t){return this.normalizers.reduce((e,n)=>n?n.normalize(e):e,t)}},Qq=Xq,Zq=class extends kr{normalize(t){let e=wf(this.config.pattern??{});return e===null?t:t.replaceAll(e,this.config.content??"")}},e4=Zq,t4=class extends kr{constructor(){super(...arguments),this.form="NFC"}normalize(t){return t=t.normalize(this.form),t}},kf=t4,n4=class extends kf{constructor(){super(...arguments),this.form="NFC"}},r4=n4,o4=class extends kf{constructor(){super(...arguments),this.form="NFD"}},s4=o4,i4=class extends kf{constructor(){super(...arguments),this.form="NFKC"}},a4=i4,c4=class extends kf{constructor(){super(...arguments),this.form="NFKD"}},u4=c4,l4=class extends kr{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}},d4=l4,f4=class extends kr{normalize(t){return NR(t)}},p4=f4,h4=class extends kr{normalize(t){return t.toLowerCase()}},g4=h4,m4=class extends kr{normalize(t){return t=this.config.prepend+t,t}},y4=m4;function _4(t){if(t===null)return null;switch(t.type){case"BertNormalizer":return new Kq(t);case"Precompiled":return new Yq(t);case"Sequence":return new Qq(t);case"Replace":return new e4(t);case"NFC":return new r4(t);case"NFD":return new s4(t);case"NFKC":return new a4(t);case"NFKD":return new u4(t);case"Strip":return new d4(t);case"StripAccents":return new p4(t);case"Lowercase":return new g4(t);case"Prepend":return new y4(t);default:throw new Error(`Unknown Normalizer type: ${t.type}`)}}var MR=_4,b4=class extends ja{pre_tokenize(t,e){return(Array.isArray(t)?t.map(n=>this.pre_tokenize_text(n,e)):this.pre_tokenize_text(t,e)).flat()}_call(t,e){return this.pre_tokenize(t,e)}},gn=b4,C4=class extends gn{constructor(t){super(),this.config=t,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu"),this.byte_encoder=FR,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(""))}},w4=C4,k4=class extends gn{pre_tokenize_text(t,e){return t.match(/\w+|[^\w\s]+/g)||[]}},S4=k4,A4=class extends gn{constructor(t){super(),this.replacement=t.replacement??"\u2581",this.str_rep=t.str_rep||this.replacement,this.prepend_scheme=t.prepend_scheme??"always"}pre_tokenize_text(t,e){let{section_index:n=void 0}=e??{},r=t.replaceAll(" ",this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&n===0)&&(r=this.str_rep+r),[r]}},E4=A4,v4=class extends gn{constructor(t){super(),this.config=t,this.pattern=wf(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(t){return this.pattern===null?[]:this.config.invert?t.match(this.pattern)||[]:this.config.behavior?.toLowerCase()==="removed"?t.split(this.pattern).filter(e=>e):Hq(t,this.pattern)}},T4=v4,x4=class extends gn{constructor(t){super(),this.config=t,this.pattern=new RegExp(`[^${Cf}]+|[${Cf}]+`,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},R4=x4,D4=class extends gn{constructor(t){super(),this.config=t;let e=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(e,"gu")}pre_tokenize_text(t){return t.match(this.pattern)||[]}},O4=D4,P4=class extends gn{constructor(){super(),this.pattern=new RegExp(`[^\\s${Cf}]+|[${Cf}]`,"gu")}pre_tokenize_text(t,e){return t.trim().match(this.pattern)||[]}},I4=P4,F4=class extends gn{constructor(t){super(),this.config=t,this.pattern=wf(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(t){return this.pattern===null?[t]:[t.replaceAll(this.pattern,this.config.content??"")]}},N4=F4,M4=class extends gn{constructor(t){super(),this.tokenizers=(t.pretokenizers??[]).map(e=>BR(e))}pre_tokenize_text(t,e){return this.tokenizers.reduce((n,r)=>r?r.pre_tokenize(n,e):n,[t])}},B4=M4,U4=class extends gn{pre_tokenize_text(t){return zq(t)}},j4=U4,L4=class extends gn{constructor(t){super(),this.config=t,this._length=t.length}pre_tokenize_text(t){let e=[];for(let n=0;n<t.length;n+=this._length)e.push(t.slice(n,n+this._length));return e}},$4=L4;function q4(t){if(t===null)return null;switch(t.type){case"BertPreTokenizer":return new I4;case"Sequence":return new B4(t);case"Whitespace":return new S4;case"WhitespaceSplit":return new j4;case"Metaspace":return new E4(t);case"ByteLevel":return new w4(t);case"Split":return new T4(t);case"Punctuation":return new R4(t);case"Digits":return new O4(t);case"Replace":return new N4(t);case"FixedLength":return new $4(t);default:throw new Error(`Unknown PreTokenizer type: ${t.type}`)}}var BR=q4,H4=class extends ja{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=Uq(e,this.tokens_to_ids,this.unk_token_id)),e}},Sf=H4,z4=class extends Sf{constructor(t){super(t),this.max_input_chars_per_word=100,this.tokens_to_ids=K_(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}},DR=z4,OR=class UR{constructor(e,n){this.is_leaf=e,this.children=n}static default(){return new UR(!1,new Map)}},W4=class{constructor(){this.root=OR.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=OR.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)}}},G4=W4,G_=class jR{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 jR(this.token_id,this.node_id,this.pos,this.length,this.score);return e.prev=this.prev,e.backtrace_score=this.backtrace_score,e}},J4=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 G_(this.bos_token_id??0,0,0,0,0),o=new G_(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 G_(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)}},K4=J4;function V4(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 Y4=class extends Sf{constructor(t,e){super(t);let n=t.vocab.length;this.vocab=new Array(n),this.scores=new Array(n);for(let r=0;r<n;++r)[this.vocab[r],this.scores[r]]=t.vocab[r];this.unk_token_id=t.unk_id,this.unk_token=this.vocab[t.unk_id],this.tokens_to_ids=new Map(this.vocab.map((r,o)=>[r,o])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=e,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=V4(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new G4,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=$q(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 K4(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}},PR=Y4,X4=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}},Q4=X4,Z4=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()}},e6=Z4,t6=class extends Sf{constructor(t){super(t),this.tokens_to_ids=K_(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 e6(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 Q4((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}},IR=t6,n6=class extends Sf{constructor(t,e){super(t);let n=t.vocab;this.tokens_to_ids=K_(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}},r6=n6;function o6(t,e){switch(t.type){case"WordPiece":return new DR(t);case"Unigram":return new PR(t,e.eos_token);case"BPE":return new IR(t);default:if(t.vocab)return Array.isArray(t.vocab)?new PR(t,e.eos_token):Object.hasOwn(t,"continuing_subword_prefix")&&Object.hasOwn(t,"unk_token")?Object.hasOwn(t,"merges")?new IR(t):new DR(t):new r6(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 s6=o6,i6=class extends ja{constructor(t){super(),this.config=t}_call(t,...e){return this.post_process(t,...e)}},La=i6,a6=class extends La{post_process(t,e=null,n=!0){let r=e===null?this.config.single:this.config.pair,o=[],s=[];for(let i of r)"SpecialToken"in i?n&&(o.push(i.SpecialToken.id),s.push(i.SpecialToken.type_id)):"Sequence"in i&&(i.Sequence.id==="A"?(o=hn(o,t),s=hn(s,new Array(t.length).fill(i.Sequence.type_id))):i.Sequence.id==="B"&&(o=hn(o,e),s=hn(s,new Array(e.length).fill(i.Sequence.type_id))));return{tokens:o,token_type_ids:s}}},c6=a6,u6=class extends La{post_process(t,e=null){return{tokens:t,tokens_pair:e}}},l6=u6,d6=class extends La{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e=null,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},f6=d6,p6=class extends La{constructor(t){super(t),this.sep=t.sep,this.cls=t.cls}post_process(t,e,n=!0){n&&(t=hn([this.cls[0]],t,[this.sep[0]]));let r=new Array(t.length).fill(0);if(e){let o=n?[this.sep[0]]:[],s=n?[this.sep[0]]:[];t=hn(t,o,e,s),r=hn(r,new Array(e.length+o.length+s.length).fill(1))}return{tokens:t,token_type_ids:r}}},h6=p6,g6=class extends La{constructor(t){super(t),this.processors=(t.processors??[]).map(e=>LR(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}},m6=g6;function y6(t){if(t===null)return null;switch(t.type){case"TemplateProcessing":return new c6(t);case"ByteLevel":return new l6(t);case"BertProcessing":return new f6(t);case"RobertaProcessing":return new h6(t);case"Sequence":return new m6(t);default:throw new Error(`Unknown PostProcessor type: ${t.type}`)}}var LR=y6,_6=class extends ja{constructor(t){super(),this.config=t,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in t?t.trim_offsets:!1}_call(t){return this.decode(t)}decode(t){return this.decode_chain(t).join("")}},Gn=_6,b6=class extends Gn{constructor(t){super(t),this.byte_decoder=Nq,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}},C6=b6,w6=class extends Gn{constructor(t){super(t),this.cleanup=t.cleanup}decode_chain(t){return t.map((e,n)=>{if(n!==0){let r=this.config.prefix;r&&e.startsWith(r)?e=e.replace(r,""):e=" "+e}return this.cleanup&&(e=J_(e)),e})}},k6=w6,S6=class extends Gn{constructor(t){super(t),this.replacement=t.replacement??"\u2581"}decode_chain(t){let e=[];for(let n=0;n<t.length;++n){let r=t[n].replaceAll(this.replacement," ");n==0&&r.startsWith(" ")&&(r=r.substring(1)),e.push(r)}return e}},A6=S6,E6=class extends Gn{constructor(t){super(t),this.suffix=t.suffix??""}decode_chain(t){return t.map((e,n)=>e.replaceAll(this.suffix,n===t.length-1?"":" "))}},v6=E6,T6=class extends Gn{constructor(t){super(t),this.pad_token=t.pad_token??"",this.word_delimiter_token=t.word_delimiter_token??"",this.cleanup=t.cleanup}convert_tokens_to_string(t){if(t.length===0)return"";let e=[t[0]];for(let o=1;o<t.length;++o)t[o]!==e.at(-1)&&e.push(t[o]);let r=e.filter(o=>o!==this.pad_token).join("");return this.cleanup&&(r=J_(r).replaceAll(this.word_delimiter_token," ").trim()),r}decode_chain(t){return[this.convert_tokens_to_string(t)]}},x6=T6,R6=class extends Gn{constructor(t){super(t),this.decoders=(t.decoders??[]).map(e=>$R(e))}decode_chain(t){return this.decoders.reduce((e,n)=>n.decode_chain(e),t)}},D6=R6,O6=class extends Gn{decode_chain(t){let e=wf(this.config.pattern),n=this.config.content??"";return e===null?t:t.map(r=>r.replaceAll(e,n))}},P6=O6,I6=class extends Gn{decode_chain(t){return[t.join("")]}},F6=I6,N6=class extends Gn{constructor(t){super(t),this.content=t.content??"",this.start=t.start??0,this.stop=t.stop??0}decode_chain(t){return t.map(e=>{let n=0;for(let o=0;o<this.start&&e[o]===this.content;++o){n=o+1;continue}let r=e.length;for(let o=0;o<this.stop;++o){let s=e.length-o-1;if(e[s]===this.content){r=s;continue}else break}return e.slice(n,r)})}},M6=N6,B6=class extends Gn{constructor(t){super(t),this.text_decoder=new TextDecoder}decode_chain(t){let e=[],n=[];for(let r of t){let o=null;if(r.length===6&&r.startsWith("<0x")&&r.endsWith(">")){let s=parseInt(r.slice(3,5),16);isNaN(s)||(o=s)}if(o!==null)n.push(o);else{if(n.length>0){let s=this.text_decoder.decode(Uint8Array.from(n));e.push(s),n=[]}e.push(r)}}if(n.length>0){let r=this.text_decoder.decode(Uint8Array.from(n));e.push(r),n=[]}return e}},U6=B6;function j6(t){if(t===null)return null;switch(t.type){case"ByteLevel":return new C6(t);case"WordPiece":return new k6(t);case"Metaspace":return new A6(t);case"BPEDecoder":return new v6(t);case"CTC":return new x6(t);case"Sequence":return new D6(t);case"Replace":return new P6(t);case"Fuse":return new F6(t);case"Strip":return new M6(t);case"ByteFallback":return new U6(t);default:throw new Error(`Unknown Decoder type: ${t.type}`)}}var $R=j6,L6=class{constructor(t,e){let n=RR(t,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(n)throw new Error(n);let r=RR(e,"Config");if(r)throw new Error(r);this.tokenizer=t,this.config=e,this.normalizer=MR(this.tokenizer.normalizer),this.pre_tokenizer=BR(this.tokenizer.pre_tokenizer),this.model=s6(this.tokenizer.model,this.config),this.post_processor=LR(this.tokenizer.post_processor),this.decoder=$R(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 Iq(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 TR(o),this.splitter_normalized=new TR(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||!Lq(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=J_(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=qq(n)),this.normalizer!==null&&(n=this.normalizer(n)),n.length===0)return[];let o=this.splitter_normalized.split(n);return o.forEach((s,i)=>{let a=this.added_tokens_map.get(s);a&&(a.lstrip&&i>0&&(o[i-1]=o[i-1].trimEnd()),a.rstrip&&i<o.length-1&&(o[i+1]=o[i+1].trimStart()))}),o.flatMap(s=>{if(s.length===0)return[];if(this.added_tokens_map.has(s))return[s];let i=this.pre_tokenizer!==null?this.pre_tokenizer(s,{section_index:r}):[s];return this.model(i)})})}tokenize_helper(t,{text_pair:e=null,add_special_tokens:n=!0}){let r=this.encode_text(t),o=this.encode_text(e||null);return this.post_processor?this.post_processor(r,o,n):{tokens:hn(r??[],o??[])}}token_to_id(t){return this.model.tokens_to_ids.get(t)}id_to_token(t){return this.model.vocab[t]}get_added_tokens_decoder(){let t=new Map;for(let e of this.added_tokens)t.set(e.id,e);return t}get_vocab(t=!0){let e=new Map;for(let n=0;n<this.model.vocab.length;++n){let r=this.model.vocab[n];(t||!this.added_tokens_map.has(r))&&e.set(r,n)}return e}},qR=L6;var vf=class{type="huggingface";name;modelId;logger;options;tokenizer=null;cacheDir;safeModelName;constructor(e,n,r={}){this.modelId=e,this.logger=n,this.options=r,this.cacheDir=r.cacheDir||Af($6(),".claude-code-router",".huggingface"),this.safeModelName=e.replace(/\//g,"_").replace(/[^a-zA-Z0-9_-]/g,"_"),this.name=`huggingface-${e.split("/").pop()}`}getCachePaths(){let e=Af(this.cacheDir,this.safeModelName);return{modelDir:e,tokenizerJson:Af(e,"tokenizer.json"),tokenizerConfig:Af(e,"tokenizer_config.json")}}ensureDir(e){V_(e)||q6(e,{recursive:!0})}async loadFromCache(){try{let e=this.getCachePaths();if(!V_(e.tokenizerJson)||!V_(e.tokenizerConfig))return null;let[n,r]=await Promise.all([Ef.readFile(e.tokenizerJson,"utf-8"),Ef.readFile(e.tokenizerConfig,"utf-8")]);return{tokenizerJson:JSON.parse(n),tokenizerConfig:JSON.parse(r)}}catch(e){return this.logger?.warn(`Failed to load from cache: ${e.message}`),null}}async downloadAndCache(){let e=this.getCachePaths(),n={json:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer.json`,config:`https://huggingface.co/${this.modelId}/resolve/main/tokenizer_config.json`};this.logger?.info(`Downloading tokenizer files for ${this.modelId}`);let r=new AbortController,o=setTimeout(()=>r.abort(),this.options.timeout||3e4);try{let[s,i]=await Promise.all([fetch(n.json,{signal:r.signal}),fetch(n.config,{signal:r.signal})]);if(!s.ok)throw new Error(`Failed to fetch tokenizer.json: ${s.statusText}`);let[a,u]=await Promise.all([s.json(),i.ok?i.json():Promise.resolve({})]);return this.ensureDir(e.modelDir),await Promise.all([Ef.writeFile(e.tokenizerJson,JSON.stringify(a,null,2)),Ef.writeFile(e.tokenizerConfig,JSON.stringify(u,null,2))]),{tokenizerJson:a,tokenizerConfig:u}}finally{clearTimeout(o)}}async initialize(){try{this.logger?.info(`Initializing HuggingFace tokenizer: ${this.modelId}`),this.ensureDir(this.cacheDir);let e=await this.loadFromCache()||await this.downloadAndCache();this.tokenizer=new qR(e.tokenizerJson,e.tokenizerConfig),this.logger?.info(`Tokenizer initialized: ${this.name}`)}catch(e){throw this.logger?.error(`Failed to initialize tokenizer: ${e.message}`),new Error(`Failed to initialize HuggingFace tokenizer for ${this.modelId}: ${e.message}`,{cause:e})}}async countTokens(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");try{let n=this.extractTextFromRequest(e);return this.tokenizer.encode(n).ids.length}catch(n){throw this.logger?.error(`Error counting tokens: ${n.message}`),n}}isInitialized(){return this.tokenizer!==null}encodeText(e){if(!this.tokenizer)throw new Error("Tokenizer not initialized");return this.tokenizer.encode(e).ids}dispose(){this.tokenizer=null}extractTextFromRequest(e){let n=[],{messages:r,system:o,tools:s}=e;if(Array.isArray(r)){for(let i of r)if(typeof i.content=="string")n.push(i.content);else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"&&a.text?n.push(a.text):a.type==="tool_use"&&a.input?n.push(JSON.stringify(a.input)):a.type==="tool_result"&&n.push(typeof a.content=="string"?a.content:JSON.stringify(a.content))}if(typeof o=="string")n.push(o);else if(Array.isArray(o)){for(let i of o)if(i.type==="text"){if(typeof i.text=="string")n.push(i.text);else if(Array.isArray(i.text))for(let a of i.text)a&&n.push(a)}}if(s)for(let i of s)i.name&&n.push(i.name),i.description&&n.push(i.description),i.input_schema&&n.push(JSON.stringify(i.input_schema));return n.join(" ")}};var Tf=class{type="api";name;config;logger;options;constructor(e,n,r={}){if(!e.url||!e.apiKey)throw new Error("API tokenizer requires url and apiKey");this.config={url:e.url,apiKey:e.apiKey,requestFormat:e.requestFormat||"standard",responseField:e.responseField||"token_count",headers:e.headers||{}},this.logger=n,this.options=r;try{let o=new URL(e.url);this.name=`api-${o.hostname}`}catch{this.name=`api-${e.url}`}}async initialize(){try{new URL(this.config.url)}catch(e){throw new Error(`Invalid API URL: ${this.config.url}`,{cause:e})}}async countTokens(e){try{let n=this.formatRequestBody(e),r={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,...this.config.headers},o=new AbortController,s=setTimeout(()=>o.abort(),this.options.timeout||3e4),i=await fetch(this.config.url,{method:"POST",headers:r,body:JSON.stringify(n),signal:o.signal});if(clearTimeout(s),!i.ok)throw new Error(`API tokenizer request failed: ${i.status} ${i.statusText}`);let a=await i.json();return this.extractTokenCount(a)}catch(n){throw n.name==="AbortError"?new Error("API tokenizer request timed out",{cause:n}):n}}isInitialized(){return!0}dispose(){}formatRequestBody(e){switch(this.config.requestFormat){case"standard":return e;case"openai":return{model:"gpt-3.5-turbo",messages:this.extractMessagesAsOpenAIFormat(e)};case"anthropic":return{messages:e.messages||[],system:e.system,tools:e.tools};case"custom":return{text:this.extractConcatenatedText(e)};default:return e}}extractMessagesAsOpenAIFormat(e){return e.messages?e.messages.map(n=>({role:n.role,content:this.extractTextFromMessage(n)})):[]}extractTextFromMessage(e){return typeof e.content=="string"?e.content:Array.isArray(e.content)?e.content.map(n=>n.type==="text"&&n.text?n.text:n.type==="tool_use"&&n.input?JSON.stringify(n.input):n.type==="tool_result"?typeof n.content=="string"?n.content:JSON.stringify(n.content):"").join(" "):""}extractConcatenatedText(e){let n=[];return e.messages&&e.messages.forEach(r=>{n.push(this.extractTextFromMessage(r))}),typeof e.system=="string"?n.push(e.system):Array.isArray(e.system)&&e.system.forEach(r=>{r.type==="text"&&(typeof r.text=="string"?n.push(r.text):Array.isArray(r.text)&&r.text.forEach(o=>{o&&n.push(o)}))}),e.tools&&e.tools.forEach(r=>{r.name&&n.push(r.name),r.description&&n.push(r.description),r.input_schema&&n.push(JSON.stringify(r.input_schema))}),n.join(" ")}extractTokenCount(e){try{let n=this.config.responseField,r=n.split("."),o=e;for(let s of r){if(o==null)throw new Error(`Field path '${n}' not found in response`);o=o[s]}if(typeof o!="number")throw new Error(`Expected number at field path '${n}', got ${typeof o}`);return o}catch(n){throw this.logger?.error(`Failed to extract token count from API response: ${n.message}. Response: ${JSON.stringify(e)}`),new Error(`Invalid response from API tokenizer: ${n.message}`,{cause:n})}}};var ai=class{tokenizers=new Map;configService;logger;options;fallbackTokenizer;constructor(e,n,r={}){this.configService=e,this.logger=n,this.options={timeout:r.timeout??3e4,...r}}async initialize(){try{this.fallbackTokenizer=new Ua("cl100k_base"),await this.fallbackTokenizer.initialize(),this.tokenizers.set("fallback",this.fallbackTokenizer),this.logger?.info("TokenizerService initialized successfully")}catch(e){throw this.logger?.error(`TokenizerService initialization error: ${e.message}`),e}}async getTokenizer(e){let n=this.getCacheKey(e);if(this.tokenizers.has(n))return this.tokenizers.get(n);let r;try{switch(e.type){case"tiktoken":r=new Ua(e.encoding||"cl100k_base");break;case"huggingface":this.logger?.info(`Initializing HuggingFace tokenizer for model: ${e.model}`),r=new vf(e.model,this.logger,{timeout:this.options.timeout});break;case"api":r=new Tf(e,this.logger,{timeout:this.options.timeout});break;default:throw new Error(`Unknown tokenizer type: ${e.type}`)}return this.logger?.info(`Calling initialize() on ${e.type} tokenizer...`),await r.initialize(),this.tokenizers.set(n,r),this.logger?.info(`Tokenizer initialized successfully: ${e.type} (${n})`),r}catch(o){return this.logger?.error(`Failed to initialize ${e.type} tokenizer: ${o.message}`),this.logger?.error(`Error stack: ${o.stack}`),this.fallbackTokenizer||await this.initialize(),this.fallbackTokenizer}}async countTokens(e,n){let r=n?await this.getTokenizer(n):this.fallbackTokenizer;return{tokenCount:await r.countTokens(e),tokenizerUsed:r.name,cached:!1}}getTokenizerConfigForModel(e,n){let o=(this.configService.get("providers")||[]).find(s=>s.name===e);if(o?.tokenizer)return o.tokenizer.models?.[n]?o.tokenizer.models[n]:o.tokenizer.default}dispose(){this.tokenizers.forEach(e=>{try{e.dispose()}catch(n){this.logger?.error(`Error disposing tokenizer: ${n}`)}}),this.tokenizers.clear()}getCacheKey(e){switch(e.type){case"tiktoken":return`tiktoken:${e.encoding||"cl100k_base"}`;case"huggingface":return`hf:${e.model}`;case"api":return`api:${e.url}`;default:return`unknown:${JSON.stringify(e)}`}}};var Y_=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()}},HR=new Y_;var JR=nr(Lp(),1);X_();Q_();Z_();WR();var Uo=new Map;function KR(t){let e=Uo.get(t);return e?{...e,tokenTimestamps:[...e.tokenTimestamps]}:void 0}function VR(){return Array.from(Uo.values()).map(t=>({...t,tokenTimestamps:[...t.tokenTimestamps]}))}var t0=new Map,YR={name:"token-speed",version:"1.0.0",description:"Statistics for streaming response token generation speed",register:(0,JR.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)ci.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&&ci.registerHandlers(s)}n.outputOptions&&ci.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 C=s.body?.metadata?.user_id;if(C&&typeof C=="string"){let y=C.match(/_session_([a-f0-9-]+)/i);f=y?y[1]:void 0}}catch{}if(!f)return;let p=await o(s);if(a instanceof ReadableStream){Uo.set(d,{requestId:d,sessionId:f,startTime:u,lastTokenTime:u,tokenCount:0,tokensPerSecond:0,tokenTimestamps:[],stream:!0});let[C,y]=a.tee();return(async()=>{let b=null,A=async w=>{let E=Uo.get(d);if(!E)return;let x=performance.now();if(w){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 GR(E,r,n.outputOptions,w,t.log).catch(O=>{t.log?.warn(`Failed to output streaming stats: ${O.message}`)})};try{let E=y.pipeThrough(new TextDecoderStream).pipeThrough(new Tn).getReader();for(b=setInterval(async()=>{Uo.get(d)&&await A(!1)},1e3);;){let{done:x,value:O}=await E.read();if(x)break;let q=O,V=Uo.get(d);if(!V)continue;let j=performance.now();if(!V.firstTokenTime&&(q.event==="content_block_start"||q.event==="content_block_delta"||q.event==="text_block"||q.event==="content_block")&&(V.firstTokenTime=j,V.timeToFirstToken=Math.round(j-V.startTime)),q.event==="content_block_delta"&&q.data?.delta){let ee=q.data.delta.type,z="";if(ee==="text_delta"?z=q.data.delta.text||"":ee==="input_json_delta"?z=q.data.delta.partial_json||"":ee==="thinking_delta"&&(z=q.data.delta.thinking||""),z){let te=p&&p.encodeText?p.encodeText(z).length:za(z);V.tokenCount+=te,V.lastTokenTime=j;for(let Q=0;Q<te;Q++)V.tokenTimestamps.push(j)}}q.event==="message_stop"&&(b&&(clearInterval(b),b=null),await A(!0),Uo.delete(d))}}catch(w){b&&clearInterval(b),w.name!=="AbortError"&&w.code!=="ERR_STREAM_PREMATURE_CLOSE"&&t.log?.warn(`Error processing token stats: ${w.message}`)}})().catch(b=>{t.log.error(b,"Background stats processing failed")}),C}let h=performance.now(),g=0;if(a&&typeof a=="string")try{let C=JSON.parse(a);if(C.usage?.output_tokens)g=C.usage.output_tokens;else{let y=C.content||C.message?.content||"";if(p)Array.isArray(y)?g=y.reduce((k,b)=>{if(b.type==="text"){let A=b.text||"";return k+(p.encodeText?p.encodeText(A).length:za(A))}return k},0):typeof y=="string"&&(g=p.encodeText?p.encodeText(y).length:za(y));else{let k=Array.isArray(y)?y.map(b=>b.text).join(""):y;g=za(k)}}}catch{}if(g>0){let C=(h-u)/1e3,y={requestId:d,sessionId:f,startTime:u,lastTokenTime:h,tokenCount:g,tokensPerSecond:C>0?Math.round(g/C):0,timeToFirstToken:Math.round(h-u),stream:!1,tokenTimestamps:[]};await GR(y,r,n.outputOptions,!0,t.log)}return a})})};function za(t){let e=(t.match(/[\u4e00-\u9fa5]/g)||[]).length,n=t.length-e;return Math.ceil(e/1.5+n/4)}async function GR(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 ci.outputToType(u,i,a)}catch(d){(o?.error??console.error)(`[TokenSpeedPlugin] Failed to output to ${u}:`,d)}}function Y6(t={}){let e=J6({bodyLimit:52428800,...t});return e.setErrorHandler(ZC),e.register(K6),e.register(XR.default,{global:!0,...V6}),e}var n0=class{app;configService;providerService;transformerService;tokenizerService;constructor(e={}){let{initialConfig:n,...r}=e;this.app=Y6({...r,logger:r.logger??!0}),this.configService=new Qo({...e,logger:this.app.log}),this.transformerService=new ii(this.configService,this.app.log),this.tokenizerService=new ai(this.configService,this.app.log),this.transformerService.initialize().finally(()=>{this.providerService=new hs(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 jh(a)});return}if(!n)throw new Error("options is required");let r=new Qo({initialConfig:{providers:n.Providers,Router:n.Router}}),o=new ii(r,this.app.log);await o.initialize();let s=new hs(r,o,this.app.log),i=new ai(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 jh(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=ar(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)}}},KY=n0;export{U_ as ANTIGRAVITY_CLIENT_ID,j_ as ANTIGRAVITY_CLIENT_SECRET,iR as ANTIGRAVITY_REDIRECT_URI,j$ as ANTIGRAVITY_SCOPES,Qo as ConfigService,jc as DEFAULT_LOG_BODY_MAX_BYTES,hs as ProviderService,Tn as SSEParserTransform,gs as SSESerializerTransform,ai as TokenizerService,ii as TransformerService,nk as calculateTokenCount,KY as default,FO as diffHeadersForLog,eq as exchangeAuthorizationCode,Z$ as fetchUserEmail,Na as getAntigravityAccessToken,Au as getClaudeAccessToken,Vd as getCodexAccessToken,VR as getGlobalTokenSpeedStats,d_ as getQwenAccessToken,KR as getTokenSpeedStats,Na as getValidAccessToken,_f as getXaiAccessToken,Xe as isClientAbortError,TP as isRoutedLlmPost,Eh as listClientRouteRegistrations,hf as loadTokens,ar as matchClientProtocol,HR as pluginManager,qi as protocolErrorBody,q_ as resolveProjectId,bk as rewriteStream,Nh as router,ah as sanitizeBodyForLog,sh as sanitizeHeadersForLog,$_ as saveTokens,ok as searchProjectBySession,Ph as sessionUsageCache,zO as setHealthReporter,YR as tokenSpeedPlugin};
|
|
438
442
|
/*! Bundled license information:
|
|
439
443
|
|
|
440
444
|
toad-cache/dist/toad-cache.cjs:
|