kinetex 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -16
- package/dist/browser/kinetex.esm.js +18 -18
- package/dist/browser/kinetex.js +581 -275
- package/dist/browser/kinetex.min.js +18 -18
- package/dist/cjs/client.js +180 -11
- package/dist/cjs/cookie-store.js +10 -0
- package/dist/cjs/core.js +53 -27
- package/dist/cjs/graphql.js +37 -8
- package/dist/cjs/interceptors.js +22 -11
- package/dist/cjs/logging.js +10 -2
- package/dist/cjs/mod.js +1 -1
- package/dist/cjs/pagination.js +6 -1
- package/dist/cjs/progress.js +13 -6
- package/dist/cjs/response.js +8 -6
- package/dist/cjs/sse.js +5 -2
- package/dist/cjs/utils.js +250 -57
- package/dist/cjs/ws.js +16 -2
- package/dist/esm/client.js +180 -11
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/cookie-store.js +10 -0
- package/dist/esm/cookie-store.js.map +1 -1
- package/dist/esm/core.js +53 -27
- package/dist/esm/core.js.map +1 -1
- package/dist/esm/graphql.js +37 -8
- package/dist/esm/graphql.js.map +1 -1
- package/dist/esm/interceptors.js +22 -11
- package/dist/esm/interceptors.js.map +1 -1
- package/dist/esm/logging.js +10 -2
- package/dist/esm/logging.js.map +1 -1
- package/dist/esm/mod.js +1 -1
- package/dist/esm/mod.js.map +1 -1
- package/dist/esm/pagination.js +6 -1
- package/dist/esm/pagination.js.map +1 -1
- package/dist/esm/progress.js +13 -6
- package/dist/esm/progress.js.map +1 -1
- package/dist/esm/response.js +8 -6
- package/dist/esm/response.js.map +1 -1
- package/dist/esm/sse.js +5 -2
- package/dist/esm/sse.js.map +1 -1
- package/dist/esm/utils.js +250 -57
- package/dist/esm/utils.js.map +1 -1
- package/dist/esm/ws.js +16 -2
- package/dist/esm/ws.js.map +1 -1
- package/dist/types/client.d.ts.map +1 -1
- package/dist/types/cookie-store.d.ts.map +1 -1
- package/dist/types/core.d.ts +4 -0
- package/dist/types/core.d.ts.map +1 -1
- package/dist/types/graphql.d.ts.map +1 -1
- package/dist/types/interceptors.d.ts.map +1 -1
- package/dist/types/logging.d.ts.map +1 -1
- package/dist/types/mod.d.ts +1 -1
- package/dist/types/mod.d.ts.map +1 -1
- package/dist/types/pagination.d.ts.map +1 -1
- package/dist/types/progress.d.ts.map +1 -1
- package/dist/types/response.d.ts.map +1 -1
- package/dist/types/sse.d.ts.map +1 -1
- package/dist/types/utils.d.ts +18 -2
- package/dist/types/utils.d.ts.map +1 -1
- package/dist/types/ws.d.ts +4 -0
- package/dist/types/ws.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
/* kinetex v1.
|
|
2
|
-
"use strict";var kinetex=(()=>{var zc=Object.create;var Mt=Object.defineProperty;var Bc=Object.getOwnPropertyDescriptor;var Fc=Object.getOwnPropertyNames;var Wc=Object.getPrototypeOf,Kc=Object.prototype.hasOwnProperty;var Bo=r=>{throw TypeError(r)};var Vc=(r,e,t)=>e in r?Mt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ke=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var q=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var ue=(r,e)=>{for(var t in e)Mt(r,t,{get:e[t],enumerable:!0})},Fo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fc(e))!Kc.call(r,s)&&s!==t&&Mt(r,s,{get:()=>e[s],enumerable:!(n=Bc(e,s))||n.enumerable});return r};var Ve=(r,e,t)=>(t=r!=null?zc(Wc(r)):{},Fo(e||!r||!r.__esModule?Mt(t,"default",{value:r,enumerable:!0}):t,r)),Jc=r=>Fo(Mt({},"__esModule",{value:!0}),r);var h=(r,e,t)=>Vc(r,typeof e!="symbol"?e+"":e,t),Qc=(r,e,t)=>e.has(r)||Bo("Cannot "+t);var Wo=(r,e,t)=>e.has(r)?Bo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var ee=(r,e,t)=>(Qc(r,e,"access private method"),t);function wn(r){return r}function oi(r){if(typeof r=="string"){for(let e of Gc)if(e===r)return e}}var Gc,_,Xe,Ye,dr,Q,te,pr,mr,gr,re,Le=q(()=>{"use strict";Gc=["ENETWORK","ETIMEOUT","EABORT","EHTTPSTATUS","ESIZELIMIT","EPARSE","EVALIDATION","EAUTH","EPROXY","EREDIRECT","EUNKNOWN"];_=class extends Error{constructor(t,n,s){super(t);h(this,"code");h(this,"request");h(this,"response");h(this,"cause");this.name="KinetexError",this.code=n,s?.request!==void 0&&(this.request=s.request),s?.response!==void 0&&(this.response=s.response),s?.cause!==void 0&&(this.cause=s.cause)}get isNetwork(){return this.code==="ENETWORK"}get isProxy(){return this.code==="EPROXY"}get isTimeout(){return this.code==="ETIMEOUT"}get isAbort(){return this.code==="EABORT"}get isHTTPError(){return this.code==="EHTTPSTATUS"}get status(){return this.response?.status??null}},Xe=class extends _{constructor(t,n,s){super(`Response size limit exceeded: ${t} bytes read, limit is ${n} bytes`,"ESIZELIMIT",s!==void 0?{request:s}:{});h(this,"bytesRead");h(this,"limit");this.bytesRead=t,this.limit=n,this.name="SizeLimitError"}},Ye=class extends _{constructor(e,t){super(`HTTP ${e.status} ${e.statusText} \u2014 ${e.url}`,"EHTTPSTATUS",{request:t,response:e}),this.name="HTTPStatusError"}get isClientError(){return(this.status??0)>=400&&(this.status??0)<500}get isServerError(){return(this.status??0)>=500}},dr=class extends _{constructor(e){super("Request was aborted","EABORT",e!==void 0?{request:e}:{}),this.name="AbortError"}},Q=class extends _{constructor(e,t){super(e,"ENETWORK",t!==void 0?{request:t}:{}),this.name="NetworkError"}},te=class extends _{constructor(e,t){super(e,"EVALIDATION",t!==void 0?{request:t}:{}),this.name="ValidationError"}},pr=class extends _{constructor(e,t){super(e,"EAUTH",t!==void 0?{request:t}:{}),this.name="AuthError"}},mr=class extends _{constructor(e,t){super(e,"EPROXY",t!==void 0?{request:t}:{}),this.name="ProxyError"}},gr=class extends _{constructor(e,t){super(e,"EREDIRECT",t!==void 0?{request:t}:{}),this.name="RedirectError"}},re=class extends _{constructor(t,n){super(`Request timed out after ${t}ms`,"ETIMEOUT",n!==void 0?{request:n}:{});h(this,"timeoutMs");this.timeoutMs=t,this.name="TimeoutError"}}});function Xc(){if(yr)return yr;let r=globalThis;if(r.process?.hrtime)return yr=r.process,yr}function Yc(){if(wr)return wr;let r=globalThis;if(r.Buffer&&typeof r.Buffer.isBuffer=="function")return wr=r.Buffer,wr}function he(r,e={}){let t={...Zc,...e};if(r.length>t.maxStringLength)return{success:!1,error:"STRING_TOO_LONG",message:`JSON string length exceeds limit of ${t.maxStringLength}`};let n=0,s=!1,o=!1;for(let i=0;i<r.length;i++){let a=r[i];if(o){o=!1;continue}if(a==="\\"){s&&(o=!0);continue}if(a==='"'){s=!s;continue}if(!s)if(a==="{"||a==="["){if(++n>t.maxDepth)return{success:!1,error:"DEPTH_EXCEEDED",message:`JSON depth exceeds limit of ${t.maxDepth}`}}else(a==="}"||a==="]")&&n--}try{let i=JSON.parse(r);return bn(i,t,0)?!t.allowNonFinite&&xn(i)?{success:!1,error:"NON_FINITE_NUMBER",message:"JSON contains NaN or Infinity values"}:{success:!0,value:i}:{success:!1,error:"VALIDATION_FAILED",message:"Parsed value exceeds size limits"}}catch{return{success:!1,error:"PARSE_ERROR",message:"Failed to parse JSON"}}}function bn(r,e,t){if(t>e.maxDepth)return!1;if(r==null)return!0;if(typeof r=="string")return r.length<=e.maxStringLength;if(typeof r=="number"||typeof r=="boolean")return!0;if(Array.isArray(r))return r.length>e.maxArrayLength?!1:r.every(n=>bn(n,e,t+1));if(typeof r=="object"){let n=Object.keys(r);if(n.length>e.maxObjectKeys||n.includes("__proto__"))return!1;if(n.includes("constructor")){let s=r.constructor;if(typeof s=="object"&&s!==null){let o=Object.keys(s);if(o.includes("prototype")||o.includes("__proto__"))return!1}}return n.every(s=>bn(r[s],e,t+1))}return!0}function xn(r){return typeof r=="number"&&!Number.isFinite(r)?!0:Array.isArray(r)?r.some(xn):typeof r=="object"&&r!==null?Object.values(r).some(xn):!1}function ii(r){let e=he(r);return e.success?e.value:r}function ai(r){return he(r,{maxDepth:16,maxStringLength:1*1024*1024,maxArrayLength:1e3,maxObjectKeys:100})}function ci(r){return r instanceof Uint8Array}function li(r){return r instanceof ArrayBuffer}function ui(r){return r!==null&&typeof r=="object"&&"getReader"in r&&typeof r.getReader=="function"}function hi(r){return r!==null&&typeof r=="object"&&"forEach"in r&&typeof r.forEach=="function"}function fi(r){return r!==null&&typeof r=="object"&&"aborted"in r&&typeof r.aborted=="boolean"}function di(r){return r!==null&&typeof r=="object"&&Object.prototype.toString.call(r)==="[object Object]"}function pi(r){return r!==null&&typeof r=="object"&&r.constructor?.name==="FormData"}function mi(r){return r!==null&&typeof r=="object"&&r.constructor?.name==="Blob"}function gi(r){return r!==null&&typeof r=="object"&&"has"in r&&typeof r.has=="function"}function et(r){return typeof r!="string"||r.length===0||r.length>4096?!1:el.test(r)}function tt(r){if(typeof r!="string"||r.length>8192)return!1;for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t<32&&t!==9||t===127||t===13||t===10)return!1}return!0}function rt(r,e=["http","https"]){try{let t=typeof r=="string"?new URL(r):r,n=t.protocol.replace(/:$/,"").toLowerCase();if(!e.some(o=>o.toLowerCase()===n)||tl.has(n))return!1;let s=t.hostname.toLowerCase();if(s.startsWith("[")&&s.endsWith("]")&&(s=s.slice(1,-1)),s==="0:0:0:0:0:0:0:1"&&(s="::1"),s==="localhost"||s==="0.0.0.0"||rl.some(o=>o.test(s))||t.hostname.includes("..")||t.pathname.includes("..")||t.hostname.length>253||t.href.length>8192)return!1;if(t.port){let o=parseInt(t.port,10);if(isNaN(o)||o<1||o>65535)return!1}return!0}catch{return!1}}function Ze(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(t=>Ze(t));if(r instanceof Date)return new Date(r.getTime());if(r instanceof Uint8Array)return new Uint8Array(r);if(r instanceof Map){let t=new Map;return r.forEach((n,s)=>t.set(s,Ze(n))),t}if(r instanceof Set){let t=new Set;return r.forEach(n=>t.add(Ze(n))),t}let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=Ze(r[t]));return e}function yi(r,e){let t=new Error(r);return Object.assign(t,e),t}function wi(r){if(r instanceof Error){let e={};for(let[n,s]of Object.entries(r))n!=="message"&&n!=="name"&&n!=="stack"&&(e[n]=s);let t=Object.keys(e).length>0?` | ${JSON.stringify(e)}`:"";return`${r.name}: ${r.message}${t}`}return String(r)}function bi(r){if(typeof r!="string"||r.length>2048)return null;try{let e=new URL(r);return rt(e)?(e.username="",e.password="",e.toString()):null}catch{return null}}function xi(){let r=Xc();if(r?.hrtime){let[t,n]=r.hrtime();return t*1e3+n/1e6}return typeof globalThis.Bun<"u",Date.now()}function _i(r,e){return e?.aborted?Promise.reject(_n()):new Promise((t,n)=>{let s=()=>{clearTimeout(o),n(_n())},o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);e&&e.addEventListener("abort",s,{once:!0})})}function br(r){if(r.length===0)return new Uint8Array(0);let e=r.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.byteLength;return t}function Si(r){if(r instanceof Uint8Array)return r.slice();if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=Yc();return e&&e.isBuffer(r)?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):null}function Ut(r){if(r.byteLength<=24576){let n="";for(let s=0;s<r.byteLength;s++)n+=String.fromCharCode(r[s]);return btoa(n)}let t=[];for(let n=0;n<r.byteLength;n+=24576){let s=r.subarray(n,n+24576),o="";for(let i=0;i<s.byteLength;i++)o+=String.fromCharCode(s[i]);t.push(btoa(o))}return t.map((n,s)=>s<t.length-1?n.replace(/=+$/,""):n).join("")}function xr(...r){let e=r.filter(s=>s!=null);if(e.length===0)return;if(e.length===1)return e[0];if(e.some(s=>s.aborted)){let s=new AbortController;return s.abort(),s.signal}let t=new AbortController,n=()=>{for(let s of e)s.removeEventListener("abort",n);t.abort(_n())};t.signal.addEventListener("abort",()=>{for(let s of e)s.removeEventListener("abort",n)},{once:!0});for(let s of e)s.addEventListener("abort",n,{once:!0});return t.signal}function _r(r){if(!(r instanceof Error))return!1;if(r.name==="AbortError")return!0;let e=r;return e.code==="ECONNRESET"||e.code==="ECONNABORTED"||r instanceof DOMException&&r.name==="AbortError"}function nt(r){let e=new Uint8Array(r);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else{let t=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID().replace(/-/g,""):"";if(t.length>=r*2)return t.slice(0,r*2);for(let n=0;n<e.length;n++)e[n]=Math.floor(Math.random()*256)}return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function _n(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let r=new Error("Aborted");return r.name="AbortError",r}function Sr(){if(ne)return ne;try{if(globalThis.process?.versions?.node)return ne="node",ne}catch{}return typeof globalThis.Deno<"u"?ne="deno":typeof globalThis.Bun<"u"?ne="bun":typeof window<"u"?ne="browser":typeof globalThis<"u"&&typeof globalThis.fetch=="function"?ne="edge":ne="unknown",ne}function Ti(){return Sr()==="node"}function Ei(){return Sr()==="browser"}function Ri(){return typeof globalThis?.fetch=="function"}function st(r){let e={};return r.forEach((t,n)=>{e[n.toLowerCase()]=t}),e}var yr,wr,Zc,el,tl,rl,ne,fe=q(()=>{"use strict";Zc={maxDepth:32,maxStringLength:10*1024*1024,maxArrayLength:1e4,maxObjectKeys:1e3,allowNonFinite:!1};el=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;tl=new Set(["file","ftp","gopher","data","javascript","dict","ldap","ldaps","rlogin","telnet","tn3270","imap","pop","smtp","nntp","news","ssh","git","svn","webcal","urn"]),rl=[/^127\./,/^10\./,/^192\.168\./,/^172\.(1[6-9]|2\d|3[01])\./,/^169\.254\./,/^0\./,/^::1$/i,/^fc00:/i,/^fd00:/i,/^fe80:/i,/^2001:db8:/i,/^::0?ffff:/i,/^0:0:0:0:0:ffff:/i,/^::ffff:127\./i,/^::ffff:10\./i,/^::ffff:192\.168\./i,/^::ffff:172\.(1[6-9]|2\d|3[01])\./i,/^::ffff:169\.254\./i,/^0:0:0:0:0:ffff:7f/i,/^::$/i];ne=null});var vi={};ue(vi,{CloudflareKVAdapter:()=>it,HTTPCache:()=>se,MemoryStorageAdapter:()=>ye,TwoTierStorageAdapter:()=>at,WebStorageAdapter:()=>Me,createKVCache:()=>An,createLocalStorageCache:()=>Rn,createMemoryCache:()=>En,createSessionStorageCache:()=>kn,createTwoTierCache:()=>Cn,getAuthFingerprint:()=>Oe});function nl(r){let e={noStore:!1,noCache:!1,mustRevalidate:!1,proxyRevalidate:!1,public:!1,private:!1,maxAge:null,sMaxAge:null,staleWhileRevalidate:null,staleIfError:null,immutable:!1};for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("="),o=(s===-1?n:n.slice(0,s)).trim().toLowerCase(),i=s===-1?null:n.slice(s+1).trim().replace(/^"|"$/g,""),a=i!==null?parseInt(i,10):null;switch(o){case"no-store":e.noStore=!0;break;case"no-cache":e.noCache=!0;break;case"must-revalidate":e.mustRevalidate=!0;break;case"proxy-revalidate":e.proxyRevalidate=!0;break;case"public":e.public=!0;break;case"private":e.private=!0;break;case"immutable":e.immutable=!0;break;case"max-age":e.maxAge=a;break;case"s-maxage":e.sMaxAge=a;break;case"stale-while-revalidate":e.staleWhileRevalidate=a;break;case"stale-if-error":e.staleIfError=a;break;case"no-transform":break;case"only-if-cached":break;case"must-understand":break;default:break}}return e}function ki(r,e){return r?r.trim()==="*"?null:r.split(",").map(s=>s.trim().toLowerCase()).sort().map(s=>{let o=e[s]??e[s.toLowerCase()]??"";return`${s}=${o}`}).join(";"):""}function ot(r){let e=["\0-","\x7F-\x9F"].join(""),t=new RegExp(`[${e}]`,"g");return r.replaceAll(t,"").replaceAll(/\s+/g," ").trim()}async function Oe(r){let e=["authorization","cookie","x-api-key","x-auth-token"],t=[];for(let i of e){let a=r[i.toLowerCase()];a&&t.push(`${i}=${a}`)}if(t.length===0)return"";let n=new TextEncoder().encode(t.join("|")),s=await crypto.subtle.digest("SHA-256",n);return`auth:${Array.from(new Uint8Array(s)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}`}async function sl(r){try{let e=new URL(r.url),t=ot(e.hostname),n=ot(e.pathname);e.searchParams.sort();let s=ot(e.search);e.hash="";let o=`${e.protocol}//${t}${e.port?":"+e.port:""}${n}${s}`,i=ot(r.method.toUpperCase()),a=await Oe(r.headers??{}),c=`${i}:${o}`;return a?`${c}:${a}`:c}catch{let e=ot(r.method.toUpperCase()),t=ot(r.url),n=await Oe(r.headers??{}),s=`${e}:${t}`;return n?`${s}:${n}`:s}}function Ai(r,e,t){let n=r.headers["cache-control"]??r.headers["Cache-Control"]??"",s=nl(n);if(t&&s.noStore)return{ttlMs:0,swrMs:0,staleOnError:0,shouldCache:!1};let o=s.sMaxAge??s.maxAge,i;if(o!==null){let l=parseInt(r.headers.age??r.headers.Age??"0",10)||0;i=Math.max(0,(o-l)*1e3)}else{let l=r.headers.expires??r.headers.Expires;if(l){let u=Date.parse(l);i=isNaN(u)?e:Math.max(0,u-Date.now())}else{let u=r.headers["last-modified"]??r.headers["Last-Modified"];if(u){let f=Date.parse(u);isNaN(f)?i=e:i=Math.min((Date.now()-f)*.1,e)}else i=e}}s.immutable&&i>0&&(i=365*24*60*60*1e3);let a=s.staleWhileRevalidate!==null?s.staleWhileRevalidate*1e3:0,c=s.staleIfError!==null?s.staleIfError*1e3:0;return{ttlMs:i,swrMs:a,staleOnError:c,shouldCache:i>0||a>0}}function Tr(r){return{...r,response:Ci(r.response),tags:[...r.tags]}}function Ci(r){return{...r,headers:{...r.headers},body:r.body instanceof Uint8Array?new Uint8Array(r.body):r.body}}function ol(r){return r?typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength:0}function En(r){return new se({...r,storage:new ye})}function Rn(r,e){if(typeof localStorage>"u")throw new Error("localStorage is not available");return new se({...e,storage:new Me(localStorage,r)})}function kn(r,e){if(typeof sessionStorage>"u")throw new Error("sessionStorage is not available");return new se({...e,storage:new Me(sessionStorage,r)})}function An(r,e){return new se({...e,storage:new it(r)})}function Cn(r,e){return new se({...e,storage:new at(r)})}var ye,Me,it,at,Sn,Tn,se,$t=q(()=>{"use strict";fe();ye=class{constructor(){h(this,"store",new Map)}get(e){return Promise.resolve(this.store.get(e)??null)}set(e,t){return this.store.set(e,t),Promise.resolve()}delete(e){return this.store.delete(e),Promise.resolve()}keys(){return Promise.resolve(Array.from(this.store.keys()))}clear(){return this.store.clear(),Promise.resolve()}get size(){return this.store.size}},Me=class{constructor(e,t="hc:"){h(this,"storage");h(this,"prefix");this.storage=e,this.prefix=t}get(e){try{let t=this.storage.getItem(this.prefix+e);if(!t)return Promise.resolve(null);let n=he(t,{maxDepth:32});return Promise.resolve(n.success&&n.value!==void 0?n.value:null)}catch{return Promise.resolve(null)}}set(e,t){try{return this.storage.setItem(this.prefix+e,JSON.stringify(t)),Promise.resolve(!0)}catch(n){return n instanceof Error&&(n.name==="QuotaExceededError"||n.name==="NS_ERROR_DOM_QUOTA_REACHED")&&console.warn("[kinetex] WebStorageAdapter: storage quota exceeded. Entry was NOT cached. Consider reducing maxBodySizeBytes or using a different storage adapter."),Promise.resolve(!1)}}delete(e){return this.storage.removeItem(this.prefix+e),Promise.resolve()}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n.slice(this.prefix.length))}return Promise.resolve(e)}clear(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}for(let t of e)this.storage.removeItem(t);return Promise.resolve()}},it=class{constructor(e,t="hc:"){h(this,"kv");h(this,"prefix");this.kv=e,this.prefix=t}async get(e){return await this.kv.get(this.prefix+e,"json")}async set(e,t){let n=t.expiresAt===1/0?void 0:Math.max(1,Math.ceil((t.expiresAt-Date.now())/1e3));await this.kv.put(this.prefix+e,JSON.stringify(t),{...n!==void 0?{expirationTtl:n}:{}})}async delete(e){await this.kv.delete(this.prefix+e)}async keys(){return(await this.kv.list({prefix:this.prefix})).keys.map(t=>t.name.slice(this.prefix.length))}async clear(){let e=await this.keys();await Promise.all(e.map(t=>this.kv.delete(this.prefix+t)))}},at=class{constructor(e){h(this,"l2");h(this,"l1",new ye);this.l2=e}async get(e){let t=await this.l1.get(e);if(t)return t;let n=await this.l2.get(e);return n&&await this.l1.set(e,n),n}async set(e,t){await Promise.all([this.l1.set(e,t),this.l2.set(e,t)])}async delete(e){await Promise.all([this.l1.delete(e),this.l2.delete(e)])}async keys(){return await this.l2.keys()}async clear(){await Promise.all([this.l1.clear(),this.l2.clear()])}};Sn=class{constructor(e,t=null,n=null){h(this,"key");h(this,"prev");h(this,"next");this.key=e,this.prev=t,this.next=n}},Tn=class{constructor(){h(this,"map",new Map);h(this,"head",null);h(this,"tail",null)}touch(e){let t=this.map.get(e);if(t)this._unlink(t),this._prepend(t);else{let n=new Sn(e);this.map.set(e,n),this._prepend(n)}}evict(){if(!this.tail)return null;let e=this.tail.key;return this._unlink(this.tail),this.map.delete(e),e}remove(e){let t=this.map.get(e);t&&(this._unlink(t),this.map.delete(e))}clear(){this.map.clear(),this.head=null,this.tail=null}get size(){return this.map.size}_prepend(e){e.prev=null,e.next=this.head,this.head&&(this.head.prev=e),this.head=e,this.tail||(this.tail=e)}_unlink(e){e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=null,e.next=null}},se=class{constructor(e={}){h(this,"cfg");h(this,"storage");h(this,"lru",new Tn);h(this,"tagIndex",new Map);h(this,"swrInFlight",new Set);h(this,"stats",{hits:0,misses:0,staleHits:0,errors:0,evictions:0,totalEntries:0,totalSizeBytes:0,hitRate:0});this.cfg={maxEntries:e.maxEntries??500,maxSizeBytes:e.maxSizeBytes??50*1024*1024,maxBodySizeBytes:e.maxBodySizeBytes??5*1024*1024,defaultTtlMs:e.defaultTtlMs??6e4,maxAbsoluteAgeMs:e.maxAbsoluteAgeMs??10080*60*1e3,honorCacheControl:e.honorCacheControl??!0,cacheMethods:e.cacheMethods??["GET","HEAD"],cacheStatuses:e.cacheStatuses??[200,203,204,206,300,301,304,404,405,410,414,501],cacheKey:e.cacheKey??sl,storage:e.storage??new ye,namespace:e.namespace??""},(this.cfg.defaultTtlMs===1/0||this.cfg.defaultTtlMs>365*24*60*60*1e3)&&(console.warn(`[Kinetex Cache] Capping defaultTtlMs from ${this.cfg.defaultTtlMs}ms to 1 year (${365*24*60*60*1e3}ms)`),this.cfg.defaultTtlMs=365*24*60*60*1e3),this.storage=this.cfg.storage}async get(e){if(!this._isCacheable(e.method))return null;let t=await this._key(e),n=await this.storage.get(t);if(!n)return this.stats.misses++,this._updateHitRate(),null;if(n.varyKey!==null&&n.varyKey!==""){let i=ki(n.response.headers.vary??n.response.headers.Vary??"",e.headers);if(i===null||i!==n.varyKey)return this.stats.misses++,this._updateHitRate(),null}let s=Date.now();return s-n.createdAt>this.cfg.maxAbsoluteAgeMs?(await this._delete(t,n),this.stats.misses++,this._updateHitRate(),null):n.expiresAt===1/0||n.expiresAt>s?(this.stats.hits++,this.lru.touch(t),this._updateHitRate(),{entry:Tr(n),stale:!1}):n.staleUntil>s?(this.stats.staleHits++,this.lru.touch(t),this._updateHitRate(),{entry:Tr(n),stale:!0}):n.staleOnError>s?(this.stats.staleHits++,this._updateHitRate(),{entry:Tr(n),stale:!0}):(await this._delete(t,n),this.stats.misses++,this._updateHitRate(),null)}async set(e,t,n={}){if(!this._isCacheable(e.method)||!this.cfg.cacheStatuses.includes(t.status))return!1;let{ttlMs:s,swrMs:o,staleOnError:i,shouldCache:a}=n.ttlMs!==void 0?{ttlMs:n.ttlMs,swrMs:0,staleOnError:0,shouldCache:!0}:Ai(t,this.cfg.defaultTtlMs,this.cfg.honorCacheControl);if(!a&&!n.force)return!1;let c=ol(t.body);if(c>this.cfg.maxBodySizeBytes)return!1;let l=Date.now(),u=this.cfg.maxAbsoluteAgeMs,f=Math.min(s===1/0?u:s,u);if(f<=0&&!n.force)return!1;let d=t.headers.vary??t.headers.Vary??null,p=d?ki(d,e.headers):"";if(p===null)return!1;let g=n.tags??[],m={response:Ci(t),createdAt:l,expiresAt:f===1/0?1/0:l+f,staleUntil:l+f+o,staleOnError:l+f+i,etag:t.headers.etag??t.headers.ETag??null,lastModified:t.headers["last-modified"]??t.headers["Last-Modified"]??null,varyKey:p,tags:g,size:c+256},y=await this._key(e);if(await this._ensureCapacity(m.size),await this.storage.set(y,m)===!1)return!1;this.lru.touch(y),this.stats.totalEntries++,this.stats.totalSizeBytes+=m.size;for(let x of g){let S=this.tagIndex.get(x)??new Set;S.add(y),this.tagIndex.set(x,S)}return!0}buildConditionalHeaders(e){let t={};return e.etag&&(t["if-none-match"]=e.etag),e.lastModified&&(t["if-modified-since"]=e.lastModified),t}async revalidate(e,t){let n=await this._key(e),s=await this.storage.get(n);if(!s)return null;let o={...s.response.headers,...t.headers},i={...s.response,headers:o},{ttlMs:a,swrMs:c,staleOnError:l}=Ai(i,this.cfg.defaultTtlMs,this.cfg.honorCacheControl),u=Date.now(),f=Math.min(a===1/0?this.cfg.maxAbsoluteAgeMs:a,this.cfg.maxAbsoluteAgeMs),d={...s,response:i,createdAt:u,expiresAt:f<=0?u:u+f,staleUntil:u+f+c,staleOnError:u+f+l,etag:o.etag??o.ETag??s.etag,lastModified:o["last-modified"]??o["Last-Modified"]??s.lastModified};return await this.storage.set(n,d),this.lru.touch(n),Tr(d)}async markSWRInFlight(e){let t=await this._key(e);return this.swrInFlight.has(t)?!1:(this.swrInFlight.add(t),!0)}async clearSWRInFlight(e){let t=await this._key(e);this.swrInFlight.delete(t)}async isSWRInFlight(e){let t=await this._key(e);return this.swrInFlight.has(t)}async delete(e){let t=await this._key(e),n=await this.storage.get(t);return n?(await this._delete(t,n),!0):!1}async invalidateByURL(e){let t=await this.storage.keys(),n=0;for(let s of t){let o=this.cfg.namespace?s.startsWith(this.cfg.namespace+":")?s.slice(this.cfg.namespace.length+1):null:s;if(o===null)continue;let i=o.indexOf(":");if(i===-1)continue;let a=o.slice(i+1),c=a.lastIndexOf(":auth:"),l=c!==-1?a.slice(0,c):a,u=e.endsWith("/")?e.slice(0,-1):e;if((l.endsWith("/")?l.slice(0,-1):l).startsWith(u)){let d=await this.storage.get(s);await this._delete(s,d??void 0),n++}}return n}async invalidateByTag(e){let t=this.tagIndex.get(e);if(!t||t.size===0)return 0;let n=0;for(let s of[...t]){let o=await this.storage.get(s);await this._delete(s,o??void 0),n++}return this.tagIndex.delete(e),n}async clear(){await this.storage.clear(),this.lru.clear(),this.tagIndex.clear(),this.swrInFlight.clear(),this.stats.totalEntries=0,this.stats.totalSizeBytes=0}async warm(e){for(let{req:t,res:n,tags:s}of e)await this.set(t,n,{...s!==void 0?{tags:s}:{},force:!0})}getStats(){return{...this.stats}}resetStats(){this.stats={hits:0,misses:0,staleHits:0,errors:0,evictions:0,totalEntries:0,totalSizeBytes:0,hitRate:0}}async serialize(){let e=await this.storage.keys(),t=[],n=Date.now();for(let s of e){let o=await this.storage.get(s);o&&(o.expiresAt!==1/0&&o.expiresAt<n||t.push([s,o]))}return JSON.stringify({version:1,entries:t})}async deserialize(e){let t=he(e,{maxDepth:32});if(!t.success)throw new Error("[kinetex] HTTPCache.deserialize: invalid JSON");let n=t.value;if(typeof n!="object"||n===null||!("version"in n)||!("entries"in n)||n.version!==1||!Array.isArray(n.entries))throw new Error("[kinetex] HTTPCache.deserialize: unexpected format (expected {version:1, entries:[\u2026]})");let{entries:s}=n,o=Date.now();for(let i of s){if(!Array.isArray(i)||i.length!==2)continue;let[a,c]=i;if(typeof a!="string"||a.length===0||a.length>2048)continue;let l=null;try{typeof c=="object"&&c!==null&&typeof c.createdAt=="number"&&typeof c.expiresAt=="number"&&typeof c.staleUntil=="number"&&typeof c.staleOnError=="number"&&typeof c.size=="number"&&Array.isArray(c.tags)&&c.tags.every(d=>typeof d=="string")&&(l=c)}catch{}if(!l)continue;let u=c;if(!(u.expiresAt!==1/0&&u.expiresAt<o)&&!(o-u.createdAt>this.cfg.maxAbsoluteAgeMs)&&!(u.size>this.cfg.maxBodySizeBytes+512)){await this.storage.set(a,u),this.lru.touch(a),this.stats.totalEntries++,this.stats.totalSizeBytes+=u.size;for(let f of u.tags){let d=this.tagIndex.get(f)??new Set;d.add(a),this.tagIndex.set(f,d)}}}}async _key(e){let t=await this.cfg.cacheKey(e);return this.cfg.namespace?`${this.cfg.namespace}:${t}`:t}_isCacheable(e){return this.cfg.cacheMethods.includes(e.toUpperCase())}async _delete(e,t){if(await this.storage.delete(e),this.lru.remove(e),t){this.stats.totalEntries=Math.max(0,this.stats.totalEntries-1),this.stats.totalSizeBytes=Math.max(0,this.stats.totalSizeBytes-t.size);for(let n of t.tags)this.tagIndex.get(n)?.delete(e)}}async _ensureCapacity(e){for(;this.stats.totalEntries>=this.cfg.maxEntries;){let t=this.lru.evict();if(!t)break;let n=await this.storage.get(t);await this._delete(t,n??void 0),this.stats.evictions++}for(;this.stats.totalSizeBytes+e>this.cfg.maxSizeBytes;){let t=this.lru.evict();if(!t)break;let n=await this.storage.get(t);await this._delete(t,n??void 0),this.stats.evictions++}}_updateHitRate(){let e=this.stats.hits+this.stats.misses+this.stats.staleHits;this.stats.hitRate=e>0?(this.stats.hits+this.stats.staleHits)/e:0}}});function Al(r){if(typeof atob<"u")return atob(r);let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="";r=r.replace(/=+$/,"");for(let n=0;n<r.length;n+=4){let s=e.indexOf(r[n]),o=n+1<r.length?e.indexOf(r[n+1]):0,i=n+2<r.length?e.indexOf(r[n+2]):0,a=n+3<r.length?e.indexOf(r[n+3]):0;t+=String.fromCharCode(s<<2|o>>4),n+2<r.length&&(t+=String.fromCharCode((o&15)<<4|i>>2)),n+3<r.length&&(t+=String.fromCharCode((i&3)<<6|a))}return t}function Vi(r){if(typeof btoa<"u")return btoa(r);let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="";for(let n=0;n<r.length;n+=3){let s=r.charCodeAt(n),o=n+1<r.length?r.charCodeAt(n+1):0,i=n+2<r.length?r.charCodeAt(n+2):0;t+=e[s>>2],t+=e[(s&3)<<4|o>>4],t+=n+1<r.length?e[(o&15)<<2|i>>6]:"=",t+=n+2<r.length?e[i&63]:"="}return t}function K(r){let e=new Map;for(let t of r.split(";")){let n=t.trim();if(!n)continue;let s=n.indexOf("=");if(s===-1)e.set(n.toLowerCase(),"");else{let o=n.slice(0,s).trim().toLowerCase(),i=n.slice(s+1).trim();i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),e.set(o,i)}}return e}function Ir(r){return r.split(",").map(e=>{let t=e.trim().split(";"),n=(t[0]??"").trim(),s=1,o=new Map;for(let i=1;i<t.length;i++){let a=t[i].trim(),c=a.indexOf("=");if(c===-1)continue;let l=a.slice(0,c).trim().toLowerCase(),u=a.slice(c+1).trim();l==="q"?s=parseFloat(u)||0:o.set(l,u)}return{value:n,quality:s,params:o}}).filter(e=>e.value!=="").sort((e,t)=>t.quality-e.quality)}function vl(r){let e=r.match(/^([A-Za-z0-9_-]+)'([A-Za-z0-9_-]*)'(.+)$/);if(!e)return null;try{return decodeURIComponent(e[3])}catch{return null}}function cs(r){if(!r)return null;let e=r.indexOf(";"),t=e===-1?r.trim():r.slice(0,e).trim(),n=t.indexOf("/");if(n===-1)return null;let s=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(!s||!o)return null;let i=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;if(!i.test(s)||!i.test(o))return null;let a=e===-1?new Map:K(r.slice(e));return{mediaType:`${s}/${o}`,type:s,subtype:o,charset:a.get("charset")??null,boundary:a.get("boundary")??null,params:a}}function ls(r){let e=r.mediaType;if(r.charset&&(e+=`; charset=${r.charset}`),r.boundary&&(e+=`; boundary=${r.boundary}`),r.params&&r.params instanceof Map)r.params.forEach((t,n)=>{n==="charset"||n==="boundary"||(e+=`; ${n}=${t.includes(" ")?`"${t}"`:t}`)});else if(r.params&&typeof r.params=="object")for(let[t,n]of Object.entries(r.params))t==="charset"||t==="boundary"||(e+=`; ${t}=${n.includes(" ")?`"${n}"`:n}`);return e}function us(r){if(!r)return null;let e=r.indexOf(";"),t=(e===-1?r:r.slice(0,e)).trim().toLowerCase(),n=e===-1?new Map:K(r.slice(e)),s=null,o=n.get("filename*");o&&(s=vl(o)),s===null&&(s=n.get("filename")??null);let i=n.get("name")??null;return{type:t,filename:s,name:i,params:n}}function hs(r){let e=r.type;if(r.name&&(e+=`; name="${r.name}"`),r.filename){e+=`; filename="${r.filename}"`;let t=encodeURIComponent(r.filename);t!==r.filename&&(e+=`; filename*=UTF-8''${t}`)}return e}function fs(r){let e={noCache:!1,noStore:!1,noTransform:!1,onlyIfCached:!1,maxAge:null,maxStale:null,minFresh:null,staleIfError:null,public:!1,private:!1,mustRevalidate:!1,proxyRevalidate:!1,sMaxAge:null,immutable:!1,mustUnderstand:!1,staleWhileRevalidate:null,unknown:new Map};for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("="),o=(s===-1?n:n.slice(0,s)).trim().toLowerCase(),i=s===-1?null:n.slice(s+1).trim().replace(/^"|"$/g,""),a=i!==null?parseInt(i,10):null;switch(o){case"no-cache":e.noCache=!0;break;case"no-store":e.noStore=!0;break;case"no-transform":e.noTransform=!0;break;case"only-if-cached":e.onlyIfCached=!0;break;case"public":e.public=!0;break;case"must-revalidate":e.mustRevalidate=!0;break;case"proxy-revalidate":e.proxyRevalidate=!0;break;case"immutable":e.immutable=!0;break;case"must-understand":e.mustUnderstand=!0;break;case"max-age":e.maxAge=a;break;case"max-stale":e.maxStale=a??1/0;break;case"min-fresh":e.minFresh=a;break;case"s-maxage":e.sMaxAge=a;break;case"stale-if-error":e.staleIfError=a;break;case"stale-while-revalidate":e.staleWhileRevalidate=a;break;case"private":e.private=i?i.split(",").map(c=>c.trim()):!0;break;default:e.unknown.set(o,i??!0)}}return e}function ds(r){let e=[];if(r.noCache&&e.push("no-cache"),r.noStore&&e.push("no-store"),r.noTransform&&e.push("no-transform"),r.onlyIfCached&&e.push("only-if-cached"),r.public&&e.push("public"),r.mustRevalidate&&e.push("must-revalidate"),r.proxyRevalidate&&e.push("proxy-revalidate"),r.immutable&&e.push("immutable"),r.mustUnderstand&&e.push("must-understand"),r.maxAge!=null&&e.push(`max-age=${r.maxAge}`),r.maxStale!=null&&e.push(r.maxStale===1/0?"max-stale":`max-stale=${r.maxStale}`),r.minFresh!=null&&e.push(`min-fresh=${r.minFresh}`),r.sMaxAge!=null&&e.push(`s-maxage=${r.sMaxAge}`),r.staleIfError!=null&&e.push(`stale-if-error=${r.staleIfError}`),r.staleWhileRevalidate!=null&&e.push(`stale-while-revalidate=${r.staleWhileRevalidate}`),r.private&&e.push(Array.isArray(r.private)?`private=${r.private.join(", ")}`:"private"),r.unknown)for(let[t,n]of r.unknown)e.push(n===!0?t:`${t}=${n}`);return e.join(", ")}function Cr(r){if(!r)return null;let e=r.indexOf(" ");if(e===-1)return{scheme:r.toLowerCase(),token:null,params:new Map,basic:null};let t=r.slice(0,e).toLowerCase(),n=r.slice(e+1).trim(),s=new Map,o=null,i=null;if(t==="basic"){o=n;try{let a=Al(n),c=a.indexOf(":");c!==-1&&(i={username:a.slice(0,c),password:a.slice(c+1)})}catch{}}else if(t==="bearer"||t==="token")o=n;else if(n.includes("="))for(let a of n.split(",")){let c=a.trim(),l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),f=c.slice(l+1).trim();f.startsWith('"')&&f.endsWith('"')&&(f=f.slice(1,-1)),s.set(u,f)}else o=n;return{scheme:t,token:o,params:s,basic:i}}function vr(r){let e=[],t=[],n="",s=!1;for(let o=0;o<r.length;o++){let i=r[o];i==='"'&&(o===0||r[o-1]!=="\\")&&(s=!s),i===","&&!s?(t.push(n.trim()),n=""):n+=i}n.trim()&&t.push(n.trim());for(let o of t){if(!o)continue;let i=o.indexOf(" "),a=(i===-1?o:o.slice(0,i)).toLowerCase(),c=i===-1?"":o.slice(i+1),l=K(c);e.push({scheme:a,realm:l.get("realm")??null,params:l})}return e}function Xi(r){return`Bearer ${r}`}function Yi(r,e){return`Basic ${Vi(`${r}:${e}`)}`}function Lr(r){return Ir(r)}function ps(r){return Ir(r)}function ms(r){return Ir(r)}function Zi(r){return r.trim()?Ir(r):[]}function ea(r,e){let t=Lr(r);for(let{value:n}of t){if(n==="*/*")return e[0]??null;let[s]=n.split("/");if(n.endsWith("/*")){let o=e.find(i=>i.startsWith(s+"/"));if(o)return o}if(e.includes(n))return n}return null}function gs(r){let e=r.indexOf("=");if(e===-1)return null;let t=r.slice(0,e).trim().toLowerCase(),n=r.slice(e+1).split(",").map(s=>{let o=s.trim(),i=o.indexOf("-");if(i===-1)return null;let a=o.slice(0,i).trim(),c=o.slice(i+1).trim();return{start:a===""?null:parseInt(a,10),end:c===""?null:parseInt(c,10)}}).filter(s=>s!==null);return{unit:t,ranges:n}}function ys(r){let e=r.match(/^(\S+)\s+(\*|\d+-\d+)\/(\*|\d+)$/);if(!e)return null;let t=e[1].toLowerCase(),n=e[2],s=e[3]==="*"?null:parseInt(e[3],10);if(n==="*")return{unit:t,start:null,end:null,total:s};let o=n.indexOf("-");return{unit:t,start:parseInt(n.slice(0,o),10),end:parseInt(n.slice(o+1),10),total:s}}function Pr(r){let e=[],t=r.split(/,\s*(?=<)/);for(let n of t){let s=n.trim(),o=s.indexOf(">");if(!s.startsWith("<")||o===-1)continue;let i=s.slice(1,o),a=s.slice(o+1),c=K(a);e.push({uri:i,rel:c.get("rel")??null,type:c.get("type")??null,hreflang:c.get("hreflang")??null,title:c.get("title")??null,media:c.get("media")??null,params:c})}return e}function ta(r){return r.map(e=>{let t=`<${e.uri}>`;e.rel&&(t+=`; rel="${e.rel}"`),e.type&&(t+=`; type="${e.type}"`),e.hreflang&&(t+=`; hreflang="${e.hreflang}"`),e.title&&(t+=`; title="${e.title}"`),e.media&&(t+=`; media="${e.media}"`);let n=e.params instanceof Map?[...e.params.entries()]:Object.entries(e.params??{});for(let[s,o]of n)["rel","type","hreflang","title","media"].includes(s)||(t+=`; ${s}="${o}"`);return t}).join(", ")}function ws(r){let e={by:null,for:[],host:null,proto:null};for(let t of r.split(",")){let n=K(t.trim());n.has("by")&&(e.by=n.get("by")),n.has("for")&&e.for.push(n.get("for")),n.has("host")&&(e.host=n.get("host")),n.has("proto")&&(e.proto=n.get("proto"))}return e}function Mr(r){let e=r.get(w.Forwarded);if(e)return ws(e);let t=r.get(w.XForwardedFor),n=r.get(w.XForwardedHost),s=r.get(w.XForwardedProto);return{by:null,for:t?t.split(",").map(o=>o.trim()):[],host:n??null,proto:s??null}}function bs(r){let e=Mr(r);return e.for.length>0?e.for[0]:r.get(w.XRealIP)}function xs(r){let e=r.trim();if(/^\d+$/.test(e))return{date:null,delay:parseInt(e,10)};let t=Date.parse(e);return isNaN(t)?{date:null,delay:null}:{date:new Date(t),delay:null}}function ra(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let o=r[s];o==='"'&&(s===0||r[s-1]!=="\\")&&(n=!n),o===","&&!n?(t.trim()&&e.push(t.trim()),t=""):t+=o}return t.trim()&&e.push(t.trim()),e.map(s=>{let o=s.match(/^(\d{3})\s+(\S+)\s+["']?([^"']+)["']?\s*(.*)$/);if(!o)return null;let i=o[1],a=o[2],c=o[3],l=o[4]??"",u=parseInt(i,10),f=(()=>{let d=l.trim().replace(/^"|"$/g,"");if(d){let p=Date.parse(d);if(!isNaN(p))return new Date(p)}})();return{code:u,agent:a,text:c,...f!==void 0?{date:f}:{}}}).filter(s=>s!==null)}function _s(r){let e=K(";"+r),t=e.get("max-age");if(t===void 0)return null;let n=parseInt(t,10);return isNaN(n)?null:{maxAge:n,includeSubDomains:e.has("includesubdomains"),preload:e.has("preload")}}function Or(r){let e=`max-age=${r.maxAge}`;return r.includeSubDomains&&(e+="; includeSubDomains"),r.preload&&(e+="; preload"),e}function Ss(r){let e=new Map;for(let t of r.split(";")){let n=t.trim().split(/\s+/);if(n.length===0||!n[0])continue;let s=n[0].toLowerCase(),o=n.slice(1);e.set(s,o)}return e}function Dr(r){let e=[];for(let[t,n]of r)e.push(n.length>0?`${t} ${n.join(" ")}`:t);return e.join("; ")}function Ts(r){return r.split(",").map(e=>{let t=e.trim().split(";"),n=(t[0]??"").trim(),s=K(t.slice(1).join(";")),o=s.get("dur");return{name:n,duration:o!==void 0?parseFloat(o):null,description:s.get("desc")??null}}).filter(e=>e.name!=="")}function na(r){return r.map(e=>{let t=e.name;return e.duration!==null&&(t+=`;dur=${e.duration}`),e.description!==null&&(t+=`;desc="${e.description}"`),t}).join(", ")}function Es(r){if(r.trim()==="clear")return[];let e=[];for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("=");if(s===-1)continue;let o=n.slice(0,s).trim().replace(/^"|"$/g,""),i=n.slice(s+1).trim(),a=i.indexOf(";"),c=a!==-1?K(";"+i.slice(a+1)):new Map,l=(a!==-1?i.slice(0,a):i).replace(/^"|"$/g,""),u,f;if(l.startsWith("[")){let d=l.indexOf("]");if(d===-1)u=l,f=443;else{u=l.slice(0,d+1);let p=l.slice(d+2);f=p?parseInt(p,10):443}}else{let d=l.lastIndexOf(":");u=d===-1?l:l.slice(0,d),f=d===-1?443:parseInt(l.slice(d+1),10)}e.push({protocol:o,host:u,port:f,maxAge:c.has("ma")?parseInt(c.get("ma"),10):null,persist:c.has("persist")&&c.get("persist")==="1"})}return e}function sa(r){let e=new ie;for(let[t,n]of Object.entries(r))if(n!==void 0)if(Array.isArray(n))for(let s of n)e.append(t,s);else e.append(t,n);return e}function oa(r){let e={};return r.forEach((t,n)=>{let o=r.getAll(n);e[n]=o.length===1?o[0]:[...o]}),e}function ia(r){return new ie(r)}function aa(r={}){let e=new ie;if(r.hsts!==!1){let t=r.hsts===!0||r.hsts===void 0?{maxAge:31536e3,includeSubDomains:!0,preload:!1}:r.hsts;e.set(w.StrictTransportSecurity,Or(t))}if(r.csp){let t=typeof r.csp=="string"?r.csp:Dr(r.csp);e.set(w.ContentSecurityPolicy,t)}return e.set(w.XFrameOptions,r.frameOptions??"DENY"),r.noSniff!==!1&&e.set(w.XContentTypeOptions,"nosniff"),e.set(w.ReferrerPolicy,r.referrer??"strict-origin-when-cross-origin"),r.permissions&&e.set(w.PermissionsPolicy,r.permissions),r.coep&&e.set(w.CrossOriginEmbedderPolicy,r.coep),r.coop&&e.set(w.CrossOriginOpenerPolicy,r.coop),r.corp&&e.set(w.CrossOriginResourcePolicy,r.corp),e}function ca(r){let e=new ie,t=Array.isArray(r.origin)?r.origin.join(", "):r.origin;return e.set(w.AccessControlAllowOrigin,t),r.methods?.length&&e.set(w.AccessControlAllowMethods,r.methods.join(", ")),r.allowHeaders?.length&&e.set(w.AccessControlAllowHeaders,r.allowHeaders.join(", ")),r.exposeHeaders?.length&&e.set(w.AccessControlExposeHeaders,r.exposeHeaders.join(", ")),r.credentials&&e.set(w.AccessControlAllowCredentials,"true"),r.maxAge!=null&&e.set(w.AccessControlMaxAge,String(r.maxAge)),e}function la(r){return new we(r)}function ua(r){return new we(r,"request")}function ha(r){return new we(r,"response")}function fa(r){return new we(r,"immutable")}var De,w,is,as,ft,Ki,Cl,U,Ji,ns,ss,os,Qi,Gi,ie,we,Bt=q(()=>{"use strict";fe();w={ContentType:"content-type",ContentLength:"content-length",ContentEncoding:"content-encoding",ContentLanguage:"content-language",ContentLocation:"content-location",ContentDisposition:"content-disposition",ContentRange:"content-range",ContentMD5:"content-md5",TransferEncoding:"transfer-encoding",TrailingHeader:"trailer",CacheControl:"cache-control",Pragma:"pragma",Expires:"expires",Age:"age",ETag:"etag",LastModified:"last-modified",Vary:"vary",IfMatch:"if-match",IfNoneMatch:"if-none-match",IfModifiedSince:"if-modified-since",IfUnmodifiedSince:"if-unmodified-since",IfRange:"if-range",Host:"host",Origin:"origin",Referer:"referer",UserAgent:"user-agent",From:"from",TE:"te",Expect:"expect",MaxForwards:"max-forwards",Accept:"accept",AcceptEncoding:"accept-encoding",AcceptLanguage:"accept-language",AcceptCharset:"accept-charset",AcceptRanges:"accept-ranges",AcceptPatch:"accept-patch",Authorization:"authorization",ProxyAuthorization:"proxy-authorization",WWWAuthenticate:"www-authenticate",ProxyAuthenticate:"proxy-authenticate",AuthenticationInfo:"authentication-info",Range:"range",Cookie:"cookie",SetCookie:"set-cookie",Location:"location",Via:"via",Forwarded:"forwarded",XForwardedFor:"x-forwarded-for",XForwardedHost:"x-forwarded-host",XForwardedProto:"x-forwarded-proto",XForwardedPort:"x-forwarded-port",XRealIP:"x-real-ip",Connection:"connection",KeepAlive:"keep-alive",Upgrade:"upgrade",AccessControlAllowOrigin:"access-control-allow-origin",AccessControlAllowMethods:"access-control-allow-methods",AccessControlAllowHeaders:"access-control-allow-headers",AccessControlExposeHeaders:"access-control-expose-headers",AccessControlMaxAge:"access-control-max-age",AccessControlAllowCredentials:"access-control-allow-credentials",AccessControlRequestMethod:"access-control-request-method",AccessControlRequestHeaders:"access-control-request-headers",Date:"date",RetryAfter:"retry-after",Allow:"allow",Server:"server",ServerTiming:"server-timing",TimingAllowOrigin:"timing-allow-origin",SecWebSocketKey:"sec-websocket-key",SecWebSocketAccept:"sec-websocket-accept",SecWebSocketProtocol:"sec-websocket-protocol",SecWebSocketVersion:"sec-websocket-version",SecWebSocketExtensions:"sec-websocket-extensions",SecFetchSite:"sec-fetch-site",SecFetchMode:"sec-fetch-mode",SecFetchUser:"sec-fetch-user",SecFetchDest:"sec-fetch-dest",StrictTransportSecurity:"strict-transport-security",ContentSecurityPolicy:"content-security-policy",ContentSecurityPolicyRO:"content-security-policy-report-only",XContentTypeOptions:"x-content-type-options",XFrameOptions:"x-frame-options",XXSSProtection:"x-xss-protection",ReferrerPolicy:"referrer-policy",PermissionsPolicy:"permissions-policy",CrossOriginOpenerPolicy:"cross-origin-opener-policy",CrossOriginEmbedderPolicy:"cross-origin-embedder-policy",CrossOriginResourcePolicy:"cross-origin-resource-policy",NEL:"nel",ReportTo:"report-to",ReportingEndpoints:"reporting-endpoints",Link:"link",AltSvc:"alt-svc",AltUsed:"alt-used",Priority:"priority",EarlyData:"early-data",PushPolicy:"push-policy",AcceptPushPolicy:"accept-push-policy",XRequestID:"x-request-id",XCorrelationID:"x-correlation-id",XRateLimitLimit:"x-ratelimit-limit",XRateLimitRemaining:"x-ratelimit-remaining",XRateLimitReset:"x-ratelimit-reset",XPoweredBy:"x-powered-by",XRequestedWith:"x-requested-with"};is=et,as=tt,ft=new Set(["set-cookie","www-authenticate","proxy-authenticate"]),Ki=new Set(["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]),Cl=new Set(["set-cookie","set-cookie2"]),ie=class{constructor(e,t="none"){Wo(this,U);h(this,"map",new Map);h(this,"guard");this.guard=t,e!=null&&ee(this,U,Ji).call(this,e)}append(e,t){ee(this,U,os).call(this,e);let n=ee(this,U,ns).call(this,e),s=ee(this,U,ss).call(this,t),o=this.map.get(n);o?o.values.push(s):this.map.set(n,{name:e,values:[s]})}delete(e){ee(this,U,Gi).call(this,e),this.map.delete(e.toLowerCase())}get(e){let t=this.map.get(e.toLowerCase());return t?ft.has(e.toLowerCase())?t.values[0]??null:t.values.join(", "):null}getAll(e){return[...this.map.get(e.toLowerCase())?.values??[]]}has(e){return this.map.has(e.toLowerCase())}set(e,t){ee(this,U,Qi).call(this,e);let n=ee(this,U,ns).call(this,e),s=ee(this,U,ss).call(this,t);this.map.set(n,{name:e,values:[s]})}forEach(e,t){for(let[n,s]of this.map){let o=ft.has(n)?s.values:[s.values.join(", ")];for(let i of o)e.call(t,i,n,this)}}keys(){return this.map.keys()}*values(){for(let[e,t]of this.map)if(ft.has(e))for(let n of t.values)yield n;else yield t.values.join(", ")}*entries(){for(let[e,t]of this.map)if(ft.has(e))for(let n of t.values)yield[e,n];else yield[e,t.values.join(", ")]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"HttpHeaders"}toObject(){let e={};for(let[t,n]of this.map){let s=n.values;e[t]=s.length===1?s[0]:[...s]}return e}toFlatObject(){let e={};for(let[t,n]of this.map)e[t]=ft.has(t)?n.values[0]??"":n.values.join(", ");return e}toWebHeaders(){if(typeof Headers>"u")throw new Error("WHATWG Headers is not available in this runtime");let e=new Headers;for(let[t,n]of this.map)for(let s of n.values)e.append(t,s);return e}toHTTP1String(){let e=[];for(let[,t]of this.map)for(let n of t.values)e.push(`${t.name}: ${n}`);return e.join(`\r
|
|
3
|
-
`)}clone(e){return new De(this,e??this.guard)}freeze(){return this.clone("immutable")}merge(e,t={}){let n=e instanceof De?e:new De(e);for(let[s,o]of n.map)if(t.append)for(let i of o.values)this.append(s,i);else this.map.set(s,{name:o.name,values:[...o.values]});return this}pick(...e){let t=new De;for(let n of e){let s=n.toLowerCase(),o=this.map.get(s);o&&t.map.set(s,{name:o.name,values:[...o.values]})}return t}omit(...e){let t=this.clone();for(let n of e)t.map.delete(n.toLowerCase());return t}redact(...e){let t=this.clone();for(let n of e){let s=n.toLowerCase(),o=t.map.get(s);o&&t.map.set(s,{name:o.name,values:o.values.map(()=>"**REDACTED**")})}return t}diff(e){let t=new De;for(let[n,s]of e.map){let o=this.get(n),i=ft.has(n)?s.values[0]??"":s.values.join(", ");o!==i&&t.map.set(n,{name:s.name,values:[...s.values]})}return t}get size(){return this.map.size}};U=new WeakSet,Ji=function(e){if(e instanceof De){for(let[t,n]of e.map)this.map.set(t,{name:n.name,values:[...n.values]});return}if(typeof Headers<"u"&&e instanceof Headers){e.forEach((t,n)=>this.append(n,t));return}if(Array.isArray(e)){for(let t of e){if(!Array.isArray(t)||t.length<2)throw new TypeError("Headers init sequence must contain [name, value] pairs");this.append(String(t[0]),String(t[1]))}return}if(typeof e=="object")for(let[t,n]of Object.entries(e))if(Array.isArray(n))for(let s of n)this.append(t,s);else this.append(t,String(n))},ns=function(e){if(!is(e))throw new TypeError(`Invalid header name: "${e}"`);return e.toLowerCase()},ss=function(e){let t=e.trim();if(!as(t))throw new TypeError(`Invalid header value for: "${t}"`);return t},os=function(e){if(this.guard==="immutable")throw new TypeError("Headers are immutable");if(this.guard==="request"&&Ki.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for request guard`);if(this.guard==="response"&&Cl.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for response guard`)},Qi=function(e){ee(this,U,os).call(this,e)},Gi=function(e){if(this.guard==="immutable")throw new TypeError("Headers are immutable");if(this.guard==="request"&&Ki.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for request guard`)};De=ie;we=class extends ie{get contentType(){let e=this.get(w.ContentType);return e?cs(e):null}set contentType(e){if(e===null){this.delete(w.ContentType);return}if(typeof e=="string"){this.set(w.ContentType,e);return}this.set(w.ContentType,ls(e))}get contentLength(){let e=this.get(w.ContentLength);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}set contentLength(e){if(e===null){this.delete(w.ContentLength);return}this.set(w.ContentLength,String(e))}get contentDisposition(){let e=this.get(w.ContentDisposition);return e?us(e):null}set contentDisposition(e){if(e===null){this.delete(w.ContentDisposition);return}if(typeof e=="string"){this.set(w.ContentDisposition,e);return}this.set(w.ContentDisposition,hs(e))}get cacheControl(){let e=this.get(w.CacheControl);return e?fs(e):null}set cacheControl(e){if(e===null){this.delete(w.CacheControl);return}if(typeof e=="string"){this.set(w.CacheControl,e);return}this.set(w.CacheControl,ds(e))}get authorization(){let e=this.get(w.Authorization);return e?Cr(e):null}set authorization(e){if(e===null){this.delete(w.Authorization);return}this.set(w.Authorization,e)}get accept(){return Lr(this.get(w.Accept)??"")}get acceptEncoding(){return ps(this.get(w.AcceptEncoding)??"")}get acceptLanguage(){return ms(this.get(w.AcceptLanguage)??"")}get range(){let e=this.get(w.Range);return e?gs(e):null}get contentRange(){let e=this.get(w.ContentRange);return e?ys(e):null}get etag(){return this.get(w.ETag)}set etag(e){if(e===null){this.delete(w.ETag);return}let t=e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`;this.set(w.ETag,t)}get links(){let e=this.get(w.Link);return e?Pr(e):[]}get retryAfter(){let e=this.get(w.RetryAfter);return e?xs(e):null}get hsts(){let e=this.get(w.StrictTransportSecurity);return e?_s(e):null}set hsts(e){if(e===null){this.delete(w.StrictTransportSecurity);return}this.set(w.StrictTransportSecurity,Or(e))}get csp(){let e=this.get(w.ContentSecurityPolicy);return e?Ss(e):null}set csp(e){if(e===null){this.delete(w.ContentSecurityPolicy);return}if(typeof e=="string"){this.set(w.ContentSecurityPolicy,e);return}this.set(w.ContentSecurityPolicy,Dr(e))}get serverTiming(){let e=this.get(w.ServerTiming);return e?Ts(e):[]}get clientIP(){return bs(this)}get forwarded(){return Mr(this)}get host(){return this.get(w.Host)}get origin(){return this.get(w.Origin)}get userAgent(){return this.get(w.UserAgent)}get location(){return this.get(w.Location)}get date(){let e=this.get(w.Date);if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get age(){let e=this.get(w.Age);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get vary(){let e=this.get(w.Vary);return e?e.split(",").map(t=>t.trim().toLowerCase()):[]}get xRequestID(){return this.get(w.XRequestID)}get xCorrelationID(){return this.get(w.XCorrelationID)}get xPoweredBy(){return this.get(w.XPoweredBy)}get xRequestedWith(){return this.get(w.XRequestedWith)}get xRateLimitLimit(){let e=this.get(w.XRateLimitLimit);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get xRateLimitRemaining(){let e=this.get(w.XRateLimitRemaining);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get xRateLimitReset(){let e=this.get(w.XRateLimitReset);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get secFetchSite(){return this.get(w.SecFetchSite)}get secFetchMode(){return this.get(w.SecFetchMode)}get secFetchUser(){return this.get(w.SecFetchUser)}get secFetchDest(){return this.get(w.SecFetchDest)}get earlyData(){let e=this.get(w.EarlyData);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get priority(){return this.get(w.Priority)}get allow(){return this.get(w.Allow)}get server(){return this.get(w.Server)}get acceptRanges(){return this.get("accept-ranges")}get lastModified(){let e=this.get("last-modified");if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get expires(){let e=this.get("expires");if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get contentEncoding(){return this.get("content-encoding")}get contentLanguage(){return this.get("content-language")}get contentLocation(){return this.get("content-location")}get link(){let e=this.get(w.Link);return e?Pr(e)[0]??null:null}get altSvc(){let e=this.get(w.AltSvc);return e?Es(e):[]}get wwwAuthenticate(){let e=this.get("www-authenticate");return e?vr(e):null}set wwwAuthenticate(e){if(e===null){this.delete("www-authenticate");return}let t=e.map(n=>{let o=[...n.params].filter(([a])=>a!=="realm").map(([a,c])=>`${a}=${c}`).join(", "),i=n.scheme;return n.realm&&(i+=` realm="${n.realm}"`),o&&(i+=`; ${o}`),i}).join(", ");this.set("www-authenticate",t)}get proxyAuthenticate(){let e=this.get(w.ProxyAuthenticate);return e?vr(e):null}set proxyAuthenticate(e){if(e===null){this.delete(w.ProxyAuthenticate);return}let t=e.map(n=>{let o=[...n.params].filter(([a])=>a!=="realm").map(([a,c])=>`${a}=${c}`).join(", "),i=n.scheme;return n.realm&&(i+=` realm="${n.realm}"`),o&&(i+=`; ${o}`),i}).join(", ");this.set(w.ProxyAuthenticate,t)}get proxyAuthorization(){let e=this.get(w.ProxyAuthorization);return e?Cr(e):null}set proxyAuthorization(e){if(e===null){this.delete(w.ProxyAuthorization);return}if(typeof e=="string"){this.set(w.ProxyAuthorization,e);return}e.basic?this.set(w.ProxyAuthorization,`Basic ${Vi(`${e.basic.username}:${e.basic.password}`)}`):e.token?this.set(w.ProxyAuthorization,`${e.scheme} ${e.token}`):this.set(w.ProxyAuthorization,e.scheme)}get setCookies(){return this.getAll(w.SetCookie)}get accessControlAllowOrigin(){return this.get(w.AccessControlAllowOrigin)}get accessControlAllowMethods(){return this.get(w.AccessControlAllowMethods)}get accessControlAllowHeaders(){return this.get(w.AccessControlAllowHeaders)}get accessControlMaxAge(){let e=this.get(w.AccessControlMaxAge);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get accessControlCredentials(){let e=this.get(w.AccessControlAllowCredentials);return e==="true"?!0:e==="false"?!1:null}}});var ma={};ue(ma,{ContentTypeError:()=>xe,HTTPResponseError:()=>Ne,ResponseCache:()=>Rs,ResponseDecodeError:()=>Ue,ResponseSizeLimitError:()=>be,applyDecompression:()=>Kt,assertOk:()=>vs,assertOkJSON:()=>Ps,createLimitedReader:()=>Ds,decodeBody:()=>Wt,decompressStream:()=>$r,diffResponses:()=>Is,extractServerTiming:()=>Ms,isBinary:()=>As,isJSON:()=>Ft,isText:()=>Nr,normalizeHeaders:()=>ae,normalizeResponse:()=>ks,parseContentType:()=>_e,parseMultipartResponse:()=>Br,readBlob:()=>qr,readBodyWithLimit:()=>Ur,readBytes:()=>Vt,readFormData:()=>Ls,readJSON:()=>Hr,readJSONStream:()=>Cs,readNDJSON:()=>zr,readStream:()=>dt,readText:()=>jr});function ae(r){return st(r)}function ks(r){return{status:r.status,statusText:r.statusText,headers:ae(r.headers),url:r.url,redirected:r.redirected,ok:r.ok,bodyUsed:r.bodyUsed}}function _e(r){if(!r||r.length>Il)return null;let e=cs(r);return e?{mediaType:e.mediaType,type:e.type,subtype:e.subtype,charset:e.charset,boundary:e.boundary}:null}function Ft(r){if(!r)return!1;let e=_e(r);return e?e.mediaType==="application/json"||e.subtype.endsWith("+json"):!1}function Nr(r){return r?_e(r)?.type==="text":!1}function As(r){return!Nr(r)&&!Ft(r)}async function Ur(r,e,t,n){let s=t.onExceed??"throw",o=r.getReader(),i=[],a=0;try{for(;;){if(n?.aborted)throw await o.cancel("aborted"),new DOMException("Response reading aborted","AbortError");let{done:c,value:l}=await o.read();if(c)break;let u=a+l.byteLength;if(u>t.maxBytes){if(t.onExceedCallback?.(u,t.maxBytes),s==="throw")throw await o.cancel("size limit exceeded"),new be(u,t.maxBytes,e);if(s==="abort"){await o.cancel("size limit exceeded");break}if(s==="truncate"){let f=t.maxBytes-a;f>0&&(i.push(l.slice(0,f)),a+=f);break}}i.push(l),a+=l.byteLength}}finally{o.releaseLock()}return pa(i)}function Ml(r){return r?Ll[r.toLowerCase()]??"utf-8":"utf-8"}function Ol(r){return r[0]===239&&r[1]===187&&r[2]===191?"utf-8":r[0]===255&&r[1]===254?"utf-16le":r[0]===254&&r[1]===255?"utf-16be":null}function Wt(r,e,t){let n=Ol(r),s=n??Ml(e),o=n?r.slice(n==="utf-8"?3:2):r;try{return new TextDecoder(s,{fatal:!0}).decode(o)}catch{try{return new TextDecoder(s,{fatal:!1}).decode(o)}catch(i){throw new Ue(String(i),s,t)}}}function Dl(r,e,t=1e8){let n=$r(r,e),s=0,o=new TransformStream({transform(i,a){if(s+=i.byteLength,s>t){a.error(new be(s,t,"decompression"));return}a.enqueue(i)}});return n.pipeThrough(o)}function $r(r,e){let t=e.trim().toLowerCase();if(t==="br")return Nl(r);if(typeof DecompressionStream>"u")return r;try{let n=t,s=new DecompressionStream(n);return r.pipeThrough(s)}catch{return r}}function Nl(r){let e=!1;try{e=typeof globalThis.process?.versions?.node=="string"}catch{}return e?new ReadableStream({async start(t){let s=(await import("node:zlib")).createBrotliDecompress(),o=r.getReader();s.on("data",i=>{t.enqueue(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))}),s.on("end",()=>t.close()),s.on("error",i=>t.error(i));try{for(;;){let{done:i,value:a}=await o.read();if(i){s.end();break}s.write(a)}}catch(i){s.destroy(i instanceof Error?i:new Error(String(i))),t.error(i)}finally{o.releaseLock()}},cancel(){r.cancel()}}):r}function Kt(r,e){let t=e["content-encoding"]??e["Content-Encoding"];if(!t||t==="identity")return r;let n=t.split(",").map(o=>o.trim()).filter(Boolean).reverse(),s=r;for(let o of n)s=Dl(s,o);return s}async function Hr(r,e={}){let n=ae(r.headers)["content-type"]??null,s=r.url;e.expectedContentType?da(n,e.expectedContentType,s):Ft(n);let o=await Os(r,s,e),i=e.charset??_e(n??"")?.charset??null,a=Wt(o,i,s);try{return JSON.parse(a)}catch(c){throw new Ue(`JSON parse failed: ${c}`,"json",s)}}async function jr(r,e={}){let n=ae(r.headers)["content-type"]??null,s=r.url;e.expectedContentType&&da(n,e.expectedContentType,s);let o=await Os(r,s,e),i=e.charset??_e(n??"")?.charset??null;return Wt(o,i,s)}async function Vt(r,e={}){let t=r.url;return await Os(r,t,e)}async function qr(r,e={}){let t=await Vt(r,e),n=r.headers.get("content-type")??"application/octet-stream",s=new ArrayBuffer(t.byteLength);return new Uint8Array(s).set(t),new Blob([s],{type:n})}function dt(r,e={}){if(!r.body)return new ReadableStream({start:s=>s.close()});let t=ae(r.headers),n=r.body;return e.decompress!==!1&&(n=Kt(n,t)),e.sizeLimit&&(n=$l(n,r.url,e.sizeLimit,e.signal)),n}async function*zr(r,e={}){let n=dt(r,e).getReader(),s=new TextDecoder("utf-8"),o="";try{for(;!e.signal?.aborted;){let{done:i,value:a}=await n.read();if(i){let l=o.trim();if(l)try{yield JSON.parse(l)}catch(u){e.onParseError?.(u,l)}break}o+=s.decode(a,{stream:!0});let c=o.split(`
|
|
4
|
-
`);o=c.pop()??"";for(let l of c){let u=l.trim();if(!(!u||u.startsWith("#")))try{yield JSON.parse(u)}catch(f){e.onParseError?.(f,u)}}}}finally{n.releaseLock()}}async function*Cs(r,e={}){let n=dt(r,e).getReader(),s=new TextDecoder("utf-8"),o=0,i="",a=-1,c=()=>{if(a===-1)return null;let l=i.slice(a);return a=-1,l};try{for(;!e.signal?.aborted;){let{done:l,value:u}=await n.read();if(l){let f=c();if(f)try{let d=JSON.parse(f);e.onObject?.(d),yield d}catch(d){e.onParseError?.(d,f)}break}i+=s.decode(u,{stream:!0});for(let f=0;f<i.length;f++){let d=i[f];if(d==="{"||d==="[")o===0&&(a=f),o++;else if((d==="}"||d==="]")&&(o--,o===0&&a!==-1)){let p=i.slice(a,f+1);try{let g=JSON.parse(p);e.onObject?.(g),yield g}catch(g){e.onParseError?.(g,p)}i=i.slice(f+1),f=-1}}if(i.length>1e7)throw new Error("JSON stream buffer exceeded 10MB limit")}}finally{n.releaseLock()}}async function vs(r,e={}){if(!(e.isError??(o=>o>=400))(r.status))return r;let n=ae(r.headers),s=null;if(e.readBody!==!1&&r.body&&!r.bodyUsed)try{s=await r.clone().text()}catch{}throw new Ne(r.status,r.statusText,r.url,n,s)}async function Ps(r){if(r.ok)return{response:r};let e=ae(r.headers),t=null;if(r.body&&!r.bodyUsed)try{t=await r.clone().text()}catch{}throw new Ne(r.status,r.statusText,r.url,e,t)}async function Is(r,e){let t=ae(r.headers),n=ae(e.headers),s={},o={},i={};for(let[c,l]of Object.entries(t))c in n?n[c]!==l&&(s[c]=[l,n[c]]):i[c]=l;for(let[c,l]of Object.entries(n))c in t||(o[c]=l);let a=!1;try{let[c,l]=await Promise.all([r.clone().text(),e.clone().text()]);a=c!==l}catch{}return{statusChanged:r.status!==e.status,headersChanged:s,headersAdded:o,headersRemoved:i,bodyChanged:a}}async function Br(r){let e=r.headers.get("content-type")??"",t=_e(e);if(!t?.boundary)throw new xe("multipart/*",e,r.url);let n=await r.arrayBuffer(),s=new Uint8Array(n),o=new TextEncoder().encode("--"+t.boundary),i=[],a=l=>{for(let u=l;u<s.length-o.length;u++)if(s.subarray(u,u+o.length).every((f,d)=>f===o[d]))return u;return-1},c=a(0);if(c===-1)return[];if(c+=o.length,s[c]===13&&s[c+1]===10?c+=2:s[c]===10&&(c+=1),s[c]===45&&s[c+1]===45)return[];for(;c<s.length;){let l=a(c);if(l===-1)break;let u=l+o.length;u<s.length&&(s[u]===13&&s[u+1]===10||s[u]===10||s[u]===45&&s[u+1]);let f=s.subarray(c,l-2),d=Ul(f);if(d===-1){c=l+o.length;continue}let p=f.subarray(0,d),g=f.subarray(d+4),m=new TextDecoder().decode(p),y={};for(let b of m.split(/\r\n/)){let x=b.indexOf(":");x!==-1&&(y[b.slice(0,x).trim().toLowerCase()]=b.slice(x+1).trim())}if(i.push({headers:y,body:g}),c=l+o.length,c<s.length-1&&s[c]===45&&s[c+1]===45)break}return i}function Ul(r){for(let e=0;e<r.length-3;e++)if(r[e]===13&&r[e+1]===10&&r[e+2]===13&&r[e+3]===10)return e;return-1}async function Ls(r){let e=await Br(r),t=new FormData;for(let n of e){let s=n.headers["content-disposition"]??"",o=s.match(/name="([^"]+)"/),i=s.match(/filename="([^"]+)"/);if(!o)continue;let a=o[1],c=i?.[1];if(c){let l=n.headers["content-type"]??"application/octet-stream",u=new ArrayBuffer(n.body.byteLength);new Uint8Array(u).set(n.body);let f=new File([u],c,{type:l});t.append(a,f)}else{let l=new TextDecoder().decode(n.body);t.append(a,l)}}return t}function Ms(r){let e=r["server-timing"]??r["Server-Timing"];return e?e.split(",").map(t=>{let n=t.trim().split(";"),s=(n[0]??"").trim(),o=Pl(n.slice(1).join(";")),i=o.get("dur");return{name:s,duration:i!==void 0?parseFloat(i):null,description:o.get("desc")??null}}).filter(t=>t.name):[]}async function Os(r,e,t){if(!r.body)return new Uint8Array(0);let n=ae(r.headers),s=r.body;if(t.decompress!==!1&&(s=Kt(s,n)),t.signal?.aborted)throw new DOMException("Response reading aborted","AbortError");if(t.sizeLimit)return Ur(s,e,t.sizeLimit,t.signal);let o=s.getReader(),i=[];try{for(;;){if(t.signal?.aborted)throw new DOMException("Response reading aborted","AbortError");let{done:a,value:c}=await o.read();if(a)break;i.push(c)}}finally{o.releaseLock()}return pa(i)}function $l(r,e,t,n){let s=t.onExceed??"throw",o=0;return new ReadableStream({async start(i){let a=r.getReader();try{for(;;){if(n?.aborted){await a.cancel("aborted"),i.error(new DOMException("Response reading aborted","AbortError"));return}let{done:c,value:l}=await a.read();if(c){i.close();break}let u=o+l.byteLength;if(u>t.maxBytes){if(t.onExceedCallback?.(u,t.maxBytes),s==="throw"){await a.cancel("size limit"),i.error(new be(u,t.maxBytes,e));return}if(s==="abort"){await a.cancel("size limit"),i.close();return}if(s==="truncate"){let f=t.maxBytes-o;f>0&&i.enqueue(l.slice(0,f)),i.close(),await a.cancel("size limit");return}}o+=l.byteLength,i.enqueue(l)}}catch(c){i.error(c)}}})}function da(r,e,t){if(!r)throw new xe(e,"(none)",t);let n=r.split(";")[0]?.trim().toLowerCase()??"",s=e.split(";")[0]?.trim().toLowerCase()??"";if(!n.startsWith(s))throw new xe(e,r,t)}function pa(r){let e=r.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.byteLength;return t}function Ds(r,e="throw"){let t={maxBytes:r,onExceed:e};return{json:(n,s)=>Hr(n,{sizeLimit:t,...s}),text:(n,s)=>jr(n,{sizeLimit:t,...s}),bytes:(n,s)=>Vt(n,{sizeLimit:t,...s}),blob:(n,s)=>qr(n,{sizeLimit:t,...s}),stream:(n,s)=>dt(n,{sizeLimit:t,...s}),ndjson:(n,s)=>zr(n,{sizeLimit:t,...s})}}var Pl,Ne,be,xe,Ue,Il,Ll,Rs,Fr=q(()=>{"use strict";Bt();fe();Pl=K,Ne=class extends Error{constructor(t,n,s,o,i){super(`HTTP ${t} ${n} \u2014 ${s}`);h(this,"code","EHTTPRESPONSE");h(this,"status");h(this,"statusText");h(this,"url");h(this,"headers");h(this,"body");this.name="HTTPResponseError",this.status=t,this.statusText=n,this.url=s,this.headers=o,this.body=i}get isClientError(){return this.status>=400&&this.status<500}get isServerError(){return this.status>=500}get isNotFound(){return this.status===404}get isUnauthorized(){return this.status===401}get isForbidden(){return this.status===403}get isTooManyRequests(){return this.status===429}get isGone(){return this.status===410}get isConflict(){return this.status===409}},be=class extends Error{constructor(t,n,s){super(`Response size limit exceeded: read ${t} bytes, limit is ${n} bytes (${s})`);h(this,"code","ESIZELIMIT");h(this,"bytesRead");h(this,"limit");h(this,"url");this.name="ResponseSizeLimitError",this.bytesRead=t,this.limit=n,this.url=s}},xe=class extends Error{constructor(t,n,s){super(`Expected content-type "${t}", got "${n}" (${s})`);h(this,"code","ECONTENTTYPE");h(this,"expected");h(this,"received");h(this,"url");this.name="ContentTypeError",this.expected=t,this.received=n,this.url=s}},Ue=class extends Error{constructor(t,n,s){super(`Failed to decode response as ${n} (${s}): ${t}`);h(this,"code","EDECODE");h(this,"charset");h(this,"url");this.name="ResponseDecodeError",this.charset=n,this.url=s}};Il=8192;Ll={"utf-8":"utf-8",utf8:"utf-8","latin-1":"latin1",latin1:"latin1","iso-8859-1":"latin1",ascii:"ascii","us-ascii":"ascii","utf-16le":"utf-16le","utf-16":"utf-16le","utf-16be":"utf-16be","windows-1252":"windows-1252",cp1252:"windows-1252"};Rs=class{constructor(e={ttlMs:6e4}){h(this,"cache",new Map);h(this,"ttlMs");this.ttlMs=e.ttlMs}hashRequest(e){let t=typeof e=="string"?e:e.url;return`${typeof e=="string"?"GET":e.method}:${t}`}async get(e){let t=this.hashRequest(e),n=this.cache.get(t);return n?Date.now()>n.expiresAt?(this.cache.delete(t),null):await Promise.resolve(n.response.clone()):null}async set(e,t){let n=this.hashRequest(e);await Promise.resolve(this.cache.set(n,{response:t.clone(),expiresAt:Date.now()+this.ttlMs}))}delete(e){this.cache.delete(this.hashRequest(e))}clear(){this.cache.clear()}get size(){return this.cache.size}}});var _a={};ue(_a,{FetchTransport:()=>$e,HAS_NATIVE_FETCH:()=>$s,HTTP_STATUS_TEXTS:()=>xa,IS_NODE:()=>He,NodeHTTP2Transport:()=>pt,RUNTIME:()=>pe,createTransport:()=>Jt,decompressBodyStream:()=>Gt,detectRuntime:()=>Kr,getEffectiveRuntime:()=>Us,normalizeHeaders:()=>ya,parseBody:()=>mt,readRawBody:()=>Qt,sendWithTimeout:()=>je,setRuntime:()=>Ns});function Kr(){let r=globalThis.Deno;return typeof r<"u"&&typeof r.version<"u"?"deno":typeof globalThis.Bun<"u"?"bun":typeof globalThis<"u"&&typeof globalThis.caches<"u"?"cloudflare-workers":typeof window<"u"&&typeof globalThis.document<"u"?"browser":Wr.process?.versions?.node!==void 0?"node":typeof globalThis.fetch=="function"?"edge":"unknown"}function Ns(r){ga=r}function Us(){return ga??pe}function Hl(){try{return globalThis.process?.env?.NODE_ENV==="production"}catch{return!1}}function Jt(r,e=!0,t,n){return He&&e?new pt({...t?.sessionTTLMs!==void 0?{sessionTTLMs:t.sessionTTLMs}:{},...t?.pingIntervalMs!==void 0?{pingIntervalMs:t.pingIntervalMs}:{},...t?.connectTimeoutMs!==void 0?{connectTimeoutMs:t.connectTimeoutMs}:{},...t?.requestTimeoutMs!==void 0?{requestTimeoutMs:t.requestTimeoutMs}:{},...n?.strict!==void 0?{strict:n.strict}:{},...n?.onDroppedHeader!==void 0?{onDroppedHeader:n.onDroppedHeader}:{}}):new $e({fetchFn:r??globalThis.fetch,...n?.strict!==void 0?{strict:n.strict}:{},...n?.onDroppedHeader!==void 0?{onDroppedHeader:n.onDroppedHeader}:{}})}async function je(r,e,t){if(t<=0)return r.send(e);let n=new AbortController,s=setTimeout(()=>{n.abort(new re(t,e))},t),o=xr(e.signal,n.signal)??null,i={...e,signal:o};try{let a=await r.send(i);if(clearTimeout(s),n.signal.aborted)throw new re(t,e);return a}catch(a){throw clearTimeout(s),n.signal.aborted?new re(t,e):a}}async function Qt(r,e,t,n){if(!r)return new Uint8Array(0);let s=r.getReader(),o=[],i=0,a,c=new Promise((u,f)=>{a=f}),l=()=>{s.cancel("aborted").catch(()=>{}),a(new _("Response reading aborted","EABORT"))};if(n?.aborted)throw s.cancel("aborted").catch(()=>{}),new _("Response reading aborted","EABORT");n?.addEventListener("abort",l,{once:!0});try{for(;;){let u=await Promise.race([s.read().catch(p=>{throw s.cancel("read error").catch(()=>{}),p}),c]),{done:f,value:d}=u;if(f)break;if(e>0){let p=i+d.byteLength;if(p>e)throw await s.cancel("size limit exceeded"),new Xe(p,e)}o.push(d),i+=d.byteLength}}catch(u){throw s.cancel("error during read").catch(()=>{}),u}finally{n?.removeEventListener("abort",l),s.releaseLock()}return br(o)}function mt(r,e,t,n,s,o){if(t)return t(r,s??{},o??"");if(!r.byteLength)return null;let i=e?.split(";")[0]?.trim().toLowerCase()??"";if(i==="application/json"||i.endsWith("+json")){let a=new TextDecoder("utf-8").decode(r),c,l;try{let u=he(a,{maxStringLength:1e7,maxDepth:100,maxArrayLength:1e5});u.success&&u.value!==void 0&&(c=u.value)}catch(u){l=u instanceof Error?u:new Error(String(u))}if(c!==void 0)return c;if(n)try{n(r,l??new Error("JSON parse failed \u2014 falling back to raw text"))}catch{}return a}return i.startsWith("text/")?new TextDecoder("utf-8").decode(r):r}function ya(r){return st(r)}function jl(r,e){let t=r;if(t.httpVersion==="2.0"||t.httpVersion==="2")return"HTTP/2";let n=r;if(n.httpVersion)return n.httpVersion;let s=r.headers.get("alt-svc"),o=r;if(o.httpVersion==="3"||o.httpVersion==="3.0"||o.protocol==="h3")return"HTTP/3";if(s){let i=s.includes('h3="')||s.includes("h3-29=")||s.includes("h3-32=");if(s.includes('h2="')||i)return"HTTP/2"}return"HTTP/1.1"}function ql(r){if(!(r instanceof Error))return!1;let e=r.message.toLowerCase();return e.includes("alpn")||e.includes("h2")||e.includes("http2")||r.code==="ERR_HTTP2_ERROR"}function wa(r){return new ReadableStream({start(e){let t=!1,n=!1;r.on("data",s=>{if(s instanceof Uint8Array)e.enqueue(s);else if(Wr.Buffer?.isBuffer(s)){let o=s;e.enqueue(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}else e.enqueue(new Uint8Array(s))}),r.once("end",()=>{if(!(t||n)){t=!0;try{e.close()}catch{}}}),r.once("error",s=>{if(!(t||n)){t=!0,n=!0;try{e.error(s)}catch{}}}),r.once("close",()=>{if(t||n)return;t=!0;let s=Object.assign(new Error("Stream closed before end"),{code:"ECONNRESET"});try{e.error(s)}catch{}})},cancel(){r.destroy()}})}async function ba(r,e){r.write(e)||await new Promise(n=>r.once("drain",n))}async function Bl(r,e){if(e instanceof ReadableStream){let t=e.getReader();for(;;){let{done:n,value:s}=await t.read();if(n){r.end();break}await ba(r,s)}}else e instanceof Uint8Array||e instanceof ArrayBuffer?r.end(Wr.Buffer?new Uint8Array(e):e):typeof e=="string"?r.end(e):r.end()}async function Fl(r,e){if(e instanceof ReadableStream){let t=e.getReader();for(;;){let{done:n,value:s}=await t.read();if(n){r.end();break}await ba(r,s)}}else e instanceof Uint8Array||e instanceof ArrayBuffer?r.end(Wr.Buffer?new Uint8Array(e):e):typeof e=="string"?r.end(e):r.end()}async function Gt(r,e){if(!r)return null;let t=e["content-encoding"]??e["Content-Encoding"];if(!t)return r;let n=t.trim().toLowerCase(),s=n.split(",").map(a=>a.trim()).filter(Boolean),o=["gzip","deflate","br","identity"];for(let a of s)if(!o.includes(a))return console.warn(`[Kinetex] Unsupported Content-Encoding: ${a}. Supported: ${o.join(", ")}. Response body is passed through compressed.`),r;if(n==="identity")return delete e["content-encoding"],delete e["Content-Encoding"],r;let{applyDecompression:i}=await Promise.resolve().then(()=>(Fr(),ma));return i(r,e)}var Wr,pe,ga,He,$s,$e,pt,zl,xa,Xt=q(()=>{"use strict";Le();fe();Bt();fe();Wr=globalThis;pe=Kr(),ga=null;He=pe==="node",$s=pe!=="node"||typeof globalThis.fetch=="function";$e=class{constructor(e=globalThis.fetch){h(this,"fetchFn");h(this,"strict");h(this,"onDroppedHeader");typeof e=="function"?(this.fetchFn=e,this.strict=!1,this.onDroppedHeader=void 0):(this.fetchFn=e.fetchFn??globalThis.fetch,this.strict=e.strict??!1,this.onDroppedHeader=e.onDroppedHeader)}async send(e){let t={};for(let[l,u]of Object.entries(e.headers??{}))if(!(typeof l!="string"||typeof u!="string")){if(!is(l)||!as(u)){if(this.strict)throw new _(`Invalid header dropped in strict mode: "${l}"`,"EVALIDATION",{request:e});this.onDroppedHeader?this.onDroppedHeader(l,u):Hl()||console.warn(`[kinetex] Invalid header dropped: "${l}" \u2014 value may contain illegal characters. Pass strictHeaders: true to throw instead.`);continue}t[l]=u}let n=t["accept-encoding"];n&&n.toLowerCase().includes("gzip")&&n.toLowerCase().includes("deflate")&&n.toLowerCase().includes("br")&&delete t["accept-encoding"];let s={method:e.method,headers:t,redirect:e.redirect??"follow",...e.signal!==null?{signal:e.signal}:{}};e.body!==null&&e.method!=="GET"&&e.method!=="HEAD"&&(s.body=e.body,He&&typeof s.body=="object"&&s.body!==null&&"getReader"in s.body&&(s.duplex="half"));let o;try{o=await this.fetchFn(e.url,s)}catch(l){throw _r(l)?new _("Request was aborted","EABORT",{request:e,cause:l}):new _(l instanceof Error?l.message:"Network request failed","ENETWORK",{request:e,cause:l})}let i=ya(o.headers),a=jl(o,i),c=!0;return pe==="deno"&&(o.headers.get("content-encoding")||"").toLowerCase().includes("deflate")&&(c=!1),{status:o.status,statusText:o.statusText,headers:i,body:o.body,url:o.url||e.url,redirected:o.redirected,httpVersion:a,alreadyDecompressed:c}}},pt=class{constructor(e={}){h(this,"sessions",new Map);h(this,"sessionTTLMs");h(this,"pingIntervalMs");h(this,"maxSessions");h(this,"pingTimers",new Map);h(this,"_sessionCreating",new Map);h(this,"sessionUsage",new Map);h(this,"_strict");h(this,"_onDroppedHeader");h(this,"_connectTimeoutMs");h(this,"_requestTimeoutMs");h(this,"_http1Fallback",null);this.sessionTTLMs=e.sessionTTLMs??5*6e4,this.pingIntervalMs=e.pingIntervalMs??3e4,this.maxSessions=e.maxSessions??100,this._strict=e.strict??!1,this._onDroppedHeader=e.onDroppedHeader,this._connectTimeoutMs=e.connectTimeoutMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??3e4}_getOrCreateSession(e,t,n){let s=this._sessionCreating.get(e);if(s)return s;let o=this._createSession(e,t,n);return this._sessionCreating.set(e,o),o.finally(()=>{this._sessionCreating.get(e)===o&&this._sessionCreating.delete(e)}).catch(()=>{}),o}async _createSession(e,t,n){let s=this.sessions.get(e);if(s&&!s.session.destroyed&&!s.session.closed&&!(Date.now()-s.createdAt>this.sessionTTLMs))return this.sessionUsage.set(e,Date.now()),s.session;if(s&&this._evictSession(e,s.session),this.sessions.size>=this.maxSessions){let i="",a=1/0;for(let[c,l]of this.sessionUsage.entries())l<a&&(a=l,i=c);if(i){let c=this.sessions.get(i);c&&this._evictSession(i,c.session)}}let o=await new Promise((i,a)=>{let c=n.connect(e,{rejectUnauthorized:!0}),l=setTimeout(()=>{c.destroy(),a(new _(`HTTP/2 connection to ${e} timed out`,"ETIMEOUT",{request:t}))},this._connectTimeoutMs);typeof l.unref=="function"&&l.unref();let u=()=>{clearTimeout(l),c.destroy(),a(new _("Connection aborted","EABORT",{request:t}))},f=()=>t.signal?.removeEventListener("abort",u);t.signal?.addEventListener("abort",u,{once:!0}),c.once("connect",()=>{f(),clearTimeout(l),i(c)}),c.once("error",d=>{f(),clearTimeout(l),a(d)})});if(o.on("goaway",()=>{this._evictSession(e,o)}),o.on("error",()=>{this._evictSession(e,o)}),this.sessions.set(e,{session:o,createdAt:Date.now()}),this.sessionUsage.set(e,Date.now()),this.pingIntervalMs>0){let i=this.pingTimers.get(e);i&&clearInterval(i);let a=setInterval(()=>{let c=this.sessions.get(e);if(!c||c.session.destroyed||c.session.closed){this._evictSession(e,c?.session);return}c.session.ping(l=>{l&&this._evictSession(e,c.session)})},this.pingIntervalMs);typeof a=="object"&&a!==null&&"unref"in a&&a.unref(),this.pingTimers.set(e,a)}return o}async send(e){let t=new URL(e.url);if(t.protocol!=="https:"||e.httpVersion==="HTTP/1.1")return this._sendHTTP1(e);try{return await this._sendHTTP2(e,t)}catch(n){if(ql(n))return this._sendHTTP1(e);throw n}}async _sendHTTP2(e,t){let n=await import("node:http2"),s=e,o=t,i=!1,a=10;for(let c=0;c<=a;c++){if(c===a)throw new _("Too many HTTP/2 redirects","ENETWORK",{request:e});let l=o.origin,u=this.sessions.get(l),f=u&&Date.now()-u.createdAt>this.sessionTTLMs,d;!u||u.session.destroyed||u.session.closed||f?d=await this._getOrCreateSession(l,s,n):(d=u.session,this.sessionUsage.set(l,Date.now()));let p={":method":s.method,":path":o.pathname+o.search,":scheme":"https",":authority":o.host,...s.headers};if(this._strict)for(let[A,M]of Object.entries(p)){if(A.startsWith(":"))continue;let N=Array.isArray(M)?M.join(", "):String(M),F=!1;for(let $=0;$<N.length;$++){let Z=N.charCodeAt($);if(Z>=0&&Z<=8||Z>=10&&Z<=31||Z===127){F=!0;break}}if(F)if(this._onDroppedHeader)this._onDroppedHeader(A,N),delete p[A];else throw new _(`Strict mode: header "${A}" contains forbidden control characters`,"EVALIDATION",{request:s})}let g=!s.body||s.method==="GET"||s.method==="HEAD",m=d.request(p,{endStream:g});s.body&&!g&&Bl(m,s.body).catch(A=>{m.destroy(A instanceof Error?A:new Error(String(A)))});let y=s.signal,b=await new Promise((A,M)=>{let N=this._requestTimeoutMs,F=setTimeout(()=>{Z(),M(new _(`HTTP/2 request to ${o} timed out after ${N}ms`,"ETIMEOUT",{request:s})),m.destroy()},N),$=()=>{clearTimeout(F),M(new _("Request was aborted","EABORT",{request:s})),m.destroy()},Z=()=>y?.removeEventListener("abort",$);y?.addEventListener("abort",$,{once:!0}),m.once("response",k=>{let P=Number(k[":status"]??200),v=xa[P]??"",L={};for(let[W,O]of Object.entries(k))W.startsWith(":")||(L[W]=Array.isArray(O)?O.join(", "):O??"");if(clearTimeout(F),Z(),y?.aborted){M(new _("Request was aborted","EABORT",{request:s})),m.destroy();return}if(s.redirect==="error"&&P>=300&&P<400&&L.location){M(new _(`Redirect not allowed (redirect:"error") \u2014 received ${P} to ${L.location}`,"ENETWORK",{request:s})),m.destroy();return}A({status:P,statusText:v,headers:L,body:wa(m),url:s.url,redirected:i,httpVersion:"HTTP/2",alreadyDecompressed:!1})}),m.once("error",k=>{clearTimeout(F),Z(),y?.aborted?M(new _("Request was aborted","EABORT",{request:s,cause:k})):M(new _(k.message,"ENETWORK",{request:s,cause:k})),m.destroy()})});if(!(b.status>=300&&b.status<400&&!!b.headers.location&&s.redirect!=="manual"))return b;try{if(b.body){let A=b.body.getReader();for(;;){let{done:M}=await A.read();if(M)break}A.releaseLock()}}catch{}let S=b.headers.location,R;try{R=new URL(S,s.url).href}catch{throw new _(`Invalid redirect Location: ${S}`,"ENETWORK",{request:e})}let C=b.status===301||b.status===302||b.status===303?"GET":s.method,T=C==="GET"||C==="HEAD"?null:s.body;s={...s,url:R,method:C,body:T},o=new URL(R),i=!0}throw new _("HTTP/2 redirect loop terminated unexpectedly","ENETWORK",{request:e})}_sendHTTP1(e){if(typeof globalThis.fetch=="function"){if(!this._http1Fallback){let t={fetchFn:globalThis.fetch,strict:this._strict};this._onDroppedHeader!==void 0&&(t.onDroppedHeader=this._onDroppedHeader),this._http1Fallback=new $e(t)}return this._http1Fallback.send(e)}return this._sendHTTP1Legacy(e)}async _sendHTTP1Legacy(e){let t=await import("node:https"),n=new URL(e.url),s={hostname:n.hostname,port:n.port||"443",path:n.pathname+n.search,method:e.method,headers:e.headers};return new Promise((o,i)=>{let a=t.request(s,u=>{let f={};for(let[p,g]of Object.entries(u.headers))g!==void 0&&(f[p]=Array.isArray(g)?g.join(", "):g);let d=zl(u);o({status:u.statusCode??200,statusText:u.statusMessage??"",headers:f,body:d,url:e.url,redirected:!1,httpVersion:"HTTP/1.1",alreadyDecompressed:!1})});a.once("error",u=>{i(new _(u.message,"ENETWORK",{request:e,cause:u}))});let c=()=>{a.destroy(),i(new _("Request was aborted","EABORT",{request:e}))};e.signal?.addEventListener("abort",c,{once:!0});let l=()=>e.signal?.removeEventListener("abort",c);a.once("close",l),a.once("error",l),e.body&&e.method!=="GET"&&e.method!=="HEAD"?Fl(a,e.body).catch(i):a.end()})}_evictSession(e,t){let n=this.pingTimers.get(e);n&&(clearInterval(n),this.pingTimers.delete(e)),this.sessions.delete(e),this.sessionUsage.delete(e),this._sessionCreating.delete(e),t&&!t.destroyed&&!t.closed&&t.destroy()}destroy(){for(let e of this.pingTimers.values())clearInterval(e);this.pingTimers.clear(),this._sessionCreating.clear();for(let[e,{session:t}]of this.sessions.entries())this._evictSession(e,t);this.sessions.clear()}};zl=wa;xa={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"}});function Vl(r){return r.split(Kl).filter(Boolean)}function Jl(r){let e=r.match(/^(\d{1,2}):(\d{2}):(\d{2})(?:[+-]\d{2}:?\d{2}|Z|GMT|UTC)?$/i);if(!e)return null;let t=+e[1],n=+e[2],s=+e[3];return t>23||n>59||s>59?null:[t,n,s]}function Ql(r){let e=r.slice(0,9).toLowerCase();return Wl[e]??null}function Gl(r){if(!/^\d{2,4}$/.test(r))return null;let e=+r;return e>=70&&e<=99&&(e+=1900),e>=0&&e<=69&&(e+=2e3),e}function Yt(r){if(!r)return null;let e=Vl(r),t={time:null,dayOfMonth:null,month:null,year:null};for(let a of e)if(a){if(t.time===null&&a.includes(":")){let c=Jl(a);if(c!==null){t.time=c;continue}}if(t.month===null&&/[a-zA-Z]/.test(a)){let c=Ql(a);if(c!==null){t.month=c;continue}}if(/^\d{1,4}(?:st|nd|rd|th)?$/i.test(a)){let c=a.replace(/[a-z]+$/i,""),l=+c;if(t.dayOfMonth===null&&c.length<=2&&l>=1&&l<=31){t.dayOfMonth=l;continue}if(t.year===null&&c.length>=2){let u=Gl(c);if(u!==null){t.year=u;continue}}if(t.dayOfMonth===null&&l>=1&&l<=31){t.dayOfMonth=l;continue}}}if(t.time===null||t.dayOfMonth===null||t.month===null||t.year===null||t.year<1601||t.year>9999||t.dayOfMonth<1||t.dayOfMonth>31)return null;let[n,s,o]=t.time,i=Date.UTC(t.year,t.month,t.dayOfMonth,n,s,o);return isNaN(i)?null:i}function gt(r){let e=r.replace(/\.$/,"").toLowerCase(),t=e.split(".");if(t.length===0||t.length===1&&t[0]==="")return null;if(zs.has(e))return e;let n=null,s=0;for(let o=0;o<t.length;o++){let i=t.slice(o).join(".");if(js.has(i)){let a=t.length-o;a>s&&(s=a,n=i)}}for(let o=0;o<t.length-1;o++){let i=t.slice(o+1).join(".");if(qs.has(i)){let a=t.slice(o).join("."),c=t.length-o;c>s&&(s=c,n=a)}}return n||(t[t.length-1]??null)}function Jr(r){let e=r.toLowerCase();if(me(e))return e;let t=gt(e);if(!t)return null;let n=t.split(".").length,s=e.split(".");return s.length<=n?null:s.slice(-(n+1)).join(".")}function yt(r){let e=r.toLowerCase();if(zs.has(e)||js.has(e))return!0;let t=e.split(".");if(t.length>=2){let n=t.slice(1).join(".");if(qs.has(n))return!0}return!1}function Yl(r){try{let c=r.lastIndexOf("-"),l=[],u=c>=0?r.slice(0,c):"";for(let S=0;S<u.length;S++){let R=u.charCodeAt(S);if(R>122||R>90&&R<97||R>57&&R<65||R<48)return r;l.push(R)}let f=c>=0?r.slice(c+1):r,d=128,p=0,g=72,m=S=>S>=65&&S<=90?S-65:S>=97&&S<=122?S-97:S>=48&&S<=57?S-48+26:-1,y=(S,R,C)=>{S=Math.floor(S/(C?700:2)),S+=Math.floor(S/R);let T=0;for(;S>910/2;)S=Math.floor(S/35),T+=36;return T+Math.floor(36*S/(S+38))},b=0;for(;b<f.length;){let S=p,R=1;for(let C=36;;C+=36){if(b>=f.length)return r;let T=m(f.charCodeAt(b++));if(T<0)return r;p+=T*R;let A=C<=g?1:C>=g+26?26:C-g;if(T<A)break;R*=36-A}g=y(p-S,l.length+1,S===0),d+=Math.floor(p/(l.length+1)),p%=l.length+1,l.splice(p,0,d),p++}return String.fromCodePoint(...l)||r}catch{return r}}function Zt(r){if(!r.toLowerCase().startsWith("xn--"))return r;let e=Intl;if(typeof Intl<"u"&&e.IDN&&typeof e.IDN.toUnicode=="function")try{return e.IDN.toUnicode(r,{standard:"tr46"})}catch{return r}if(Hs){let t=r+".invalid",n=Hs(t);if(n&&n.length>8&&n.endsWith(".invalid")){let s=n.slice(0,-8);if(s!==r)return s}}if(r.startsWith("xn--"))try{let t=Yl(r.slice(4));if(t&&t!==r.slice(4))return t}catch{}return r}function ce(r){return r.replace(/^\./,"").replace(/\.$/,"").toLowerCase().split(".").map(Zt).join(".")}function me(r){let e=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;return Zl.test(e)?e.split(".").map(Number).every(n=>n>=0&&n<=255):eu.test(e)&&e.includes(":")}function wt(r,e){let t=r.toLowerCase(),n=e.toLowerCase();return t===n?!0:!(me(t)||!t.endsWith("."+n)||me(n)||gt(t)===t)}function bt(r){if(!r||r===""||r[0]!=="/")return"/";let e=r.lastIndexOf("/");return e===0?"/":r.slice(0,e)}function Vr(r){if(!r.startsWith("/"))return"/"+r;let e=[],t=r.split("/");for(let n of t)n===""||n==="."||(n===".."?e.length>0&&e.pop():e.push(n));return"/"+e.join("/")}function xt(r,e){let t=Vr(r),n=Vr(e);return!!(t===n||t.startsWith(n)&&(n.endsWith("/")||t[n.length]==="/"))}function ru(r){return r===""?!0:tu.test(r)}function nu(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=0&&t<=8||t>=10&&t<=31||t===127)return!1}return!0}function _t(r){if(!r||r.trim()==="")return null;let e=r.indexOf(";"),t=e===-1?r:r.slice(0,e),n=e===-1?"":r.slice(e+1),s=t.indexOf("="),o,i;if(s===-1?(o="",i=t.trim()):(o=t.slice(0,s).trim(),i=t.slice(s+1).trim()),!ru(o)||(i.length>=2&&i[0]==='"'&&i[i.length-1]==='"'&&(i=i.slice(1,-1)),!nu(i)))return null;let a=new Map,c=n.split(";");for(let A of c){let M=A.trim();if(!M)continue;let N=M.indexOf("=");if(N===-1)a.set(M.toLowerCase(),"");else{let F=M.slice(0,N).trim().toLowerCase(),$=M.slice(N+1).trim();a.has(F)||a.set(F,$)}}let l=a.has("domain")?a.get("domain"):null,u=a.has("path")?a.get("path"):null,f=a.has("expires")?a.get("expires"):null,d=a.has("max-age")?a.get("max-age"):null,p=a.has("secure"),g=a.has("httponly"),m="Unset";if(a.has("samesite")){let A=a.get("samesite").toLowerCase();A==="strict"?m="Strict":A==="lax"?m="Lax":A==="none"&&(m="None")}let y=a.has("sameparty"),b=null;if(a.has("priority")){let A=a.get("priority").toLowerCase();A==="low"?b="Low":A==="medium"?b="Medium":A==="high"&&(b="High")}let x=a.has("partitioned"),S=null;d!==null&&d.match(/^-?\d+$/)&&(S=parseInt(d,10));let R=null;S===null&&f!==null&&(R=Yt(f));let C=null;l!==null&&l!==""&&(C=ce(l));let T=null;return u!==null&&u.startsWith("/")&&(T=u),{name:o,value:i,domain:C,path:T,expires:R,maxAge:S,secure:p,httpOnly:g,sameSite:m,sameParty:y,priority:b,partitioned:x}}function Sa(r){let e=[];if(r.value.includes(";")||r.value.includes(",")||r.value.includes(" ")||r.value.includes('"')?e.push(`${r.name}="${r.value.replace(/"/g,'\\"')}"`):e.push(`${r.name}=${r.value}`),r.path&&e.push(`Path=${r.path}`),r.domain&&e.push(`Domain=${r.domain}`),r.expires!==null){let t=new Date(r.expires);e.push(`Expires=${t.toUTCString()}`)}return r.maxAge!==null&&e.push(`Max-Age=${r.maxAge}`),r.secure&&e.push("Secure"),r.httpOnly&&e.push("HttpOnly"),r.sameSite&&r.sameSite!=="Unset"&&e.push(`SameSite=${r.sameSite}`),r.sameParty&&e.push("SameParty"),r.priority&&e.push(`Priority=${r.priority}`),r.partitioned&&e.push("Partitioned"),e.join("; ")}function qe(r){let e=[],t="",n=0,s=!1,o=!1,i=!1,a=!1,c=!1,l=()=>{i&&a&&t.trim()&&e.push(t.trim()),t="",i=!1,a=!1,c=!1};for(;n<r.length;){let u=r[n],f=r[n+1]??"";if(o){t+=u,o=!1,n++;continue}if(u==="\\"&&(s||f==='"'||f==="\\")){t+=u,o=!0,n++;continue}if(u==='"'){!s&&i?s=!0:s&&(s=!1,a=!0),t+=u,n++;continue}if(s){t+=u,n++;continue}if(u===","&&!s&&(c||a||i)){for(l();n+1<r.length&&/\s/.test(r[n+1]);)n++;n++;continue}if(u===";"){i||(i=!0),a&&(c=!0),t+=u,n++;continue}if(u==="="&&!i){i=!0,a=!0,t+=u,n++;continue}if(i&&!a&&u!==";"&&u!==","&&(a=!0),u===" "||u===" "){t.length>0&&t.trim()!==""&&(t+=u),n++;continue}t+=u,n++}return i&&a&&t.trim()&&e.push(t.trim()),e}function St(r){if(typeof Headers<"u"&&r instanceof Headers){if(typeof r.getSetCookie=="function")return r.getSetCookie();let n=r.get("set-cookie");return n?qe(n):[]}let e=r,t=e["set-cookie"]??e["Set-Cookie"];return t?Array.isArray(t)?t.flatMap(n=>qe(n)):qe(t):[]}var Wl,Kl,Xl,js,qs,zs,Hs,Zl,eu,tu,Qr=q(()=>{"use strict";Wl={jan:0,january:0,feb:1,february:1,mar:2,march:2,apr:3,april:3,may:4,jun:5,june:5,jul:6,july:6,aug:7,august:7,sep:8,september:8,oct:9,october:9,nov:10,november:10,dec:11,december:11},Kl=/[\t\x20-\x2f\x3b-\x40\x5b-\x60\x7b-\x7e]+/;Xl=["!www.ck","!city.kobe.jp","!city.nagoya.jp","!city.sapporo.jp","!city.sendai.jp","!city.yokohama.jp","*.ck","*.er","*.bd","*.fj","*.fk","*.gu","*.jm","*.kh","*.mm","*.np","*.pg","*.ss","*.tp","*.vi","*.ye","*.zm","*.kawasaki.jp","*.kitakyushu.jp","*.kobe.jp","*.nagoya.jp","*.osaka.jp","*.sapporo.jp","*.sendai.jp","*.yokohama.jp","com","net","org","edu","gov","mil","int","arpa","info","biz","name","mobi","tel","travel","museum","coop","aero","pro","jobs","cat","post","xxx","app","dev","io","ai","co","me","tv","fm","blog","shop","store","online","site","web","tech","cloud","digital","media","news","press","agency","solutions","services","systems","network","group","team","studio","design","art","photography","email","marketing","consulting","management","finance","money","bank","insurance","healthcare","medical","hospital","clinic","pharmacy","dental","legal","law","attorney","lawyer","accountant","pm","sh","ac","cc","cx","nu","ms","pw","sc","sx","tc","tk","ac","ad","ae","af","ag","ai","al","am","an","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","su","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","uk","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","yt","za","zm","zw","com.au","net.au","org.au","edu.au","gov.au","asn.au","id.au","info.au","conf.au","oz.au","act.au","nsw.au","nt.au","qld.au","sa.au","tas.au","vic.au","wa.au","com.br","net.br","org.br","edu.br","gov.br","mil.br","art.br","ind.br","adm.br","adv.br","agr.br","am.br","arq.br","ato.br","b.br","bio.br","blog.br","bmd.br","cim.br","cng.br","cnt.br","coop.br","ecn.br","eco.br","emp.br","eng.br","esp.br","etc.br","eti.br","far.br","flog.br","fm.br","fnd.br","fot.br","fst.br","g12.br","ggf.br","imb.br","inf.br","jor.br","jus.br","leg.br","lel.br","mat.br","med.br","mp.br","mus.br","not.br","ntr.br","odo.br","ppg.br","pro.br","psc.br","psi.br","qsl.br","radio.br","rec.br","slg.br","srv.br","taxi.br","teo.br","tmp.br","trd.br","tur.br","tv.br","vet.br","vlog.br","wiki.br","zlg.br","ab.ca","bc.ca","mb.ca","nb.ca","nf.ca","nl.ca","ns.ca","nt.ca","nu.ca","on.ca","pe.ca","qc.ca","sk.ca","yk.ca","com.cn","net.cn","org.cn","edu.cn","gov.cn","mil.cn","ac.cn","ah.cn","bj.cn","cq.cn","fj.cn","gd.cn","gs.cn","gz.cn","gx.cn","ha.cn","hb.cn","he.cn","hi.cn","hl.cn","hn.cn","jl.cn","js.cn","jx.cn","ln.cn","nm.cn","nx.cn","qh.cn","sc.cn","sd.cn","sh.cn","sn.cn","sx.cn","tj.cn","xj.cn","xz.cn","yn.cn","zj.cn","co.uk","me.uk","org.uk","ltd.uk","plc.uk","net.uk","sch.uk","gov.uk","nhs.uk","police.uk","mod.uk","ac.uk","judiciary.uk","parliament.uk","co.jp","ne.jp","or.jp","ac.jp","ad.jp","ed.jp","go.jp","gr.jp","lg.jp","aichi.jp","akita.jp","aomori.jp","chiba.jp","ehime.jp","fukui.jp","fukuoka.jp","fukushima.jp","gifu.jp","gunma.jp","hiroshima.jp","hokkaido.jp","hyogo.jp","ibaraki.jp","ishikawa.jp","iwate.jp","kagawa.jp","kagoshima.jp","kanagawa.jp","kochi.jp","kumamoto.jp","kyoto.jp","mie.jp","miyagi.jp","miyazaki.jp","nagano.jp","nagasaki.jp","nara.jp","niigata.jp","oita.jp","okayama.jp","okinawa.jp","osaka.jp","saga.jp","saitama.jp","shiga.jp","shimane.jp","shizuoka.jp","tochigi.jp","tokushima.jp","tokyo.jp","tottori.jp","toyama.jp","wakayama.jp","yamagata.jp","yamaguchi.jp","yamanashi.jp","co.nz","net.nz","org.nz","edu.nz","govt.nz","school.nz","geek.nz","maori.nz","iwi.nz","mil.nz","parliament.nz","ac.nz","co.za","net.za","org.za","edu.za","gov.za","mil.za","ac.za","alt.za","agric.za","cybernet.za","db.za","grondar.za","nis.za","nom.za","ngo.za","pty.za","school.za","tm.za","web.za","co.in","net.in","org.in","edu.in","gov.in","mil.in","ac.in","res.in","firm.in","gen.in","ind.in","int.in","nic.in","com.ar","net.ar","org.ar","edu.ar","gov.ar","mil.ar","int.ar","tur.ar","com.mx","net.mx","org.mx","edu.mx","gob.mx","com.sg","net.sg","org.sg","edu.sg","gov.sg","per.sg","com.hk","net.hk","org.hk","edu.hk","gov.hk","idv.hk","com.tw","net.tw","org.tw","edu.tw","gov.tw","mil.tw","idv.tw","game.tw","ebiz.tw","club.tw","com.my","net.my","org.my","edu.my","gov.my","mil.my","name.my","sch.my","com.ph","net.ph","org.ph","edu.ph","gov.ph","mil.ph","ngo.ph","i.ph","com.pk","net.pk","org.pk","edu.pk","gov.pk","mil.pk","ac.pk","res.pk","biz.pk","fam.pk","gob.pk","gok.pk","gon.pk","gop.pk","gos.pk","info.pk","com.eg","net.eg","org.eg","edu.eg","gov.eg","mil.eg","sci.eg","eun.eg","info.eg","name.eg","com.sa","net.sa","org.sa","edu.sa","gov.sa","med.sa","pub.sa","sch.sa","com.ae","net.ae","org.ae","edu.ae","gov.ae","mil.ae","sch.ae","ac.ae","pro.ae","name.ae","com.tr","net.tr","org.tr","edu.tr","gov.tr","mil.tr","bel.tr","k12.tr","av.tr","bbs.tr","dr.tr","gen.tr","info.tr","name.tr","pol.tr","tel.tr","web.tr","com.ua","net.ua","org.ua","edu.ua","gov.ua","mil.ua","in.ua","co.ua","cherkassy.ua","chernigov.ua","chernovtsy.ua","dn.ua","dnepropetrovsk.ua","donetsk.ua","dp.ua","if.ua","kh.ua","kharkov.ua","kherson.ua","khmelnitskiy.ua","kiev.ua","kirovograd.ua","km.ua","kr.ua","lg.ua","lugansk.ua","lutsk.ua","lviv.ua","mk.ua","mykolaiv.ua","nikolaev.ua","od.ua","odessa.ua","pl.ua","poltava.ua","rivne.ua","rovno.ua","rv.ua","sebastopol.ua","sumy.ua","te.ua","ternopil.ua","uzhgorod.ua","vinnica.ua","vn.ua","volyn.ua","yalta.ua","zp.ua","zaporizhzhe.ua","zt.ua","zhitomir.ua","com.ru","net.ru","org.ru","edu.ru","gov.ru","mil.ru","pp.ru","int.ru","ac.ru","msk.ru","spb.ru","com.pl","net.pl","org.pl","edu.pl","gov.pl","mil.pl","co.pl","info.pl","biz.pl","nom.pl","waw.pl","poznan.pl","lodz.pl","krakow.pl","wroclaw.pl","com.de","co.de","com.fr","co.fr","asso.fr","nom.fr","prd.fr","presse.fr","tm.fr","aeroport.fr","assedic.fr","avocat.fr","avoues.fr","cci.fr","chambagri.fr","chirurgiens-dentistes.fr","experts-comptables.fr","geometre-expert.fr","gouv.fr","greta.fr","huissier-justice.fr","medecin.fr","notaires.fr","pharmacien.fr","port.fr","veterinaire.fr","com.it","co.it","com.es","co.es","nom.es","org.es","edu.es","gob.es","com.nl","co.nl","com.be","co.be","ac.be","org.be","net.be","com.ch","co.ch","com.at","co.at","ac.at","gv.at","or.at","priv.at","com.se","co.se","ac.se","bd.se","brand.se","fh.se","fhsk.se","fhv.se","tm.se","pp.se","press.se","parti.se","komforb.se","kommunalforbund.se","komvux.se","lanarb.se","lanbib.se","naturbruksgymn.se","sshn.se","com.no","co.no","stat.no","fylkesbibl.no","folkebibl.no","museum.no","idrett.no","priv.no","mil.no","vgs.no","videregaaende.no","kommune.no","herad.no","aa.no","ah.no","bu.no","fm.no","hl.no","hm.no","jan-mayen.no","mr.no","nl.no","nt.no","of.no","ol.no","oslo.no","rl.no","sf.no","st.no","svalbard.no","tm.no","tr.no","va.no","vf.no","com.dk","co.dk","ac.dk","com.fi","co.fi","ac.fi","iki.fi","aland.fi","www.fi","com.pt","co.pt","edu.pt","gov.pt","int.pt","net.pt","nome.pt","org.pt","publ.pt","dyndns.pt","com.gr","co.gr","edu.gr","gov.gr","net.gr","org.gr","store.gr","com.ie","co.ie","gov.ie","net.ie","org.ie","teagasc.ie","com.cz","co.cz","edu.cz","net.cz","org.cz","info.cz","com.sk","co.sk","edu.sk","net.sk","org.sk","com.hu","co.hu","edu.hu","film.hu","gov.hu","info.hu","net.hu","org.hu","priv.hu","sport.hu","tm.hu","2000.hu","agrar.hu","bolt.hu","casino.hu","city.hu","erotica.hu","erotika.hu","forum.hu","games.hu","hotel.hu","ingatlan.hu","jogasz.hu","konyvelo.hu","lakas.hu","media.hu","news.hu","reklam.hu","sex.hu","shop.hu","suli.hu","szex.hu","tozsde.hu","utazas.hu","video.hu","com.ro","co.ro","edu.ro","gov.ro","info.ro","net.ro","nom.ro","org.ro","rec.ro","store.ro","tm.ro","www.ro","arts.ro","firm.ro","nt.ro","shop.ro","com.bg","co.bg","edu.bg","gov.bg","net.bg","org.bg","tel.bg","biz.bg","com.hr","co.hr","from.hr","iz.hr","name.hr","net.hr","com.rs","co.rs","edu.rs","gov.rs","in.rs","net.rs","org.rs","com.ba","co.ba","edu.ba","gov.ba","mil.ba","net.ba","org.ba","rs.ba","unbi.ba","unmo.ba","unsa.ba","untz.ba","unze.ba","com.co","net.co","org.co","edu.co","gov.co","mil.co","nom.co","com.ve","net.ve","org.ve","edu.ve","gov.ve","mil.ve","int.ve","co.ve","arts.ve","bib.ve","firm.ve","info.ve","nom.ve","rec.ve","store.ve","tec.ve","web.ve","com.pe","net.pe","org.pe","edu.pe","gov.pe","mil.pe","nom.pe","sld.pe","com.cl","co.cl","gob.cl","gov.cl","net.cl","org.cl","mil.cl","edu.cl","co.kr","ne.kr","or.kr","re.kr","pe.kr","go.kr","mil.kr","ac.kr","hs.kr","ms.kr","es.kr","sc.kr","kg.kr","seoul.kr","busan.kr","daegu.kr","incheon.kr","gwangju.kr","daejeon.kr","ulsan.kr","gyeonggi.kr","gangwon.kr","chungbuk.kr","chungnam.kr","jeonbuk.kr","jeonnam.kr","gyeongbuk.kr","gyeongnam.kr","jeju.kr","co.id","net.id","or.id","ac.id","web.id","sch.id","go.id","mil.id","my.id","co.th","net.th","org.th","ac.th","go.th","in.th","mi.th","com.vn","net.vn","org.vn","edu.vn","gov.vn","int.vn","ac.vn","biz.vn","info.vn","name.vn","pro.vn","health.vn","com.ng","net.ng","org.ng","edu.ng","gov.ng","mil.ng","mobi.ng","name.ng","sch.ng","co.ke","or.ke","ne.ke","go.ke","ac.ke","sc.ke","me.ke","mobi.ke","co.il","net.il","org.il","edu.il","gov.il","muni.il","ac.il","idf.il","com.ir","net.ir","org.ir","edu.ir","gov.ir","ac.ir","id.ir"],js=new Set,qs=new Set,zs=new Set;for(let r of Xl)r.startsWith("!")?zs.add(r.slice(1).toLowerCase()):r.startsWith("*.")?qs.add(r.slice(2).toLowerCase()):js.add(r.toLowerCase());(async()=>{try{let r=await import("node:url");typeof r.domainToUnicode=="function"&&(Hs=r.domainToUnicode)}catch{}})();Zl=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,eu=/^[\da-f:]+$/i;tu=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});function au(r,e){let t=r.name;return!(t.startsWith("__Secure-")&&(!r.secure||e.protocol!=="https:")||t.startsWith("__Host-")&&(!r.secure||e.protocol!=="https:"||r.path!=="/"||!r.hostOnly))}function cu(r,e){switch(r){case"Strict":return e==="strict";case"Lax":return e==="strict"||e==="lax";case"Unset":return e!=="cross-site";case"None":return!0}}function Bs(r){try{return new URL(r)}catch{return null}}function Gr(){return new Se}function Xr(r){return Se.fromJSON(r)}var su,ou,iu,Ta,Se,Ea=q(()=>{"use strict";Qr();su=4096,ou=50,iu=3e3,Ta=400*24*60*60*1e3;Se=class r{constructor(e={}){h(this,"dm",new Map);h(this,"total",0);h(this,"cleanupTimer",null);h(this,"maxTotal");h(this,"maxPerDomain");h(this,"domainMatcherFn");this.maxTotal=e.maxTotal??iu,this.maxPerDomain=e.maxPerDomain??ou,this.domainMatcherFn=e.domainMatcher??null,this.cleanupTimer=setInterval(()=>{this.clearExpired()},300*1e3),typeof this.cleanupTimer=="object"&&this.cleanupTimer!==null&&"unref"in this.cleanupTimer&&this.cleanupTimer.unref()}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}setCookie(e,t){let n=Bs(t.url);if(!n)return!1;let s=_t(e);if(!s)return!1;let o=Date.now(),i=n.hostname.toLowerCase(),a=i.replace(/^\[|\]$/g,""),c=n.protocol==="https:"||a==="localhost"||a==="127.0.0.1"||a==="::1";if(s.name.length+1+s.value.length>su)return!1;let u,f;if(s.domain!==null&&s.domain!==""){let b=s.domain;if(!(this.domainMatcherFn??wt)(i,b)||yt(b))return!1;u=b,f=!1}else u=i,f=!0;let d=s.path??bt(n.pathname),p=s.secure;if(p&&!c)return!1;let g=s.sameSite;if(g==="None"&&!p)return!1;let m;if(s.maxAge!==null){if(s.maxAge<=0)return this.removeCookie(u,d,s.name),!0;let b=Math.min(s.maxAge*1e3,Ta);m=o+b}else if(s.expires!==null){if(m=s.expires,m<=o)return this.removeCookie(u,d,s.name),!0;m=Math.min(m,o+Ta)}else m=1/0;let y={name:s.name,value:s.value,domain:u,path:d,expires:m,maxAge:s.maxAge,secure:p,httpOnly:s.httpOnly,sameSite:g,createdAt:o,lastAccessed:o,hostOnly:f};return au(y,n)?(this.putCookie(y),!0):!1}getCookies(e){Math.random()<.01&&this.clearExpired();let t=Bs(e.url);if(!t)return[];let n=t.hostname.toLowerCase(),s=n.replace(/^\[|\]$/g,""),o=t.pathname||"/",i=t.protocol==="https:"||s==="localhost"||s==="127.0.0.1"||s==="::1",a=e.http!==!1,c=e.sameSiteContext??"none",l=Date.now(),u=[];for(let[d,p]of this.dm)if(this.matchDomain(n,d))for(let[,g]of p)for(let[,m]of g)m.hostOnly&&n!==m.domain||m.expires!==1/0&&m.expires<l||xt(o,m.path)&&(m.secure&&!i||m.httpOnly&&!a||cu(m.sameSite,c)&&u.push(m));u.sort((d,p)=>{let g=p.path.length-d.path.length;return g!==0?g:d.createdAt-p.createdAt});let f=Date.now();for(let d of u)d.lastAccessed=f;return u}getCookieHeader(e){return this.getCookies(e).map(t=>t.name?`${t.name}=${t.value}`:t.value).join("; ")}getCookiesForDomain(e){let t=ce(e),n=[];for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t))for(let[,i]of o)for(let[,a]of i)a.expires!==1/0&&a.expires<Date.now()||n.push(a);return n}processResponseHeaders(e,t){for(let n of St(e))this.setCookie(n,t)}removeCookie(e,t,n){let s=ce(e),o=this.dm.get(s);if(!o)return!1;let i=o.get(t);if(!i)return!1;let a=i.delete(n);return a&&(this.total--,i.size===0&&o.delete(t),o.size===0&&this.dm.delete(s)),a}clear(){this.dm.clear(),this.total=0}clearExpired(){let e=Date.now(),t=0;for(let[n,s]of this.dm){for(let[o,i]of s){for(let[a,c]of i)c.expires!==1/0&&c.expires<e&&(i.delete(a),this.total--,t++);i.size===0&&s.delete(o)}s.size===0&&this.dm.delete(n)}return t}clearSession(){let e=0;for(let[t,n]of this.dm){for(let[s,o]of n){for(let[i,a]of o)a.expires===1/0&&(o.delete(i),this.total--,e++);o.size===0&&n.delete(s)}n.size===0&&this.dm.delete(t)}return e}clearForDomain(e){let t=ce(e),n=0;for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t)){let i=0;for(let a of o.values())i+=a.size;this.dm.delete(s),this.total-=i,n+=i}return n}clearForUrl(e){let t=Bs(e);return t?this.clearForDomain(t.hostname):0}toJSON(){let e=Date.now(),t=[];for(let[,n]of this.dm)for(let[,s]of n)for(let[,o]of s)o.expires!==1/0&&o.expires<e||t.push({name:o.name,value:o.value,domain:o.domain,path:o.path,expires:o.expires===1/0?null:o.expires,maxAge:o.maxAge,secure:o.secure,httpOnly:o.httpOnly,sameSite:o.sameSite,createdAt:o.createdAt,lastAccessed:o.lastAccessed,hostOnly:o.hostOnly});return t}toString(){return JSON.stringify(this.toJSON(),null,2)}static fromJSON(e){let t=new r,n=typeof e=="string"?JSON.parse(e):e,s=Date.now();for(let o of n){let i=o.expires===null?1/0:o.expires;if(i!==1/0&&i<s)continue;let a={name:o.name,value:o.value,domain:o.domain,path:o.path,expires:i,maxAge:o.maxAge,secure:o.secure,httpOnly:o.httpOnly,sameSite:o.sameSite,createdAt:o.createdAt,lastAccessed:o.lastAccessed,hostOnly:o.hostOnly};t.putCookie(a)}return t}get count(){return this.total}getAll(){let e=[];for(let[,t]of this.dm)for(let[,n]of t)for(let[,s]of n)e.push({...s});return e}getForDomain(e){let t=ce(e),n=[];for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t))for(let[,i]of o)for(let[,a]of i)n.push({...a});return n}putCookie(e){let{domain:t,path:n,name:s}=e;this.dm.has(t)||this.dm.set(t,new Map);let o=this.dm.get(t);o.has(n)||o.set(n,new Map);let i=o.get(n);if(i.has(s)){let a=i.get(s);i.set(s,{...e,createdAt:a.createdAt})}else this.evictForDomain(t,o),this.evictGlobal(),i.set(s,e),this.total++}evictForDomain(e,t){let n=0;for(let i of t.values())n+=i.size;if(n<this.maxPerDomain)return;let s=[];for(let[i,a]of t)for(let[c,l]of a)s.push([i,c,l]);s.sort((i,a)=>i[2].lastAccessed-a[2].lastAccessed);let o=0;for(;n>=this.maxPerDomain&&o<s.length;){let[i,a]=s[o++];t.get(i)?.delete(a)&&(this.total--,n--)}for(let[i,a]of t)a.size===0&&t.delete(i)}evictGlobal(){if(this.total<this.maxTotal)return;let e=[];for(let[n,s]of this.dm)for(let[o,i]of s)for(let[a,c]of i)e.push([n,o,a,c]);e.sort((n,s)=>n[3].lastAccessed-s[3].lastAccessed);let t=0;for(;this.total>=this.maxTotal&&t<e.length;){let[n,s,o]=e[t++],i=this.dm.get(n),a=i?.get(s);a?.delete(o)&&(this.total--,a.size===0&&i.delete(s),i.size===0&&this.dm.delete(n))}}matchDomain(e,t){return this.domainMatcherFn?this.domainMatcherFn(e,t):e===t?!0:me(e)?!1:e.endsWith("."+t)}}});var Ra={};ue(Ra,{CookieJar:()=>Se,canonicalizeDomainFull:()=>ce,createCookieJar:()=>Gr,decodeIDNLabel:()=>Zt,defaultPath:()=>bt,domainMatch:()=>wt,extractSetCookieHeaders:()=>St,formatSetCookieHeader:()=>Sa,getPublicSuffix:()=>gt,getRegistrableDomain:()=>Jr,isIPAddress:()=>me,isPublicSuffix:()=>yt,loadCookieJar:()=>Xr,normalizePath:()=>Vr,parseCookieDate:()=>Yt,parseSetCookieHeader:()=>_t,pathMatch:()=>xt,splitSetCookieHeaders:()=>qe});var Fs=q(()=>{"use strict";Ea();Qr()});var Ca={};ue(Ca,{BatchingTransport:()=>Rt,ConsoleTransport:()=>ze,HTTPLogger:()=>Ee,JSONTransport:()=>Et,LogLevel:()=>Tt,MultiTransport:()=>At,Redactor:()=>Ct,RemoteTransport:()=>kt,createDevelopmentLogger:()=>Js,createLogger:()=>Ks,createProductionLogger:()=>Vs,toOTelSpan:()=>Ws});function mu(){let r=Date.now().toString(36),e=(++pu).toString(36).padStart(4,"0"),t=Math.random().toString(36).slice(2,6);return`${r}-${e}-${t}`}function Aa(r,e){if(!r||typeof r!="object"||e.length===0)return;let[t,...n]=e;if(t===void 0)return;let s=r;if(n.length===0){t in s&&(s[t]="***");return}typeof s[t]=="object"&&Aa(s[t],n)}function ka(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}function Ws(r){let e={"http.request.id":r.requestId,"http.request.method":r.method,"url.full":r.url};return r.type==="response"&&(e["http.response.status_code"]=r.status,e["http.response.body.size"]=r.bodySize,e["http.time_to_first_byte"]=r.durationMs),r.type==="error"&&(e.error=!0,e["error.type"]=r.error.name,e["error.message"]=r.error.message,e["http.status_code"]=r.status),e}function gu(r){if(r instanceof Error){let e=r.code,t=r.stack;return{name:r.name,message:r.message,...e!==void 0?{code:e}:{},...t!==void 0?{stack:t}:{}}}return{name:"Error",message:String(r)}}function Yr(){return typeof performance<"u"?performance.now():Date.now()}function Ks(r){return new Ee(r)}function Vs(r){let e=[new Et];return r.endpoint&&e.push(new Rt(new kt(r.endpoint))),new Ee({level:r.level??"INFO",transports:[new At(e)],...r.context!==void 0?{context:r.context}:{}})}function Js(r={}){return new Ee({level:r.level??"DEBUG",transports:[new ze({pretty:!0,useColors:!0,onWrite:e=>console.log(e)})],redaction:{logRequestBody:r.logBodies??!0,logResponseBody:r.logBodies??!0,maxBodyLength:2048}})}var lu,Tt,uu,hu,fu,ze,du,Et,Rt,kt,At,pu,Ct,Te,Ee,Zr=q(()=>{"use strict";lu=()=>{try{return globalThis.process?.env?.NODE_ENV}catch{return}},Tt={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},uu=["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-refresh-token","x-csrf-token","x-session-id","x-session-token","x-secret","x-secret-key","x-private-key","api-key","apikey","bearer","token","authentication","credentials","password","passwd","secret"],hu=["token","api_key","apikey","access_token","refresh_token","secret","password","pass","pwd","key","auth"],fu=["application/json","application/x-www-form-urlencoded","text/"],ze=class{constructor(e={pretty:!1,onWrite:t=>console.log(t)}){h(this,"pretty");h(this,"onWrite");this.pretty=e.pretty??lu()!=="production",this.onWrite=e.onWrite,e.useColors}write(e){let t=this.pretty?this._prettyFormat(e):JSON.stringify(e);this.onWrite(t)}_prettyFormat(e){let t=new Date(e.timestampMs).toISOString().slice(11,23),n=e.level.padEnd(5),s=e.requestId.slice(-8);if(e.type==="request")return`[${t}] ${n} \u2190 ${e.method} ${e.url} [${s}]`;if(e.type==="response"){let o=`${e.durationMs.toFixed(0)}ms`,i=e.cached?" (cached)":"";return`[${t}] ${n} \u2192 ${e.status} ${e.method} ${e.url} ${o}${i} [${s}]`}return`[${t}] ${n} \u2717 ${e.method} ${e.url} ${e.error.message} [${s}]`}},du=()=>{try{return typeof globalThis.process?.stdout?.write=="function"}catch{return!1}},Et=class{constructor(e=t=>{du()?globalThis.process.stdout.write(t+`
|
|
5
|
-
`):console.log(t)}){h(this,"writeLine");this.writeLine=e}write(e){this.writeLine(JSON.stringify(e))}},
|
|
6
|
-
`),retry:this.retry,raw:[...this.lines]};return this.lines=[],this.event="message",this.data=[],this.retry=null,e}reset(){this.lines=[],this.id=null,this.event="message",this.data=[],this.retry=null,this.buffer=""}get lastId(){return this.id}},
|
|
1
|
+
/* kinetex v1.2.0 | MIT | https://github.com/kinetexjs/kinetex */
|
|
2
|
+
"use strict";var kinetex=(()=>{var Qc=Object.create;var Ot=Object.defineProperty;var Gc=Object.getOwnPropertyDescriptor;var Xc=Object.getOwnPropertyNames;var Yc=Object.getPrototypeOf,Zc=Object.prototype.hasOwnProperty;var Jo=r=>{throw TypeError(r)};var el=(r,e,t)=>e in r?Ot(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var Ge=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var F=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var fe=(r,e)=>{for(var t in e)Ot(r,t,{get:e[t],enumerable:!0})},Qo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xc(e))!Zc.call(r,s)&&s!==t&&Ot(r,s,{get:()=>e[s],enumerable:!(n=Gc(e,s))||n.enumerable});return r};var Xe=(r,e,t)=>(t=r!=null?Qc(Yc(r)):{},Qo(e||!r||!r.__esModule?Ot(t,"default",{value:r,enumerable:!0}):t,r)),tl=r=>Qo(Ot({},"__esModule",{value:!0}),r);var h=(r,e,t)=>el(r,typeof e!="symbol"?e+"":e,t),rl=(r,e,t)=>e.has(r)||Jo("Cannot "+t);var Go=(r,e,t)=>e.has(r)?Jo("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t);var se=(r,e,t)=>(rl(r,e,"access private method"),t);function nl(){if(dr)return dr;let r=globalThis;if(r.process?.hrtime)return dr=r.process,dr}function sl(){if(pr)return pr;let r=globalThis;if(r.Buffer&&typeof r.Buffer.isBuffer=="function")return pr=r.Buffer,pr}function de(r,e={}){let t={...ol,...e};if(r.length>t.maxStringLength)return{success:!1,error:"STRING_TOO_LONG",message:`JSON string length exceeds limit of ${t.maxStringLength}`};let n=0,s=!1,o=!1;for(let i=0;i<r.length;i++){let a=r[i];if(o){o=!1;continue}if(a==="\\"){s&&(o=!0);continue}if(a==='"'){s=!s;continue}if(!s)if(a==="{"||a==="["){if(++n>t.maxDepth)return{success:!1,error:"DEPTH_EXCEEDED",message:`JSON depth exceeds limit of ${t.maxDepth}`}}else(a==="}"||a==="]")&&n--}try{let i=JSON.parse(r);return xn(i,t,0)?!t.allowNonFinite&&_n(i)?{success:!1,error:"NON_FINITE_NUMBER",message:"JSON contains NaN or Infinity values"}:{success:!0,value:i}:{success:!1,error:"VALIDATION_FAILED",message:"Parsed value exceeds size limits"}}catch{return{success:!1,error:"PARSE_ERROR",message:"Failed to parse JSON"}}}function xn(r,e,t){if(t>e.maxDepth)return!1;if(r==null)return!0;if(typeof r=="string")return r.length<=e.maxStringLength;if(typeof r=="number"||typeof r=="boolean")return!0;if(Array.isArray(r))return r.length>e.maxArrayLength?!1:r.every(n=>xn(n,e,t+1));if(typeof r=="object"){let n=Object.keys(r);if(n.length>e.maxObjectKeys||n.includes("__proto__"))return!1;if(n.includes("constructor")){let s=r.constructor;if(typeof s=="object"&&s!==null){let o=Object.keys(s);if(o.includes("prototype")||o.includes("__proto__"))return!1}}return n.every(s=>xn(r[s],e,t+1))}return!0}function _n(r){return typeof r=="number"&&!Number.isFinite(r)?!0:Array.isArray(r)?r.some(_n):typeof r=="object"&&r!==null?Object.values(r).some(_n):!1}function li(r){let e=de(r);return e.success?e.value:r}function M(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r)){for(let t=0;t<r.length;t++)r[t]=M(r[t]);return r}let e=r;for(let t of Object.keys(e)){if(t==="__proto__"||t==="constructor"||t==="prototype"){delete e[t];continue}M(e[t])}return r}function ui(r){return de(r,{maxDepth:16,maxStringLength:1*1024*1024,maxArrayLength:1e3,maxObjectKeys:100})}function hi(r){return r instanceof Uint8Array}function fi(r){return r instanceof ArrayBuffer}function di(r){return r!==null&&typeof r=="object"&&"getReader"in r&&typeof r.getReader=="function"}function pi(r){return r!==null&&typeof r=="object"&&"forEach"in r&&typeof r.forEach=="function"}function mi(r){return r!==null&&typeof r=="object"&&"aborted"in r&&typeof r.aborted=="boolean"}function gi(r){return r!==null&&typeof r=="object"&&Object.prototype.toString.call(r)==="[object Object]"}function yi(r){return r!==null&&typeof r=="object"&&r.constructor?.name==="FormData"}function wi(r){return r!==null&&typeof r=="object"&&r.constructor?.name==="Blob"}function bi(r){return r!==null&&typeof r=="object"&&"has"in r&&typeof r.has=="function"}function Me(r){return typeof r!="string"||r.length===0||r.length>4096?!1:il.test(r)}function we(r){if(typeof r!="string"||r.length>8192)return!1;for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t<32&&t!==9||t===127||t===13||t===10)return!1}return!0}function Ut(r){return cl.some(([e,t])=>r>=e&&r<=t)}function bn(r){return r===""?null:/^0[xX][0-9a-fA-F]+$/.test(r)?parseInt(r,16):/^0[0-7]+$/.test(r)?parseInt(r,8):/^\d+$/.test(r)?parseInt(r,10):null}function xi(r){if(r.includes(":")||!/^[0-9a-fA-FxX.]+$/.test(r))return null;let e=r.endsWith(".")?r.slice(0,-1):r;if(e==="")return null;let t=e.split(".");if(t.length>4||t.length<1)return null;if(t.length===1){let i=bn(t[0]);return i===null||i>4294967295?null:i>>>0}let n=[];for(let i=0;i<t.length-1;i++){let a=bn(t[i]);if(a===null||a>255)return null;n.push(a)}let s=bn(t[t.length-1]),o=2**(8*(5-t.length));if(s===null||s>=o)return null;for(let i=8*(4-t.length);i>=0;i-=8)n.push(s>>>i&255);return(n[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0}function ll(r){if(!r.includes(":"))return null;let e=r.split("%")[0],t=e.split("::");if(t.length>2)return null;let n=o=>{if(o==="")return[];let i=o.split(":"),a=[];for(let c=0;c<i.length;c++){let l=i[c];if(l==="")return null;if(l.includes(".")){if(c!==i.length-1)return null;let u=xi(l);if(u===null)return null;a.push(u>>>24&255,u>>>16&255,u>>>8&255,u&255)}else{if(!/^[0-9a-fA-F]{1,4}$/.test(l))return null;let u=parseInt(l,16);a.push(u>>>8&255,u&255)}}return a},s;if(t.length===2){let o=n(t[0]),i=n(t[1]);if(!o||!i)return null;let a=16-o.length-i.length;if(a<0)return null;s=[...o,...new Array(a).fill(0),...i]}else{let o=n(e);if(!o||o.length!==16)return null;s=o}return s.length===16?new Uint8Array(s):null}function ul(r){let e=n=>(r[n]<<24|r[n+1]<<16|r[n+2]<<8|r[n+3])>>>0;if(r.every(n=>n===0)||r.slice(0,15).every(n=>n===0)&&r[15]===1)return!0;let t=r[0];return(t&254)===252||t===254&&(r[1]&192)===128||t===255||r[0]===32&&r[1]===1&&r[2]===13&&r[3]===184?!0:r.slice(0,10).every(n=>n===0)&&r[10]===255&&r[11]===255||r.slice(0,12).every(n=>n===0)||r[0]===0&&r[1]===100&&r[2]===255&&r[3]===155&&r.slice(4,12).every(n=>n===0)?Ut(e(12)):r[0]===32&&r[1]===2?Ut(e(2)):!1}function Oe(r,e=["http","https"]){try{let t=typeof r=="string"?new URL(r):r,n=t.protocol.replace(/:$/,"").toLowerCase();if(!e.some(i=>i.toLowerCase()===n)||al.has(n))return!1;let s=t.hostname.toLowerCase(),o=s.startsWith("[")&&s.endsWith("]");if(o&&(s=s.slice(1,-1)),s==="localhost"||s.endsWith(".localhost")||s==="0.0.0.0")return!1;if(o||s.includes(":")){let i=ll(s);if(i===null||ul(i))return!1}else{let i=xi(s);if(i!==null&&Ut(i))return!1}if(t.hostname.includes("..")||t.pathname.includes("..")||t.hostname.length>253||t.href.length>8192)return!1;if(t.port){let i=parseInt(t.port,10);if(isNaN(i)||i<1||i>65535)return!1}return!0}catch{return!1}}function et(r){if(r===null||typeof r!="object")return r;if(Array.isArray(r))return r.map(t=>et(t));if(r instanceof Date)return new Date(r.getTime());if(r instanceof Uint8Array)return new Uint8Array(r);if(r instanceof Map){let t=new Map;return r.forEach((n,s)=>t.set(s,et(n))),t}if(r instanceof Set){let t=new Set;return r.forEach(n=>t.add(et(n))),t}let e={};for(let t in r)t==="__proto__"||t==="constructor"||t==="prototype"||Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=et(r[t]));return e}function _i(r,e){let t=new Error(r);return Object.assign(t,e),t}function Si(r){if(r instanceof Error){let e={};for(let[n,s]of Object.entries(r))n!=="message"&&n!=="name"&&n!=="stack"&&(e[n]=s);let t=Object.keys(e).length>0?` | ${JSON.stringify(e)}`:"";return`${r.name}: ${r.message}${t}`}return String(r)}function Ei(r){if(typeof r!="string"||r.length>2048)return null;try{let e=new URL(r);return Oe(e)?(e.username="",e.password="",e.toString()):null}catch{return null}}function Ti(){let r=nl();if(r?.hrtime){let[t,n]=r.hrtime();return t*1e3+n/1e6}return typeof globalThis.Bun<"u",Date.now()}function Ri(r,e){return e?.aborted?Promise.reject(Sn()):new Promise((t,n)=>{let s=()=>{clearTimeout(o),n(Sn())},o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);e&&e.addEventListener("abort",s,{once:!0})})}function mr(r){if(r.length===0)return new Uint8Array(0);let e=r.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.byteLength;return t}function ki(r){if(r instanceof Uint8Array)return r.slice();if(r instanceof ArrayBuffer)return new Uint8Array(r);let e=sl();return e&&e.isBuffer(r)?new Uint8Array(r):typeof r=="string"?new TextEncoder().encode(r):null}function $t(r){if(r.byteLength<=24576){let n="";for(let s=0;s<r.byteLength;s++)n+=String.fromCharCode(r[s]);return btoa(n)}let t=[];for(let n=0;n<r.byteLength;n+=24576){let s=r.subarray(n,n+24576),o="";for(let i=0;i<s.byteLength;i++)o+=String.fromCharCode(s[i]);t.push(btoa(o))}return t.map((n,s)=>s<t.length-1?n.replace(/=+$/,""):n).join("")}function gr(...r){let e=r.filter(s=>s!=null);if(e.length===0)return;if(e.length===1)return e[0];if(e.some(s=>s.aborted)){let s=new AbortController;return s.abort(),s.signal}let t=new AbortController,n=()=>{for(let s of e)s.removeEventListener("abort",n);t.abort(Sn())};t.signal.addEventListener("abort",()=>{for(let s of e)s.removeEventListener("abort",n)},{once:!0});for(let s of e)s.addEventListener("abort",n,{once:!0});return t.signal}function yr(r){if(!(r instanceof Error))return!1;if(r.name==="AbortError")return!0;let e=r;return e.code==="ECONNRESET"||e.code==="ECONNABORTED"||r instanceof DOMException&&r.name==="AbortError"}function tt(r){if(!Number.isInteger(r)||r<0||r>65536)throw new Error(`randomBytes: invalid byteCount ${r}`);let e=new Uint8Array(r);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(e);else throw new Error("randomBytes: no CSPRNG available in this runtime \u2014 crypto.getRandomValues is required");return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Sn(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let r=new Error("Aborted");return r.name="AbortError",r}function wr(){if(oe)return oe;try{if(globalThis.process?.versions?.node)return oe="node",oe}catch{}return typeof globalThis.Deno<"u"?oe="deno":typeof globalThis.Bun<"u"?oe="bun":typeof window<"u"?oe="browser":typeof globalThis<"u"&&typeof globalThis.fetch=="function"?oe="edge":oe="unknown",oe}function Ai(){return wr()==="node"}function Ci(){return wr()==="browser"}function vi(){return typeof globalThis?.fetch=="function"}function rt(r){let e={};return r.forEach((t,n)=>{e[n.toLowerCase()]=t}),e}var dr,pr,ol,il,al,cl,oe,z=F(()=>{"use strict";ol={maxDepth:32,maxStringLength:10*1024*1024,maxArrayLength:1e4,maxObjectKeys:1e3,allowNonFinite:!1};il=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;al=new Set(["file","ftp","gopher","data","javascript","dict","ldap","ldaps","rlogin","telnet","tn3270","imap","pop","smtp","nntp","news","ssh","git","svn","webcal","urn"]),cl=[[0,16777215],[167772160,184549375],[1681915904,1686110207],[2130706432,2147483647],[2851995648,2852061183],[2886729728,2887778303],[3221225472,3221225727],[3221225984,3221226239],[3232235520,3232301055],[3323068416,3323199487],[3325256704,3325256959],[3405803776,3405804031],[3758096384,4026531839],[4026531840,4294967295]];oe=null});function En(r){return r}function Ii(r){if(typeof r=="string"){for(let e of hl)if(e===r)return e}}var hl,S,st,ot,xr,Z,J,_r,Sr,Er,Q,Ne=F(()=>{"use strict";hl=["ENETWORK","ETIMEOUT","EABORT","EHTTPSTATUS","ESIZELIMIT","EPARSE","EVALIDATION","EAUTH","EPROXY","EREDIRECT","EUNKNOWN"];S=class extends Error{constructor(t,n,s){super(t);h(this,"code");h(this,"request");h(this,"response");h(this,"cause");this.name="KinetexError",this.code=n,s?.request!==void 0&&(this.request=s.request),s?.response!==void 0&&(this.response=s.response),s?.cause!==void 0&&(this.cause=s.cause)}get isNetwork(){return this.code==="ENETWORK"}get isProxy(){return this.code==="EPROXY"}get isTimeout(){return this.code==="ETIMEOUT"}get isAbort(){return this.code==="EABORT"}get isHTTPError(){return this.code==="EHTTPSTATUS"}get status(){return this.response?.status??null}},st=class extends S{constructor(t,n,s){super(`Response size limit exceeded: ${t} bytes read, limit is ${n} bytes`,"ESIZELIMIT",s!==void 0?{request:s}:{});h(this,"bytesRead");h(this,"limit");this.bytesRead=t,this.limit=n,this.name="SizeLimitError"}},ot=class extends S{constructor(e,t){super(`HTTP ${e.status} ${e.statusText} \u2014 ${e.url}`,"EHTTPSTATUS",{request:t,response:e}),this.name="HTTPStatusError"}get isClientError(){return(this.status??0)>=400&&(this.status??0)<500}get isServerError(){return(this.status??0)>=500}},xr=class extends S{constructor(e){super("Request was aborted","EABORT",e!==void 0?{request:e}:{}),this.name="AbortError"}},Z=class extends S{constructor(e,t){super(e,"ENETWORK",t!==void 0?{request:t}:{}),this.name="NetworkError"}},J=class extends S{constructor(e,t){super(e,"EVALIDATION",t!==void 0?{request:t}:{}),this.name="ValidationError"}},_r=class extends S{constructor(e,t){super(e,"EAUTH",t!==void 0?{request:t}:{}),this.name="AuthError"}},Sr=class extends S{constructor(e,t){super(e,"EPROXY",t!==void 0?{request:t}:{}),this.name="ProxyError"}},Er=class extends S{constructor(e,t){super(e,"EREDIRECT",t!==void 0?{request:t}:{}),this.name="RedirectError"}},Q=class extends S{constructor(t,n){super(`Request timed out after ${t}ms`,"ETIMEOUT",n!==void 0?{request:n}:{});h(this,"timeoutMs");this.timeoutMs=t,this.name="TimeoutError"}}});var Di={};fe(Di,{CloudflareKVAdapter:()=>at,HTTPCache:()=>ie,MemoryStorageAdapter:()=>be,TwoTierStorageAdapter:()=>ct,WebStorageAdapter:()=>Ue,createKVCache:()=>vn,createLocalStorageCache:()=>An,createMemoryCache:()=>kn,createSessionStorageCache:()=>Cn,createTwoTierCache:()=>Pn,getAuthFingerprint:()=>$e});function fl(r){let e={noStore:!1,noCache:!1,mustRevalidate:!1,proxyRevalidate:!1,public:!1,private:!1,maxAge:null,sMaxAge:null,staleWhileRevalidate:null,staleIfError:null,immutable:!1};for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("="),o=(s===-1?n:n.slice(0,s)).trim().toLowerCase(),i=s===-1?null:n.slice(s+1).trim().replace(/^"|"$/g,""),a=i!==null?parseInt(i,10):null;switch(o){case"no-store":e.noStore=!0;break;case"no-cache":e.noCache=!0;break;case"must-revalidate":e.mustRevalidate=!0;break;case"proxy-revalidate":e.proxyRevalidate=!0;break;case"public":e.public=!0;break;case"private":e.private=!0;break;case"immutable":e.immutable=!0;break;case"max-age":e.maxAge=a;break;case"s-maxage":e.sMaxAge=a;break;case"stale-while-revalidate":e.staleWhileRevalidate=a;break;case"stale-if-error":e.staleIfError=a;break;case"no-transform":break;case"only-if-cached":break;case"must-understand":break;default:break}}return e}function Li(r,e){return r?r.trim()==="*"?null:r.split(",").map(s=>s.trim().toLowerCase()).sort().map(s=>{let o=e[s]??e[s.toLowerCase()]??"";return`${s}=${o}`}).join(";"):""}function it(r){let e=["\0-","\x7F-\x9F"].join(""),t=new RegExp(`[${e}]`,"g");return r.replaceAll(t,"").replaceAll(/\s+/g," ").trim()}async function $e(r){let e=["authorization","cookie","x-api-key","x-auth-token"],t=[];for(let i of e){let a=r[i.toLowerCase()];a&&t.push(`${i}=${a}`)}if(t.length===0)return"";let n=new TextEncoder().encode(t.join("|")),s=await crypto.subtle.digest("SHA-256",n);return`auth:${Array.from(new Uint8Array(s)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}`}async function dl(r){try{let e=new URL(r.url),t=it(e.hostname),n=it(e.pathname);e.searchParams.sort();let s=it(e.search);e.hash="";let o=`${e.protocol}//${t}${e.port?":"+e.port:""}${n}${s}`,i=it(r.method.toUpperCase()),a=await $e(r.headers??{}),c=`${i}:${o}`;return a?`${c}:${a}`:c}catch{let e=it(r.method.toUpperCase()),t=it(r.url),n=await $e(r.headers??{}),s=`${e}:${t}`;return n?`${s}:${n}`:s}}function Mi(r,e,t){let n=r.headers["cache-control"]??r.headers["Cache-Control"]??"",s=fl(n);if(t&&s.noStore)return{ttlMs:0,swrMs:0,staleOnError:0,shouldCache:!1};let o=s.sMaxAge??s.maxAge,i;if(o!==null){let l=parseInt(r.headers.age??r.headers.Age??"0",10)||0;i=Math.max(0,(o-l)*1e3)}else{let l=r.headers.expires??r.headers.Expires;if(l){let u=Date.parse(l);i=isNaN(u)?e:Math.max(0,u-Date.now())}else{let u=r.headers["last-modified"]??r.headers["Last-Modified"];if(u){let f=Date.parse(u);isNaN(f)?i=e:i=Math.min((Date.now()-f)*.1,e)}else i=e}}s.immutable&&i>0&&(i=365*24*60*60*1e3);let a=s.staleWhileRevalidate!==null?s.staleWhileRevalidate*1e3:0,c=s.staleIfError!==null?s.staleIfError*1e3:0;return{ttlMs:i,swrMs:a,staleOnError:c,shouldCache:i>0||a>0}}function Tr(r){return{...r,response:Oi(r.response),tags:[...r.tags]}}function Oi(r){return{...r,headers:{...r.headers},body:r.body instanceof Uint8Array?new Uint8Array(r.body):r.body}}function pl(r){return r?typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength:0}function kn(r){return new ie({...r,storage:new be})}function An(r,e){if(typeof localStorage>"u")throw new Error("localStorage is not available");return new ie({...e,storage:new Ue(localStorage,r)})}function Cn(r,e){if(typeof sessionStorage>"u")throw new Error("sessionStorage is not available");return new ie({...e,storage:new Ue(sessionStorage,r)})}function vn(r,e){return new ie({...e,storage:new at(r)})}function Pn(r,e){return new ie({...e,storage:new ct(r)})}var be,Ue,at,ct,Tn,Rn,ie,jt=F(()=>{"use strict";z();be=class{constructor(){h(this,"store",new Map)}get(e){return Promise.resolve(this.store.get(e)??null)}set(e,t){return this.store.set(e,t),Promise.resolve()}delete(e){return this.store.delete(e),Promise.resolve()}keys(){return Promise.resolve(Array.from(this.store.keys()))}clear(){return this.store.clear(),Promise.resolve()}get size(){return this.store.size}},Ue=class{constructor(e,t="hc:"){h(this,"storage");h(this,"prefix");this.storage=e,this.prefix=t}get(e){try{let t=this.storage.getItem(this.prefix+e);if(!t)return Promise.resolve(null);let n=de(t,{maxDepth:32});return Promise.resolve(n.success&&n.value!==void 0?n.value:null)}catch{return Promise.resolve(null)}}set(e,t){try{return this.storage.setItem(this.prefix+e,JSON.stringify(t)),Promise.resolve(!0)}catch(n){return n instanceof Error&&(n.name==="QuotaExceededError"||n.name==="NS_ERROR_DOM_QUOTA_REACHED")&&console.warn("[kinetex] WebStorageAdapter: storage quota exceeded. Entry was NOT cached. Consider reducing maxBodySizeBytes or using a different storage adapter."),Promise.resolve(!1)}}delete(e){return this.storage.removeItem(this.prefix+e),Promise.resolve()}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n.slice(this.prefix.length))}return Promise.resolve(e)}clear(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}for(let t of e)this.storage.removeItem(t);return Promise.resolve()}},at=class{constructor(e,t="hc:"){h(this,"kv");h(this,"prefix");this.kv=e,this.prefix=t}async get(e){return await this.kv.get(this.prefix+e,"json")}async set(e,t){let n=t.expiresAt===1/0?void 0:Math.max(1,Math.ceil((t.expiresAt-Date.now())/1e3));await this.kv.put(this.prefix+e,JSON.stringify(t),{...n!==void 0?{expirationTtl:n}:{}})}async delete(e){await this.kv.delete(this.prefix+e)}async keys(){return(await this.kv.list({prefix:this.prefix})).keys.map(t=>t.name.slice(this.prefix.length))}async clear(){let e=await this.keys();await Promise.all(e.map(t=>this.kv.delete(this.prefix+t)))}},ct=class{constructor(e){h(this,"l2");h(this,"l1",new be);this.l2=e}async get(e){let t=await this.l1.get(e);if(t)return t;let n=await this.l2.get(e);return n&&await this.l1.set(e,n),n}async set(e,t){await Promise.all([this.l1.set(e,t),this.l2.set(e,t)])}async delete(e){await Promise.all([this.l1.delete(e),this.l2.delete(e)])}async keys(){return await this.l2.keys()}async clear(){await Promise.all([this.l1.clear(),this.l2.clear()])}};Tn=class{constructor(e,t=null,n=null){h(this,"key");h(this,"prev");h(this,"next");this.key=e,this.prev=t,this.next=n}},Rn=class{constructor(){h(this,"map",new Map);h(this,"head",null);h(this,"tail",null)}touch(e){let t=this.map.get(e);if(t)this._unlink(t),this._prepend(t);else{let n=new Tn(e);this.map.set(e,n),this._prepend(n)}}evict(){if(!this.tail)return null;let e=this.tail.key;return this._unlink(this.tail),this.map.delete(e),e}remove(e){let t=this.map.get(e);t&&(this._unlink(t),this.map.delete(e))}clear(){this.map.clear(),this.head=null,this.tail=null}get size(){return this.map.size}_prepend(e){e.prev=null,e.next=this.head,this.head&&(this.head.prev=e),this.head=e,this.tail||(this.tail=e)}_unlink(e){e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=null,e.next=null}},ie=class{constructor(e={}){h(this,"cfg");h(this,"storage");h(this,"lru",new Rn);h(this,"tagIndex",new Map);h(this,"swrInFlight",new Set);h(this,"stats",{hits:0,misses:0,staleHits:0,errors:0,evictions:0,totalEntries:0,totalSizeBytes:0,hitRate:0});this.cfg={maxEntries:e.maxEntries??500,maxSizeBytes:e.maxSizeBytes??50*1024*1024,maxBodySizeBytes:e.maxBodySizeBytes??5*1024*1024,defaultTtlMs:e.defaultTtlMs??6e4,maxAbsoluteAgeMs:e.maxAbsoluteAgeMs??10080*60*1e3,honorCacheControl:e.honorCacheControl??!0,cacheMethods:e.cacheMethods??["GET","HEAD"],cacheStatuses:e.cacheStatuses??[200,203,204,206,300,301,304,404,405,410,414,501],cacheKey:e.cacheKey??dl,storage:e.storage??new be,namespace:e.namespace??""},(this.cfg.defaultTtlMs===1/0||this.cfg.defaultTtlMs>365*24*60*60*1e3)&&(console.warn(`[Kinetex Cache] Capping defaultTtlMs from ${this.cfg.defaultTtlMs}ms to 1 year (${365*24*60*60*1e3}ms)`),this.cfg.defaultTtlMs=365*24*60*60*1e3),this.storage=this.cfg.storage}async get(e){if(!this._isCacheable(e.method))return null;let t=await this._key(e),n=await this.storage.get(t);if(!n)return this.stats.misses++,this._updateHitRate(),null;if(n.varyKey!==null&&n.varyKey!==""){let i=Li(n.response.headers.vary??n.response.headers.Vary??"",e.headers);if(i===null||i!==n.varyKey)return this.stats.misses++,this._updateHitRate(),null}let s=Date.now();return s-n.createdAt>this.cfg.maxAbsoluteAgeMs?(await this._delete(t,n),this.stats.misses++,this._updateHitRate(),null):n.expiresAt===1/0||n.expiresAt>s?(this.stats.hits++,this.lru.touch(t),this._updateHitRate(),{entry:Tr(n),stale:!1}):n.staleUntil>s?(this.stats.staleHits++,this.lru.touch(t),this._updateHitRate(),{entry:Tr(n),stale:!0}):n.staleOnError>s?(this.stats.staleHits++,this._updateHitRate(),{entry:Tr(n),stale:!0}):(await this._delete(t,n),this.stats.misses++,this._updateHitRate(),null)}async set(e,t,n={}){if(!this._isCacheable(e.method)||!this.cfg.cacheStatuses.includes(t.status))return!1;let{ttlMs:s,swrMs:o,staleOnError:i,shouldCache:a}=n.ttlMs!==void 0?{ttlMs:n.ttlMs,swrMs:0,staleOnError:0,shouldCache:!0}:Mi(t,this.cfg.defaultTtlMs,this.cfg.honorCacheControl);if(!a&&!n.force)return!1;let c=pl(t.body);if(c>this.cfg.maxBodySizeBytes)return!1;let l=Date.now(),u=this.cfg.maxAbsoluteAgeMs,f=Math.min(s===1/0?u:s,u);if(f<=0&&!n.force)return!1;let p=t.headers.vary??t.headers.Vary??null,d=p?Li(p,e.headers):"";if(d===null)return!1;let g=n.tags??[],m={response:Oi(t),createdAt:l,expiresAt:f===1/0?1/0:l+f,staleUntil:l+f+o,staleOnError:l+f+i,etag:t.headers.etag??t.headers.ETag??null,lastModified:t.headers["last-modified"]??t.headers["Last-Modified"]??null,varyKey:d,tags:g,size:c+256},y=await this._key(e);if(await this._ensureCapacity(m.size),await this.storage.set(y,m)===!1)return!1;this.lru.touch(y),this.stats.totalEntries++,this.stats.totalSizeBytes+=m.size;for(let x of g){let E=this.tagIndex.get(x)??new Set;E.add(y),this.tagIndex.set(x,E)}return!0}buildConditionalHeaders(e){let t={};return e.etag&&(t["if-none-match"]=e.etag),e.lastModified&&(t["if-modified-since"]=e.lastModified),t}async revalidate(e,t){let n=await this._key(e),s=await this.storage.get(n);if(!s)return null;let o={...s.response.headers,...t.headers},i={...s.response,headers:o},{ttlMs:a,swrMs:c,staleOnError:l}=Mi(i,this.cfg.defaultTtlMs,this.cfg.honorCacheControl),u=Date.now(),f=Math.min(a===1/0?this.cfg.maxAbsoluteAgeMs:a,this.cfg.maxAbsoluteAgeMs),p={...s,response:i,createdAt:u,expiresAt:f<=0?u:u+f,staleUntil:u+f+c,staleOnError:u+f+l,etag:o.etag??o.ETag??s.etag,lastModified:o["last-modified"]??o["Last-Modified"]??s.lastModified};return await this.storage.set(n,p),this.lru.touch(n),Tr(p)}async markSWRInFlight(e){let t=await this._key(e);return this.swrInFlight.has(t)?!1:(this.swrInFlight.add(t),!0)}async clearSWRInFlight(e){let t=await this._key(e);this.swrInFlight.delete(t)}async isSWRInFlight(e){let t=await this._key(e);return this.swrInFlight.has(t)}async delete(e){let t=await this._key(e),n=await this.storage.get(t);return n?(await this._delete(t,n),!0):!1}async invalidateByURL(e){let t=await this.storage.keys(),n=0;for(let s of t){let o=this.cfg.namespace?s.startsWith(this.cfg.namespace+":")?s.slice(this.cfg.namespace.length+1):null:s;if(o===null)continue;let i=o.indexOf(":");if(i===-1)continue;let a=o.slice(i+1),c=a.lastIndexOf(":auth:"),l=c!==-1?a.slice(0,c):a,u=e.endsWith("/")?e.slice(0,-1):e;if((l.endsWith("/")?l.slice(0,-1):l).startsWith(u)){let p=await this.storage.get(s);await this._delete(s,p??void 0),n++}}return n}async invalidateByTag(e){let t=this.tagIndex.get(e);if(!t||t.size===0)return 0;let n=0;for(let s of[...t]){let o=await this.storage.get(s);await this._delete(s,o??void 0),n++}return this.tagIndex.delete(e),n}async clear(){await this.storage.clear(),this.lru.clear(),this.tagIndex.clear(),this.swrInFlight.clear(),this.stats.totalEntries=0,this.stats.totalSizeBytes=0}async warm(e){for(let{req:t,res:n,tags:s}of e)await this.set(t,n,{...s!==void 0?{tags:s}:{},force:!0})}getStats(){return{...this.stats}}resetStats(){this.stats={hits:0,misses:0,staleHits:0,errors:0,evictions:0,totalEntries:0,totalSizeBytes:0,hitRate:0}}async serialize(){let e=await this.storage.keys(),t=[],n=Date.now();for(let s of e){let o=await this.storage.get(s);o&&(o.expiresAt!==1/0&&o.expiresAt<n||t.push([s,o]))}return JSON.stringify({version:1,entries:t})}async deserialize(e){let t=de(e,{maxDepth:32});if(!t.success)throw new Error("[kinetex] HTTPCache.deserialize: invalid JSON");let n=t.value;if(typeof n!="object"||n===null||!("version"in n)||!("entries"in n)||n.version!==1||!Array.isArray(n.entries))throw new Error("[kinetex] HTTPCache.deserialize: unexpected format (expected {version:1, entries:[\u2026]})");let{entries:s}=n,o=Date.now();for(let i of s){if(!Array.isArray(i)||i.length!==2)continue;let[a,c]=i;if(typeof a!="string"||a.length===0||a.length>2048)continue;let l=null;try{typeof c=="object"&&c!==null&&typeof c.createdAt=="number"&&typeof c.expiresAt=="number"&&typeof c.staleUntil=="number"&&typeof c.staleOnError=="number"&&typeof c.size=="number"&&Array.isArray(c.tags)&&c.tags.every(p=>typeof p=="string")&&(l=c)}catch{}if(!l)continue;let u=c;if(!(u.expiresAt!==1/0&&u.expiresAt<o)&&!(o-u.createdAt>this.cfg.maxAbsoluteAgeMs)&&!(u.size>this.cfg.maxBodySizeBytes+512)){await this.storage.set(a,u),this.lru.touch(a),this.stats.totalEntries++,this.stats.totalSizeBytes+=u.size;for(let f of u.tags){let p=this.tagIndex.get(f)??new Set;p.add(a),this.tagIndex.set(f,p)}}}}async _key(e){let t=await this.cfg.cacheKey(e);return this.cfg.namespace?`${this.cfg.namespace}:${t}`:t}_isCacheable(e){return this.cfg.cacheMethods.includes(e.toUpperCase())}async _delete(e,t){if(await this.storage.delete(e),this.lru.remove(e),t){this.stats.totalEntries=Math.max(0,this.stats.totalEntries-1),this.stats.totalSizeBytes=Math.max(0,this.stats.totalSizeBytes-t.size);for(let n of t.tags)this.tagIndex.get(n)?.delete(e)}}async _ensureCapacity(e){for(;this.stats.totalEntries>=this.cfg.maxEntries;){let t=this.lru.evict();if(!t)break;let n=await this.storage.get(t);await this._delete(t,n??void 0),this.stats.evictions++}for(;this.stats.totalSizeBytes+e>this.cfg.maxSizeBytes;){let t=this.lru.evict();if(!t)break;let n=await this.storage.get(t);await this._delete(t,n??void 0),this.stats.evictions++}}_updateHitRate(){let e=this.stats.hits+this.stats.misses+this.stats.staleHits;this.stats.hitRate=e>0?(this.stats.hits+this.stats.staleHits)/e:0}}});function Nl(r){if(typeof atob<"u")return atob(r);let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="";r=r.replace(/=+$/,"");for(let n=0;n<r.length;n+=4){let s=e.indexOf(r[n]),o=n+1<r.length?e.indexOf(r[n+1]):0,i=n+2<r.length?e.indexOf(r[n+2]):0,a=n+3<r.length?e.indexOf(r[n+3]):0;t+=String.fromCharCode(s<<2|o>>4),n+2<r.length&&(t+=String.fromCharCode((o&15)<<4|i>>2)),n+3<r.length&&(t+=String.fromCharCode((i&3)<<6|a))}return t}function Zi(r){if(typeof btoa<"u")return btoa(r);let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="";for(let n=0;n<r.length;n+=3){let s=r.charCodeAt(n),o=n+1<r.length?r.charCodeAt(n+1):0,i=n+2<r.length?r.charCodeAt(n+2):0;t+=e[s>>2],t+=e[(s&3)<<4|o>>4],t+=n+1<r.length?e[(o&15)<<2|i>>6]:"=",t+=n+2<r.length?e[i&63]:"="}return t}function G(r){let e=new Map;for(let t of r.split(";")){let n=t.trim();if(!n)continue;let s=n.indexOf("=");if(s===-1)e.set(n.toLowerCase(),"");else{let o=n.slice(0,s).trim().toLowerCase(),i=n.slice(s+1).trim();i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),e.set(o,i)}}return e}function Lr(r){return r.split(",").map(e=>{let t=e.trim().split(";"),n=(t[0]??"").trim(),s=1,o=new Map;for(let i=1;i<t.length;i++){let a=t[i].trim(),c=a.indexOf("=");if(c===-1)continue;let l=a.slice(0,c).trim().toLowerCase(),u=a.slice(c+1).trim();l==="q"?s=parseFloat(u)||0:o.set(l,u)}return{value:n,quality:s,params:o}}).filter(e=>e.value!=="").sort((e,t)=>t.quality-e.quality)}function $l(r){let e=r.match(/^([A-Za-z0-9_-]+)'([A-Za-z0-9_-]*)'(.+)$/);if(!e)return null;try{return decodeURIComponent(e[3])}catch{return null}}function fs(r){if(!r)return null;let e=r.indexOf(";"),t=e===-1?r.trim():r.slice(0,e).trim(),n=t.indexOf("/");if(n===-1)return null;let s=t.slice(0,n).toLowerCase(),o=t.slice(n+1).toLowerCase();if(!s||!o)return null;let i=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;if(!i.test(s)||!i.test(o))return null;let a=e===-1?new Map:G(r.slice(e));return{mediaType:`${s}/${o}`,type:s,subtype:o,charset:a.get("charset")??null,boundary:a.get("boundary")??null,params:a}}function ds(r){let e=r.mediaType;if(r.charset&&(e+=`; charset=${r.charset}`),r.boundary&&(e+=`; boundary=${r.boundary}`),r.params&&r.params instanceof Map)r.params.forEach((t,n)=>{n==="charset"||n==="boundary"||(e+=`; ${n}=${t.includes(" ")?`"${t}"`:t}`)});else if(r.params&&typeof r.params=="object")for(let[t,n]of Object.entries(r.params))t==="charset"||t==="boundary"||(e+=`; ${t}=${n.includes(" ")?`"${n}"`:n}`);return e}function ps(r){if(!r)return null;let e=r.indexOf(";"),t=(e===-1?r:r.slice(0,e)).trim().toLowerCase(),n=e===-1?new Map:G(r.slice(e)),s=null,o=n.get("filename*");o&&(s=$l(o)),s===null&&(s=n.get("filename")??null);let i=n.get("name")??null;return{type:t,filename:s,name:i,params:n}}function ms(r){let e=r.type;if(r.name&&(e+=`; name="${r.name}"`),r.filename){e+=`; filename="${r.filename}"`;let t=encodeURIComponent(r.filename);t!==r.filename&&(e+=`; filename*=UTF-8''${t}`)}return e}function gs(r){let e={noCache:!1,noStore:!1,noTransform:!1,onlyIfCached:!1,maxAge:null,maxStale:null,minFresh:null,staleIfError:null,public:!1,private:!1,mustRevalidate:!1,proxyRevalidate:!1,sMaxAge:null,immutable:!1,mustUnderstand:!1,staleWhileRevalidate:null,unknown:new Map};for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("="),o=(s===-1?n:n.slice(0,s)).trim().toLowerCase(),i=s===-1?null:n.slice(s+1).trim().replace(/^"|"$/g,""),a=i!==null?parseInt(i,10):null;switch(o){case"no-cache":e.noCache=!0;break;case"no-store":e.noStore=!0;break;case"no-transform":e.noTransform=!0;break;case"only-if-cached":e.onlyIfCached=!0;break;case"public":e.public=!0;break;case"must-revalidate":e.mustRevalidate=!0;break;case"proxy-revalidate":e.proxyRevalidate=!0;break;case"immutable":e.immutable=!0;break;case"must-understand":e.mustUnderstand=!0;break;case"max-age":e.maxAge=a;break;case"max-stale":e.maxStale=a??1/0;break;case"min-fresh":e.minFresh=a;break;case"s-maxage":e.sMaxAge=a;break;case"stale-if-error":e.staleIfError=a;break;case"stale-while-revalidate":e.staleWhileRevalidate=a;break;case"private":e.private=i?i.split(",").map(c=>c.trim()):!0;break;default:e.unknown.set(o,i??!0)}}return e}function ys(r){let e=[];if(r.noCache&&e.push("no-cache"),r.noStore&&e.push("no-store"),r.noTransform&&e.push("no-transform"),r.onlyIfCached&&e.push("only-if-cached"),r.public&&e.push("public"),r.mustRevalidate&&e.push("must-revalidate"),r.proxyRevalidate&&e.push("proxy-revalidate"),r.immutable&&e.push("immutable"),r.mustUnderstand&&e.push("must-understand"),r.maxAge!=null&&e.push(`max-age=${r.maxAge}`),r.maxStale!=null&&e.push(r.maxStale===1/0?"max-stale":`max-stale=${r.maxStale}`),r.minFresh!=null&&e.push(`min-fresh=${r.minFresh}`),r.sMaxAge!=null&&e.push(`s-maxage=${r.sMaxAge}`),r.staleIfError!=null&&e.push(`stale-if-error=${r.staleIfError}`),r.staleWhileRevalidate!=null&&e.push(`stale-while-revalidate=${r.staleWhileRevalidate}`),r.private&&e.push(Array.isArray(r.private)?`private=${r.private.join(", ")}`:"private"),r.unknown)for(let[t,n]of r.unknown)e.push(n===!0?t:`${t}=${n}`);return e.join(", ")}function vr(r){if(!r)return null;let e=r.indexOf(" ");if(e===-1)return{scheme:r.toLowerCase(),token:null,params:new Map,basic:null};let t=r.slice(0,e).toLowerCase(),n=r.slice(e+1).trim(),s=new Map,o=null,i=null;if(t==="basic"){o=n;try{let a=Nl(n),c=a.indexOf(":");c!==-1&&(i={username:a.slice(0,c),password:a.slice(c+1)})}catch{}}else if(t==="bearer"||t==="token")o=n;else if(n.includes("="))for(let a of n.split(",")){let c=a.trim(),l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),f=c.slice(l+1).trim();f.startsWith('"')&&f.endsWith('"')&&(f=f.slice(1,-1)),s.set(u,f)}else o=n;return{scheme:t,token:o,params:s,basic:i}}function Pr(r){let e=[],t=[],n="",s=!1;for(let o=0;o<r.length;o++){let i=r[o];i==='"'&&(o===0||r[o-1]!=="\\")&&(s=!s),i===","&&!s?(t.push(n.trim()),n=""):n+=i}n.trim()&&t.push(n.trim());for(let o of t){if(!o)continue;let i=o.indexOf(" "),a=(i===-1?o:o.slice(0,i)).toLowerCase(),c=i===-1?"":o.slice(i+1),l=G(c);e.push({scheme:a,realm:l.get("realm")??null,params:l})}return e}function na(r){return`Bearer ${r}`}function sa(r,e){return`Basic ${Zi(`${r}:${e}`)}`}function Mr(r){return Lr(r)}function ws(r){return Lr(r)}function bs(r){return Lr(r)}function oa(r){return r.trim()?Lr(r):[]}function ia(r,e){let t=Mr(r);for(let{value:n}of t){if(n==="*/*")return e[0]??null;let[s]=n.split("/");if(n.endsWith("/*")){let o=e.find(i=>i.startsWith(s+"/"));if(o)return o}if(e.includes(n))return n}return null}function xs(r){let e=r.indexOf("=");if(e===-1)return null;let t=r.slice(0,e).trim().toLowerCase(),n=r.slice(e+1).split(",").map(s=>{let o=s.trim(),i=o.indexOf("-");if(i===-1)return null;let a=o.slice(0,i).trim(),c=o.slice(i+1).trim();return{start:a===""?null:parseInt(a,10),end:c===""?null:parseInt(c,10)}}).filter(s=>s!==null);return{unit:t,ranges:n}}function _s(r){let e=r.match(/^(\S+)\s+(\*|\d+-\d+)\/(\*|\d+)$/);if(!e)return null;let t=e[1].toLowerCase(),n=e[2],s=e[3]==="*"?null:parseInt(e[3],10);if(n==="*")return{unit:t,start:null,end:null,total:s};let o=n.indexOf("-");return{unit:t,start:parseInt(n.slice(0,o),10),end:parseInt(n.slice(o+1),10),total:s}}function Ir(r){let e=[],t=r.split(/,\s*(?=<)/);for(let n of t){let s=n.trim(),o=s.indexOf(">");if(!s.startsWith("<")||o===-1)continue;let i=s.slice(1,o),a=s.slice(o+1),c=G(a);e.push({uri:i,rel:c.get("rel")??null,type:c.get("type")??null,hreflang:c.get("hreflang")??null,title:c.get("title")??null,media:c.get("media")??null,params:c})}return e}function aa(r){return r.map(e=>{let t=`<${e.uri}>`;e.rel&&(t+=`; rel="${e.rel}"`),e.type&&(t+=`; type="${e.type}"`),e.hreflang&&(t+=`; hreflang="${e.hreflang}"`),e.title&&(t+=`; title="${e.title}"`),e.media&&(t+=`; media="${e.media}"`);let n=e.params instanceof Map?[...e.params.entries()]:Object.entries(e.params??{});for(let[s,o]of n)["rel","type","hreflang","title","media"].includes(s)||(t+=`; ${s}="${o}"`);return t}).join(", ")}function Ss(r){let e={by:null,for:[],host:null,proto:null};for(let t of r.split(",")){let n=G(t.trim());n.has("by")&&(e.by=n.get("by")),n.has("for")&&e.for.push(n.get("for")),n.has("host")&&(e.host=n.get("host")),n.has("proto")&&(e.proto=n.get("proto"))}return e}function Or(r){let e=r.get(w.Forwarded);if(e)return Ss(e);let t=r.get(w.XForwardedFor),n=r.get(w.XForwardedHost),s=r.get(w.XForwardedProto);return{by:null,for:t?t.split(",").map(o=>o.trim()):[],host:n??null,proto:s??null}}function Es(r){let e=Or(r);return e.for.length>0?e.for[0]:r.get(w.XRealIP)}function Ts(r){let e=r.trim();if(/^\d+$/.test(e))return{date:null,delay:parseInt(e,10)};let t=Date.parse(e);return isNaN(t)?{date:null,delay:null}:{date:new Date(t),delay:null}}function ca(r){let e=[],t="",n=!1;for(let s=0;s<r.length;s++){let o=r[s];o==='"'&&(s===0||r[s-1]!=="\\")&&(n=!n),o===","&&!n?(t.trim()&&e.push(t.trim()),t=""):t+=o}return t.trim()&&e.push(t.trim()),e.map(s=>{let o=s.match(/^(\d{3})\s+(\S+)\s+["']?([^"']+)["']?\s*(.*)$/);if(!o)return null;let i=o[1],a=o[2],c=o[3],l=o[4]??"",u=parseInt(i,10),f=(()=>{let p=l.trim().replace(/^"|"$/g,"");if(p){let d=Date.parse(p);if(!isNaN(d))return new Date(d)}})();return{code:u,agent:a,text:c,...f!==void 0?{date:f}:{}}}).filter(s=>s!==null)}function Rs(r){let e=G(";"+r),t=e.get("max-age");if(t===void 0)return null;let n=parseInt(t,10);return isNaN(n)?null:{maxAge:n,includeSubDomains:e.has("includesubdomains"),preload:e.has("preload")}}function Dr(r){let e=`max-age=${r.maxAge}`;return r.includeSubDomains&&(e+="; includeSubDomains"),r.preload&&(e+="; preload"),e}function ks(r){let e=new Map;for(let t of r.split(";")){let n=t.trim().split(/\s+/);if(n.length===0||!n[0])continue;let s=n[0].toLowerCase(),o=n.slice(1);e.set(s,o)}return e}function Nr(r){let e=[];for(let[t,n]of r)e.push(n.length>0?`${t} ${n.join(" ")}`:t);return e.join("; ")}function As(r){return r.split(",").map(e=>{let t=e.trim().split(";"),n=(t[0]??"").trim(),s=G(t.slice(1).join(";")),o=s.get("dur");return{name:n,duration:o!==void 0?parseFloat(o):null,description:s.get("desc")??null}}).filter(e=>e.name!=="")}function la(r){return r.map(e=>{let t=e.name;return e.duration!==null&&(t+=`;dur=${e.duration}`),e.description!==null&&(t+=`;desc="${e.description}"`),t}).join(", ")}function Cs(r){if(r.trim()==="clear")return[];let e=[];for(let t of r.split(",")){let n=t.trim(),s=n.indexOf("=");if(s===-1)continue;let o=n.slice(0,s).trim().replace(/^"|"$/g,""),i=n.slice(s+1).trim(),a=i.indexOf(";"),c=a!==-1?G(";"+i.slice(a+1)):new Map,l=(a!==-1?i.slice(0,a):i).replace(/^"|"$/g,""),u,f;if(l.startsWith("[")){let p=l.indexOf("]");if(p===-1)u=l,f=443;else{u=l.slice(0,p+1);let d=l.slice(p+2);f=d?parseInt(d,10):443}}else{let p=l.lastIndexOf(":");u=p===-1?l:l.slice(0,p),f=p===-1?443:parseInt(l.slice(p+1),10)}e.push({protocol:o,host:u,port:f,maxAge:c.has("ma")?parseInt(c.get("ma"),10):null,persist:c.has("persist")&&c.get("persist")==="1"})}return e}function ua(r){let e=new ce;for(let[t,n]of Object.entries(r))if(n!==void 0)if(Array.isArray(n))for(let s of n)e.append(t,s);else e.append(t,n);return e}function ha(r){let e={};return r.forEach((t,n)=>{let o=r.getAll(n);e[n]=o.length===1?o[0]:[...o]}),e}function fa(r){return new ce(r)}function da(r={}){let e=new ce;if(r.hsts!==!1){let t=r.hsts===!0||r.hsts===void 0?{maxAge:31536e3,includeSubDomains:!0,preload:!1}:r.hsts;e.set(w.StrictTransportSecurity,Dr(t))}if(r.csp){let t=typeof r.csp=="string"?r.csp:Nr(r.csp);e.set(w.ContentSecurityPolicy,t)}return e.set(w.XFrameOptions,r.frameOptions??"DENY"),r.noSniff!==!1&&e.set(w.XContentTypeOptions,"nosniff"),e.set(w.ReferrerPolicy,r.referrer??"strict-origin-when-cross-origin"),r.permissions&&e.set(w.PermissionsPolicy,r.permissions),r.coep&&e.set(w.CrossOriginEmbedderPolicy,r.coep),r.coop&&e.set(w.CrossOriginOpenerPolicy,r.coop),r.corp&&e.set(w.CrossOriginResourcePolicy,r.corp),e}function pa(r){let e=new ce,t=Array.isArray(r.origin)?r.origin.join(", "):r.origin;return e.set(w.AccessControlAllowOrigin,t),r.methods?.length&&e.set(w.AccessControlAllowMethods,r.methods.join(", ")),r.allowHeaders?.length&&e.set(w.AccessControlAllowHeaders,r.allowHeaders.join(", ")),r.exposeHeaders?.length&&e.set(w.AccessControlExposeHeaders,r.exposeHeaders.join(", ")),r.credentials&&e.set(w.AccessControlAllowCredentials,"true"),r.maxAge!=null&&e.set(w.AccessControlMaxAge,String(r.maxAge)),e}function ma(r){return new xe(r)}function ga(r){return new xe(r,"request")}function ya(r){return new xe(r,"response")}function wa(r){return new xe(r,"immutable")}var He,w,us,hs,dt,Yi,Ul,$,ea,as,cs,ls,ta,ra,ce,xe,Ft=F(()=>{"use strict";z();w={ContentType:"content-type",ContentLength:"content-length",ContentEncoding:"content-encoding",ContentLanguage:"content-language",ContentLocation:"content-location",ContentDisposition:"content-disposition",ContentRange:"content-range",ContentMD5:"content-md5",TransferEncoding:"transfer-encoding",TrailingHeader:"trailer",CacheControl:"cache-control",Pragma:"pragma",Expires:"expires",Age:"age",ETag:"etag",LastModified:"last-modified",Vary:"vary",IfMatch:"if-match",IfNoneMatch:"if-none-match",IfModifiedSince:"if-modified-since",IfUnmodifiedSince:"if-unmodified-since",IfRange:"if-range",Host:"host",Origin:"origin",Referer:"referer",UserAgent:"user-agent",From:"from",TE:"te",Expect:"expect",MaxForwards:"max-forwards",Accept:"accept",AcceptEncoding:"accept-encoding",AcceptLanguage:"accept-language",AcceptCharset:"accept-charset",AcceptRanges:"accept-ranges",AcceptPatch:"accept-patch",Authorization:"authorization",ProxyAuthorization:"proxy-authorization",WWWAuthenticate:"www-authenticate",ProxyAuthenticate:"proxy-authenticate",AuthenticationInfo:"authentication-info",Range:"range",Cookie:"cookie",SetCookie:"set-cookie",Location:"location",Via:"via",Forwarded:"forwarded",XForwardedFor:"x-forwarded-for",XForwardedHost:"x-forwarded-host",XForwardedProto:"x-forwarded-proto",XForwardedPort:"x-forwarded-port",XRealIP:"x-real-ip",Connection:"connection",KeepAlive:"keep-alive",Upgrade:"upgrade",AccessControlAllowOrigin:"access-control-allow-origin",AccessControlAllowMethods:"access-control-allow-methods",AccessControlAllowHeaders:"access-control-allow-headers",AccessControlExposeHeaders:"access-control-expose-headers",AccessControlMaxAge:"access-control-max-age",AccessControlAllowCredentials:"access-control-allow-credentials",AccessControlRequestMethod:"access-control-request-method",AccessControlRequestHeaders:"access-control-request-headers",Date:"date",RetryAfter:"retry-after",Allow:"allow",Server:"server",ServerTiming:"server-timing",TimingAllowOrigin:"timing-allow-origin",SecWebSocketKey:"sec-websocket-key",SecWebSocketAccept:"sec-websocket-accept",SecWebSocketProtocol:"sec-websocket-protocol",SecWebSocketVersion:"sec-websocket-version",SecWebSocketExtensions:"sec-websocket-extensions",SecFetchSite:"sec-fetch-site",SecFetchMode:"sec-fetch-mode",SecFetchUser:"sec-fetch-user",SecFetchDest:"sec-fetch-dest",StrictTransportSecurity:"strict-transport-security",ContentSecurityPolicy:"content-security-policy",ContentSecurityPolicyRO:"content-security-policy-report-only",XContentTypeOptions:"x-content-type-options",XFrameOptions:"x-frame-options",XXSSProtection:"x-xss-protection",ReferrerPolicy:"referrer-policy",PermissionsPolicy:"permissions-policy",CrossOriginOpenerPolicy:"cross-origin-opener-policy",CrossOriginEmbedderPolicy:"cross-origin-embedder-policy",CrossOriginResourcePolicy:"cross-origin-resource-policy",NEL:"nel",ReportTo:"report-to",ReportingEndpoints:"reporting-endpoints",Link:"link",AltSvc:"alt-svc",AltUsed:"alt-used",Priority:"priority",EarlyData:"early-data",PushPolicy:"push-policy",AcceptPushPolicy:"accept-push-policy",XRequestID:"x-request-id",XCorrelationID:"x-correlation-id",XRateLimitLimit:"x-ratelimit-limit",XRateLimitRemaining:"x-ratelimit-remaining",XRateLimitReset:"x-ratelimit-reset",XPoweredBy:"x-powered-by",XRequestedWith:"x-requested-with"};us=Me,hs=we,dt=new Set(["set-cookie","www-authenticate","proxy-authenticate"]),Yi=new Set(["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]),Ul=new Set(["set-cookie","set-cookie2"]),ce=class{constructor(e,t="none"){Go(this,$);h(this,"map",new Map);h(this,"guard");this.guard=t,e!=null&&se(this,$,ea).call(this,e)}append(e,t){se(this,$,ls).call(this,e);let n=se(this,$,as).call(this,e),s=se(this,$,cs).call(this,t),o=this.map.get(n);o?o.values.push(s):this.map.set(n,{name:e,values:[s]})}delete(e){se(this,$,ra).call(this,e),this.map.delete(e.toLowerCase())}get(e){let t=this.map.get(e.toLowerCase());return t?dt.has(e.toLowerCase())?t.values[0]??null:t.values.join(", "):null}getAll(e){return[...this.map.get(e.toLowerCase())?.values??[]]}has(e){return this.map.has(e.toLowerCase())}set(e,t){se(this,$,ta).call(this,e);let n=se(this,$,as).call(this,e),s=se(this,$,cs).call(this,t);this.map.set(n,{name:e,values:[s]})}forEach(e,t){for(let[n,s]of this.map){let o=dt.has(n)?s.values:[s.values.join(", ")];for(let i of o)e.call(t,i,n,this)}}keys(){return this.map.keys()}*values(){for(let[e,t]of this.map)if(dt.has(e))for(let n of t.values)yield n;else yield t.values.join(", ")}*entries(){for(let[e,t]of this.map)if(dt.has(e))for(let n of t.values)yield[e,n];else yield[e,t.values.join(", ")]}[Symbol.iterator](){return this.entries()}get[Symbol.toStringTag](){return"HttpHeaders"}toObject(){let e={};for(let[t,n]of this.map){let s=n.values;e[t]=s.length===1?s[0]:[...s]}return e}toFlatObject(){let e={};for(let[t,n]of this.map)e[t]=dt.has(t)?n.values[0]??"":n.values.join(", ");return e}toWebHeaders(){if(typeof Headers>"u")throw new Error("WHATWG Headers is not available in this runtime");let e=new Headers;for(let[t,n]of this.map)for(let s of n.values)e.append(t,s);return e}toHTTP1String(){let e=[];for(let[,t]of this.map)for(let n of t.values)e.push(`${t.name}: ${n}`);return e.join(`\r
|
|
3
|
+
`)}clone(e){return new He(this,e??this.guard)}freeze(){return this.clone("immutable")}merge(e,t={}){let n=e instanceof He?e:new He(e);for(let[s,o]of n.map)if(t.append)for(let i of o.values)this.append(s,i);else this.map.set(s,{name:o.name,values:[...o.values]});return this}pick(...e){let t=new He;for(let n of e){let s=n.toLowerCase(),o=this.map.get(s);o&&t.map.set(s,{name:o.name,values:[...o.values]})}return t}omit(...e){let t=this.clone();for(let n of e)t.map.delete(n.toLowerCase());return t}redact(...e){let t=this.clone();for(let n of e){let s=n.toLowerCase(),o=t.map.get(s);o&&t.map.set(s,{name:o.name,values:o.values.map(()=>"**REDACTED**")})}return t}diff(e){let t=new He;for(let[n,s]of e.map){let o=this.get(n),i=dt.has(n)?s.values[0]??"":s.values.join(", ");o!==i&&t.map.set(n,{name:s.name,values:[...s.values]})}return t}get size(){return this.map.size}};$=new WeakSet,ea=function(e){if(e instanceof He){for(let[t,n]of e.map)this.map.set(t,{name:n.name,values:[...n.values]});return}if(typeof Headers<"u"&&e instanceof Headers){e.forEach((t,n)=>this.append(n,t));return}if(Array.isArray(e)){for(let t of e){if(!Array.isArray(t)||t.length<2)throw new TypeError("Headers init sequence must contain [name, value] pairs");this.append(String(t[0]),String(t[1]))}return}if(typeof e=="object")for(let[t,n]of Object.entries(e))if(Array.isArray(n))for(let s of n)this.append(t,s);else this.append(t,String(n))},as=function(e){if(!us(e))throw new TypeError(`Invalid header name: "${e}"`);return e.toLowerCase()},cs=function(e){let t=e.trim();if(!hs(t))throw new TypeError(`Invalid header value for: "${t}"`);return t},ls=function(e){if(this.guard==="immutable")throw new TypeError("Headers are immutable");if(this.guard==="request"&&Yi.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for request guard`);if(this.guard==="response"&&Ul.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for response guard`)},ta=function(e){se(this,$,ls).call(this,e)},ra=function(e){if(this.guard==="immutable")throw new TypeError("Headers are immutable");if(this.guard==="request"&&Yi.has(e.toLowerCase()))throw new TypeError(`Header "${e}" is forbidden for request guard`)};He=ce;xe=class extends ce{get contentType(){let e=this.get(w.ContentType);return e?fs(e):null}set contentType(e){if(e===null){this.delete(w.ContentType);return}if(typeof e=="string"){this.set(w.ContentType,e);return}this.set(w.ContentType,ds(e))}get contentLength(){let e=this.get(w.ContentLength);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}set contentLength(e){if(e===null){this.delete(w.ContentLength);return}this.set(w.ContentLength,String(e))}get contentDisposition(){let e=this.get(w.ContentDisposition);return e?ps(e):null}set contentDisposition(e){if(e===null){this.delete(w.ContentDisposition);return}if(typeof e=="string"){this.set(w.ContentDisposition,e);return}this.set(w.ContentDisposition,ms(e))}get cacheControl(){let e=this.get(w.CacheControl);return e?gs(e):null}set cacheControl(e){if(e===null){this.delete(w.CacheControl);return}if(typeof e=="string"){this.set(w.CacheControl,e);return}this.set(w.CacheControl,ys(e))}get authorization(){let e=this.get(w.Authorization);return e?vr(e):null}set authorization(e){if(e===null){this.delete(w.Authorization);return}this.set(w.Authorization,e)}get accept(){return Mr(this.get(w.Accept)??"")}get acceptEncoding(){return ws(this.get(w.AcceptEncoding)??"")}get acceptLanguage(){return bs(this.get(w.AcceptLanguage)??"")}get range(){let e=this.get(w.Range);return e?xs(e):null}get contentRange(){let e=this.get(w.ContentRange);return e?_s(e):null}get etag(){return this.get(w.ETag)}set etag(e){if(e===null){this.delete(w.ETag);return}let t=e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`;this.set(w.ETag,t)}get links(){let e=this.get(w.Link);return e?Ir(e):[]}get retryAfter(){let e=this.get(w.RetryAfter);return e?Ts(e):null}get hsts(){let e=this.get(w.StrictTransportSecurity);return e?Rs(e):null}set hsts(e){if(e===null){this.delete(w.StrictTransportSecurity);return}this.set(w.StrictTransportSecurity,Dr(e))}get csp(){let e=this.get(w.ContentSecurityPolicy);return e?ks(e):null}set csp(e){if(e===null){this.delete(w.ContentSecurityPolicy);return}if(typeof e=="string"){this.set(w.ContentSecurityPolicy,e);return}this.set(w.ContentSecurityPolicy,Nr(e))}get serverTiming(){let e=this.get(w.ServerTiming);return e?As(e):[]}get clientIP(){return Es(this)}get forwarded(){return Or(this)}get host(){return this.get(w.Host)}get origin(){return this.get(w.Origin)}get userAgent(){return this.get(w.UserAgent)}get location(){return this.get(w.Location)}get date(){let e=this.get(w.Date);if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get age(){let e=this.get(w.Age);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get vary(){let e=this.get(w.Vary);return e?e.split(",").map(t=>t.trim().toLowerCase()):[]}get xRequestID(){return this.get(w.XRequestID)}get xCorrelationID(){return this.get(w.XCorrelationID)}get xPoweredBy(){return this.get(w.XPoweredBy)}get xRequestedWith(){return this.get(w.XRequestedWith)}get xRateLimitLimit(){let e=this.get(w.XRateLimitLimit);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get xRateLimitRemaining(){let e=this.get(w.XRateLimitRemaining);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get xRateLimitReset(){let e=this.get(w.XRateLimitReset);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get secFetchSite(){return this.get(w.SecFetchSite)}get secFetchMode(){return this.get(w.SecFetchMode)}get secFetchUser(){return this.get(w.SecFetchUser)}get secFetchDest(){return this.get(w.SecFetchDest)}get earlyData(){let e=this.get(w.EarlyData);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get priority(){return this.get(w.Priority)}get allow(){return this.get(w.Allow)}get server(){return this.get(w.Server)}get acceptRanges(){return this.get("accept-ranges")}get lastModified(){let e=this.get("last-modified");if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get expires(){let e=this.get("expires");if(!e)return null;let t=Date.parse(e);return isNaN(t)?null:new Date(t)}get contentEncoding(){return this.get("content-encoding")}get contentLanguage(){return this.get("content-language")}get contentLocation(){return this.get("content-location")}get link(){let e=this.get(w.Link);return e?Ir(e)[0]??null:null}get altSvc(){let e=this.get(w.AltSvc);return e?Cs(e):[]}get wwwAuthenticate(){let e=this.get("www-authenticate");return e?Pr(e):null}set wwwAuthenticate(e){if(e===null){this.delete("www-authenticate");return}let t=e.map(n=>{let o=[...n.params].filter(([a])=>a!=="realm").map(([a,c])=>`${a}=${c}`).join(", "),i=n.scheme;return n.realm&&(i+=` realm="${n.realm}"`),o&&(i+=`; ${o}`),i}).join(", ");this.set("www-authenticate",t)}get proxyAuthenticate(){let e=this.get(w.ProxyAuthenticate);return e?Pr(e):null}set proxyAuthenticate(e){if(e===null){this.delete(w.ProxyAuthenticate);return}let t=e.map(n=>{let o=[...n.params].filter(([a])=>a!=="realm").map(([a,c])=>`${a}=${c}`).join(", "),i=n.scheme;return n.realm&&(i+=` realm="${n.realm}"`),o&&(i+=`; ${o}`),i}).join(", ");this.set(w.ProxyAuthenticate,t)}get proxyAuthorization(){let e=this.get(w.ProxyAuthorization);return e?vr(e):null}set proxyAuthorization(e){if(e===null){this.delete(w.ProxyAuthorization);return}if(typeof e=="string"){this.set(w.ProxyAuthorization,e);return}e.basic?this.set(w.ProxyAuthorization,`Basic ${Zi(`${e.basic.username}:${e.basic.password}`)}`):e.token?this.set(w.ProxyAuthorization,`${e.scheme} ${e.token}`):this.set(w.ProxyAuthorization,e.scheme)}get setCookies(){return this.getAll(w.SetCookie)}get accessControlAllowOrigin(){return this.get(w.AccessControlAllowOrigin)}get accessControlAllowMethods(){return this.get(w.AccessControlAllowMethods)}get accessControlAllowHeaders(){return this.get(w.AccessControlAllowHeaders)}get accessControlMaxAge(){let e=this.get(w.AccessControlMaxAge);if(!e)return null;let t=parseInt(e,10);return isNaN(t)?null:t}get accessControlCredentials(){let e=this.get(w.AccessControlAllowCredentials);return e==="true"?!0:e==="false"?!1:null}}});var _a={};fe(_a,{ContentTypeError:()=>Se,HTTPResponseError:()=>je,ResponseCache:()=>vs,ResponseDecodeError:()=>ze,ResponseSizeLimitError:()=>_e,applyDecompression:()=>Vt,assertOk:()=>Ms,assertOkJSON:()=>Os,createLimitedReader:()=>Hs,decodeBody:()=>Kt,decompressStream:()=>Hr,diffResponses:()=>Ds,extractServerTiming:()=>Us,isBinary:()=>Is,isJSON:()=>Wt,isText:()=>Ur,normalizeHeaders:()=>le,normalizeResponse:()=>Ps,parseContentType:()=>Ee,parseMultipartResponse:()=>Fr,readBlob:()=>qr,readBodyWithLimit:()=>$r,readBytes:()=>Jt,readFormData:()=>Ns,readJSON:()=>jr,readJSONStream:()=>Ls,readNDJSON:()=>Br,readStream:()=>pt,readText:()=>zr});function le(r){return rt(r)}function Ps(r){return{status:r.status,statusText:r.statusText,headers:le(r.headers),url:r.url,redirected:r.redirected,ok:r.ok,bodyUsed:r.bodyUsed}}function Ee(r){if(!r||r.length>jl)return null;let e=fs(r);return e?{mediaType:e.mediaType,type:e.type,subtype:e.subtype,charset:e.charset,boundary:e.boundary}:null}function Wt(r){if(!r)return!1;let e=Ee(r);return e?e.mediaType==="application/json"||e.subtype.endsWith("+json"):!1}function Ur(r){return r?Ee(r)?.type==="text":!1}function Is(r){return!Ur(r)&&!Wt(r)}async function $r(r,e,t,n){let s=t.onExceed??"throw",o=r.getReader(),i=[],a=0;try{for(;;){if(n?.aborted)throw await o.cancel("aborted"),new DOMException("Response reading aborted","AbortError");let{done:c,value:l}=await o.read();if(c)break;let u=a+l.byteLength;if(u>t.maxBytes){if(t.onExceedCallback?.(u,t.maxBytes),s==="throw")throw await o.cancel("size limit exceeded"),new _e(u,t.maxBytes,e);if(s==="abort"){await o.cancel("size limit exceeded");break}if(s==="truncate"){let f=t.maxBytes-a;f>0&&(i.push(l.slice(0,f)),a+=f);break}}i.push(l),a+=l.byteLength}}finally{o.releaseLock()}return xa(i)}function ql(r){return r?zl[r.toLowerCase()]??"utf-8":"utf-8"}function Bl(r){return r[0]===239&&r[1]===187&&r[2]===191?"utf-8":r[0]===255&&r[1]===254?"utf-16le":r[0]===254&&r[1]===255?"utf-16be":null}function Kt(r,e,t){let n=Bl(r),s=n??ql(e),o=n?r.slice(n==="utf-8"?3:2):r;try{return new TextDecoder(s,{fatal:!0}).decode(o)}catch{try{return new TextDecoder(s,{fatal:!1}).decode(o)}catch(i){throw new ze(String(i),s,t)}}}function Fl(r,e,t=1e8){let n=Hr(r,e),s=0,o=new TransformStream({transform(i,a){if(s+=i.byteLength,s>t){a.error(new _e(s,t,"decompression"));return}a.enqueue(i)}});return n.pipeThrough(o)}function Hr(r,e){let t=e.trim().toLowerCase();if(t==="br")return Wl(r);if(typeof DecompressionStream>"u")return r;try{let n=t,s=new DecompressionStream(n);return r.pipeThrough(s)}catch{return r}}function Wl(r){let e=!1;try{e=typeof globalThis.process?.versions?.node=="string"}catch{}return e?new ReadableStream({async start(t){let s=(await import("node:zlib")).createBrotliDecompress(),o=r.getReader();s.on("data",i=>{t.enqueue(new Uint8Array(i.buffer,i.byteOffset,i.byteLength))}),s.on("end",()=>t.close()),s.on("error",i=>t.error(i));try{for(;;){let{done:i,value:a}=await o.read();if(i){s.end();break}s.write(a)}}catch(i){s.destroy(i instanceof Error?i:new Error(String(i))),t.error(i)}finally{o.releaseLock()}},cancel(){r.cancel()}}):r}function Vt(r,e){let t=e["content-encoding"]??e["Content-Encoding"];if(!t||t==="identity")return r;let n=t.split(",").map(o=>o.trim()).filter(Boolean).reverse(),s=r;for(let o of n)s=Fl(s,o);return s}async function jr(r,e={}){let n=le(r.headers)["content-type"]??null,s=r.url;e.expectedContentType?ba(n,e.expectedContentType,s):Wt(n);let o=await $s(r,s,e),i=e.charset??Ee(n??"")?.charset??null,a=Kt(o,i,s);try{return M(JSON.parse(a))}catch(c){throw new ze(`JSON parse failed: ${c}`,"json",s)}}async function zr(r,e={}){let n=le(r.headers)["content-type"]??null,s=r.url;e.expectedContentType&&ba(n,e.expectedContentType,s);let o=await $s(r,s,e),i=e.charset??Ee(n??"")?.charset??null;return Kt(o,i,s)}async function Jt(r,e={}){let t=r.url;return await $s(r,t,e)}async function qr(r,e={}){let t=await Jt(r,e),n=r.headers.get("content-type")??"application/octet-stream",s=new ArrayBuffer(t.byteLength);return new Uint8Array(s).set(t),new Blob([s],{type:n})}function pt(r,e={}){if(!r.body)return new ReadableStream({start:s=>s.close()});let t=le(r.headers),n=r.body;return e.decompress!==!1&&(n=Vt(n,t)),e.sizeLimit&&(n=Vl(n,r.url,e.sizeLimit,e.signal)),n}async function*Br(r,e={}){let n=pt(r,e).getReader(),s=new TextDecoder("utf-8"),o="";try{for(;!e.signal?.aborted;){let{done:i,value:a}=await n.read();if(i){let l=o.trim();if(l)try{yield M(JSON.parse(l))}catch(u){e.onParseError?.(u,l)}break}o+=s.decode(a,{stream:!0});let c=o.split(`
|
|
4
|
+
`);o=c.pop()??"";for(let l of c){let u=l.trim();if(!(!u||u.startsWith("#")))try{yield M(JSON.parse(u))}catch(f){e.onParseError?.(f,u)}}}}finally{n.releaseLock()}}async function*Ls(r,e={}){let n=pt(r,e).getReader(),s=new TextDecoder("utf-8"),o=0,i="",a=-1,c=()=>{if(a===-1)return null;let l=i.slice(a);return a=-1,l};try{for(;!e.signal?.aborted;){let{done:l,value:u}=await n.read();if(l){let f=c();if(f)try{let p=M(JSON.parse(f));e.onObject?.(p),yield p}catch(p){e.onParseError?.(p,f)}break}i+=s.decode(u,{stream:!0});for(let f=0;f<i.length;f++){let p=i[f];if(p==="{"||p==="[")o===0&&(a=f),o++;else if((p==="}"||p==="]")&&(o--,o===0&&a!==-1)){let d=i.slice(a,f+1);try{let g=M(JSON.parse(d));e.onObject?.(g),yield g}catch(g){e.onParseError?.(g,d)}i=i.slice(f+1),f=-1}}if(i.length>1e7)throw new Error("JSON stream buffer exceeded 10MB limit")}}finally{n.releaseLock()}}async function Ms(r,e={}){if(!(e.isError??(o=>o>=400))(r.status))return r;let n=le(r.headers),s=null;if(e.readBody!==!1&&r.body&&!r.bodyUsed)try{s=await r.clone().text()}catch{}throw new je(r.status,r.statusText,r.url,n,s)}async function Os(r){if(r.ok)return{response:r};let e=le(r.headers),t=null;if(r.body&&!r.bodyUsed)try{t=await r.clone().text()}catch{}throw new je(r.status,r.statusText,r.url,e,t)}async function Ds(r,e){let t=le(r.headers),n=le(e.headers),s={},o={},i={};for(let[c,l]of Object.entries(t))c in n?n[c]!==l&&(s[c]=[l,n[c]]):i[c]=l;for(let[c,l]of Object.entries(n))c in t||(o[c]=l);let a=!1;try{let[c,l]=await Promise.all([r.clone().text(),e.clone().text()]);a=c!==l}catch{}return{statusChanged:r.status!==e.status,headersChanged:s,headersAdded:o,headersRemoved:i,bodyChanged:a}}async function Fr(r){let e=r.headers.get("content-type")??"",t=Ee(e);if(!t?.boundary)throw new Se("multipart/*",e,r.url);let n=await r.arrayBuffer(),s=new Uint8Array(n),o=new TextEncoder().encode("--"+t.boundary),i=[],a=l=>{for(let u=l;u<s.length-o.length;u++)if(s.subarray(u,u+o.length).every((f,p)=>f===o[p]))return u;return-1},c=a(0);if(c===-1)return[];if(c+=o.length,s[c]===13&&s[c+1]===10?c+=2:s[c]===10&&(c+=1),s[c]===45&&s[c+1]===45)return[];for(;c<s.length;){let l=a(c);if(l===-1)break;let u=l+o.length;u<s.length&&(s[u]===13&&s[u+1]===10||s[u]===10||s[u]===45&&s[u+1]);let f=s.subarray(c,l-2),p=Kl(f);if(p===-1){c=l+o.length;continue}let d=f.subarray(0,p),g=f.subarray(p+4),m=new TextDecoder().decode(d),y={};for(let b of m.split(/\r\n/)){let x=b.indexOf(":");x!==-1&&(y[b.slice(0,x).trim().toLowerCase()]=b.slice(x+1).trim())}if(i.push({headers:y,body:g}),c=l+o.length,c<s.length-1&&s[c]===45&&s[c+1]===45)break}return i}function Kl(r){for(let e=0;e<r.length-3;e++)if(r[e]===13&&r[e+1]===10&&r[e+2]===13&&r[e+3]===10)return e;return-1}async function Ns(r){let e=await Fr(r),t=new FormData;for(let n of e){let s=n.headers["content-disposition"]??"",o=s.match(/name="([^"]+)"/),i=s.match(/filename="([^"]+)"/);if(!o)continue;let a=o[1],c=i?.[1];if(c){let l=n.headers["content-type"]??"application/octet-stream",u=new ArrayBuffer(n.body.byteLength);new Uint8Array(u).set(n.body);let f=new File([u],c,{type:l});t.append(a,f)}else{let l=new TextDecoder().decode(n.body);t.append(a,l)}}return t}function Us(r){let e=r["server-timing"]??r["Server-Timing"];return e?e.split(",").map(t=>{let n=t.trim().split(";"),s=(n[0]??"").trim(),o=Hl(n.slice(1).join(";")),i=o.get("dur");return{name:s,duration:i!==void 0?parseFloat(i):null,description:o.get("desc")??null}}).filter(t=>t.name):[]}async function $s(r,e,t){if(!r.body)return new Uint8Array(0);let n=le(r.headers),s=r.body;if(t.decompress!==!1&&(s=Vt(s,n)),t.signal?.aborted)throw new DOMException("Response reading aborted","AbortError");if(t.sizeLimit)return $r(s,e,t.sizeLimit,t.signal);let o=s.getReader(),i=[];try{for(;;){if(t.signal?.aborted)throw new DOMException("Response reading aborted","AbortError");let{done:a,value:c}=await o.read();if(a)break;i.push(c)}}finally{o.releaseLock()}return xa(i)}function Vl(r,e,t,n){let s=t.onExceed??"throw",o=0;return new ReadableStream({async start(i){let a=r.getReader();try{for(;;){if(n?.aborted){await a.cancel("aborted"),i.error(new DOMException("Response reading aborted","AbortError"));return}let{done:c,value:l}=await a.read();if(c){i.close();break}let u=o+l.byteLength;if(u>t.maxBytes){if(t.onExceedCallback?.(u,t.maxBytes),s==="throw"){await a.cancel("size limit"),i.error(new _e(u,t.maxBytes,e));return}if(s==="abort"){await a.cancel("size limit"),i.close();return}if(s==="truncate"){let f=t.maxBytes-o;f>0&&i.enqueue(l.slice(0,f)),i.close(),await a.cancel("size limit");return}}o+=l.byteLength,i.enqueue(l)}}catch(c){i.error(c)}}})}function ba(r,e,t){if(!r)throw new Se(e,"(none)",t);let n=r.split(";")[0]?.trim().toLowerCase()??"",s=e.split(";")[0]?.trim().toLowerCase()??"";if(!n.startsWith(s))throw new Se(e,r,t)}function xa(r){let e=r.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.byteLength;return t}function Hs(r,e="throw"){let t={maxBytes:r,onExceed:e};return{json:(n,s)=>jr(n,{sizeLimit:t,...s}),text:(n,s)=>zr(n,{sizeLimit:t,...s}),bytes:(n,s)=>Jt(n,{sizeLimit:t,...s}),blob:(n,s)=>qr(n,{sizeLimit:t,...s}),stream:(n,s)=>pt(n,{sizeLimit:t,...s}),ndjson:(n,s)=>Br(n,{sizeLimit:t,...s})}}var Hl,je,_e,Se,ze,jl,zl,vs,Wr=F(()=>{"use strict";Ft();z();Hl=G,je=class extends Error{constructor(t,n,s,o,i){super(`HTTP ${t} ${n} \u2014 ${s}`);h(this,"code","EHTTPRESPONSE");h(this,"status");h(this,"statusText");h(this,"url");h(this,"headers");h(this,"body");this.name="HTTPResponseError",this.status=t,this.statusText=n,this.url=s,this.headers=o,this.body=i}get isClientError(){return this.status>=400&&this.status<500}get isServerError(){return this.status>=500}get isNotFound(){return this.status===404}get isUnauthorized(){return this.status===401}get isForbidden(){return this.status===403}get isTooManyRequests(){return this.status===429}get isGone(){return this.status===410}get isConflict(){return this.status===409}},_e=class extends Error{constructor(t,n,s){super(`Response size limit exceeded: read ${t} bytes, limit is ${n} bytes (${s})`);h(this,"code","ESIZELIMIT");h(this,"bytesRead");h(this,"limit");h(this,"url");this.name="ResponseSizeLimitError",this.bytesRead=t,this.limit=n,this.url=s}},Se=class extends Error{constructor(t,n,s){super(`Expected content-type "${t}", got "${n}" (${s})`);h(this,"code","ECONTENTTYPE");h(this,"expected");h(this,"received");h(this,"url");this.name="ContentTypeError",this.expected=t,this.received=n,this.url=s}},ze=class extends Error{constructor(t,n,s){super(`Failed to decode response as ${n} (${s}): ${t}`);h(this,"code","EDECODE");h(this,"charset");h(this,"url");this.name="ResponseDecodeError",this.charset=n,this.url=s}};jl=8192;zl={"utf-8":"utf-8",utf8:"utf-8","latin-1":"latin1",latin1:"latin1","iso-8859-1":"latin1",ascii:"ascii","us-ascii":"ascii","utf-16le":"utf-16le","utf-16":"utf-16le","utf-16be":"utf-16be","windows-1252":"windows-1252",cp1252:"windows-1252"};vs=class{constructor(e={ttlMs:6e4}){h(this,"cache",new Map);h(this,"ttlMs");this.ttlMs=e.ttlMs}hashRequest(e){let t=typeof e=="string"?e:e.url;return`${typeof e=="string"?"GET":e.method}:${t}`}async get(e){let t=this.hashRequest(e),n=this.cache.get(t);return n?Date.now()>n.expiresAt?(this.cache.delete(t),null):await Promise.resolve(n.response.clone()):null}async set(e,t){let n=this.hashRequest(e);await Promise.resolve(this.cache.set(n,{response:t.clone(),expiresAt:Date.now()+this.ttlMs}))}delete(e){this.cache.delete(this.hashRequest(e))}clear(){this.cache.clear()}get size(){return this.cache.size}}});var Aa={};fe(Aa,{FetchTransport:()=>qe,HAS_NATIVE_FETCH:()=>qs,HTTP_STATUS_TEXTS:()=>ka,IS_NODE:()=>Be,NodeHTTP2Transport:()=>mt,RUNTIME:()=>me,createTransport:()=>Qt,decompressBodyStream:()=>Xt,detectRuntime:()=>Vr,getEffectiveRuntime:()=>zs,normalizeHeaders:()=>Ea,parseBody:()=>gt,readRawBody:()=>Gt,sendWithTimeout:()=>Fe,setRuntime:()=>js});function Vr(){let r=globalThis.Deno;return typeof r<"u"&&typeof r.version<"u"?"deno":typeof globalThis.Bun<"u"?"bun":typeof globalThis<"u"&&typeof globalThis.caches<"u"?"cloudflare-workers":typeof window<"u"&&typeof globalThis.document<"u"?"browser":Kr.process?.versions?.node!==void 0?"node":typeof globalThis.fetch=="function"?"edge":"unknown"}function js(r){Sa=r}function zs(){return Sa??me}function Jl(){try{return globalThis.process?.env?.NODE_ENV==="production"}catch{return!1}}function Qt(r,e=!0,t,n){return Be&&e&&!r?new mt({...t?.sessionTTLMs!==void 0?{sessionTTLMs:t.sessionTTLMs}:{},...t?.pingIntervalMs!==void 0?{pingIntervalMs:t.pingIntervalMs}:{},...t?.connectTimeoutMs!==void 0?{connectTimeoutMs:t.connectTimeoutMs}:{},...t?.requestTimeoutMs!==void 0?{requestTimeoutMs:t.requestTimeoutMs}:{},...n?.strict!==void 0?{strict:n.strict}:{},...n?.onDroppedHeader!==void 0?{onDroppedHeader:n.onDroppedHeader}:{}}):new qe({fetchFn:r??globalThis.fetch,...n?.strict!==void 0?{strict:n.strict}:{},...n?.onDroppedHeader!==void 0?{onDroppedHeader:n.onDroppedHeader}:{}})}async function Fe(r,e,t){if(t<=0)return r.send(e);let n=new AbortController,s=setTimeout(()=>{n.abort(new Q(t,e))},t),o=gr(e.signal,n.signal)??null,i={...e,signal:o},a=new Promise((c,l)=>{n.signal.addEventListener("abort",()=>l(new Q(t,e)),{once:!0})});try{let c=await Promise.race([r.send(i),a]);if(clearTimeout(s),n.signal.aborted)throw new Q(t,e);return c}catch(c){throw clearTimeout(s),n.signal.aborted&&!(c instanceof Q)?new Q(t,e):c}}async function Gt(r,e,t,n){if(!r)return new Uint8Array(0);let s=r.getReader(),o=[],i=0,a,c=new Promise((u,f)=>{a=f}),l=()=>{s.cancel("aborted").catch(()=>{}),a(new S("Response reading aborted","EABORT"))};if(n?.aborted)throw s.cancel("aborted").catch(()=>{}),new S("Response reading aborted","EABORT");n?.addEventListener("abort",l,{once:!0});try{for(;;){let u=await Promise.race([s.read().catch(d=>{throw s.cancel("read error").catch(()=>{}),d}),c]),{done:f,value:p}=u;if(f)break;if(e>0){let d=i+p.byteLength;if(d>e)throw await s.cancel("size limit exceeded"),new st(d,e)}o.push(p),i+=p.byteLength}}catch(u){throw s.cancel("error during read").catch(()=>{}),u}finally{n?.removeEventListener("abort",l),s.releaseLock()}return mr(o)}function gt(r,e,t,n,s,o){if(t)return t(r,s??{},o??"");if(!r.byteLength)return null;let i=e?.split(";")[0]?.trim().toLowerCase()??"";if(i==="application/json"||i.endsWith("+json")){let a=new TextDecoder("utf-8").decode(r),c,l;try{let u=de(a,{maxStringLength:1e7,maxDepth:100,maxArrayLength:1e5});u.success&&u.value!==void 0&&(c=u.value)}catch(u){l=u instanceof Error?u:new Error(String(u))}if(c!==void 0)return c;if(n)try{n(r,l??new Error("JSON parse failed \u2014 falling back to raw text"))}catch{}return a}return i.startsWith("text/")?new TextDecoder("utf-8").decode(r):r}function Ea(r){return rt(r)}function Ql(r,e){let t=r;if(t.httpVersion==="2.0"||t.httpVersion==="2")return"HTTP/2";let n=r;if(n.httpVersion)return n.httpVersion;let s=r.headers.get("alt-svc"),o=r;if(o.httpVersion==="3"||o.httpVersion==="3.0"||o.protocol==="h3")return"HTTP/3";if(s){let i=s.includes('h3="')||s.includes("h3-29=")||s.includes("h3-32=");if(s.includes('h2="')||i)return"HTTP/2"}return"HTTP/1.1"}function Gl(r){if(!(r instanceof Error))return!1;let e=r.message.toLowerCase();return e.includes("alpn")||e.includes("h2")||e.includes("http2")||r.code==="ERR_HTTP2_ERROR"}function Ta(r){return new ReadableStream({start(e){let t=!1,n=!1;r.on("data",s=>{if(s instanceof Uint8Array)e.enqueue(s);else if(Kr.Buffer?.isBuffer(s)){let o=s;e.enqueue(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))}else e.enqueue(new Uint8Array(s))}),r.once("end",()=>{if(!(t||n)){t=!0;try{e.close()}catch{}}}),r.once("error",s=>{if(!(t||n)){t=!0,n=!0;try{e.error(s)}catch{}}}),r.once("close",()=>{if(t||n)return;t=!0;let s=Object.assign(new Error("Stream closed before end"),{code:"ECONNRESET"});try{e.error(s)}catch{}})},cancel(){r.destroy()}})}async function Ra(r,e){r.write(e)||await new Promise(n=>r.once("drain",n))}async function Yl(r,e){if(e instanceof ReadableStream){let t=e.getReader();for(;;){let{done:n,value:s}=await t.read();if(n){r.end();break}await Ra(r,s)}}else e instanceof Uint8Array||e instanceof ArrayBuffer?r.end(Kr.Buffer?new Uint8Array(e):e):typeof e=="string"?r.end(e):r.end()}async function Zl(r,e){if(e instanceof ReadableStream){let t=e.getReader();for(;;){let{done:n,value:s}=await t.read();if(n){r.end();break}await Ra(r,s)}}else e instanceof Uint8Array||e instanceof ArrayBuffer?r.end(Kr.Buffer?new Uint8Array(e):e):typeof e=="string"?r.end(e):r.end()}async function Xt(r,e){if(!r)return null;let t=e["content-encoding"]??e["Content-Encoding"];if(!t)return r;let n=t.trim().toLowerCase(),s=n.split(",").map(a=>a.trim()).filter(Boolean),o=["gzip","deflate","br","identity"];for(let a of s)if(!o.includes(a))return console.warn(`[Kinetex] Unsupported Content-Encoding: ${a}. Supported: ${o.join(", ")}. Response body is passed through compressed.`),r;if(n==="identity")return delete e["content-encoding"],delete e["Content-Encoding"],r;let{applyDecompression:i}=await Promise.resolve().then(()=>(Wr(),_a));return i(r,e)}var Kr,me,Sa,Be,qs,qe,mt,Xl,ka,Yt=F(()=>{"use strict";Ne();z();Ft();z();Kr=globalThis;me=Vr(),Sa=null;Be=me==="node",qs=me!=="node"||typeof globalThis.fetch=="function";qe=class{constructor(e=globalThis.fetch){h(this,"fetchFn");h(this,"strict");h(this,"onDroppedHeader");typeof e=="function"?(this.fetchFn=e,this.strict=!1,this.onDroppedHeader=void 0):(this.fetchFn=e.fetchFn??globalThis.fetch,this.strict=e.strict??!1,this.onDroppedHeader=e.onDroppedHeader)}async send(e){let t={};for(let[l,u]of Object.entries(e.headers??{}))if(!(typeof l!="string"||typeof u!="string")){if(!us(l)||!hs(u)){if(this.strict)throw new S(`Invalid header dropped in strict mode: "${l}"`,"EVALIDATION",{request:e});this.onDroppedHeader?this.onDroppedHeader(l,u):Jl()||console.warn(`[kinetex] Invalid header dropped: "${l}" \u2014 value may contain illegal characters. Pass strictHeaders: true to throw instead.`);continue}t[l]=u}let n=t["accept-encoding"];n&&n.toLowerCase().includes("gzip")&&n.toLowerCase().includes("deflate")&&n.toLowerCase().includes("br")&&delete t["accept-encoding"];let s={method:e.method,headers:t,redirect:e.redirect??"follow",...e.signal!==null?{signal:e.signal}:{}};e.body!==null&&e.method!=="GET"&&e.method!=="HEAD"&&(s.body=e.body,Be&&typeof s.body=="object"&&s.body!==null&&"getReader"in s.body&&(s.duplex="half"));let o;try{o=await this.fetchFn(e.url,s)}catch(l){throw yr(l)?new S("Request was aborted","EABORT",{request:e,cause:l}):new S(l instanceof Error?l.message:"Network request failed","ENETWORK",{request:e,cause:l})}let i=Ea(o.headers),a=Ql(o,i),c=!0;return me==="deno"&&(o.headers.get("content-encoding")||"").toLowerCase().includes("deflate")&&(c=!1),{status:o.status,statusText:o.statusText,headers:i,body:o.body,url:o.url||e.url,redirected:o.redirected,httpVersion:a,alreadyDecompressed:c}}},mt=class{constructor(e={}){h(this,"sessions",new Map);h(this,"sessionTTLMs");h(this,"pingIntervalMs");h(this,"maxSessions");h(this,"pingTimers",new Map);h(this,"_sessionCreating",new Map);h(this,"sessionUsage",new Map);h(this,"_strict");h(this,"_onDroppedHeader");h(this,"_ca");h(this,"_connectTimeoutMs");h(this,"_requestTimeoutMs");h(this,"_http1Fallback",null);this.sessionTTLMs=e.sessionTTLMs??5*6e4,this.pingIntervalMs=e.pingIntervalMs??3e4,this.maxSessions=e.maxSessions??100,this._strict=e.strict??!1,this._onDroppedHeader=e.onDroppedHeader,this._ca=e.ca,this._connectTimeoutMs=e.connectTimeoutMs??3e4,this._requestTimeoutMs=e.requestTimeoutMs??3e4}_getOrCreateSession(e,t,n){let s=this._sessionCreating.get(e);if(s)return s;let o=this._createSession(e,t,n);return this._sessionCreating.set(e,o),o.finally(()=>{this._sessionCreating.get(e)===o&&this._sessionCreating.delete(e)}).catch(()=>{}),o}async _createSession(e,t,n){let s=this.sessions.get(e);if(s&&!s.session.destroyed&&!s.session.closed&&!(Date.now()-s.createdAt>this.sessionTTLMs))return this.sessionUsage.set(e,Date.now()),s.session;if(s&&this._evictSession(e,s.session),this.sessions.size>=this.maxSessions){let i="",a=1/0;for(let[c,l]of this.sessionUsage.entries())l<a&&(a=l,i=c);if(i){let c=this.sessions.get(i);c&&this._evictSession(i,c.session)}}let o=await new Promise((i,a)=>{let c=n.connect(e,{rejectUnauthorized:!0,...this._ca!==void 0?{ca:this._ca}:{}}),l=setTimeout(()=>{c.destroy(),a(new S(`HTTP/2 connection to ${e} timed out`,"ETIMEOUT",{request:t}))},this._connectTimeoutMs);typeof l.unref=="function"&&l.unref();let u=()=>{clearTimeout(l),c.destroy(),a(new S("Connection aborted","EABORT",{request:t}))},f=()=>t.signal?.removeEventListener("abort",u);t.signal?.addEventListener("abort",u,{once:!0}),c.once("connect",()=>{f(),clearTimeout(l),i(c)}),c.once("error",p=>{f(),clearTimeout(l),a(p)})});if(o.on("goaway",()=>{this._evictSession(e,o)}),o.on("error",()=>{this._evictSession(e,o)}),this.sessions.set(e,{session:o,createdAt:Date.now()}),this.sessionUsage.set(e,Date.now()),this.pingIntervalMs>0){let i=this.pingTimers.get(e);i&&clearInterval(i);let a=setInterval(()=>{let c=this.sessions.get(e);if(!c||c.session.destroyed||c.session.closed){this._evictSession(e,c?.session);return}c.session.ping(l=>{l&&this._evictSession(e,c.session)})},this.pingIntervalMs);typeof a=="object"&&a!==null&&"unref"in a&&a.unref(),this.pingTimers.set(e,a)}return o}async send(e){let t=new URL(e.url);if(t.protocol!=="https:"||e.httpVersion==="HTTP/1.1")return this._sendHTTP1(e);try{return await this._sendHTTP2(e,t)}catch(n){if(Gl(n))return this._sendHTTP1(e);throw n}}async _sendHTTP2(e,t){let n=await import("node:http2"),s=e,o=t,i=!1,a=10;for(let c=0;c<=a;c++){if(c===a)throw new S("Too many HTTP/2 redirects","ENETWORK",{request:e});let l=o.origin,u=this.sessions.get(l),f=u&&Date.now()-u.createdAt>this.sessionTTLMs,p;!u||u.session.destroyed||u.session.closed||f?p=await this._getOrCreateSession(l,s,n):(p=u.session,this.sessionUsage.set(l,Date.now()));let d={":method":s.method,":path":o.pathname+o.search,":scheme":"https",":authority":o.host,...s.headers};for(let[_,v]of Object.entries(d)){if(_.startsWith(":"))continue;let O=Array.isArray(v)?v.join(", "):String(v),H=!1;for(let j=0;j<O.length;j++){let ne=O.charCodeAt(j);if(ne>=0&&ne<=8||ne>=10&&ne<=31||ne===127){H=!0;break}}if(H){if(this._strict)throw new S(`Strict mode: header "${_}" contains forbidden control characters`,"EVALIDATION",{request:s});this._onDroppedHeader?this._onDroppedHeader(_,O):typeof console<"u"&&console.warn(`[kinetex] Invalid header dropped (HTTP/2): "${_}" \u2014 value contains illegal control characters. Pass strictHeaders: true to throw instead.`),delete d[_]}}let g=!s.body||s.method==="GET"||s.method==="HEAD",m=p.request(d,{endStream:g});s.body&&!g&&Yl(m,s.body).catch(_=>{m.destroy(_ instanceof Error?_:new Error(String(_)))});let y=s.signal,b=await new Promise((_,v)=>{let O=this._requestTimeoutMs,H=setTimeout(()=>{ne(),v(new S(`HTTP/2 request to ${o} timed out after ${O}ms`,"ETIMEOUT",{request:s})),m.destroy()},O),j=()=>{clearTimeout(H),v(new S("Request was aborted","EABORT",{request:s})),m.destroy()},ne=()=>y?.removeEventListener("abort",j);y?.addEventListener("abort",j,{once:!0}),m.once("response",k=>{let P=Number(k[":status"]??200),C=ka[P]??"",L={};for(let[V,D]of Object.entries(k))V.startsWith(":")||(L[V]=Array.isArray(D)?D.join(", "):D??"");if(clearTimeout(H),ne(),y?.aborted){v(new S("Request was aborted","EABORT",{request:s})),m.destroy();return}if(s.redirect==="error"&&P>=300&&P<400&&L.location){v(new S(`Redirect not allowed (redirect:"error") \u2014 received ${P} to ${L.location}`,"ENETWORK",{request:s})),m.destroy();return}_({status:P,statusText:C,headers:L,body:Ta(m),url:s.url,redirected:i,httpVersion:"HTTP/2",alreadyDecompressed:!1})}),m.once("error",k=>{clearTimeout(H),ne(),y?.aborted?v(new S("Request was aborted","EABORT",{request:s,cause:k})):v(new S(k.message,"ENETWORK",{request:s,cause:k})),m.destroy()})});if(!(b.status>=300&&b.status<400&&!!b.headers.location&&s.redirect!=="manual"))return b;try{if(b.body){let _=b.body.getReader();for(;;){let{done:v}=await _.read();if(v)break}_.releaseLock()}}catch{}let E=b.headers.location,R;try{R=new URL(E,s.url).href}catch{throw new S(`Invalid redirect Location: ${E}`,"ENETWORK",{request:e})}let A=b.status===301||b.status===302||b.status===303?"GET":s.method,U=A==="GET"||A==="HEAD"?null:s.body;s={...s,url:R,method:A,body:U},o=new URL(R),i=!0}throw new S("HTTP/2 redirect loop terminated unexpectedly","ENETWORK",{request:e})}_sendHTTP1(e){if(typeof globalThis.fetch=="function"){if(!this._http1Fallback){let t={fetchFn:globalThis.fetch,strict:this._strict};this._onDroppedHeader!==void 0&&(t.onDroppedHeader=this._onDroppedHeader),this._http1Fallback=new qe(t)}return this._http1Fallback.send(e)}return this._sendHTTP1Legacy(e)}async _sendHTTP1Legacy(e){let t=await import("node:https"),n=new URL(e.url),s={hostname:n.hostname,port:n.port||"443",path:n.pathname+n.search,method:e.method,headers:e.headers};return new Promise((o,i)=>{let a=t.request(s,u=>{let f={};for(let[d,g]of Object.entries(u.headers))g!==void 0&&(f[d]=Array.isArray(g)?g.join(", "):g);let p=Xl(u);o({status:u.statusCode??200,statusText:u.statusMessage??"",headers:f,body:p,url:e.url,redirected:!1,httpVersion:"HTTP/1.1",alreadyDecompressed:!1})});a.once("error",u=>{i(new S(u.message,"ENETWORK",{request:e,cause:u}))});let c=()=>{a.destroy(),i(new S("Request was aborted","EABORT",{request:e}))};e.signal?.addEventListener("abort",c,{once:!0});let l=()=>e.signal?.removeEventListener("abort",c);a.once("close",l),a.once("error",l),e.body&&e.method!=="GET"&&e.method!=="HEAD"?Zl(a,e.body).catch(i):a.end()})}_evictSession(e,t){let n=this.pingTimers.get(e);n&&(clearInterval(n),this.pingTimers.delete(e)),this.sessions.delete(e),this.sessionUsage.delete(e),this._sessionCreating.delete(e),t&&!t.destroyed&&!t.closed&&t.destroy()}destroy(){for(let e of this.pingTimers.values())clearInterval(e);this.pingTimers.clear(),this._sessionCreating.clear();for(let[e,{session:t}]of this.sessions.entries())this._evictSession(e,t);this.sessions.clear()}};Xl=Ta;ka={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"}});function ru(r){return r.split(tu).filter(Boolean)}function nu(r){let e=r.match(/^(\d{1,2}):(\d{2}):(\d{2})(?:[+-]\d{2}:?\d{2}|Z|GMT|UTC)?$/i);if(!e)return null;let t=+e[1],n=+e[2],s=+e[3];return t>23||n>59||s>59?null:[t,n,s]}function su(r){let e=r.slice(0,9).toLowerCase();return eu[e]??null}function ou(r){if(!/^\d{2,4}$/.test(r))return null;let e=+r;return e>=70&&e<=99&&(e+=1900),e>=0&&e<=69&&(e+=2e3),e}function Zt(r){if(!r)return null;let e=ru(r),t={time:null,dayOfMonth:null,month:null,year:null};for(let a of e)if(a){if(t.time===null&&a.includes(":")){let c=nu(a);if(c!==null){t.time=c;continue}}if(t.month===null&&/[a-zA-Z]/.test(a)){let c=su(a);if(c!==null){t.month=c;continue}}if(/^\d{1,4}(?:st|nd|rd|th)?$/i.test(a)){let c=a.replace(/[a-z]+$/i,""),l=+c;if(t.dayOfMonth===null&&c.length<=2&&l>=1&&l<=31){t.dayOfMonth=l;continue}if(t.year===null&&c.length>=2){let u=ou(c);if(u!==null){t.year=u;continue}}if(t.dayOfMonth===null&&l>=1&&l<=31){t.dayOfMonth=l;continue}}}if(t.time===null||t.dayOfMonth===null||t.month===null||t.year===null||t.year<1601||t.year>9999||t.dayOfMonth<1||t.dayOfMonth>31)return null;let[n,s,o]=t.time,i=Date.UTC(t.year,t.month,t.dayOfMonth,n,s,o);return isNaN(i)?null:i}function yt(r){let e=r.replace(/\.$/,"").toLowerCase(),t=e.split(".");if(t.length===0||t.length===1&&t[0]==="")return null;if(Ks.has(e))return e;let n=null,s=0;for(let o=0;o<t.length;o++){let i=t.slice(o).join(".");if(Fs.has(i)){let a=t.length-o;a>s&&(s=a,n=i)}}for(let o=0;o<t.length-1;o++){let i=t.slice(o+1).join(".");if(Ws.has(i)){let a=t.slice(o).join("."),c=t.length-o;c>s&&(s=c,n=a)}}return n||(t[t.length-1]??null)}function Qr(r){let e=r.toLowerCase();if(ge(e))return e;let t=yt(e);if(!t)return null;let n=t.split(".").length,s=e.split(".");return s.length<=n?null:s.slice(-(n+1)).join(".")}function wt(r){let e=r.toLowerCase();if(Ks.has(e)||Fs.has(e))return!0;let t=e.split(".");if(t.length>=2){let n=t.slice(1).join(".");if(Ws.has(n))return!0}return!1}function au(r){try{let c=r.lastIndexOf("-"),l=[],u=c>=0?r.slice(0,c):"";for(let E=0;E<u.length;E++){let R=u.charCodeAt(E);if(R>122||R>90&&R<97||R>57&&R<65||R<48)return r;l.push(R)}let f=c>=0?r.slice(c+1):r,p=128,d=0,g=72,m=E=>E>=65&&E<=90?E-65:E>=97&&E<=122?E-97:E>=48&&E<=57?E-48+26:-1,y=(E,R,A)=>{E=Math.floor(E/(A?700:2)),E+=Math.floor(E/R);let U=0;for(;E>910/2;)E=Math.floor(E/35),U+=36;return U+Math.floor(36*E/(E+38))},b=0;for(;b<f.length;){let E=d,R=1;for(let A=36;;A+=36){if(b>=f.length)return r;let U=m(f.charCodeAt(b++));if(U<0)return r;d+=U*R;let _=A<=g?1:A>=g+26?26:A-g;if(U<_)break;R*=36-_}g=y(d-E,l.length+1,E===0),p+=Math.floor(d/(l.length+1)),d%=l.length+1,l.splice(d,0,p),d++}return String.fromCodePoint(...l)||r}catch{return r}}function er(r){if(!r.toLowerCase().startsWith("xn--"))return r;let e=Intl;if(typeof Intl<"u"&&e.IDN&&typeof e.IDN.toUnicode=="function")try{return e.IDN.toUnicode(r,{standard:"tr46"})}catch{return r}if(Bs){let t=r+".invalid",n=Bs(t);if(n&&n.length>8&&n.endsWith(".invalid")){let s=n.slice(0,-8);if(s!==r)return s}}if(r.startsWith("xn--"))try{let t=au(r.slice(4));if(t&&t!==r.slice(4))return t}catch{}return r}function ue(r){return r.replace(/^\./,"").replace(/\.$/,"").toLowerCase().split(".").map(er).join(".")}function ge(r){let e=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;return cu.test(e)?e.split(".").map(Number).every(n=>n>=0&&n<=255):lu.test(e)&&e.includes(":")}function bt(r,e){let t=r.toLowerCase(),n=e.toLowerCase();return t===n?!0:!(ge(t)||!t.endsWith("."+n)||ge(n)||yt(t)===t)}function xt(r){if(!r||r===""||r[0]!=="/")return"/";let e=r.lastIndexOf("/");return e===0?"/":r.slice(0,e)}function Jr(r){if(!r.startsWith("/"))return"/"+r;let e=[],t=r.split("/");for(let n of t)n===""||n==="."||(n===".."?e.length>0&&e.pop():e.push(n));return"/"+e.join("/")}function _t(r,e){let t=Jr(r),n=Jr(e);return!!(t===n||t.startsWith(n)&&(n.endsWith("/")||t[n.length]==="/"))}function hu(r){return r===""?!0:uu.test(r)}function fu(r){for(let e=0;e<r.length;e++){let t=r.charCodeAt(e);if(t>=0&&t<=8||t>=10&&t<=31||t===127)return!1}return!0}function St(r){if(!r||r.trim()==="")return null;let e=r.indexOf(";"),t=e===-1?r:r.slice(0,e),n=e===-1?"":r.slice(e+1),s=t.indexOf("="),o,i;if(s===-1?(o="",i=t.trim()):(o=t.slice(0,s).trim(),i=t.slice(s+1).trim()),!hu(o)||(i.length>=2&&i[0]==='"'&&i[i.length-1]==='"'&&(i=i.slice(1,-1)),!fu(i)))return null;let a=new Map,c=n.split(";");for(let _ of c){let v=_.trim();if(!v)continue;let O=v.indexOf("=");if(O===-1)a.set(v.toLowerCase(),"");else{let H=v.slice(0,O).trim().toLowerCase(),j=v.slice(O+1).trim();a.has(H)||a.set(H,j)}}let l=a.has("domain")?a.get("domain"):null,u=a.has("path")?a.get("path"):null,f=a.has("expires")?a.get("expires"):null,p=a.has("max-age")?a.get("max-age"):null,d=a.has("secure"),g=a.has("httponly"),m="Unset";if(a.has("samesite")){let _=a.get("samesite").toLowerCase();_==="strict"?m="Strict":_==="lax"?m="Lax":_==="none"&&(m="None")}let y=a.has("sameparty"),b=null;if(a.has("priority")){let _=a.get("priority").toLowerCase();_==="low"?b="Low":_==="medium"?b="Medium":_==="high"&&(b="High")}let x=a.has("partitioned"),E=null;p!==null&&p.match(/^-?\d+$/)&&(E=parseInt(p,10));let R=null;E===null&&f!==null&&(R=Zt(f));let A=null;l!==null&&l!==""&&(A=ue(l));let U=null;return u!==null&&u.startsWith("/")&&(U=u),{name:o,value:i,domain:A,path:U,expires:R,maxAge:E,secure:d,httpOnly:g,sameSite:m,sameParty:y,priority:b,partitioned:x}}function Ca(r){let e=[];if(r.value.includes(";")||r.value.includes(",")||r.value.includes(" ")||r.value.includes('"')?e.push(`${r.name}="${r.value.replace(/"/g,'\\"')}"`):e.push(`${r.name}=${r.value}`),r.path&&e.push(`Path=${r.path}`),r.domain&&e.push(`Domain=${r.domain}`),r.expires!==null){let t=new Date(r.expires);e.push(`Expires=${t.toUTCString()}`)}return r.maxAge!==null&&e.push(`Max-Age=${r.maxAge}`),r.secure&&e.push("Secure"),r.httpOnly&&e.push("HttpOnly"),r.sameSite&&r.sameSite!=="Unset"&&e.push(`SameSite=${r.sameSite}`),r.sameParty&&e.push("SameParty"),r.priority&&e.push(`Priority=${r.priority}`),r.partitioned&&e.push("Partitioned"),e.join("; ")}function We(r){let e=[],t="",n=0,s=!1,o=!1,i=!1,a=!1,c=!1,l=()=>{i&&a&&t.trim()&&e.push(t.trim()),t="",i=!1,a=!1,c=!1};for(;n<r.length;){let u=r[n],f=r[n+1]??"";if(o){t+=u,o=!1,n++;continue}if(u==="\\"&&(s||f==='"'||f==="\\")){t+=u,o=!0,n++;continue}if(u==='"'){!s&&i?s=!0:s&&(s=!1,a=!0),t+=u,n++;continue}if(s){t+=u,n++;continue}if(u===","&&!s&&(c||a||i)){for(l();n+1<r.length&&/\s/.test(r[n+1]);)n++;n++;continue}if(u===";"){i||(i=!0),a&&(c=!0),t+=u,n++;continue}if(u==="="&&!i){i=!0,a=!0,t+=u,n++;continue}if(i&&!a&&u!==";"&&u!==","&&(a=!0),u===" "||u===" "){t.length>0&&t.trim()!==""&&(t+=u),n++;continue}t+=u,n++}return i&&a&&t.trim()&&e.push(t.trim()),e}function Et(r){if(typeof Headers<"u"&&r instanceof Headers){if(typeof r.getSetCookie=="function")return r.getSetCookie();let n=r.get("set-cookie");return n?We(n):[]}let e=r,t=e["set-cookie"]??e["Set-Cookie"];return t?Array.isArray(t)?t.flatMap(n=>We(n)):We(t):[]}var eu,tu,iu,Fs,Ws,Ks,Bs,cu,lu,uu,Gr=F(()=>{"use strict";eu={jan:0,january:0,feb:1,february:1,mar:2,march:2,apr:3,april:3,may:4,jun:5,june:5,jul:6,july:6,aug:7,august:7,sep:8,september:8,oct:9,october:9,nov:10,november:10,dec:11,december:11},tu=/[\t\x20-\x2f\x3b-\x40\x5b-\x60\x7b-\x7e]+/;iu=["!www.ck","!city.kobe.jp","!city.nagoya.jp","!city.sapporo.jp","!city.sendai.jp","!city.yokohama.jp","*.ck","*.er","*.bd","*.fj","*.fk","*.gu","*.jm","*.kh","*.mm","*.np","*.pg","*.ss","*.tp","*.vi","*.ye","*.zm","*.kawasaki.jp","*.kitakyushu.jp","*.kobe.jp","*.nagoya.jp","*.osaka.jp","*.sapporo.jp","*.sendai.jp","*.yokohama.jp","com","net","org","edu","gov","mil","int","arpa","info","biz","name","mobi","tel","travel","museum","coop","aero","pro","jobs","cat","post","xxx","app","dev","io","ai","co","me","tv","fm","blog","shop","store","online","site","web","tech","cloud","digital","media","news","press","agency","solutions","services","systems","network","group","team","studio","design","art","photography","email","marketing","consulting","management","finance","money","bank","insurance","healthcare","medical","hospital","clinic","pharmacy","dental","legal","law","attorney","lawyer","accountant","pm","sh","ac","cc","cx","nu","ms","pw","sc","sx","tc","tk","ac","ad","ae","af","ag","ai","al","am","an","ao","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cu","cv","cw","cx","cy","cz","de","dj","dk","dm","do","dz","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","su","sv","sx","sy","sz","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","uk","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","yt","za","zm","zw","com.au","net.au","org.au","edu.au","gov.au","asn.au","id.au","info.au","conf.au","oz.au","act.au","nsw.au","nt.au","qld.au","sa.au","tas.au","vic.au","wa.au","com.br","net.br","org.br","edu.br","gov.br","mil.br","art.br","ind.br","adm.br","adv.br","agr.br","am.br","arq.br","ato.br","b.br","bio.br","blog.br","bmd.br","cim.br","cng.br","cnt.br","coop.br","ecn.br","eco.br","emp.br","eng.br","esp.br","etc.br","eti.br","far.br","flog.br","fm.br","fnd.br","fot.br","fst.br","g12.br","ggf.br","imb.br","inf.br","jor.br","jus.br","leg.br","lel.br","mat.br","med.br","mp.br","mus.br","not.br","ntr.br","odo.br","ppg.br","pro.br","psc.br","psi.br","qsl.br","radio.br","rec.br","slg.br","srv.br","taxi.br","teo.br","tmp.br","trd.br","tur.br","tv.br","vet.br","vlog.br","wiki.br","zlg.br","ab.ca","bc.ca","mb.ca","nb.ca","nf.ca","nl.ca","ns.ca","nt.ca","nu.ca","on.ca","pe.ca","qc.ca","sk.ca","yk.ca","com.cn","net.cn","org.cn","edu.cn","gov.cn","mil.cn","ac.cn","ah.cn","bj.cn","cq.cn","fj.cn","gd.cn","gs.cn","gz.cn","gx.cn","ha.cn","hb.cn","he.cn","hi.cn","hl.cn","hn.cn","jl.cn","js.cn","jx.cn","ln.cn","nm.cn","nx.cn","qh.cn","sc.cn","sd.cn","sh.cn","sn.cn","sx.cn","tj.cn","xj.cn","xz.cn","yn.cn","zj.cn","co.uk","me.uk","org.uk","ltd.uk","plc.uk","net.uk","sch.uk","gov.uk","nhs.uk","police.uk","mod.uk","ac.uk","judiciary.uk","parliament.uk","co.jp","ne.jp","or.jp","ac.jp","ad.jp","ed.jp","go.jp","gr.jp","lg.jp","aichi.jp","akita.jp","aomori.jp","chiba.jp","ehime.jp","fukui.jp","fukuoka.jp","fukushima.jp","gifu.jp","gunma.jp","hiroshima.jp","hokkaido.jp","hyogo.jp","ibaraki.jp","ishikawa.jp","iwate.jp","kagawa.jp","kagoshima.jp","kanagawa.jp","kochi.jp","kumamoto.jp","kyoto.jp","mie.jp","miyagi.jp","miyazaki.jp","nagano.jp","nagasaki.jp","nara.jp","niigata.jp","oita.jp","okayama.jp","okinawa.jp","osaka.jp","saga.jp","saitama.jp","shiga.jp","shimane.jp","shizuoka.jp","tochigi.jp","tokushima.jp","tokyo.jp","tottori.jp","toyama.jp","wakayama.jp","yamagata.jp","yamaguchi.jp","yamanashi.jp","co.nz","net.nz","org.nz","edu.nz","govt.nz","school.nz","geek.nz","maori.nz","iwi.nz","mil.nz","parliament.nz","ac.nz","co.za","net.za","org.za","edu.za","gov.za","mil.za","ac.za","alt.za","agric.za","cybernet.za","db.za","grondar.za","nis.za","nom.za","ngo.za","pty.za","school.za","tm.za","web.za","co.in","net.in","org.in","edu.in","gov.in","mil.in","ac.in","res.in","firm.in","gen.in","ind.in","int.in","nic.in","com.ar","net.ar","org.ar","edu.ar","gov.ar","mil.ar","int.ar","tur.ar","com.mx","net.mx","org.mx","edu.mx","gob.mx","com.sg","net.sg","org.sg","edu.sg","gov.sg","per.sg","com.hk","net.hk","org.hk","edu.hk","gov.hk","idv.hk","com.tw","net.tw","org.tw","edu.tw","gov.tw","mil.tw","idv.tw","game.tw","ebiz.tw","club.tw","com.my","net.my","org.my","edu.my","gov.my","mil.my","name.my","sch.my","com.ph","net.ph","org.ph","edu.ph","gov.ph","mil.ph","ngo.ph","i.ph","com.pk","net.pk","org.pk","edu.pk","gov.pk","mil.pk","ac.pk","res.pk","biz.pk","fam.pk","gob.pk","gok.pk","gon.pk","gop.pk","gos.pk","info.pk","com.eg","net.eg","org.eg","edu.eg","gov.eg","mil.eg","sci.eg","eun.eg","info.eg","name.eg","com.sa","net.sa","org.sa","edu.sa","gov.sa","med.sa","pub.sa","sch.sa","com.ae","net.ae","org.ae","edu.ae","gov.ae","mil.ae","sch.ae","ac.ae","pro.ae","name.ae","com.tr","net.tr","org.tr","edu.tr","gov.tr","mil.tr","bel.tr","k12.tr","av.tr","bbs.tr","dr.tr","gen.tr","info.tr","name.tr","pol.tr","tel.tr","web.tr","com.ua","net.ua","org.ua","edu.ua","gov.ua","mil.ua","in.ua","co.ua","cherkassy.ua","chernigov.ua","chernovtsy.ua","dn.ua","dnepropetrovsk.ua","donetsk.ua","dp.ua","if.ua","kh.ua","kharkov.ua","kherson.ua","khmelnitskiy.ua","kiev.ua","kirovograd.ua","km.ua","kr.ua","lg.ua","lugansk.ua","lutsk.ua","lviv.ua","mk.ua","mykolaiv.ua","nikolaev.ua","od.ua","odessa.ua","pl.ua","poltava.ua","rivne.ua","rovno.ua","rv.ua","sebastopol.ua","sumy.ua","te.ua","ternopil.ua","uzhgorod.ua","vinnica.ua","vn.ua","volyn.ua","yalta.ua","zp.ua","zaporizhzhe.ua","zt.ua","zhitomir.ua","com.ru","net.ru","org.ru","edu.ru","gov.ru","mil.ru","pp.ru","int.ru","ac.ru","msk.ru","spb.ru","com.pl","net.pl","org.pl","edu.pl","gov.pl","mil.pl","co.pl","info.pl","biz.pl","nom.pl","waw.pl","poznan.pl","lodz.pl","krakow.pl","wroclaw.pl","com.de","co.de","com.fr","co.fr","asso.fr","nom.fr","prd.fr","presse.fr","tm.fr","aeroport.fr","assedic.fr","avocat.fr","avoues.fr","cci.fr","chambagri.fr","chirurgiens-dentistes.fr","experts-comptables.fr","geometre-expert.fr","gouv.fr","greta.fr","huissier-justice.fr","medecin.fr","notaires.fr","pharmacien.fr","port.fr","veterinaire.fr","com.it","co.it","com.es","co.es","nom.es","org.es","edu.es","gob.es","com.nl","co.nl","com.be","co.be","ac.be","org.be","net.be","com.ch","co.ch","com.at","co.at","ac.at","gv.at","or.at","priv.at","com.se","co.se","ac.se","bd.se","brand.se","fh.se","fhsk.se","fhv.se","tm.se","pp.se","press.se","parti.se","komforb.se","kommunalforbund.se","komvux.se","lanarb.se","lanbib.se","naturbruksgymn.se","sshn.se","com.no","co.no","stat.no","fylkesbibl.no","folkebibl.no","museum.no","idrett.no","priv.no","mil.no","vgs.no","videregaaende.no","kommune.no","herad.no","aa.no","ah.no","bu.no","fm.no","hl.no","hm.no","jan-mayen.no","mr.no","nl.no","nt.no","of.no","ol.no","oslo.no","rl.no","sf.no","st.no","svalbard.no","tm.no","tr.no","va.no","vf.no","com.dk","co.dk","ac.dk","com.fi","co.fi","ac.fi","iki.fi","aland.fi","www.fi","com.pt","co.pt","edu.pt","gov.pt","int.pt","net.pt","nome.pt","org.pt","publ.pt","dyndns.pt","com.gr","co.gr","edu.gr","gov.gr","net.gr","org.gr","store.gr","com.ie","co.ie","gov.ie","net.ie","org.ie","teagasc.ie","com.cz","co.cz","edu.cz","net.cz","org.cz","info.cz","com.sk","co.sk","edu.sk","net.sk","org.sk","com.hu","co.hu","edu.hu","film.hu","gov.hu","info.hu","net.hu","org.hu","priv.hu","sport.hu","tm.hu","2000.hu","agrar.hu","bolt.hu","casino.hu","city.hu","erotica.hu","erotika.hu","forum.hu","games.hu","hotel.hu","ingatlan.hu","jogasz.hu","konyvelo.hu","lakas.hu","media.hu","news.hu","reklam.hu","sex.hu","shop.hu","suli.hu","szex.hu","tozsde.hu","utazas.hu","video.hu","com.ro","co.ro","edu.ro","gov.ro","info.ro","net.ro","nom.ro","org.ro","rec.ro","store.ro","tm.ro","www.ro","arts.ro","firm.ro","nt.ro","shop.ro","com.bg","co.bg","edu.bg","gov.bg","net.bg","org.bg","tel.bg","biz.bg","com.hr","co.hr","from.hr","iz.hr","name.hr","net.hr","com.rs","co.rs","edu.rs","gov.rs","in.rs","net.rs","org.rs","com.ba","co.ba","edu.ba","gov.ba","mil.ba","net.ba","org.ba","rs.ba","unbi.ba","unmo.ba","unsa.ba","untz.ba","unze.ba","com.co","net.co","org.co","edu.co","gov.co","mil.co","nom.co","com.ve","net.ve","org.ve","edu.ve","gov.ve","mil.ve","int.ve","co.ve","arts.ve","bib.ve","firm.ve","info.ve","nom.ve","rec.ve","store.ve","tec.ve","web.ve","com.pe","net.pe","org.pe","edu.pe","gov.pe","mil.pe","nom.pe","sld.pe","com.cl","co.cl","gob.cl","gov.cl","net.cl","org.cl","mil.cl","edu.cl","co.kr","ne.kr","or.kr","re.kr","pe.kr","go.kr","mil.kr","ac.kr","hs.kr","ms.kr","es.kr","sc.kr","kg.kr","seoul.kr","busan.kr","daegu.kr","incheon.kr","gwangju.kr","daejeon.kr","ulsan.kr","gyeonggi.kr","gangwon.kr","chungbuk.kr","chungnam.kr","jeonbuk.kr","jeonnam.kr","gyeongbuk.kr","gyeongnam.kr","jeju.kr","co.id","net.id","or.id","ac.id","web.id","sch.id","go.id","mil.id","my.id","co.th","net.th","org.th","ac.th","go.th","in.th","mi.th","com.vn","net.vn","org.vn","edu.vn","gov.vn","int.vn","ac.vn","biz.vn","info.vn","name.vn","pro.vn","health.vn","com.ng","net.ng","org.ng","edu.ng","gov.ng","mil.ng","mobi.ng","name.ng","sch.ng","co.ke","or.ke","ne.ke","go.ke","ac.ke","sc.ke","me.ke","mobi.ke","co.il","net.il","org.il","edu.il","gov.il","muni.il","ac.il","idf.il","com.ir","net.ir","org.ir","edu.ir","gov.ir","ac.ir","id.ir"],Fs=new Set,Ws=new Set,Ks=new Set;for(let r of iu)r.startsWith("!")?Ks.add(r.slice(1).toLowerCase()):r.startsWith("*.")?Ws.add(r.slice(2).toLowerCase()):Fs.add(r.toLowerCase());(async()=>{try{let r=await import("node:url");typeof r.domainToUnicode=="function"&&(Bs=r.domainToUnicode)}catch{}})();cu=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/,lu=/^[\da-f:]+$/i;uu=/^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/});function gu(r,e){let t=r.name;return!(t.startsWith("__Secure-")&&(!r.secure||e.protocol!=="https:")||t.startsWith("__Host-")&&(!r.secure||e.protocol!=="https:"||r.path!=="/"||!r.hostOnly))}function yu(r,e){switch(r){case"Strict":return e==="strict";case"Lax":return e==="strict"||e==="lax";case"Unset":return e!=="cross-site";case"None":return!0}}function Vs(r){try{return new URL(r)}catch{return null}}function Xr(){return new Te}function Yr(r){return Te.fromJSON(r)}var du,pu,mu,va,Te,Pa=F(()=>{"use strict";Gr();du=4096,pu=50,mu=3e3,va=400*24*60*60*1e3;Te=class r{constructor(e={}){h(this,"dm",new Map);h(this,"total",0);h(this,"cleanupTimer",null);h(this,"maxTotal");h(this,"maxPerDomain");h(this,"domainMatcherFn");this.maxTotal=e.maxTotal??mu,this.maxPerDomain=e.maxPerDomain??pu,this.domainMatcherFn=e.domainMatcher??null,this.cleanupTimer=setInterval(()=>{this.clearExpired()},300*1e3),typeof this.cleanupTimer=="object"&&this.cleanupTimer!==null&&"unref"in this.cleanupTimer&&this.cleanupTimer.unref()}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}setCookie(e,t){let n=Vs(t.url);if(!n)return!1;let s=St(e);if(!s)return!1;let o=Date.now(),i=n.hostname.toLowerCase(),a=i.replace(/^\[|\]$/g,""),c=n.protocol==="https:"||a==="localhost"||a==="127.0.0.1"||a==="::1";if(s.name.length+1+s.value.length>du)return!1;let u,f;if(s.domain!==null&&s.domain!==""){let b=s.domain;if(!(this.domainMatcherFn??bt)(i,b)||wt(b))return!1;u=b,f=!1}else u=i,f=!0;let p=s.path??xt(n.pathname),d=s.secure;if(d&&!c)return!1;let g=s.sameSite;if(g==="None"&&!d)return!1;let m;if(s.maxAge!==null){if(s.maxAge<=0)return this.removeCookie(u,p,s.name),!0;let b=Math.min(s.maxAge*1e3,va);m=o+b}else if(s.expires!==null){if(m=s.expires,m<=o)return this.removeCookie(u,p,s.name),!0;m=Math.min(m,o+va)}else m=1/0;let y={name:s.name,value:s.value,domain:u,path:p,expires:m,maxAge:s.maxAge,secure:d,httpOnly:s.httpOnly,sameSite:g,createdAt:o,lastAccessed:o,hostOnly:f};return gu(y,n)?(this.putCookie(y),!0):!1}getCookies(e){Math.random()<.01&&this.clearExpired();let t=Vs(e.url);if(!t)return[];let n=t.hostname.toLowerCase(),s=n.replace(/^\[|\]$/g,""),o=t.pathname||"/",i=t.protocol==="https:"||s==="localhost"||s==="127.0.0.1"||s==="::1",a=e.http!==!1,c=e.sameSiteContext??"none",l=Date.now(),u=[];for(let[p,d]of this.dm)if(this.matchDomain(n,p))for(let[,g]of d)for(let[,m]of g)m.hostOnly&&n!==m.domain||m.expires!==1/0&&m.expires<l||_t(o,m.path)&&(m.secure&&!i||m.httpOnly&&!a||yu(m.sameSite,c)&&(m.name.startsWith("__Secure-")&&!(m.secure&&i)||m.name.startsWith("__Host-")&&!(m.secure&&i&&m.path==="/"&&m.hostOnly)||u.push(m)));u.sort((p,d)=>{let g=d.path.length-p.path.length;return g!==0?g:p.createdAt-d.createdAt});let f=Date.now();for(let p of u)p.lastAccessed=f;return u}getCookieHeader(e){return this.getCookies(e).map(t=>t.name?`${t.name}=${t.value}`:t.value).join("; ")}getCookiesForDomain(e){let t=ue(e),n=[];for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t))for(let[,i]of o)for(let[,a]of i)a.expires!==1/0&&a.expires<Date.now()||n.push(a);return n}processResponseHeaders(e,t){for(let n of Et(e))this.setCookie(n,t)}removeCookie(e,t,n){let s=ue(e),o=this.dm.get(s);if(!o)return!1;let i=o.get(t);if(!i)return!1;let a=i.delete(n);return a&&(this.total--,i.size===0&&o.delete(t),o.size===0&&this.dm.delete(s)),a}clear(){this.dm.clear(),this.total=0}clearExpired(){let e=Date.now(),t=0;for(let[n,s]of this.dm){for(let[o,i]of s){for(let[a,c]of i)c.expires!==1/0&&c.expires<e&&(i.delete(a),this.total--,t++);i.size===0&&s.delete(o)}s.size===0&&this.dm.delete(n)}return t}clearSession(){let e=0;for(let[t,n]of this.dm){for(let[s,o]of n){for(let[i,a]of o)a.expires===1/0&&(o.delete(i),this.total--,e++);o.size===0&&n.delete(s)}n.size===0&&this.dm.delete(t)}return e}clearForDomain(e){let t=ue(e),n=0;for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t)){let i=0;for(let a of o.values())i+=a.size;this.dm.delete(s),this.total-=i,n+=i}return n}clearForUrl(e){let t=Vs(e);return t?this.clearForDomain(t.hostname):0}toJSON(){let e=Date.now(),t=[];for(let[,n]of this.dm)for(let[,s]of n)for(let[,o]of s)o.expires!==1/0&&o.expires<e||t.push({name:o.name,value:o.value,domain:o.domain,path:o.path,expires:o.expires===1/0?null:o.expires,maxAge:o.maxAge,secure:o.secure,httpOnly:o.httpOnly,sameSite:o.sameSite,createdAt:o.createdAt,lastAccessed:o.lastAccessed,hostOnly:o.hostOnly});return t}toString(){return JSON.stringify(this.toJSON(),null,2)}static fromJSON(e){let t=new r,n=typeof e=="string"?JSON.parse(e):e,s=Date.now();for(let o of n){let i=o.expires===null?1/0:o.expires;if(i!==1/0&&i<s)continue;let a={name:o.name,value:o.value,domain:o.domain,path:o.path,expires:i,maxAge:o.maxAge,secure:o.secure,httpOnly:o.httpOnly,sameSite:o.sameSite,createdAt:o.createdAt,lastAccessed:o.lastAccessed,hostOnly:o.hostOnly};t.putCookie(a)}return t}get count(){return this.total}getAll(){let e=[];for(let[,t]of this.dm)for(let[,n]of t)for(let[,s]of n)e.push({...s});return e}getForDomain(e){let t=ue(e),n=[];for(let[s,o]of this.dm)if(s===t||s.endsWith("."+t))for(let[,i]of o)for(let[,a]of i)n.push({...a});return n}putCookie(e){let{domain:t,path:n,name:s}=e;this.dm.has(t)||this.dm.set(t,new Map);let o=this.dm.get(t);o.has(n)||o.set(n,new Map);let i=o.get(n);if(i.has(s)){let a=i.get(s);i.set(s,{...e,createdAt:a.createdAt})}else this.evictForDomain(t,o),this.evictGlobal(),i.set(s,e),this.total++}evictForDomain(e,t){let n=0;for(let i of t.values())n+=i.size;if(n<this.maxPerDomain)return;let s=[];for(let[i,a]of t)for(let[c,l]of a)s.push([i,c,l]);s.sort((i,a)=>i[2].lastAccessed-a[2].lastAccessed);let o=0;for(;n>=this.maxPerDomain&&o<s.length;){let[i,a]=s[o++];t.get(i)?.delete(a)&&(this.total--,n--)}for(let[i,a]of t)a.size===0&&t.delete(i)}evictGlobal(){if(this.total<this.maxTotal)return;let e=[];for(let[n,s]of this.dm)for(let[o,i]of s)for(let[a,c]of i)e.push([n,o,a,c]);e.sort((n,s)=>n[3].lastAccessed-s[3].lastAccessed);let t=0;for(;this.total>=this.maxTotal&&t<e.length;){let[n,s,o]=e[t++],i=this.dm.get(n),a=i?.get(s);a?.delete(o)&&(this.total--,a.size===0&&i.delete(s),i.size===0&&this.dm.delete(n))}}matchDomain(e,t){return this.domainMatcherFn?this.domainMatcherFn(e,t):e===t?!0:ge(e)?!1:e.endsWith("."+t)}}});var Ia={};fe(Ia,{CookieJar:()=>Te,canonicalizeDomainFull:()=>ue,createCookieJar:()=>Xr,decodeIDNLabel:()=>er,defaultPath:()=>xt,domainMatch:()=>bt,extractSetCookieHeaders:()=>Et,formatSetCookieHeader:()=>Ca,getPublicSuffix:()=>yt,getRegistrableDomain:()=>Qr,isIPAddress:()=>ge,isPublicSuffix:()=>wt,loadCookieJar:()=>Yr,normalizePath:()=>Jr,parseCookieDate:()=>Zt,parseSetCookieHeader:()=>St,pathMatch:()=>_t,splitSetCookieHeaders:()=>We});var Js=F(()=>{"use strict";Pa();Gr()});var Oa={};fe(Oa,{BatchingTransport:()=>kt,ConsoleTransport:()=>Ke,HTTPLogger:()=>ke,JSONTransport:()=>Rt,LogLevel:()=>Tt,MultiTransport:()=>Ct,Redactor:()=>vt,RemoteTransport:()=>At,createDevelopmentLogger:()=>Ys,createLogger:()=>Gs,createProductionLogger:()=>Xs,toOTelSpan:()=>Qs});function Tu(){let r=Date.now().toString(36),e=(++Eu).toString(36).padStart(4,"0"),t=Math.random().toString(36).slice(2,6);return`${r}-${e}-${t}`}function Ma(r,e){if(!r||typeof r!="object"||e.length===0)return;let[t,...n]=e;if(t===void 0||t==="__proto__"||t==="constructor"||t==="prototype")return;let s=r;if(n.length===0){Object.prototype.hasOwnProperty.call(s,t)&&(s[t]="***");return}typeof s[t]=="object"&&Ma(s[t],n)}function La(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r.byteLength}function Qs(r){let e={"http.request.id":r.requestId,"http.request.method":r.method,"url.full":r.url};return r.type==="response"&&(e["http.response.status_code"]=r.status,e["http.response.body.size"]=r.bodySize,e["http.time_to_first_byte"]=r.durationMs),r.type==="error"&&(e.error=!0,e["error.type"]=r.error.name,e["error.message"]=r.error.message,e["http.status_code"]=r.status),e}function Ru(r){if(r instanceof Error){let e=r.code,t=r.stack;return{name:r.name,message:r.message,...e!==void 0?{code:e}:{},...t!==void 0?{stack:t}:{}}}return{name:"Error",message:String(r)}}function Zr(){return typeof performance<"u"?performance.now():Date.now()}function Gs(r){return new ke(r)}function Xs(r){let e=[new Rt];return r.endpoint&&e.push(new kt(new At(r.endpoint))),new ke({level:r.level??"INFO",transports:[new Ct(e)],...r.context!==void 0?{context:r.context}:{}})}function Ys(r={}){return new ke({level:r.level??"DEBUG",transports:[new Ke({pretty:!0,useColors:!0,onWrite:e=>console.log(e)})],redaction:{logRequestBody:r.logBodies??!0,logResponseBody:r.logBodies??!0,maxBodyLength:2048}})}var wu,Tt,bu,xu,_u,Ke,Su,Rt,kt,At,Ct,Eu,vt,Re,ke,en=F(()=>{"use strict";z();wu=()=>{try{return globalThis.process?.env?.NODE_ENV}catch{return}},Tt={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},bu=["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-refresh-token","x-csrf-token","x-session-id","x-session-token","x-secret","x-secret-key","x-private-key","api-key","apikey","bearer","token","authentication","credentials","password","passwd","secret"],xu=["token","api_key","apikey","access_token","refresh_token","secret","password","pass","pwd","key","auth"],_u=["application/json","application/x-www-form-urlencoded","text/"],Ke=class{constructor(e={pretty:!1,onWrite:t=>console.log(t)}){h(this,"pretty");h(this,"onWrite");this.pretty=e.pretty??wu()!=="production",this.onWrite=e.onWrite,e.useColors}write(e){let t=this.pretty?this._prettyFormat(e):JSON.stringify(e);this.onWrite(t)}_prettyFormat(e){let t=new Date(e.timestampMs).toISOString().slice(11,23),n=e.level.padEnd(5),s=e.requestId.slice(-8);if(e.type==="request")return`[${t}] ${n} \u2190 ${e.method} ${e.url} [${s}]`;if(e.type==="response"){let o=`${e.durationMs.toFixed(0)}ms`,i=e.cached?" (cached)":"";return`[${t}] ${n} \u2192 ${e.status} ${e.method} ${e.url} ${o}${i} [${s}]`}return`[${t}] ${n} \u2717 ${e.method} ${e.url} ${e.error.message} [${s}]`}},Su=()=>{try{return typeof globalThis.process?.stdout?.write=="function"}catch{return!1}},Rt=class{constructor(e=t=>{Su()?globalThis.process.stdout.write(t+`
|
|
5
|
+
`):console.log(t)}){h(this,"writeLine");this.writeLine=e}write(e){this.writeLine(JSON.stringify(e))}},kt=class{constructor(e,t={}){h(this,"inner");h(this,"options");h(this,"buffer",[]);h(this,"timer",null);this.inner=e,this.options=t}write(e){if(this.buffer.push(e),this.buffer.length>=(this.options.maxBatch??100)){this._flush();return}this.timer||(this.timer=setTimeout(()=>this._flush(),this.options.flushMs??5e3))}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null),this._flush(),this.inner.flush&&await this.inner.flush()}_flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0);for(let t of e)this.inner.write(t)}},At=class{constructor(e,t={}){h(this,"endpoint");h(this,"options");h(this,"buffer",[]);h(this,"timer",null);this.endpoint=e,this.options=t}write(e){if(this.buffer.push(e),this.buffer.length>=(this.options.batchSize??50)){this._flush();return}this.timer||(this.timer=setTimeout(()=>this._flush(),this.options.flushMs??3e3))}async flush(){this.timer&&(clearTimeout(this.timer),this.timer=null),await this._flushAsync()}_flush(){this._flushAsync().catch(this.options.onError??(e=>console.error("[logging] Flush error:",e)))}async _flushAsync(){if(this.buffer.length===0)return;let e=this.buffer.splice(0),t=this.options.fetch??globalThis.fetch;if(e.length<=10)await t(this.endpoint,{method:"POST",headers:{"content-type":"application/json",...this.options.headers},body:JSON.stringify(e)});else try{let{Readable:n}=await import("node:stream"),s=n.from([JSON.stringify(e)]);await t(this.endpoint,{method:"POST",headers:{"content-type":"application/json",...this.options.headers},body:s,duplex:"half"})}catch{await t(this.endpoint,{method:"POST",headers:{"content-type":"application/json",...this.options.headers},body:JSON.stringify(e)})}}},Ct=class{constructor(e){h(this,"transports");this.transports=e}write(e){for(let t of this.transports)try{t.write(e)}catch{}}async flush(){await Promise.allSettled(this.transports.map(e=>e.flush?.()))}},Eu=0;vt=class{constructor(e={}){h(this,"headerSet");h(this,"paramSet");h(this,"bodyFields");h(this,"patterns");h(this,"maxBody");h(this,"logReqBody");h(this,"logResBody");h(this,"allowedTypes");let t=e.headers??bu,n=e.queryParams??xu;this.headerSet=new Set(t.map(s=>s.toLowerCase())),this.paramSet=new Set(n.map(s=>s.toLowerCase())),this.bodyFields=e.bodyFields??[],this.patterns=e.bodyPatterns??[],this.maxBody=e.maxBodyLength??4096,this.logReqBody=e.logRequestBody??!1,this.logResBody=e.logResponseBody??!1,this.allowedTypes=e.allowedBodyTypes??_u}redactHeaders(e){let t={};for(let[n,s]of Object.entries(e))t[n]=this.headerSet.has(n.toLowerCase())?"***":s;return t}redactURL(e){try{let t=new URL(e);for(let n of[...t.searchParams.keys()])this.paramSet.has(n.toLowerCase())&&t.searchParams.set(n,"***");return t.toString()}catch{return e}}redactBody(e,t,n){if(!(n?this.logResBody:this.logReqBody)||!e)return{body:null,size:e?La(e):null};let o=t??"";if(!this.allowedTypes.some(l=>o.startsWith(l)))return{body:`[${o||"binary"}]`,size:e?La(e):null};let a;if(e instanceof Uint8Array)try{a=new TextDecoder().decode(e)}catch{return{body:"[binary]",size:e.byteLength}}else a=e;let c=a.length;if(o.includes("application/json")&&this.bodyFields.length>0)try{let l=M(JSON.parse(a));for(let u of this.bodyFields)Ma(l,u.split("."));a=JSON.stringify(l)}catch{}for(let l of this.patterns)a=a.replace(l,"***");return a.length>this.maxBody&&(a=a.slice(0,this.maxBody)+`... [truncated ${a.length-this.maxBody} bytes]`),{body:a,size:c}}};Re=class Re{constructor(e={}){h(this,"cfg");h(this,"redactor");h(this,"level");h(this,"activeIds",new Map);this.cfg={level:e.level??"INFO",transports:e.transports??[new Ke],redaction:e.redaction??{},sampleRate:e.sampleRate??1,methods:e.methods??[],statuses:e.statuses??[],excludeURLs:e.excludeURLs??[],context:e.context??{},generateId:e.generateId??Tu},this.redactor=new vt(this.cfg.redaction),this.level=Tt[this.cfg.level]}_cleanupActiveIds(){let e=Zr();if(this.activeIds.size>Re.MAX_ACTIVE_IDS){let t=Array.from(this.activeIds.entries()),n=t.slice(0,t.length-Math.floor(Re.MAX_ACTIVE_IDS*.8));for(let[s]of n)this.activeIds.delete(s)}for(let[t,n]of this.activeIds)e-n.startMs>Re.IDLE_TIMEOUT_MS&&this.activeIds.delete(t)}logRequest(e,t,n,s,o,i,a={}){if(!this._shouldLog("INFO",t,n))return;this.activeIds.size>500&&this._cleanupActiveIds(),this.activeIds.set(e,{startMs:Zr(),method:t,url:n});let c=s["content-type"]??s["Content-Type"]??null,l=this.redactor.redactBody(o,c,!1),u={type:"request",requestId:e,timestamp:new Date().toISOString(),timestampMs:Date.now(),level:"INFO",method:t.toUpperCase(),url:this.redactor.redactURL(n),headers:this.redactor.redactHeaders(s),bodySize:l.size,body:l.body,attempt:i,meta:{...this.cfg.context,...a}};this._write(u)}logResponse(e,t,n,s,o,i,a,c={}){let l=this.activeIds.get(e),u=l?Zr()-l.startMs:0,f=l?.method??"GET",p=l?.url??"";if(!this._shouldLog("INFO",f,p,t))return;let d=s["content-type"]??s["Content-Type"]??null,g=this.redactor.redactBody(o,d,!0),m=t>=500?"ERROR":t>=400?"WARN":"INFO",y={type:"response",requestId:e,timestamp:new Date().toISOString(),timestampMs:Date.now(),level:m,method:f.toUpperCase(),url:this.redactor.redactURL(p),status:t,statusText:n,headers:this.redactor.redactHeaders(s),bodySize:g.size,body:g.body,durationMs:Math.round(u),attempt:i,cached:a,meta:{...this.cfg.context,...c}};this.activeIds.delete(e),this._write(y)}logError(e,t,n,s,o={}){let i=this.activeIds.get(e),a=i?Zr()-i.startMs:0,c=i?.method??"GET",l=i?.url??"";if(!this._shouldLog("ERROR",c,l))return;let u={type:"error",requestId:e,timestamp:new Date().toISOString(),timestampMs:Date.now(),level:"ERROR",method:c.toUpperCase(),url:this.redactor.redactURL(l),error:Ru(t),status:n,durationMs:Math.round(a),attempt:s,meta:{...this.cfg.context,...o}};this.activeIds.delete(e),this._write(u)}generateRequestId(){return this.cfg.generateId()}child(e){return new Re({...this.cfg,context:{...this.cfg.context,...e}})}async flush(){await Promise.allSettled(this.cfg.transports.map(e=>e.flush?.()))}_write(e){if(!(Tt[e.level]<this.level))for(let n of this.cfg.transports)try{let s=n.write(e);s&&typeof s.then=="function"&&s.catch(()=>{})}catch{}}_shouldLog(e,t,n,s){if(Tt[e]<this.level||this.cfg.sampleRate<1&&Math.random()>this.cfg.sampleRate||this.cfg.methods.length>0&&!this.cfg.methods.includes(t.toUpperCase())||s!==void 0&&this.cfg.statuses.length>0&&!this.cfg.statuses.includes(s))return!1;for(let o of this.cfg.excludeURLs)if(o.test(n))return!1;return!0}};h(Re,"MAX_ACTIVE_IDS",1e4),h(Re,"IDLE_TIMEOUT_MS",6e4);ke=Re});var no={};fe(no,{SSEClient:()=>Ve,SSEError:()=>he,SSEMaxReconnectsError:()=>Je,SSEParser:()=>Ae,SSERouter:()=>rr,SSEServerResponse:()=>Pt,SSETransformStream:()=>tr,createJSONSSEStream:()=>eo,createSSEResponse:()=>to,createSSEStream:()=>Zs,jsonSSE:()=>tn,parseSSEText:()=>ro});async function*tn(r,e={}){for await(let t of r)if(!(!t.data&&t.data!==""))try{let n=M(JSON.parse(t.data,e.reviver));yield{event:t.event,data:n,id:t.id}}catch(n){e.onError?.(n,t)}}function Zs(r){return new Ve(r)}function eo(r,e={}){return tn(new Ve(r),e)}function to(r,e={}){let t=new Pt;return(async()=>{try{await r(t)}catch(n){console.error("[sse] Generator error:",n)}t.close()})(),t.toResponse(e)}function ro(r){let e=new Ae,t=e.feed(r),n=e.flush();return n&&t.push(n),t}function Da(r){return new Promise(e=>setTimeout(e,r))}var Ae,tr,Ve,rr,Pt,he,Je,nr=F(()=>{"use strict";z();Ae=class{constructor(){h(this,"lines",[]);h(this,"id",null);h(this,"event","message");h(this,"data",[]);h(this,"retry",null);h(this,"buffer","")}feed(e){let t=[];this.buffer+=e;let n=this.buffer.split(/\r\n|\r|\n/);this.buffer=n.pop()??"";for(let s of n){let o=this._processLine(s);o&&t.push(o)}return t}flush(){return this.buffer&&(this._processLine(this.buffer),this.buffer=""),this.data.length>0?this._dispatch():null}_processLine(e){if(this.lines.push(e),e==="")return this.data.length===0?(this.lines=[],null):this._dispatch();if(e.startsWith(":"))return null;let t=e.indexOf(":"),n,s;switch(t===-1?(n=e,s=""):(n=e.slice(0,t),s=e.slice(t+1).replace(/^ /,"")),n){case"id":this.id=s||null;break;case"event":this.event=s;break;case"data":this.data.push(s);break;case"retry":{let o=parseInt(s,10);!isNaN(o)&&o>=0&&(this.retry=o);break}}return null}_dispatch(){let e={id:this.id,event:this.event,data:this.data.join(`
|
|
6
|
+
`),retry:this.retry,raw:[...this.lines]};return this.lines=[],this.event="message",this.data=[],this.retry=null,e}reset(){this.lines=[],this.id=null,this.event="message",this.data=[],this.retry=null,this.buffer=""}get lastId(){return this.id}},tr=class extends TransformStream{constructor(t={}){super({transform:(n,s)=>{try{let o=typeof n=="string"?n:this.decoder.decode(n,{stream:!0}),i=this.parser.feed(o);for(let a of i)s.enqueue(a)}catch(o){t.onParseError?.(o,String(n))}},flush:n=>{let s=this.parser.flush();s&&n.enqueue(s)}});h(this,"parser",new Ae);h(this,"decoder",new TextDecoder("utf-8"))}},Ve=class{constructor(e){h(this,"config");h(this,"health");h(this,"_closed",!1);h(this,"_streamController",null);this.config={fetch:globalThis.fetch,headers:{},signal:e.signal??void 0,lastEventId:"",reconnect:!0,reconnectDelayMs:3e3,maxReconnectDelayMs:3e4,reconnectJitter:.3,maxReconnects:0,onReconnect:()=>{},onParseError:t=>{},heartbeatTimeoutMs:0,method:"GET",body:null,validateResponse:()=>!0,...e},this.health={connected:!1,totalEvents:0,totalReconnects:0,lastEventAt:null,lastEventId:this.config.lastEventId||null,reconnectAttempt:0}}get url(){return this.config.url}get closed(){return this._closed}async*[Symbol.asyncIterator](){yield*this._stream()}async*stream(){yield*this._stream()}async*on(e){for await(let t of this._stream())t.event===e&&(yield t)}async collect(e={}){let t=[],n=0;for await(let s of this._stream())if(t.push(s),n++,e.limit&&n>=e.limit||e.signal?.aborted)break;return t}close(){this._closed=!0,this._streamController&&(this._streamController.abort(),this._streamController=null),this.health.connected=!1}destroy(){this.close(),this.health={connected:!1,totalEvents:this.health.totalEvents,totalReconnects:this.health.totalReconnects,lastEventAt:this.health.lastEventAt,lastEventId:this.health.lastEventId,reconnectAttempt:0}}get streamHealth(){return{...this.health}}async*_stream(){let e=this.config,t=e.reconnectDelayMs,n=0;for(this._streamController=new AbortController;!this._closed&&!this._streamController?.signal.aborted;){let s=this._closed;if(s||e.signal?.aborted||this._streamController?.signal.aborted)break;let o=new Ae,i=null;try{let c={accept:"text/event-stream","cache-control":"no-cache",...e.headers};this.health.lastEventId&&(c["last-event-id"]=this.health.lastEventId);let l={method:e.method,headers:c,body:e.body??null,signal:e.signal??null};e.body!==null&&e.body!==void 0&&(l.duplex="half");let u=await e.fetch(e.url,l),f=e.validateResponse(u);if(f!==!0){let b=typeof f=="string"?f:`SSE server returned ${u.status}`;throw new he(b,u.status,u)}if(!u.ok)throw new he(`SSE server error: ${u.status}`,u.status,u);if(!u.body)throw new he("SSE response has no body",u.status,u);let p=u.headers.get("content-type")??"";if(!p.startsWith("text/event-stream"))throw new he(`Expected text/event-stream, got: ${p}`,u.status,u);this.health.connected=!0,n=0,t=e.reconnectDelayMs;let d=u.body.getReader(),g=new TextDecoder("utf-8"),m=()=>{i&&clearTimeout(i),e.heartbeatTimeoutMs>0&&(i=setTimeout(()=>{d.cancel("heartbeat timeout")},e.heartbeatTimeoutMs))};m();try{for(;!s&&!e.signal?.aborted;){let{done:b,value:x}=await d.read();if(b)break;let E=g.decode(x,{stream:!0}),R=o.feed(E);for(let A of R)m(),A.retry!==null&&(t=Math.min(A.retry,e.maxReconnectDelayMs)),A.id!==null&&(this.health.lastEventId=A.id),this.health.totalEvents++,this.health.lastEventAt=Date.now(),yield A}}finally{i&&clearTimeout(i);try{d.cancel()}catch{}}let y=o.flush();y&&(this.health.totalEvents++,this.health.lastEventAt=Date.now(),yield y)}catch(c){if(this.health.connected=!1,s||c instanceof Error&&c.name==="AbortError"||e.signal?.aborted)break;if(c instanceof he&&c.status&&[401,403,404].includes(c.status)||!e.reconnect)throw c;if(e.maxReconnects>0&&n>=e.maxReconnects)throw new Je(n,e.url);n++,this.health.totalReconnects++,this.health.reconnectAttempt=n;let l=t*e.reconnectJitter*Math.random(),u=Math.min(t+l,e.maxReconnectDelayMs);t=Math.min(t*2,e.maxReconnectDelayMs),e.onReconnect(n,u),i&&(clearTimeout(i),i=null),await Da(u),o.reset();continue}if(this.health.connected=!1,!e.reconnect)break;if(e.maxReconnects>0&&n>=e.maxReconnects)throw new Je(n,e.url);n++,this.health.totalReconnects++;let a=Math.min(t,e.maxReconnectDelayMs);e.onReconnect(n,a),i&&(clearTimeout(i),i=null),await Da(a)}this.health.connected=!1}};rr=class{constructor(){h(this,"handlers",new Map);h(this,"fallback",null)}on(e,t){let n=this.handlers.get(e)??[];return n.push(t),this.handlers.set(e,n),this}onJSON(e,t){return this.on(e,async(n,s)=>{try{let o=M(JSON.parse(n));await t(o,s)}catch{}})}onMessage(e){return this.on("message",e)}onAny(e){return this.fallback=e,this}async dispatch(e){let t=this.handlers.get(e.event);if(t&&t.length>0)for(let n of t)await n(e.data,e);else this.fallback&&await this.fallback(e.data,e)}async consume(e){for await(let t of e)await this.dispatch(t)}},Pt=class{constructor(){h(this,"controller");h(this,"stream");h(this,"_closed",!1);let e;this.stream=new ReadableStream({start:t=>{e=t},cancel:()=>{this._closed=!0}}),this.controller=e}comment(e=""){return this._closed||this.controller.enqueue(`: ${e}
|
|
7
7
|
|
|
8
8
|
`),this}send(e,t={}){return this.sendEvent("message",e,t)}sendEvent(e,t,n={}){if(this._closed)return this;let s="";n.id!==void 0&&(s+=`id: ${n.id}
|
|
9
9
|
`),e!=="message"&&(s+=`event: ${e}
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
`;return s+=`
|
|
14
14
|
`,this.controller.enqueue(s),this}sendJSON(e,t,n={}){return this.sendEvent(e,JSON.stringify(t),n)}heartbeat(){return this.comment("heartbeat")}setReconnectDelay(e){return this._closed||this.controller.enqueue(`retry: ${e}
|
|
15
15
|
|
|
16
|
-
`),this}close(){if(!this._closed){this._closed=!0;try{this.controller.close()}catch{}}}get closed(){return this._closed}toResponse(e={}){let t=new TextEncoder,n=this.stream.pipeThrough(new TransformStream({transform:(s,o)=>o.enqueue(t.encode(s))}));return new Response(n,{headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no",...e}})}},
|
|
17
|
-
${s}`,"ENETWORK",void 0,e,void 0,new Error(`HTTP ${r.status}`))}let n;try{n=await r.json()}catch(s){throw new
|
|
16
|
+
`),this}close(){if(!this._closed){this._closed=!0;try{this.controller.close()}catch{}}}get closed(){return this._closed}toResponse(e={}){let t=new TextEncoder,n=this.stream.pipeThrough(new TransformStream({transform:(s,o)=>o.enqueue(t.encode(s))}));return new Response(n,{headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no",...e}})}},he=class extends Error{constructor(t,n,s){super(t);h(this,"status");h(this,"response");h(this,"code","ESSE");this.status=n,this.response=s,this.name="SSEError"}},Je=class extends Error{constructor(t,n){super(`SSE max reconnects (${t}) reached for ${n}`);h(this,"attempts");h(this,"url");h(this,"code","ESSEMAXRECONNECTS");this.attempts=t,this.url=n,this.name="SSEMaxReconnectsError"}}});var Ba={};fe(Ba,{GraphQLClient:()=>te,GraphQLClientError:()=>N,authLink:()=>ao,clearAPQCache:()=>po,createGraphQLClient:()=>ho,detectOperationType:()=>sn,errorLink:()=>co,extractOperationName:()=>ye,getAPQMetrics:()=>mo,gql:()=>fo,loggingLink:()=>lo,retryLink:()=>uo});function rn(r,e,t){let n=r.map(s=>s.message).join("; ");return new N(n,"EGRAPHQL",r,e,t)}function Ha(r){return new Promise(e=>setTimeout(e,r))}function ku(r,e){return r.reduceRight((t,n)=>s=>n(s,t),e)}function sn(r){let e=r.replace(/^\s*#.*$/gm,"").trim();return/^\s*mutation\s/i.test(e)?"mutation":/^\s*subscription\s/i.test(e)?"subscription":"query"}function ye(r){let t=r.replace(/^\s*#.*$/gm,"").trim().match(/^\s*(?:query|mutation|subscription)\s+([A-Za-z_][A-Za-z0-9_]*)/im);return t?t[1]:null}async function ja(r){let e=new TextEncoder().encode(r),t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}async function nn(r,e={}){let t={"content-type":"application/json",accept:"application/json"},n=typeof r.headers=="function"?await r.headers():r.headers??{};return{...t,...n,...e}}function za(r){if(r.length>Na)throw new J(`GraphQL query exceeds maximum length of ${Na} bytes`);for(let n of vu)if(n.test(r))throw new J(`GraphQL query contains potentially malicious pattern: ${n}`);let e=0,t=0;for(let n=0;n<r.length;n++){let s=r[n];s==="{"?(e++,t=Math.max(t,e)):s==="}"&&e--}if(t>Ua)throw new J(`GraphQL query exceeds maximum depth of ${Ua}`);if(e!==0)throw new J("GraphQL query has unbalanced braces")}function io(r,e=1e4){let t=JSON.stringify(r);if(t.length>e)throw new J(`String value exceeds maximum length of ${e} characters`);return t}function $a(r,e){e.query&&za(e.query);let t=new URL(r),n=sr(e);return t.searchParams.set("query",e.query),e.operationName&&t.searchParams.set("operationName",e.operationName),e.variables&&Object.keys(e.variables).length>0&&t.searchParams.set("variables",io(e.variables)),e.extensions&&Object.keys(e.extensions).length>0&&t.searchParams.set("extensions",io(e.extensions)),t.toString()}function sr(r){za(r.query);let e={query:r.query};return r.operationName&&(e.operationName=r.operationName),r.variables&&(e.variables=r.variables),r.extensions&&(e.extensions=r.extensions),io(e,1e5)}function Pu(r,e){let t=new FormData,n=JSON.parse(sr(r)),s={};for(let o=0;o<e.length;o++){let i=e[o];s[String(o)]=[i.path],Iu(n,i.path,null)}t.append("operations",JSON.stringify(n)),t.append("map",JSON.stringify(s));for(let o=0;o<e.length;o++){let i=e[o],a=i.file instanceof File?i.file.name:`file_${o}`;t.append(String(o),i.file,a)}return t}function Iu(r,e,t){let n=e.split("."),s=r;for(let i=0;i<n.length-1;i++){let a=n[i];if(a==="__proto__"||a==="constructor"||a==="prototype")throw new J(`Invalid upload path: "${e}" \u2014 reserved key "${a}"`);(!s[a]||typeof s[a]!="object")&&(s[a]={}),s=s[a]}let o=n[n.length-1];if(o==="__proto__"||o==="constructor"||o==="prototype")throw new J(`Invalid upload path: "${e}" \u2014 reserved key "${o}"`);s[o]=t}async function qa(r,e){let t=r.headers.get("content-type")??"";if(!r.ok&&!t.includes("application/json")){let s=await r.text().catch(()=>"(unreadable)");throw new N(`HTTP ${r.status}: ${r.statusText}
|
|
17
|
+
${s}`,"ENETWORK",void 0,e,void 0,new Error(`HTTP ${r.status}`))}let n;try{n=M(await r.json())}catch(s){throw new N("Failed to parse GraphQL response as JSON","EPARSE",void 0,e,void 0,s)}return n}async function oo(r,e,t,n="none",s){let o=await nn(e),i=sn(r.query),a=e.useGETForQueries&&i==="query",c=e.url,l=null,u={...o};if(n==="omitQuery"||n==="full"){let m=s?await s(r.query):await ja(r.query),y={...r.extensions,persistedQuery:{version:1,sha256Hash:m}},b=n==="omitQuery"?{...r,query:"",extensions:y}:{...r,extensions:y};a?c=$a(e.url,b):l=sr(b)}else a?c=$a(e.url,r):l=sr(r);a||(u["content-type"]="application/json");let f=new AbortController,p=e.timeoutMs>0?setTimeout(()=>f.abort(),e.timeoutMs):null,d=()=>f.abort();t?.addEventListener("abort",d,{once:!0});let g;try{g=await e.fetch(c,{method:a?"GET":"POST",headers:u,body:l,signal:f.signal})}catch(m){throw p&&clearTimeout(p),f.signal.aborted?new N("Request timed out","ETIMEOUT",void 0,r,void 0,m):new N(m instanceof Error?m.message:"Network error","ENETWORK",void 0,r,void 0,m)}finally{p&&clearTimeout(p),t?.removeEventListener("abort",d)}return qa(g,r)}function ao(r,e="Bearer"){return async(t,n)=>{let s=await r();if(s){let o=t.request.headers??{};t.request={...t.request,headers:{...o,authorization:`${e} ${s}`}};let i=typeof t.config.headers=="object"&&!Array.isArray(t.config.headers)?t.config.headers:{};t={...t,config:{...t.config,headers:{...i,authorization:`${e} ${s}`}}}}return n(t)}}function co(r){return async(e,t)=>{try{return await t(e)}catch(n){if(!(n instanceof N))throw n;let s=r(n,e,()=>t(e));if(s)return s;throw n}}}function lo(r=(e,t)=>console.log(e,t)){return async(e,t)=>{let n=Date.now();r("\u2192 GraphQL",{operation:e.request.operationName??"anonymous",url:e.config.url});try{let s=await t(e);return r("\u2190 GraphQL",{operation:e.request.operationName,durationMs:Date.now()-n,errors:s.errors}),s}catch(s){throw r("\u2717 GraphQL",{operation:e.request.operationName,durationMs:Date.now()-n,error:String(s)}),s}}}function uo(r={}){let e=r.maxRetries??3,t=r.delayMs??300,n=r.shouldRetry??(s=>!(s instanceof N&&s.isGraphQLError));return async(s,o)=>{let i;for(let a=0;a<=e;a++){a>0&&await Ha(t*Math.pow(2,a-1));try{return await o(s)}catch(c){if(i=c,!n(c,a))throw c}}throw i}}function ho(r){return new te(r)}async function fo(r,e,t,n){return await new te({url:r,...n!==void 0?{headers:n}:{}}).query(e,t)}var N,Au,so,Cu,Na,Ua,vu,T,te,Lu,po,mo,on=F(()=>{"use strict";Ne();z();N=class extends Error{constructor(t,n,s,o,i,a){super(t);h(this,"graphQLErrors");h(this,"request");h(this,"response");h(this,"networkError");h(this,"code");this.graphQLErrors=s,this.request=o,this.response=i,this.networkError=a,this.name="GraphQLClientError",this.code=n}get isGraphQLError(){return!!this.graphQLErrors&&this.graphQLErrors.length>0}get isNetworkError(){return!!this.networkError}get firstErrorMessage(){return this.graphQLErrors?.[0]?.message??null}};Au=1e3,so=1800*1e3,Cu=300*1e3;Na=100*1024,Ua=100,vu=[/\{\s*\{/,/<\s*</,/<!--/,/<script/,/javascript:/i,/onerror\s*=/i,/eval\s*\(/i];T=class T{constructor(e){h(this,"config");h(this,"executeLink");this.config={fetch:globalThis.fetch,headers:{},useGETForQueries:!1,enableAPQ:!1,timeoutMs:3e4,retries:0,retryDelayMs:300,links:[],signal:e.signal??new AbortController().signal,onRequest:()=>{},onResponse:()=>{},onError:()=>{},...e};let t=n=>this._executeWithAPQ(n.request,n.signal??null);this.executeLink=ku(this.config.links,t)}static _ensureAPQCleanup(){T._apqCleanupTimer||(T._apqCleanupTimer=setInterval(()=>{let e=Date.now();for(let[t,n]of T.apqCache)e-n.createdAt>so&&(T.apqCache.delete(t),T.apqHashToQuery.delete(n.hash));for(let[t,n]of T.apqHashToQuery)if(e-n.createdAt>so){T.apqHashToQuery.delete(t);for(let[s,o]of T.apqCache)if(o.hash===t){T.apqCache.delete(s);break}}},Cu),typeof T._apqCleanupTimer=="object"&&T._apqCleanupTimer!==null&&"unref"in T._apqCleanupTimer&&T._apqCleanupTimer.unref())}async _getAPQHash(e){T._ensureAPQCleanup();let t=T.apqCache.get(e);if(t){if(Date.now()-t.createdAt<=so)return T._apqHits++,t.hash;T.apqCache.delete(e),T.apqHashToQuery.delete(t.hash)}T._apqMisses++;let n=await ja(e),s=Date.now(),o=T.apqHashToQuery.get(n);if(o&&o.query!==e&&(console.warn("[GraphQL] APQ hash collision detected"),T.apqCache.delete(o.query),T.apqHashToQuery.delete(n)),T.apqCache.size>=Au){let i="",a=1/0;for(let[c,l]of T.apqCache)l.createdAt<a&&(a=l.createdAt,i=c);if(i){let c=T.apqCache.get(i);c&&(T.apqCache.delete(i),T.apqHashToQuery.delete(c.hash))}}return T.apqCache.set(e,{hash:n,createdAt:s}),T.apqHashToQuery.set(n,{query:e,createdAt:s}),n}clearAPQCache(){T.apqCache.clear(),T.apqHashToQuery.clear(),T._apqHits=0,T._apqMisses=0,T._apqCleanupTimer&&(clearInterval(T._apqCleanupTimer),T._apqCleanupTimer=null)}getAPQMetrics(){return{size:T.apqCache.size,hits:T._apqHits,misses:T._apqMisses}}async query(e,t,n={}){let s={query:e,...t!==void 0?{variables:t}:{},...n.operationName!==void 0?{operationName:n.operationName}:ye(e)!==void 0?{operationName:ye(e)}:{},...n.extensions!==void 0?{extensions:n.extensions}:{}};return await this._execute(s,n.signal??null)}async mutate(e,t,n={}){return await this.query(e,t,n)}async upload(e,t,n,s={}){let o={query:e,variables:t,...s.operationName!==void 0?{operationName:s.operationName}:ye(e)!==void 0?{operationName:ye(e)}:{}},i=await nn(this.config,{});delete i["content-type"];let a=Pu(o,n),c=new AbortController,l=()=>c.abort();s.signal?.addEventListener("abort",l,{once:!0}),this.config.onRequest(o);let u;try{u=await this.config.fetch(this.config.url,{method:"POST",headers:i,body:a,signal:c.signal})}catch(p){let d=new N(p instanceof Error?p.message:"Upload network error","ENETWORK",void 0,o,void 0,p);throw this.config.onError(d,o),d}finally{s.signal?.removeEventListener("abort",l)}let f=await qa(u,o);if(this.config.onResponse(f,o),f.errors?.length){let p=rn(f.errors,o,f);throw this.config.onError(p,o),p}if(f.data===void 0)throw new N("No data in upload response","ENODATA",void 0,o,f);return f.data}async batch(e,t={}){let n=await nn(this.config),s=new AbortController,o=()=>s.abort();t.signal?.addEventListener("abort",o,{once:!0});let i;try{i=await this.config.fetch(this.config.url,{method:"POST",headers:n,body:JSON.stringify(e),signal:s.signal})}catch(l){throw new N(l instanceof Error?l.message:"Batch network error","ENETWORK",void 0,e[0],void 0,l)}finally{t.signal?.removeEventListener("abort",o)}let a=M(await i.json());if(!Array.isArray(a))throw new N("Batch response must be an array of GraphQL responses","EINVALIDRESPONSE",void 0,e[0],a);return a.map((l,u)=>{if(l.errors?.length)throw rn(l.errors,e[u],l);if(l.data===void 0)throw new N("No data in batch response","ENODATA",void 0,e[u],l);return l.data})}async*subscribe(e,t,n={}){let s={query:e,...t!==void 0?{variables:t}:{},...n.operationName!==void 0?{operationName:n.operationName}:ye(e)!==void 0?{operationName:ye(e)}:{}},o=n.url??this.config.url,i=await nn(this.config,{accept:"text/event-stream"}),a=sr(s),{SSEClient:c}=await Promise.resolve().then(()=>(nr(),no)),l=new c({url:o,method:"POST",headers:i,body:a,signal:n.signal??this.config.signal,reconnect:!1,fetch:this.config.fetch});for await(let u of l){if(u.event==="complete")return;if(!u.data)continue;let f;try{f=M(JSON.parse(u.data))}catch{continue}if(f.errors?.length)throw rn(f.errors,s,f);f.data!==void 0&&(yield f.data)}}async introspect(){return await this.query(Lu)}async raw(e,t){return await this._executeRaw(e,t??null)}async _execute(e,t){this.config.onRequest(e);let n=await this._executeWithRetry(e,t);if(this.config.onResponse(n,e),n.errors?.length){let s=rn(n.errors,e,n);throw this.config.onError(s,e),s}if(n.data===void 0)throw new N("Response contained no data","ENODATA",void 0,e,n);return n.data}async _executeRaw(e,t){return await this.executeLink({request:e,config:this.config,...t!=null?{signal:t}:{}})}async _executeWithRetry(e,t){let n;for(let s=0;s<=this.config.retries;s++){s>0&&await Ha(this.config.retryDelayMs*Math.pow(2,s-1));try{return await this._executeRaw(e,t)}catch(o){if(n=o,o instanceof N&&o.isGraphQLError||t?.aborted)throw o}}throw n}async _executeWithAPQ(e,t){if(!this.config.enableAPQ)return oo(e,this.config,t,"none",void 0);let n=await oo(e,this.config,t,"omitQuery",o=>this._getAPQHash(o));return n.errors?.some(o=>o.extensions?.code==="PERSISTED_QUERY_NOT_FOUND")?oo(e,this.config,t,"full",o=>this._getAPQHash(o)):n}};h(T,"apqCache",new Map),h(T,"apqHashToQuery",new Map),h(T,"_apqHits",0),h(T,"_apqMisses",0),h(T,"_apqCleanupTimer",null);te=T;Lu=`
|
|
18
18
|
query IntrospectionQuery {
|
|
19
19
|
__schema {
|
|
20
20
|
queryType { name }
|
|
@@ -71,16 +71,16 @@ ${s}`,"ENETWORK",void 0,e,void 0,new Error(`HTTP ${r.status}`))}let n;try{n=awai
|
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
|
-
`;lo=X.prototype.clearAPQCache.bind(X.prototype),uo=X.prototype.getAPQMetrics.bind(X.prototype)});var $a={};ue($a,{collectAll:()=>ho,collectPages:()=>fo,createCursorPaginator:()=>yo,createKeysetPaginator:()=>_o,createLinkHeaderPaginator:()=>bo,createOffsetPaginator:()=>mo,createPagePaginator:()=>go,createRelayPaginator:()=>wo,createTokenPaginator:()=>xo,deserializePaginationState:()=>To,mergePaginators:()=>Ro,paginate:()=>H,paginateItems:()=>on,parseLinkHeaderNext:()=>an,prefetchPaginate:()=>ku,serializePaginationState:()=>So,takeItems:()=>po,toPaginationIterator:()=>Eo});function Eu(r,e){return{strategy:e,page:r.startPage??1,offset:r.startOffset??0,cursor:r.startCursor??null,prevCursor:null,token:r.startToken??null,done:!1,totalFetched:0}}function Ru(r,e,t,n,s,o){let i=n.getTotal?.(e)??null,a=n.perPage??null,c=i!==null&&a!==null?Math.ceil(i/a):null,l=t.page>1||t.offset>0||t.prevCursor!==null;return{items:r,total:i,page:t.page,perPage:a,totalPages:c,hasNext:o??n.hasNext(e,t),hasPrev:l,nextCursor:s?.cursor??null,prevCursor:t.prevCursor??null,raw:e}}async function*H(r,e="page"){let t=Eu(r,e),n=0;for(;!t.done&&!(r.signal?.aborted||r.maxPages&&n>=r.maxPages);){n>0&&r.delayMs&&r.delayMs>0&&await Au(r.delayMs,r.signal);let s;try{s=await r.fetch(t)}catch(u){if(r.signal?.aborted)break;throw u}let o=r.getItems(s,t);r.transform&&(o=o.map(r.transform)),r.filter&&(o=o.filter(r.filter));let i=r.getNext?r.getNext(s,t):null,a=r.hasNext(s,t),c=Ru(o,s,t,r,i,a),l=t.cursor;if(t={...t,page:i?.page??t.page+1,offset:i?.offset??t.offset+o.length,cursor:i?.cursor??t.cursor,token:i?.token??t.token,done:!a,totalFetched:t.totalFetched+o.length,prevCursor:l},n++,r.onPage?.(c,t),yield c,!a)break}}async function*on(r,e="page"){for await(let t of H(r,e))for(let n of t.items)yield n}async function ho(r,e="page"){let t=[];for await(let n of H(r,e))t.push(...n.items);return t}async function fo(r,e="page"){let t=[];for await(let n of H(r,e))t.push(n);return t}async function po(r,e,t="page"){let n=[];for await(let s of on(e,t))if(n.push(s),n.length>=r)break;return n}function mo(r){let e=r.paramNames??{},t=e.offset??"offset",n=e.limit??"limit",s=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},perPage:r.limit,fetch:async o=>{let i=new URL(r.url);return i.searchParams.set(t,String(o.offset)),i.searchParams.set(n,String(r.limit)),(await s(i.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:(o,i)=>r.getItems(o),getTotal:r.getTotal??(()=>null),hasNext:(o,i)=>{let a=r.getTotal?.(o)??null;return r.hasMore?r.hasMore(o,i.totalFetched+r.limit,a):a!==null?i.offset+r.limit<a:r.getItems(o).length===r.limit},getNext:(o,i)=>({offset:i.offset+r.limit})},"offset")}function go(r){let e=r.paramNames??{},t=e.page??"page",n=e.perPage??"per_page",s=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.perPage!==void 0?{perPage:r.perPage}:{},startPage:r.startPage??1,fetch:async o=>{let i=new URL(r.url);return i.searchParams.set(t,String(o.page)),i.searchParams.set(n,String(r.perPage)),(await s(i.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:o=>r.getItems(o),getTotal:r.getTotal??(()=>null),hasNext:(o,i)=>{let a=r.getTotalPages?.(o)??null;if(a!==null)return i.page<a;let c=r.getTotal?.(o)??null;return c!==null?i.page*r.perPage<c:r.getItems(o).length===r.perPage},getNext:(o,i)=>({page:i.page+1})},"page")}function yo(r){let e=r.paramName??"cursor",t=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},startCursor:r.startCursor??null,fetch:async n=>{let s=new URL(r.url);return n.cursor&&s.searchParams.set(e,n.cursor),(await t(s.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:n=>r.getItems(n),hasNext:n=>r.getNextCursor(n)!==null,getNext:n=>{let s=r.getNextCursor(n);return s?{cursor:s}:null}},"cursor")}function wo(r){let e=r.first??20;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.transform!==void 0?{transform:r.transform}:{},...r.filter!==void 0?{filter:r.filter}:{},...r.onPage!==void 0?{onPage:r.onPage}:{},startCursor:r.startCursor??null,perPage:e,fetch:t=>r.fetch({first:e,after:t.cursor}),getItems:t=>t.edges.map(n=>n.node),getTotal:t=>t.totalCount??null,hasNext:t=>t.pageInfo.hasNextPage,getNext:t=>{let n=t.pageInfo.endCursor??null;return n?{cursor:n}:null}},"relay")}function bo(r){let e=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},fetch:async t=>{let n=t.cursor??r.url,s=await e(n,{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}}),o=an(s.headers.get("link")??"");return{data:await s.json(),headers:s.headers,nextUrl:o}},getItems:t=>r.getItems(t.data),getTotal:t=>r.getTotal?.(t.data,t.headers)??null,hasNext:t=>t.nextUrl!==null,getNext:t=>t.nextUrl?{cursor:t.nextUrl}:null},"link-header")}function an(r){if(!r)return null;for(let e of r.split(",")){let t=e.match(/<([^>]+)>.*?rel=["']([^"']+)["']/);if(t&&t[2]&&t[2].split(/\s+/).includes("next"))return t[1]}return null}function xo(r){let e=r.tokenParam??"pageToken",t=r.pageSizeParam??"pageSize",n=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.pageSize!==void 0?{perPage:r.pageSize}:{},fetch:async s=>{let o=new URL(r.url);return s.token&&o.searchParams.set(e,s.token),r.pageSize&&o.searchParams.set(t,String(r.pageSize)),(await n(o.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:s=>r.getItems(s),getTotal:r.getTotal??(()=>null),hasNext:s=>r.getNextToken(s)!==null,getNext:s=>{let o=r.getNextToken(s);return o?{token:o}:null}},"token")}function _o(r){let e=r.pageSizeParam??"limit",t=r.fetch??globalThis.fetch;return H({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.pageSize!==void 0?{perPage:r.pageSize}:{},startCursor:r.startKey??null,fetch:async n=>{let s=new URL(r.url);return n.cursor&&s.searchParams.set(r.keyParam,n.cursor),r.pageSize&&s.searchParams.set(e,String(r.pageSize)),(await t(s.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:n=>r.getItems(n),hasNext:(n,s)=>{let o=r.getItems(n);return r.hasMore?r.hasMore(o,n):r.pageSize?o.length>=r.pageSize:o.length>0},getNext:(n,s)=>{let o=r.getItems(n),i=r.getLastKey(o);return i?{cursor:i}:null}},"keyset")}async function*ku(r,e="page",t=2){let n=[],s=H(r,e),o=!1;async function i(){if(o)return;let{value:a,done:c}=await s.next();o=c??!1,n.push(Promise.resolve(a??null))}for(let a=0;a<t+1;a++)await i();for(;n.length>0;){let a=await n.shift();if(a==null)break;await i(),yield a}}function So(r){return btoa(JSON.stringify(r))}function To(r){try{return JSON.parse(atob(r))}catch{throw new Error("Invalid pagination state string")}}function Au(r,e){return new Promise(t=>{if(e?.aborted){t();return}let n=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(n),t()},{once:!0})})}function Eo(r){let e=r[Symbol.asyncIterator]();return{next:()=>e.next(),return:t=>e.return?.(t)??Promise.resolve({value:t,done:!0}),throw:t=>e.throw?.(t)??Promise.reject(t),[Symbol.asyncIterator](){return this}}}async function*Ro(...r){let e=r.map(n=>n[Symbol.asyncIterator]()),t=new Set(e.map((n,s)=>s));for(;t.size>0;)for(let n of[...t]){let{value:s,done:o}=await e[n].next();if(o){t.delete(n);continue}yield s}}var cn=q(()=>{"use strict"});var sh={};ue(sh,{AbortError:()=>dr,AuthError:()=>pr,BatchQueue:()=>un,BatchingTransport:()=>Rt,CircuitBreaker:()=>Qe,CircuitBreakerRegistry:()=>Pe,CircuitOpenError:()=>Je,CloudflareKVAdapter:()=>it,ConsoleTransport:()=>ze,ContentTypeError:()=>xe,CookieJar:()=>Se,DedupMap:()=>ve,FetchTransport:()=>$e,FluentRequest:()=>or,GraphQLClient:()=>X,GraphQLClientError:()=>D,HAS_NATIVE_FETCH:()=>$s,HTTPCache:()=>se,HTTPError:()=>cr,HTTPLogger:()=>Ee,HTTPResponseError:()=>Ne,HTTPStatusError:()=>Ye,HeaderName:()=>w,HookEmitter:()=>ir,HookRegistry:()=>hn,HttpHeaders:()=>ie,IS_NODE:()=>He,InterceptorManager:()=>jt,JSONTransport:()=>Et,Kinetex:()=>It,KinetexError:()=>_,LogLevel:()=>Tt,MemoryStorageAdapter:()=>ye,MultiPartProgressAggregator:()=>hr,MultiTransport:()=>At,NetworkError:()=>Q,NodeHTTP2Transport:()=>pt,ProgressTracker:()=>z,ProxyError:()=>mr,RUNTIME:()=>pe,RateLimitError:()=>ct,Redactor:()=>Ct,RedirectError:()=>gr,RedirectTracker:()=>fn,RemoteTransport:()=>kt,ResponseDecodeError:()=>Ue,ResponseSizeLimitError:()=>be,ResponseValidationError:()=>lr,RichHeaders:()=>we,SSEClient:()=>Be,SSEError:()=>le,SSEMaxReconnectsError:()=>Fe,SSEParser:()=>Re,SSERouter:()=>tr,SSEServerResponse:()=>vt,SSETransformStream:()=>er,SigV4Signer:()=>oe,SizeLimitError:()=>Xe,Socks5Error:()=>I,TimeoutError:()=>re,TooManyRedirectsError:()=>ar,TwoTierStorageAdapter:()=>at,URLBuilder:()=>Ae,ValidationError:()=>te,WSClient:()=>Ie,WSConnectTimeoutError:()=>Ge,WSError:()=>B,WSMaxReconnectsError:()=>Nt,WSRateLimitError:()=>fr,WebStorageAdapter:()=>Me,applyDecompression:()=>Kt,assertOk:()=>vs,assertOkJSON:()=>Ps,authLink:()=>no,buildDataURL:()=>Cc,cachingCredentials:()=>Kn,canonicalizeDomainFull:()=>ce,chainCredentials:()=>Ui,clearAPQCache:()=>lo,collectAll:()=>ho,collectPages:()=>fo,collectStream:()=>Xo,compilePattern:()=>gc,composeAround:()=>Qa,composeBeforeRequest:()=>Va,composeBeforeResponse:()=>Ja,computeBodySize:()=>zn,computeDigestResponse:()=>ts,concatUint8Arrays:()=>br,connectWS:()=>si,corsHeaders:()=>ca,createAPIGatewaySigner:()=>Bi,createAbortHook:()=>Za,createAuthInterceptor:()=>Dn,createBodyNormalizationHook:()=>Ya,createCacheInterceptor:()=>$n,createCircuitBreaker:()=>ri,createCircuitBreakerRegistry:()=>ni,createCookieJar:()=>Gr,createCursorPaginator:()=>yo,createDedupMap:()=>ti,createDedupeInterceptor:()=>Hn,createDevelopmentLogger:()=>Js,createDigestAuthorization:()=>Ar,createDynamoDBSigner:()=>Wi,createGraphQLClient:()=>ao,createHARInterceptor:()=>jn,createHeaders:()=>la,createHookContext:()=>ec,createImmutableHeaders:()=>fa,createInterceptorSuite:()=>Oi,createJSONSSEStream:()=>Gs,createKVCache:()=>An,createKeysetPaginator:()=>_o,createLimitedReader:()=>Ds,createLinkHeaderPaginator:()=>bo,createLocalStorageCache:()=>Rn,createLogger:()=>Ks,createLoggingHooks:()=>Ga,createLoggingInterceptor:()=>Un,createMemoryCache:()=>En,createMethodCircuitBreakerKey:()=>qa,createMetricsInterceptor:()=>qn,createOffsetPaginator:()=>mo,createPagePaginator:()=>go,createProductionLogger:()=>Vs,createRateLimitInterceptor:()=>qt,createRelayPaginator:()=>wo,createRequestHeaders:()=>ua,createResponseHeaders:()=>ha,createRetryInterceptor:()=>On,createS3Signer:()=>zi,createSSEResponse:()=>Xs,createSSEStream:()=>Qs,createSTSSigner:()=>Fi,createSessionStorageCache:()=>kn,createSocks5Tunnel:()=>Do,createStructuredError:()=>yi,createTimeoutInterceptor:()=>Nn,createTimingHook:()=>Xa,createTokenPaginator:()=>xo,createTransport:()=>Jt,createTwoTierCache:()=>Cn,decodeBody:()=>Wt,decodeIDNLabel:()=>Zt,decompressBodyStream:()=>Gt,decompressStream:()=>$r,deepClone:()=>Ze,default:()=>nh,defaultPath:()=>bt,denoTcpConnector:()=>nc,deriveSigningKey:()=>ht,deserializePaginationState:()=>To,detectClockSkew:()=>Yn,detectOperationType:()=>nn,detectRuntime:()=>Kr,diffResponses:()=>Is,diffURLs:()=>vc,domainMatch:()=>wt,encodePathComponent:()=>Uo,encodeQueryValue:()=>We,envCredentials:()=>Ni,errorLink:()=>so,expandTemplate:()=>mc,extractOperationName:()=>ge,extractServerTiming:()=>Ms,extractSetCookieHeaders:()=>St,fillPathParams:()=>qo,formatAmzDate:()=>zt,formatBasic:()=>Yi,formatBearer:()=>Xi,formatBytes:()=>Ot,formatCSP:()=>Dr,formatCacheControl:()=>ds,formatContentDisposition:()=>hs,formatContentType:()=>ls,formatDateStamp:()=>lt,formatDigestAuth:()=>rs,formatETA:()=>yn,formatError:()=>wi,formatHSTS:()=>Or,formatLinkHeader:()=>ta,formatProgress:()=>Zo,formatRate:()=>gn,formatServerTiming:()=>na,fromNodeHeaders:()=>sa,fromWebHeaders:()=>ia,getAPQMetrics:()=>uo,getAuthFingerprint:()=>Oe,getClientIP:()=>bs,getEffectiveRuntime:()=>Us,getOrigin:()=>pn,getPublicSuffix:()=>gt,getRegistrableDomain:()=>Jr,getRuntime:()=>Sr,gql:()=>co,hasNativeFetch:()=>Ri,imdsCredentials:()=>$i,initChunkedSigning:()=>Gn,injectHeaders:()=>Ba,isAbortError:()=>_r,isAbortSignal:()=>fi,isAbsolute:()=>zo,isArrayBuffer:()=>li,isBinary:()=>As,isBlob:()=>mi,isBlobURL:()=>Rc,isBrowserEnvironment:()=>Ei,isClockSkewError:()=>Zn,isDataURL:()=>Ec,isFormData:()=>pi,isHTTP:()=>Tc,isHTTPS:()=>Sc,isHeaders:()=>hi,isIPAddress:()=>me,isJSON:()=>Ft,isLocalhost:()=>kc,isNodeEnvironment:()=>Ti,isPlainObject:()=>di,isPublicSuffix:()=>yt,isReadableStream:()=>ui,isRelative:()=>_c,isSafeURL:()=>rt,isSameOrigin:()=>yc,isSameSite:()=>wc,isText:()=>Nr,isURLSearchParams:()=>gi,isUint8Array:()=>ci,isValidHeaderName:()=>et,isValidHeaderValue:()=>tt,joinPath:()=>Ho,jsonSSE:()=>en,kinetex:()=>Uc,loadCookieJar:()=>Xr,loggingLink:()=>oo,mergePaginators:()=>Ro,mergeQuery:()=>lc,mergeSignals:()=>xr,negotiateContentType:()=>ea,nodeTcpConnector:()=>sc,normalizeForwardedHeaders:()=>Mr,normalizeHeaders:()=>st,normalizePath:()=>jo,normalizeResponse:()=>ks,normalizeURL:()=>pc,omitQuery:()=>hc,paginate:()=>H,paginateItems:()=>on,parseAccept:()=>Lr,parseAcceptEncoding:()=>ps,parseAcceptLanguage:()=>ms,parseAltSvc:()=>Es,parseAuthorization:()=>Cr,parseBody:()=>mt,parseCSP:()=>Ss,parseCacheControl:()=>fs,parseContentDisposition:()=>us,parseContentLanguage:()=>Zi,parseContentRange:()=>ys,parseContentType:()=>_e,parseCookieDate:()=>Yt,parseDataURL:()=>Ac,parseDigestChallenge:()=>es,parseForwarded:()=>ws,parseHSTS:()=>_s,parseLinkHeader:()=>Pr,parseLinkHeaderNext:()=>an,parseMultipartResponse:()=>Br,parseParams:()=>K,parseQuery:()=>$o,parseRange:()=>gs,parseRetryAfter:()=>xs,parseSSEText:()=>Ys,parseServerTiming:()=>Ts,parseSetCookieHeader:()=>_t,parseSocks5Url:()=>rc,parseUntrustedJSON:()=>ai,parseWWWAuthenticate:()=>vr,parseWarning:()=>ra,pathMatch:()=>xt,pathSegments:()=>dc,percentDecode:()=>ke,percentEncode:()=>dn,perfNow:()=>xi,pickQuery:()=>uc,presignRequest:()=>Qn,readBlob:()=>qr,readBodyWithLimit:()=>Ur,readBytes:()=>Vt,readFormData:()=>Ls,readJSON:()=>Hr,readJSONStream:()=>Cs,readNDJSON:()=>zr,readRawBody:()=>Qt,readStream:()=>dt,readText:()=>jr,redactURL:()=>Nc,relativeURL:()=>xc,resolveURL:()=>bc,retryLink:()=>io,safeJSONParse:()=>he,safeParseURL:()=>Ce,sanitizeURL:()=>bi,securityHeaders:()=>aa,sendWithTimeout:()=>je,serializePaginationState:()=>So,setRuntime:()=>Ns,sigV4UriEncode:()=>Jn,signChunk:()=>ji,signFinalChunk:()=>qi,signRequest:()=>Rr,signS3PostPolicy:()=>Xn,sleep:()=>_i,socks5Connector:()=>oc,splitSetCookieHeaders:()=>qe,staticCredentials:()=>Di,streamWithProgress:()=>Go,stringifyQuery:()=>cc,stripHash:()=>Lc,stripQuery:()=>Mc,takeItems:()=>po,tap:()=>za,throttleProgress:()=>ei,throwOnHTTPError:()=>Wa,toNodeHeaders:()=>oa,toOTelSpan:()=>Ws,toPaginationIterator:()=>Eo,toRequestId:()=>wn,toUint8Array:()=>Si,tryParseJSON:()=>ii,uint8ArrayToBase64:()=>Ut,urlExtension:()=>Oc,urlFilename:()=>Dc,validateErrorCode:()=>oi,validateResponse:()=>Ka,withBaseURL:()=>Fa,withBlobUploadProgress:()=>Jo,withDownloadProgress:()=>Qo,withTrailingSlash:()=>Pc,withUploadProgress:()=>Dt,withoutTrailingSlash:()=>Ic,xhrFetch:()=>Yo});var z=class{constructor(e,t={}){h(this,"loaded",0);h(this,"total");h(this,"startMs");h(this,"lastMs");h(this,"lastLoaded",0);h(this,"smoothedRate",0);h(this,"smoothing");h(this,"_done",!1);h(this,"lastEmitMs",0);h(this,"minIntervalMs");h(this,"onProgress");this.total=e,this.startMs=ur(),this.lastMs=this.startMs,this.smoothing=t.smoothingFactor??.3,this.onProgress=t.onProgress??null;let n=t.throttleHz??10;this.minIntervalMs=n>0?1e3/n:0}update(e){this.loaded+=e;let t=this._snapshot();if(this.onProgress){let n=ur();(this.minIntervalMs===0||n-this.lastEmitMs>=this.minIntervalMs)&&(this.lastEmitMs=n,this.onProgress(t))}return t}complete(){this._done=!0;let e=this._snapshot();return this.onProgress?.(e),e}snapshot(){return this._snapshot()}get bytesLoaded(){return this.loaded}get isDone(){return this._done}_snapshot(){let e=ur(),t=e-this.startMs,n=e-this.lastMs;if(n>0){let i=(this.loaded-this.lastLoaded)/n*1e3;this.smoothedRate=this.smoothedRate===0?i:this.smoothedRate*(1-this.smoothing)+i*this.smoothing,this.lastMs=e,this.lastLoaded=this.loaded}let s=this.total!==null&&this.total>0?Math.min(100,this.loaded/this.total*100):null,o=this.total!==null&&this.smoothedRate>0?Math.max(0,(this.total-this.loaded)/this.smoothedRate*1e3):null;return{loaded:this.loaded,total:this.total,percent:this._done?this.total!==null?100:null:s,rate:this.smoothedRate,eta:this._done?0:o,elapsed:t,done:this._done}}};function Dt(r,e,t={}){let n=new z(e,t);if(!r)return n.complete(),{stream:new ReadableStream({start:i=>i.close()}),tracker:n};let s;if(r instanceof ReadableStream)s=r;else if(typeof r=="string"){let i=new TextEncoder().encode(r);s=new ReadableStream({start(a){a.enqueue(i),a.close()}})}else s=new ReadableStream({start(i){i.enqueue(r),i.close()}});return{stream:new ReadableStream({async start(i){let a=s.getReader();if(t.signal?.aborted){a.cancel("aborted").catch(()=>{}),i.error(new DOMException("Upload aborted","AbortError"));return}t.signal?.addEventListener("abort",()=>{a.cancel("aborted").catch(()=>{}),i.error(new DOMException("Upload aborted","AbortError"))},{once:!0});try{for(;;){let{done:c,value:l}=await a.read();if(c){n.complete(),i.close();break}n.update(l.byteLength),i.enqueue(l)}}catch(c){n.complete(),i.error(c)}}}),tracker:n}}function Jo(r,e={}){return Dt(r.stream(),r.size,e)}function Qo(r,e={}){let t=r.headers.get("content-length"),n=t?parseInt(t,10):null,s=new z(isNaN(n)?null:n,e);if(!r.body)return s.complete(),{response:r,tracker:s};let o=r.body,i=new ReadableStream({async start(c){let l=o.getReader(),u=!1,f=()=>{u||(u=!0,l.cancel("aborted").catch(()=>{}),c.error(new DOMException("Download aborted","AbortError")))};e.signal?.addEventListener("abort",f,{once:!0});try{for(;;){let{done:d,value:p}=await l.read();if(d){s.complete(),c.close();break}s.update(p.byteLength),c.enqueue(p)}}catch(d){u||s.complete(),c.error(d)}finally{u||e.signal?.removeEventListener("abort",f)}}});return{response:new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers}),tracker:s}}async function*Go(r,e,t={}){let n=new z(e,t),s=r.getReader();try{for(;;){if(t.signal?.aborted)throw new DOMException("Stream aborted","AbortError");let{done:o,value:i}=await s.read();if(o){let c=n.complete();yield{chunk:new Uint8Array(0),progress:c};break}let a=n.update(i.byteLength);yield{chunk:i,progress:a}}}finally{s.releaseLock()}}async function Xo(r,e,t={}){let n=new z(e,t),s=[],o=r.getReader();if(t.signal?.aborted)throw o.cancel("aborted").catch(()=>{}),new DOMException("Stream aborted","AbortError");if(t.signal){let l=()=>{o.cancel("aborted").catch(()=>{})};t.signal.addEventListener("abort",l,{once:!0})}try{for(;;){let{done:l,value:u}=await o.read();if(l)break;s.push(u),n.update(u.byteLength)}}finally{o.releaseLock()}n.complete();let i=s.reduce((l,u)=>l+u.byteLength,0),a=new Uint8Array(i),c=0;for(let l of s)a.set(l,c),c+=l.byteLength;return{data:a,tracker:n}}var hr=class{constructor(e,t){h(this,"partCount");h(this,"trackers",new Map);h(this,"totals",new Map);h(this,"onOverall");this.partCount=e,this.onOverall=t??null}createPartTracker(e,t,n={}){this.totals.set(e,t);let s=new z(t,{...n,onProgress:o=>{n.onProgress?.(o),this._emit()}});return this.trackers.set(e,s),s}getOverall(){let e=[],t=0,n=0,s=0,o=!0,i=0;for(let f=0;f<this.partCount;f++){let p=this.trackers.get(f)?.snapshot()??{loaded:0,total:this.totals.get(f)??null,percent:0,rate:0,eta:null,elapsed:0,done:!1};e.push(p),t+=p.loaded,p.total!==null&&(n+=p.total),s+=p.rate,p.done||(o=!1),p.elapsed>i&&(i=p.elapsed)}let a=n>0,c=a?Math.min(100,t/n*100):null,l=a&&s>0?Math.max(0,(n-t)/s*1e3):null;return{parts:e,overall:{loaded:t,total:a?n:null,percent:c,rate:s,eta:o?0:l,elapsed:i,done:o}}}_emit(){this.onOverall&&this.onOverall(this.getOverall())}},Ko=globalThis.XMLHttpRequest;function Yo(r,e){return new Promise((t,n)=>{if(!Ko){n(new Error("XMLHttpRequest is not available in this runtime. Use fetch() instead."));return}let s=new Ko,o=new z(null,{...e.onUploadProgress!==void 0?{onProgress:e.onUploadProgress}:{},...e.throttleHz!==void 0?{throttleHz:e.throttleHz}:{},...e.smoothingFactor!==void 0?{smoothingFactor:e.smoothingFactor}:{}}),i=new z(null,{...e.onDownloadProgress!==void 0?{onProgress:e.onDownloadProgress}:{},...e.throttleHz!==void 0?{throttleHz:e.throttleHz}:{},...e.smoothingFactor!==void 0?{smoothingFactor:e.smoothingFactor}:{}});s.open(e.method??"GET",r,!0);for(let[a,c]of Object.entries(e.headers??{}))s.setRequestHeader(a,c);e.responseType&&(s.responseType=e.responseType),s.upload&&e.onUploadProgress&&(s.upload.addEventListener("loadstart",a=>{}),s.upload.addEventListener("progress",a=>{o.update(a.loaded-o.bytesLoaded)}),s.upload.addEventListener("load",()=>o.complete())),e.onDownloadProgress&&s.addEventListener("progress",a=>{i.update(a.loaded-i.bytesLoaded)}),e.signal?.addEventListener("abort",()=>{s.abort(),n(new DOMException("Request aborted","AbortError"))},{once:!0}),s.addEventListener("load",()=>{i.complete();let a=s.getAllResponseHeaders(),c={};for(let l of a.trim().split(/[\r\n]+/)){let u=l.indexOf(": ");u!==-1&&(c[l.slice(0,u).toLowerCase()]=l.slice(u+2))}t({status:s.status,statusText:s.statusText,headers:c,body:typeof s.response=="string"?s.response:String(s.response??"")})}),s.addEventListener("error",()=>{n(new TypeError("Network request failed"))}),s.addEventListener("timeout",()=>{n(new TypeError("Request timed out"))}),s.send(e.body??null)})}var Vo=["B","KB","MB","GB","TB"];function Ot(r,e=2){if(r===0)return"0 B";let t=1024,n=Math.max(0,e),s=Math.floor(Math.log(r)/Math.log(t)),o=Vo[Math.min(s,Vo.length-1)];return`${parseFloat((r/Math.pow(t,s)).toFixed(n))} ${o}`}function gn(r){return`${Ot(r)}/s`}function yn(r){if(!isFinite(r)||r<0)return"\u221E";let e=Math.round(r/1e3),t=Math.floor(e/3600),n=Math.floor(e%3600/60),s=e%60;return t>0?`${t}h ${n}m ${s}s`:n>0?`${n}m ${s}s`:`${s}s`}function Zo(r){let e=Ot(r.loaded),t=r.total!==null?` / ${Ot(r.total)}`:"",n=r.percent!==null?` (${r.percent.toFixed(1)}%)`:"",s=r.rate>0?` @ ${gn(r.rate)}`:"",o=r.eta!==null&&!r.done?` ETA ${yn(r.eta)}`:"";return`${e}${t}${n}${s}${o}`}function ei(r,e=10){let t=e>0?1e3/e:0,n=0;return s=>{let o=ur();(s.done||o-n>=t)&&(n=o,r(s))}}function ur(){return typeof performance<"u"?performance.now():Date.now()}var ve=class{constructor(e={}){h(this,"inflight",new Map);h(this,"timeouts",new Map);h(this,"windowMs");h(this,"methods");h(this,"keyFn");h(this,"_globalSignal");h(this,"_hits",0);h(this,"_misses",0);this.windowMs=e.windowMs??0,this.methods=new Set((e.methods??["GET","HEAD"]).map(t=>t.toUpperCase())),this.keyFn=e.keyFn??((t,n)=>`${t}::${n}`),this._globalSignal=e.signal??null}execute(e,t,n,s,o,i){let a=o??this.windowMs,c=i??this._globalSignal;if(c?.aborted||!this.methods.has(e.toUpperCase()))return n();let l=this.keyFn(e,t,s),u=this.inflight.get(l);if(u){if(u.resolvedAt!==null&&a>0&&Date.now()-u.resolvedAt<=a)return this._hits++,u.promise;if(u.resolvedAt===null)return this._hits++,u.promise;this.inflight.delete(l)}this._misses++;let f={resolvedAt:null,promise:void 0};return this.inflight.set(l,f),f.promise=(async()=>{let d=c?()=>{this.inflight.delete(l);let p=this.timeouts.get(l);p!==void 0&&(clearTimeout(p),this.timeouts.delete(l))}:null;c&&d&&c.addEventListener("abort",d,{once:!0});try{return await n()}finally{c&&d&&c.removeEventListener("abort",d)}})().then(d=>{if(f.resolvedAt=Date.now(),f.result=d,a<=0)this.inflight.delete(l);else{let p=setTimeout(()=>{this.inflight.delete(l),this.timeouts.delete(l)},a);this.timeouts.set(l,p)}return d},d=>{f.resolvedAt=Date.now(),f.error=d,this.inflight.delete(l);let p=this.timeouts.get(l);throw p!==void 0&&(clearTimeout(p),this.timeouts.delete(l)),d}),f.promise}get hits(){return this._hits}get misses(){return this._misses}get inFlightCount(){let e=0;for(let t of this.inflight.values())t.resolvedAt===null&&e++;return e}get keys(){return[...this.inflight.keys()]}getStats(){let e=this._hits+this._misses;return{hits:this._hits,misses:this._misses,totalRequests:e,hitRate:e===0?0:this._hits/e,inFlightCount:this.inFlightCount,trackedKeys:this.inflight.size}}resetMetrics(){this._hits=0,this._misses=0}clear(){this.inflight.clear();for(let e of this.timeouts.values())clearTimeout(e);this.timeouts.clear()}invalidate(e){let t=this.timeouts.get(e);return t&&(clearTimeout(t),this.timeouts.delete(e)),this.inflight.delete(e)}destroy(){this.clear()}};function ti(r){return new ve(r)}var Je=class extends Error{constructor(t,n){super(`Circuit breaker OPEN for "${t}" \u2014 request rejected`);h(this,"code","ECIRCUITOPEN");h(this,"state");this.name="CircuitOpenError",this.state=n}},Qe=class{constructor(e,t={}){h(this,"key");h(this,"failureThreshold");h(this,"windowSize");h(this,"resetTimeoutMs");h(this,"successThreshold");h(this,"halfOpenConcurrency");h(this,"failureFilter");h(this,"cfg");h(this,"_state","CLOSED");h(this,"_window",[]);h(this,"_consecutiveFails",0);h(this,"_consecutiveSucc",0);h(this,"_openedAt",null);h(this,"_halfOpenAt",null);h(this,"_lastFailureAt",null);h(this,"_lastSuccessAt",null);h(this,"_inFlightProbes",0);h(this,"_totalRequests",0);h(this,"_totalFailures",0);h(this,"_totalSuccesses",0);h(this,"_totalRejected",0);this.key=e,this.failureThreshold=t.failureThreshold??5,this.windowSize=t.windowSize??10,this.resetTimeoutMs=t.resetTimeoutMs??3e4,this.successThreshold=t.successThreshold??2,this.halfOpenConcurrency=t.halfOpenConcurrency??1,this.failureFilter={networkErrors:t.failures?.networkErrors??!0,timeouts:t.failures?.timeouts??!0,serverErrors:t.failures?.serverErrors??!1,statusCodes:t.failures?.statusCodes??[]},this.cfg=t}get state(){return this._state}get snapshot(){return{state:this._state,failureCount:this.windowSize>0?this._window.filter(e=>!e).length:this._consecutiveFails,successCount:this._consecutiveSucc,lastFailureAt:this._lastFailureAt,lastSuccessAt:this._lastSuccessAt,openedAt:this._openedAt,halfOpenAt:this._halfOpenAt,totalRequests:this._totalRequests,totalFailures:this._totalFailures,totalSuccesses:this._totalSuccesses,totalRejected:this._totalRejected,inFlightProbes:this._inFlightProbes}}execute(e){if(this._checkTransition(),this._state==="OPEN"){this._totalRejected++;let t=this.snapshot;return this.cfg.onRejected?.(t),Promise.reject(new Je(this.key,t))}if(this._state==="HALF_OPEN"){if(this._inFlightProbes>=this.halfOpenConcurrency){this._totalRejected++;let t=this.snapshot;return this.cfg.onRejected?.(t),Promise.reject(new Je(this.key,t))}this._inFlightProbes++}return this._totalRequests++,e().then(t=>(this._state==="HALF_OPEN"&&(this._inFlightProbes=Math.max(0,this._inFlightProbes-1)),this._recordSuccess(),t),t=>{throw this._state==="HALF_OPEN"&&(this._inFlightProbes=Math.max(0,this._inFlightProbes-1)),this._isCountableFailure(t)&&this._recordFailure(),t})}trip(){this._state!=="OPEN"&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))}reset(){this._state="CLOSED",this._window=[],this._consecutiveFails=0,this._consecutiveSucc=0,this._openedAt=null,this._halfOpenAt=null,this._inFlightProbes=0,this.cfg.onClose?.(this.snapshot)}_checkTransition(){this._state==="OPEN"&&this._openedAt!==null&&Date.now()-this._openedAt>=this.resetTimeoutMs&&(this._state="HALF_OPEN",this._halfOpenAt=Date.now(),this._consecutiveSucc=0,this._inFlightProbes=0,this.cfg.onHalfOpen?.(this.snapshot))}_recordSuccess(){if(this._lastSuccessAt=Date.now(),this._totalSuccesses++,this._consecutiveFails=0,this._state==="HALF_OPEN"){this._consecutiveSucc++,this._consecutiveSucc>=this.successThreshold&&this.reset();return}this.windowSize>0&&(this._window.push(!0),this._window.length>this.windowSize&&this._window.shift())}_recordFailure(){if(this._lastFailureAt=Date.now(),this._totalFailures++,this._consecutiveSucc=0,this._consecutiveFails++,this._state==="HALF_OPEN"){this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot);return}this.windowSize>0?(this._window.push(!1),this._window.length>this.windowSize&&this._window.shift(),this._window.filter(t=>!t).length>=this.failureThreshold&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))):this._consecutiveFails>=this.failureThreshold&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))}_isCountableFailure(e){if(!(e instanceof Error))return!1;let t=e.code;if(this.failureFilter.networkErrors&&t==="ENETWORK"||this.failureFilter.timeouts&&t==="ETIMEOUT")return!0;if(this.failureFilter.serverErrors){let n=e.status;if(n&&n>=500)return!0}if(this.failureFilter.statusCodes&&this.failureFilter.statusCodes.length>0){let n=e.status;if(n&&this.failureFilter.statusCodes.includes(n))return!0}return!1}},Pe=class{constructor(e={}){h(this,"breakers",new Map);h(this,"defaultConfig");this.defaultConfig=e}get(e,t){return this.breakers.has(e)||this.breakers.set(e,new Qe(e,{...this.defaultConfig,...t})),this.breakers.get(e)}execute(e,t,n){return this.get(e,n).execute(t)}trip(e){this.get(e).trip()}reset(e){this.get(e).reset()}snapshots(){let e={};for(let[t,n]of this.breakers)e[t]=n.snapshot;return e}delete(e){this.breakers.delete(e)}clear(){this.breakers.clear()}get size(){return this.breakers.size}};function ri(r,e){return new Qe(r,e)}function ni(r){return new Pe(r)}var B=class extends Error{constructor(t,n){super(t,n!=null?{cause:n}:void 0);h(this,"code","EWSCONNECT");h(this,"originalCause");this.name="WSError",this.originalCause=n}},Nt=class extends Error{constructor(t){super(`WebSocket gave up after ${t} reconnect attempts`);h(this,"attempts");h(this,"code","EWSMAXRECONNECTS");this.attempts=t,this.name="WSMaxReconnectsError"}},Ge=class extends Error{constructor(t,n){super(`WebSocket connect to ${t} timed out after ${n}ms`);h(this,"code","EWSCONNECTTIMEOUT");this.name="WSConnectTimeoutError"}},fr=class extends Error{constructor(t){super(`WebSocket send rate limited; retry in ${t}ms`);h(this,"delayMs");h(this,"code","EWSRATELIMIT");this.delayMs=t,this.name="WSRateLimitError"}},Ie=class{constructor(e){h(this,"_url");h(this,"_protocols");h(this,"_headers");h(this,"_maxReconnects");h(this,"_reconnectBaseMs");h(this,"_reconnectMaxMs");h(this,"_reconnectJitter");h(this,"_pingIntervalMs");h(this,"_pingPayload");h(this,"_pongMatcher");h(this,"_pongTimeoutMs");h(this,"_connectTimeoutMs");h(this,"_bufferMessages");h(this,"_maxBufferSize");h(this,"_cbOpen");h(this,"_cbMessage");h(this,"_cbClose");h(this,"_cbError");h(this,"_cbReconnect");h(this,"_cbGiveUp");h(this,"_ws",null);h(this,"_state","CLOSED");h(this,"_reconnAttempt",0);h(this,"_buffer",[]);h(this,"_pingTimer",null);h(this,"_pongTimer",null);h(this,"_reconnTimer",null);h(this,"_msgListeners",[]);h(this,"_closeListeners",[]);h(this,"_openWaiters",[]);h(this,"_correlations",new Map);h(this,"_aborted",!1);h(this,"_iterQueue",[]);h(this,"_iterWaiter",null);h(this,"_iterDone",!1);h(this,"_rooms",[]);h(this,"_keepRooms");h(this,"_highWaterMark");h(this,"_lowWaterMark");h(this,"_bufferedBytes",0);h(this,"_drainWaiters",[]);h(this,"_cbBackpressure");h(this,"_wasBackpressured",!1);h(this,"_maxSendRate");h(this,"_tokens",0);h(this,"_lastToken",0);h(this,"_serverEndpoint",null);h(this,"_mx",{messagesSent:0,messagesReceived:0,bytesSent:0,bytesReceived:0,reconnectCount:0,totalConnectAttempts:0,connectedAt:null,closedAt:null,uptimeMs:0});h(this,"_openedAt",null);if(this._url=e.url,this._protocols=e.protocols,this._headers=e.headers,this._maxReconnects=e.maxReconnects??10,this._reconnectBaseMs=e.reconnectBaseMs??1e3,this._reconnectMaxMs=e.reconnectMaxMs??3e4,this._reconnectJitter=e.reconnectJitter??.3,this._pingIntervalMs=e.pingIntervalMs??3e4,this._pingPayload=e.pingPayload??"ping",this._pongMatcher=e.pongMatcher,this._pongTimeoutMs=e.pongTimeoutMs??1e4,this._connectTimeoutMs=e.connectTimeoutMs??3e4,this._bufferMessages=e.bufferMessages??!0,this._maxBufferSize=e.maxBufferSize??100,this._cbOpen=e.onOpen,this._cbMessage=e.onMessage,this._cbClose=e.onClose,this._cbError=e.onError,this._cbReconnect=e.onReconnect,this._cbGiveUp=e.onGiveUp,this._cbBackpressure=e.onBackpressure,this._highWaterMark=e.highWaterMark??65536,this._lowWaterMark=e.lowWaterMark??16384,this._maxSendRate=e.maxSendRate??0,this._keepRooms=e.keepRooms??!0,e.rooms&&e.rooms.length>0)for(let t of e.rooms)this._rooms.push({room:t,joinedAt:0});e.signal?.addEventListener("abort",()=>this.close(1e3,"AbortSignal aborted"),{once:!0})}get state(){return this._state}get connected(){return this._state==="OPEN"}get bufferedCount(){return this._buffer.length}get metrics(){return{...this._mx,uptimeMs:this._mx.uptimeMs+(this._openedAt!=null?Date.now()-this._openedAt:0)}}connect(){return this._state==="OPEN"?Promise.resolve():this._state==="CONNECTING"||this._state==="RECONNECTING"?new Promise((e,t)=>this._openWaiters.push({resolve:e,reject:t})):this._doConnect(!1)}waitForOpen(e=6e4){return this._state==="OPEN"?Promise.resolve():new Promise((t,n)=>{let s=e>0?setTimeout(()=>{let o=this._openWaiters.findIndex(i=>i.resolve===t);o!==-1&&this._openWaiters.splice(o,1),n(new Ge(this._url,e))},e):null;this._openWaiters.push({resolve:()=>{s&&clearTimeout(s),t()},reject:o=>{s&&clearTimeout(s),n(o)}})})}close(e=1e3,t="Client closed"){this._aborted=!0,this._stopAll();for(let s of this._drainWaiters.splice(0))s();this._state="CLOSING";let n=this._ws;if(n){if(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.readyState<2)try{n.close(e,t)}catch{}this._ws=null}this._buffer=[],this._bufferedBytes=0,this._iterQueue=[],this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null);for(let s of this._openWaiters.splice(0))s.reject(new Error("Client closed"));this._rooms=[];for(let s of this._correlations.values())s.timer&&clearTimeout(s.timer),s.reject(new Error("Client closed"));this._correlations.clear(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now(),this._state="CLOSED";for(let s of this._closeListeners)try{s({code:e,reason:t})}catch{}this._closeListeners=[],this._msgListeners=[],this._cbClose?.(e,t,!1)}destroy(){this._aborted=!0,this._stopAll();for(let t of this._drainWaiters.splice(0))t();this._state="CLOSING";let e=this._ws;if(e){if(e.onopen=e.onmessage=e.onerror=e.onclose=null,e.readyState<2)try{e.close(1e3,"Destroyed")}catch{}this._ws=null}this._buffer=[],this._bufferedBytes=0,this._iterQueue=[],this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null),this._msgListeners=[];for(let t of this._openWaiters.splice(0))t.reject(new Error("Client destroyed"));this._rooms=[];for(let t of this._correlations.values())t.timer&&clearTimeout(t.timer),t.reject(new Error("Client destroyed"));this._correlations.clear(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now(),this._state="CLOSED";for(let t of this._closeListeners)try{t({code:1e3,reason:"Destroyed"})}catch{}this._closeListeners=[],this._cbClose?.(1e3,"Destroyed",!1)}send(e){this._tx(e)&&this._mx.messagesSent++}sendBinary(e){let t=e instanceof Uint8Array?e.slice().buffer:e;this._tx(t)&&this._mx.messagesSent++}sendJSON(e){this.send(JSON.stringify(e))}request(e,t,n=o=>o.json??o.data,s=1e4){return new Promise((o,i)=>{let a=`${Date.now()}-${Math.random()}`,c=s>0?setTimeout(()=>{let l=this._correlations.get(a);l?.timer&&clearTimeout(l.timer),this._correlations.delete(a),i(new B(`request() timed out after ${s}ms waiting for reply`))},s):null;this._correlations.set(a,{matcher:t,extract:n,resolve:o,reject:i,timer:c}),typeof e=="string"?this.send(e):this.sendJSON(e)})}onMessage(e){return this._msgListeners.push(e),()=>{let t=this._msgListeners.indexOf(e);t!==-1&&this._msgListeners.splice(t,1)}}onClose(e){return this._closeListeners.push(e),()=>{let t=this._closeListeners.indexOf(e);t!==-1&&this._closeListeners.splice(t,1)}}drainBuffer(){let e=this._buffer.splice(0);return this._bufferedBytes=0,this._updateBackpressure(),e}join(e,t){this._rooms.some(n=>n.room===e&&n.namespace===t)||(this._rooms.push({room:e,namespace:t,joinedAt:Date.now()}),this.sendJSON({type:"room:join",room:e,namespace:t??null}))}leave(e,t){let n=this._rooms.findIndex(s=>s.room===e&&s.namespace===t);n!==-1&&(this._rooms.splice(n,1),this.sendJSON({type:"room:leave",room:e,namespace:t??null}))}get rooms(){return this._rooms}get backpressure(){return{bufferedBytes:this._bufferedBytes,highWaterMark:this._highWaterMark,lowWaterMark:this._lowWaterMark,isBackpressured:this._bufferedBytes>=this._highWaterMark}}drain(e=3e4){return this._state==="CLOSED"?Promise.reject(new B("Cannot drain \u2014 socket is CLOSED")):this._bufferedBytes<this._lowWaterMark?Promise.resolve():new Promise((t,n)=>{let s=e>0?setTimeout(()=>n(new B(`drain() timed out after ${e}ms`)),e):null;this._drainWaiters.push(()=>{s&&clearTimeout(s),t()})})}async drainAndClose(e=3e4){if(this._state!=="CLOSED"){try{await this.drain(e)}catch{}this.close(1e3,"Graceful shutdown")}}get serverEndpoint(){return this._serverEndpoint}[Symbol.asyncIterator](){return{next:()=>this._iterQueue.length>0?Promise.resolve({done:!1,value:this._iterQueue.shift()}):this._iterDone?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this._iterWaiter=e}),return:()=>(this.close(1e3,"Iterator returned"),Promise.resolve({done:!0,value:void 0}))}}_doConnect(e){return this._mx.totalConnectAttempts++,this._state="CONNECTING",new Promise((t,n)=>{let s=!1,o=null;this._connectTimeoutMs>0&&(o=setTimeout(()=>{if(s)return;s=!0;let u=new Ge(this._url,this._connectTimeoutMs);n(u),this._cbError?.(u);let f=this._ws;if(f&&(f.onopen=f.onmessage=f.onerror=f.onclose=null,f.close(),this._ws=null),!this._aborted&&this._canRecon())this._scheduleRecon();else{this._state="CLOSED";for(let d of this._openWaiters.splice(0))d.reject(u);this._rejectCorrelations("Connection timeout")}},this._connectTimeoutMs));let i=()=>{o&&(clearTimeout(o),o=null)},a=this._url,c=(()=>{try{let u=globalThis;if(typeof globalThis.Deno<"u"||typeof globalThis.Bun<"u"||u.process?.versions?.node||typeof window>"u")return!1;let f=window;return typeof f.navigator<"u"&&typeof f.document<"u"}catch{return!1}})();if(this._headers&&c){let u=new URL(a);for(let[f,d]of Object.entries(this._headers))u.searchParams.set(f,d);a=u.href}let l;try{l=this._protocols?new WebSocket(a,this._protocols):new WebSocket(a)}catch(u){i(),this._state="CLOSED",n(new B("Failed to construct WebSocket",u instanceof Error?u:void 0));return}if(this._headers&&!c){let u=l;if(typeof u.setHeader=="function")for(let[f,d]of Object.entries(this._headers))u.setHeader(f,d)}this._ws=l,l.binaryType="arraybuffer",l.onopen=()=>{if(i(),!s){if(s=!0,this._state="OPEN",this._openedAt=Date.now(),this._mx.connectedAt=this._openedAt,e&&this._mx.reconnectCount++,this._serverEndpoint=l.url??this._url,this._reconnAttempt=0,this._rooms.length>0&&this._keepRooms)for(let u of this._rooms)try{l.send(JSON.stringify({type:"room:join",room:u.room,namespace:u.namespace??null}))}catch{}this._startPing(),this._flushBuf(),this._cbOpen?.(this._mx.reconnectCount),t();for(let u of this._openWaiters.splice(0))u.resolve()}},l.onmessage=async u=>{if(this._aborted)return;let f,d,p;if(typeof u.data=="string"){f=u.data,p=new TextEncoder().encode(f).byteLength;try{d=JSON.parse(f)}catch{}}else if(u.data instanceof ArrayBuffer)f=new Uint8Array(u.data),p=f.byteLength;else if(typeof Blob<"u"&&u.data instanceof Blob){let m=await u.data.arrayBuffer();f=new Uint8Array(m),p=f.byteLength}else f=new Uint8Array(u.data),p=f.byteLength;this._mx.messagesReceived++,this._mx.bytesReceived+=p;let g={data:f,json:d,timestamp:Date.now()};if(this._pongMatcher&&typeof f=="string"&&(typeof this._pongMatcher=="string"?f===this._pongMatcher:this._pongMatcher.test(f))){this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null);return}for(let[m,y]of this._correlations)if(y.matcher(g)){this._correlations.delete(m),y.timer&&clearTimeout(y.timer);try{y.resolve(y.extract(g))}catch(b){y.reject(b)}return}for(let m of this._msgListeners)try{m(g)}catch{}if(this._cbMessage?.(g),this._iterWaiter){let m=this._iterWaiter;this._iterWaiter=null,m({done:!1,value:g})}else this._iterQueue.length>=this._maxBufferSize&&this._iterQueue.shift(),this._iterQueue.push(g)},l.onerror=u=>{this._cbError?.(new B(u.message??"WebSocket error",u.error))},l.onclose=u=>{i(),this._stopPing(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now();for(let d of this._closeListeners)try{d({code:u.code,reason:u.reason})}catch{}if(s||(s=!0,n(new B(`Socket closed before open (code ${u.code}: ${u.reason})`))),this._aborted||u.code===1e3||u.code===1001){this._state="CLOSED",this._cbClose?.(u.code,u.reason,!1),this._terminateIter();for(let d of this._openWaiters.splice(0))d.reject(new B(`Socket closed (code ${u.code})`));this._rejectCorrelations(`Socket closed (code ${u.code})`);return}let f=this._canRecon();if(this._cbClose?.(u.code,u.reason,f),f)this._scheduleRecon();else{this._cbGiveUp?.(this._reconnAttempt),this._state="CLOSED",this._terminateIter();let d=new Nt(this._reconnAttempt);for(let p of this._openWaiters.splice(0))p.reject(d);this._rejectCorrelations("Max reconnects exceeded")}}})}_canRecon(){return this._maxReconnects===0||this._reconnAttempt<this._maxReconnects}_scheduleRecon(){this._state="RECONNECTING",this._reconnAttempt++;let e=this._reconnectBaseMs*Math.pow(2,this._reconnAttempt-1),t=Math.min(e,this._reconnectMaxMs),n=Math.floor(t*(1+this._reconnectJitter*Math.random()));this._cbReconnect?.(this._reconnAttempt,n),this._reconnTimer=setTimeout(()=>{this._aborted||this._doConnect(!0).catch(()=>{})},n),typeof this._reconnTimer=="object"&&this._reconnTimer!==null&&"unref"in this._reconnTimer&&this._reconnTimer.unref()}_tx(e){let t=this._ws,n=typeof e=="string"?new TextEncoder().encode(e).byteLength:e.byteLength;if(this._maxSendRate>0){let s=Date.now();this._lastToken===0&&(this._lastToken=s,this._tokens=this._maxSendRate);let o=s-this._lastToken;if(this._tokens=Math.min(this._maxSendRate,this._tokens+o*this._maxSendRate/1e3),this._lastToken=s,this._tokens<1)return this._bufferMessage(e,n),!1;this._tokens--}if(this._bufferedBytes>=this._highWaterMark)return this._bufferMessage(e,n),!1;if(t&&t.readyState===1)try{return t.send(e),this._mx.bytesSent+=n,!0}catch(s){if(this._cbError?.(new B(`WebSocket send failed: ${s instanceof Error?s.message:String(s)}`,s)),t.readyState===1)try{t.close(4001,"Send error")}catch{}return this._ws=null,!this._aborted&&this._canRecon()&&this._scheduleRecon(),!1}return this._bufferMessage(e,n),!1}_bufferMessage(e,t){if(this._bufferMessages&&!this._aborted){let n=this._buffer.length>=this._maxBufferSize?this._buffer.shift():void 0;n!==void 0&&(this._bufferedBytes-=typeof n=="string"?new TextEncoder().encode(n).byteLength:n.byteLength),this._buffer.push(e),this._bufferedBytes+=t,this._updateBackpressure()}}_flushBuf(){let e=this._buffer.splice(0);for(let t of e)try{this._ws?.send(t),this._mx.messagesSent++,this._mx.bytesSent+=typeof t=="string"?new TextEncoder().encode(t).byteLength:t.byteLength}catch{}this._bufferedBytes=0,this._updateBackpressure()}_updateBackpressure(){let e=this._bufferedBytes>=this._highWaterMark;if(e!==this._wasBackpressured&&(this._wasBackpressured=e,this._cbBackpressure?.(e,this.backpressure)),!e&&this._bufferedBytes<this._lowWaterMark&&this._drainWaiters.length>0)for(let t of this._drainWaiters.splice(0))t()}_startPing(){this._pingIntervalMs<=0||(this._pingTimer=setInterval(()=>{let e=this._ws;if(!(!e||e.readyState!==1)){try{e.send(this._pingPayload),this._mx.messagesSent++,this._mx.bytesSent+=new TextEncoder().encode(this._pingPayload).byteLength}catch{}this._pongMatcher&&this._pongTimeoutMs>0&&(this._pongTimer&&clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{this._pongTimer=null;let t=this._ws;t&&(t.onopen=t.onmessage=t.onerror=t.onclose=null,t.close(4e3,"Pong timeout"),this._ws=null),!this._aborted&&this._canRecon()?(this._cbClose?.(4e3,"Pong timeout",!0),this._scheduleRecon()):this._state="CLOSED"},this._pongTimeoutMs),typeof this._pongTimer=="object"&&this._pongTimer!==null&&"unref"in this._pongTimer&&this._pongTimer.unref())}},this._pingIntervalMs),typeof this._pingTimer=="object"&&this._pingTimer!==null&&"unref"in this._pingTimer&&this._pingTimer.unref())}_stopPing(){this._pingTimer&&(clearInterval(this._pingTimer),this._pingTimer=null),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null)}_stopAll(){this._stopPing(),this._reconnTimer&&(clearTimeout(this._reconnTimer),this._reconnTimer=null)}_terminateIter(){this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null)}_rejectCorrelations(e){for(let t of this._correlations.values())t.timer&&clearTimeout(t.timer),t.reject(new B(e));this._correlations.clear()}};async function si(r){let e=new Ie(r);return await e.connect(),e}Le();fe();$t();var il=0;function vn(){return`interceptor_${++il}`}function Pn(r){return[...r].sort((e,t)=>e.priority-t.priority)}var jt=class{constructor(){h(this,"requestInterceptors",[]);h(this,"responseInterceptors",[]);h(this,"errorInterceptors",[])}useRequest(e,t={}){let n=t.id??vn();return this.requestInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}useResponse(e,t={}){let n=t.id??vn();return this.responseInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}useError(e,t={}){let n=t.id??vn();return this.errorInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}use(e,t,n={}){let s=e?this.useRequest(e,n):null,o=t?this.useResponse(t,n):null;return{requestId:s,responseId:o}}eject(e){let t=this.requestInterceptors.length+this.responseInterceptors.length+this.errorInterceptors.length;return this.requestInterceptors=this.requestInterceptors.filter(s=>s.id!==e),this.responseInterceptors=this.responseInterceptors.filter(s=>s.id!==e),this.errorInterceptors=this.errorInterceptors.filter(s=>s.id!==e),this.requestInterceptors.length+this.responseInterceptors.length+this.errorInterceptors.length<t}ejectAll(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}has(e){return this.requestInterceptors.some(t=>t.id===e)||this.responseInterceptors.some(t=>t.id===e)||this.errorInterceptors.some(t=>t.id===e)}get requestCount(){return this.requestInterceptors.length}get responseCount(){return this.responseInterceptors.length}get errorCount(){return this.errorInterceptors.length}async execute(e,t){let n={request:e,response:null,error:null,startedAt:G(),attempt:0,aborted:!1,store:new Map};return await this._run(n,t)}async _run(e,t){e.attempt++;let n=new Set;for(let s of Pn(this.requestInterceptors)){if(e.aborted)break;if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){e.error=i;for(let a of n)this.eject(a);return this._runErrorPhase(e,t)}if(s.once&&n.add(s.id),o!=null){if(In(o)){e.response=o;for(let i of n)this.eject(i);return this._runResponsePhase(e,t)}Pi(o)&&(e.request=o)}}for(let s of n)this.eject(s);try{e.response=await t(e.request)}catch(s){return e.error=s,this._runErrorPhase(e,t)}return this._runResponsePhase(e,t)}async _runResponsePhase(e,t){let n=new Set;for(let s of Pn(this.responseInterceptors)){if(e.aborted)break;if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){e.error=i;for(let a of n)this.eject(a);return this._runErrorPhase(e,t)}if(s.once&&n.add(s.id),o!=null){if(Pi(o)){e.request=o,e.response=null,e.error=null;for(let i of n)this.eject(i);return this._run(e,t)}In(o)&&(e.response=o)}}for(let s of n)this.eject(s);if(!e.response)throw new Error("Pipeline produced no response");return e.response}async _runErrorPhase(e,t){let n=new Set;for(let s of Pn(this.errorInterceptors)){if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){if(i.__retrySignal){for(let a of n)this.eject(a);return e.error=null,e.response=null,this._run(e,t)}e.error=i;continue}if(s.once&&n.add(s.id),o!=null&&In(o)){e.response=o,e.error=null;for(let i of n)this.eject(i);return this._runResponsePhase(e,t)}}for(let s of n)this.eject(s);throw e.error}};function In(r){return r!==null&&typeof r=="object"&&typeof r.status=="number"&&"headers"in r&&"request"in r}function Pi(r){return r!==null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.method=="string"&&!("status"in r)}var al={maxRetries:3,baseDelayMs:300,maxDelayMs:3e4,jitter:.3,retryStatuses:[408,429,500,502,503,504],retryOnError:!0,retryMethods:["GET","HEAD","PUT","DELETE","OPTIONS","TRACE","POST"],shouldRetry:null,onRetry:null};function On(r={}){let e={...al,...r};function t(a,c){if(c!==null)return Math.min(c,e.maxDelayMs);let l=e.baseDelayMs*Math.pow(2,a-1),u=Math.min(l,e.maxDelayMs),f=u*e.jitter*Math.random();return Math.floor(u+f)}function n(a){return a.attempt>e.maxRetries||!e.retryMethods.includes(a.request.method.toUpperCase())?!1:e.shouldRetry?e.shouldRetry(a):a.error?e.retryOnError:a.response?e.retryStatuses.includes(a.response.status):!1}function s(a){let c=a.response?.headers["retry-after"]??a.response?.headers["Retry-After"];if(!c)return null;if(/^\d+$/.test(c.trim()))return parseInt(c,10)*1e3;let l=Date.parse(c);return isNaN(l)?null:Math.max(0,l-Date.now())}return{responseInterceptor:async a=>{if(!n(a))return;let c=t(a.attempt,s(a));return e.onRetry?.(a,c),await Mi(c),{...a.request}},errorInterceptor:async a=>{if(!n(a))return;let c=t(a.attempt,null);throw e.onRetry?.(a,c),await Mi(c),a.error=null,new Ln(a.request)}}}var Ln=class{constructor(e){h(this,"request");h(this,"__retrySignal",!0);this.request=e}},cl={getToken:()=>null,refreshToken:null,headerName:"authorization",scheme:"Bearer ",refreshOnStatuses:[401],maxQueue:50,refreshRetryDelay:3e4};function Dn(r){let e={...cl,...r},t=null,n=[],s=null,o=e.refreshRetryDelay??3e4;async function i(){if(s!==null){let l=Date.now()-s;if(l<o)throw new Error(`Auth refresh circuit breaker: last failure ${Math.round(l/1e3)}s ago, retry after ${Math.round((o-l)/1e3)}s`)}if(t){if(n.length>=e.maxQueue)throw new Error("Auth refresh queue full");return await new Promise((l,u)=>n.push({resolve:l,reject:u}))}return e.refreshToken?(t=e.refreshToken().then(l=>{for(let u of n)u.resolve(l);return n.length=0,t=null,s=null,l},l=>{for(let u of n)u.reject(l);throw n.length=0,t=null,s=Date.now(),l}),t):null}return{requestInterceptor:async l=>{let u=await e.getToken();u&&(l.request.headers[e.headerName]=`${e.scheme}${u}`)},responseInterceptor:async l=>{if(!l.response||!e.refreshOnStatuses.includes(l.response.status)||!e.refreshToken||l.request.meta.__authRetried)return;let u=await i();return u?{...l.request,headers:{...l.request.headers,[e.headerName]:`${e.scheme}${u}`},meta:{...l.request.meta,__authRetried:!0}}:void 0}}}var ll={timeoutMs:3e4,methodTimeouts:{},message:"Request timed out"};function Nn(r={}){let e={...ll,...r};return{id:"timeout",requestInterceptor:o=>{let i=e.methodTimeouts[o.request.method.toUpperCase()]??e.timeoutMs;if(i<=0)return;let a=new AbortController,c=setTimeout(()=>{o.aborted=!0,a.abort(new Mn(e.message,i))},i),l=o.request.signal;l&&l.addEventListener("abort",()=>{clearTimeout(c),a.abort(l.reason)},{once:!0}),o.request={...o.request,signal:a.signal},o.store.set(Ht,c)},responseInterceptor:o=>{let i=o.store.get(Ht);i&&(clearTimeout(i),o.store.delete(Ht))},errorInterceptor:o=>{let i=o.store.get(Ht);i&&(clearTimeout(i),o.store.delete(Ht))}}}var Ht=Symbol("timeoutTimer"),Mn=class extends Error{constructor(t,n){super(t);h(this,"timeoutMs");h(this,"code","ETIMEDOUT");this.timeoutMs=n,this.name="TimeoutError"}},ul={logger:r=>console.log(JSON.stringify(r)),redactHeaders:["authorization","cookie","set-cookie","proxy-authorization"],logRequests:!0,logResponses:!0,logErrors:!0},Ii=Symbol("requestId"),hl=0;function Un(r={}){let e={...ul,...r},t=new Set(e.redactHeaders.map(c=>c.toLowerCase()));function n(c){let l={};for(let[u,f]of Object.entries(c))l[u]=t.has(u.toLowerCase())?"**REDACTED**":f;return l}function s(c,l){let u=l.store.get(Ii)??"unknown";return{type:c,timestamp:Date.now(),requestId:u,method:l.request.method,url:l.request.url,status:l.response?.status??null,durationMs:c!=="request"?G()-l.startedAt:null,attempt:l.attempt,error:l.error instanceof Error?l.error.message:null}}return{requestInterceptor:c=>{let l=`req_${++hl}`;c.store.set(Ii,l),e.logRequests&&e.logger(s("request",c))},responseInterceptor:c=>{e.logResponses&&e.logger(s("response",c))},errorInterceptor:c=>{e.logErrors&&e.logger(s("error",c))}}}var fl={maxEntries:500,defaultTtlMs:6e4,cacheMethods:["GET","HEAD"],cacheKey:null,honorCacheControl:!0};function $n(r={}){let e={...fl,...r},t=new Map,n=[];function s(l){return e.cacheKey?e.cacheKey(l):`${l.method}:${l.url}`}function o(l){let u=n.indexOf(l);for(u!==-1&&n.splice(u,1),n.unshift(l);n.length>e.maxEntries;){let f=n.pop();t.delete(f)}}function i(l){let u=l.headers["cache-control"]??l.headers["Cache-Control"]??"",f=u.match(/max-age=(\d+)/)?.[1],d=u.match(/stale-while-revalidate=(\d+)/)?.[1],p=/no-store/i.test(u),g=/no-cache/i.test(u);if(e.honorCacheControl&&(p||g))return{ttlMs:0,swrMs:0};let m=f?parseInt(f,10)*1e3:e.defaultTtlMs,y=d?parseInt(d,10)*1e3:0;return{ttlMs:m,swrMs:y}}return{requestInterceptor:l=>{if(!e.cacheMethods.includes(l.request.method.toUpperCase()))return;let u=s(l.request),f=t.get(u);if(!f)return;let d=G();if(f.expiresAt>d)return o(u),l.store.set(dl,!0),{...f.response,request:l.request};f.staleUntil>d&&(o(u),l.store.set(Li,f),f.etag?l.request={...l.request,headers:{...l.request.headers,"if-none-match":f.etag}}:f.lastModified&&(l.request={...l.request,headers:{...l.request.headers,"if-modified-since":f.lastModified}}))},responseInterceptor:l=>{if(!l.response||!e.cacheMethods.includes(l.request.method.toUpperCase()))return;let u=s(l.request);if(l.response.status===304){let m=l.store.get(Li);if(m){let{ttlMs:y,swrMs:b}=i(m.response),x=G(),S={...m,createdAt:x,expiresAt:x+y,staleUntil:x+y+b};t.set(u,S),o(u),l.response={...m.response,request:l.request};return}}let{ttlMs:f,swrMs:d}=i(l.response);if(f<=0)return;let p=G(),g={response:l.response,createdAt:p,expiresAt:p+f,staleUntil:p+f+d,etag:l.response.headers.etag??l.response.headers.ETag??null,lastModified:l.response.headers["last-modified"]??null};t.set(u,g),o(u)},store:t}}var dl=Symbol("cacheHit"),Li=Symbol("cacheStale");function Hn(){let r=new Map;function e(o){return`${o.method.toUpperCase()}:${o.url}`}return{requestInterceptor:o=>{if(o.request.method.toUpperCase()!=="GET"&&o.request.method.toUpperCase()!=="HEAD")return;let i=e(o.request),a=r.get(i);if(!a){r.set(i,{promise:void 0,waiters:[]});return}return o.store.set(pl,i),new Promise((c,l)=>{a.waiters.push({resolve:u=>c(u),reject:u=>l(u)})})},responseInterceptor:o=>{if(!o.response)return;let i=e(o.request),a=r.get(i);if(a){r.delete(i);for(let c of a.waiters)c.resolve(o.response)}},errorInterceptor:o=>{let i=e(o.request),a=r.get(i);if(a){r.delete(i);for(let c of a.waiters)c.reject(o.error)}}}}var pl=Symbol("dedupeQueued"),ml={limit:60,windowMs:6e4,queue:!0,maxQueue:100};function qt(r={}){let e={...ml,...r},t=e.limit,n=G(),s=[],o=null;function i(){let l=G(),u=(l-n)/e.windowMs;t=Math.min(e.limit,t+u*e.limit),n=l}function a(){o===null&&(o=setInterval(()=>{for(i();t>=1&&s.length>0;)t--,s.shift()();s.length===0&&o!==null&&(clearInterval(o),o=null)},Math.ceil(e.windowMs/e.limit)),typeof o=="object"&&o!==null&&"unref"in o&&o.unref())}async function c(){if(i(),t>=1){t--;return}if(!e.queue)throw new ct("Rate limit exceeded");if(s.length>=e.maxQueue)throw new ct("Rate limit queue full");await new Promise(l=>{s.push(()=>l()),a()})}return async()=>{await c()}}var ct=class extends Error{constructor(t){super(t);h(this,"code","ERATELIMIT");this.name="RateLimitError"}};function jn(){let r=[],e=Symbol("harStart");function t(i){return Object.entries(i).map(([a,c])=>({name:a,value:c}))}function n(i){try{let a=new URL(i);return Array.from(a.searchParams.entries()).map(([c,l])=>({name:c,value:l}))}catch{return[]}}return{requestInterceptor:i=>{i.store.set(e,G())},responseInterceptor:i=>{if(!i.response)return;let a=i.store.get(e)??i.startedAt,c=G()-a,l=i.response.headers["content-type"]??i.response.headers["Content-Type"]??"application/octet-stream",u=i.response.body,f=u instanceof Uint8Array?u.byteLength:typeof u=="string"?u.length:0;r.push({startedDateTime:new Date(Date.now()-c).toISOString(),time:c,request:{method:i.request.method.toUpperCase(),url:i.request.url,httpVersion:"HTTP/1.1",headers:t(i.request.headers),queryString:n(i.request.url),bodySize:zn(i.request.body)},response:{status:i.response.status,statusText:i.response.statusText,httpVersion:"HTTP/1.1",headers:t(i.response.headers),content:{size:f,mimeType:l,...typeof u=="string"?{text:u}:{}},bodySize:f,redirectURL:i.response.headers.location??""},timings:{send:0,wait:Math.floor(c*.9),receive:Math.floor(c*.1)}})},getHAR:()=>({version:"1.2",creator:{name:"kinetex",version:"0.0.3"},entries:[...r]}),clearHAR:()=>{r.length=0}}}function qn(){let r=Symbol("metricsStart"),e=0,t=0,n=0,s={"2xx":0,"3xx":0,"4xx":0,"5xx":0},o=1e4,i=[],a=p=>{p.store.set(r,G()),e++,p.attempt>1&&n++},c=p=>{if(!p.response)return;let g=p.store.get(r);if(g!==void 0){let y=G()-g;i.length>=o&&i.shift(),i.push(y)}let m=`${Math.floor(p.response.status/100)}xx`;if(m in s){let y=s;y[m]=(y[m]??0)+1}},l=()=>{t++};function u(p,g){if(p.length===0)return 0;let m=Math.ceil(g/100*p.length)-1,y=Math.min(Math.max(0,m),p.length-1);return p[y]}return{requestInterceptor:a,responseInterceptor:c,errorInterceptor:l,snapshot:()=>{let p=[...i].sort((m,y)=>m-y),g=p.length?p.reduce((m,y)=>m+y,0)/p.length:0;return{totalRequests:e,totalErrors:t,totalRetries:n,statusBuckets:{...s},avgDurationMs:Math.round(g),p50DurationMs:u(p,50),p95DurationMs:u(p,95),p99DurationMs:u(p,99)}},reset:()=>{e=0,t=0,n=0;for(let p of Object.keys(s))s[p]=0;i.length=0}}}function G(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Mi(r){return new Promise(e=>setTimeout(e,r))}function zn(r){return r?typeof r=="string"?r.length:r instanceof Uint8Array||r instanceof ArrayBuffer?r.byteLength:-1:0}function Oi(r={}){let e=new jt,t=Nn(r.timeout);e.useRequest(t.requestInterceptor,{priority:-100,id:"timeout-req"}),e.useResponse(t.responseInterceptor,{priority:-100,id:"timeout-res"}),e.useError(t.errorInterceptor,{priority:-100,id:"timeout-err"}),r.rateLimit&&e.useRequest(qt(r.rateLimit),{priority:-90,id:"ratelimit"});let n=Hn();e.useRequest(n.requestInterceptor,{priority:-80,id:"dedupe-req"}),e.useResponse(n.responseInterceptor,{priority:-80,id:"dedupe-res"}),e.useError(n.errorInterceptor,{priority:-80,id:"dedupe-err"});let s=$n(r.cache);e.useRequest(s.requestInterceptor,{priority:-70,id:"cache-req"}),e.useResponse(s.responseInterceptor,{priority:-70,id:"cache-res"});let o=null;r.auth&&(o=Dn(r.auth),e.useRequest(o.requestInterceptor,{priority:-50,id:"auth-req"}),e.useResponse(o.responseInterceptor,{priority:-50,id:"auth-res"}));let i=On(r.retry);e.useResponse(i.responseInterceptor,{priority:50,id:"retry-res"}),e.useError(i.errorInterceptor,{priority:50,id:"retry-err"});let a=Un(r.logging);e.useRequest(a.requestInterceptor,{priority:90,id:"log-req"}),e.useResponse(a.responseInterceptor,{priority:90,id:"log-res"}),e.useError(a.errorInterceptor,{priority:90,id:"log-err"});let c=jn();e.useRequest(c.requestInterceptor,{priority:95,id:"har-req"}),e.useResponse(c.responseInterceptor,{priority:95,id:"har-res"});let l=qn();return e.useRequest(l.requestInterceptor,{priority:100,id:"metrics-req"}),e.useResponse(l.responseInterceptor,{priority:100,id:"metrics-res"}),e.useError(l.errorInterceptor,{priority:100,id:"metrics-err"}),{manager:e,retry:i,auth:o,timeout:{id:t.id},logging:a,cache:s,dedupe:n,har:c,metrics:l}}Le();function Di(r){return()=>Promise.resolve(r)}function Ni(){return()=>{let r=Bn("AWS_ACCESS_KEY_ID"),e=Bn("AWS_SECRET_ACCESS_KEY"),t=Bn("AWS_SESSION_TOKEN");return!r||!e?Promise.reject(new Q("AWS credentials not found in environment. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.")):Promise.resolve({accessKeyId:r,secretAccessKey:e,...t!==void 0?{sessionToken:t}:{}})}}function Ui(...r){return async()=>{let e=[];for(let t of r)try{return await t()}catch(n){e.push(n instanceof Error?n:new Error(String(n)))}throw new Q(`All credential providers failed:
|
|
74
|
+
`;po=te.prototype.clearAPQCache.bind(te.prototype),mo=te.prototype.getAPQMetrics.bind(te.prototype)});var Fa={};fe(Fa,{collectAll:()=>go,collectPages:()=>yo,createCursorPaginator:()=>_o,createKeysetPaginator:()=>Ro,createLinkHeaderPaginator:()=>Eo,createOffsetPaginator:()=>bo,createPagePaginator:()=>xo,createRelayPaginator:()=>So,createTokenPaginator:()=>To,deserializePaginationState:()=>Ao,mergePaginators:()=>vo,paginate:()=>q,paginateItems:()=>an,parseLinkHeaderNext:()=>cn,prefetchPaginate:()=>Du,serializePaginationState:()=>ko,takeItems:()=>wo,toPaginationIterator:()=>Co});function Mu(r,e){return{strategy:e,page:r.startPage??1,offset:r.startOffset??0,cursor:r.startCursor??null,prevCursor:null,token:r.startToken??null,done:!1,totalFetched:0}}function Ou(r,e,t,n,s,o){let i=n.getTotal?.(e)??null,a=n.perPage??null,c=i!==null&&a!==null?Math.ceil(i/a):null,l=t.page>1||t.offset>0||t.prevCursor!==null;return{items:r,total:i,page:t.page,perPage:a,totalPages:c,hasNext:o??n.hasNext(e,t),hasPrev:l,nextCursor:s?.cursor??null,prevCursor:t.prevCursor??null,raw:e}}async function*q(r,e="page"){let t=Mu(r,e),n=0;for(;!t.done&&!(r.signal?.aborted||r.maxPages&&n>=r.maxPages);){n>0&&r.delayMs&&r.delayMs>0&&await Nu(r.delayMs,r.signal);let s;try{s=await r.fetch(t)}catch(u){if(r.signal?.aborted)break;throw u}let o=r.getItems(s,t);r.transform&&(o=o.map(r.transform)),r.filter&&(o=o.filter(r.filter));let i=r.getNext?r.getNext(s,t):null,a=r.hasNext(s,t),c=Ou(o,s,t,r,i,a),l=t.cursor;if(t={...t,page:i?.page??t.page+1,offset:i?.offset??t.offset+o.length,cursor:i?.cursor??t.cursor,token:i?.token??t.token,done:!a,totalFetched:t.totalFetched+o.length,prevCursor:l},n++,r.onPage?.(c,t),yield c,!a)break}}async function*an(r,e="page"){for await(let t of q(r,e))for(let n of t.items)yield n}async function go(r,e="page"){let t=[];for await(let n of q(r,e))t.push(...n.items);return t}async function yo(r,e="page"){let t=[];for await(let n of q(r,e))t.push(n);return t}async function wo(r,e,t="page"){let n=[];for await(let s of an(e,t))if(n.push(s),n.length>=r)break;return n}function bo(r){let e=r.paramNames??{},t=e.offset??"offset",n=e.limit??"limit",s=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},perPage:r.limit,fetch:async o=>{let i=new URL(r.url);return i.searchParams.set(t,String(o.offset)),i.searchParams.set(n,String(r.limit)),(await s(i.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:(o,i)=>r.getItems(o),getTotal:r.getTotal??(()=>null),hasNext:(o,i)=>{let a=r.getTotal?.(o)??null;return r.hasMore?r.hasMore(o,i.totalFetched+r.limit,a):a!==null?i.offset+r.limit<a:r.getItems(o).length===r.limit},getNext:(o,i)=>({offset:i.offset+r.limit})},"offset")}function xo(r){let e=r.paramNames??{},t=e.page??"page",n=e.perPage??"per_page",s=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.perPage!==void 0?{perPage:r.perPage}:{},startPage:r.startPage??1,fetch:async o=>{let i=new URL(r.url);return i.searchParams.set(t,String(o.page)),i.searchParams.set(n,String(r.perPage)),(await s(i.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:o=>r.getItems(o),getTotal:r.getTotal??(()=>null),hasNext:(o,i)=>{let a=r.getTotalPages?.(o)??null;if(a!==null)return i.page<a;let c=r.getTotal?.(o)??null;return c!==null?i.page*r.perPage<c:r.getItems(o).length===r.perPage},getNext:(o,i)=>({page:i.page+1})},"page")}function _o(r){let e=r.paramName??"cursor",t=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},startCursor:r.startCursor??null,fetch:async n=>{let s=new URL(r.url);return n.cursor&&s.searchParams.set(e,n.cursor),(await t(s.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:n=>r.getItems(n),hasNext:n=>r.getNextCursor(n)!==null,getNext:n=>{let s=r.getNextCursor(n);return s?{cursor:s}:null}},"cursor")}function So(r){let e=r.first??20;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.transform!==void 0?{transform:r.transform}:{},...r.filter!==void 0?{filter:r.filter}:{},...r.onPage!==void 0?{onPage:r.onPage}:{},startCursor:r.startCursor??null,perPage:e,fetch:t=>r.fetch({first:e,after:t.cursor}),getItems:t=>t.edges.map(n=>n.node),getTotal:t=>t.totalCount??null,hasNext:t=>t.pageInfo.hasNextPage,getNext:t=>{let n=t.pageInfo.endCursor??null;return n?{cursor:n}:null}},"relay")}function Eo(r){let e=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},fetch:async t=>{let n=t.cursor??r.url,s=await e(n,{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}}),o=cn(s.headers.get("link")??"");return{data:await s.json(),headers:s.headers,nextUrl:o}},getItems:t=>r.getItems(t.data),getTotal:t=>r.getTotal?.(t.data,t.headers)??null,hasNext:t=>t.nextUrl!==null,getNext:t=>t.nextUrl?{cursor:t.nextUrl}:null},"link-header")}function cn(r){if(!r)return null;for(let e of r.split(",")){let t=e.match(/<([^>]+)>.*?rel=["']([^"']+)["']/);if(t&&t[2]&&t[2].split(/\s+/).includes("next"))return t[1]}return null}function To(r){let e=r.tokenParam??"pageToken",t=r.pageSizeParam??"pageSize",n=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.pageSize!==void 0?{perPage:r.pageSize}:{},fetch:async s=>{let o=new URL(r.url);return s.token&&o.searchParams.set(e,s.token),r.pageSize&&o.searchParams.set(t,String(r.pageSize)),(await n(o.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:s=>r.getItems(s),getTotal:r.getTotal??(()=>null),hasNext:s=>r.getNextToken(s)!==null,getNext:s=>{let o=r.getNextToken(s);return o?{token:o}:null}},"token")}function Ro(r){let e=r.pageSizeParam??"limit",t=r.fetch??globalThis.fetch;return q({...r.signal!==void 0?{signal:r.signal}:{},...r.maxPages!==void 0?{maxPages:r.maxPages}:{},...r.delayMs!==void 0?{delayMs:r.delayMs}:{},...r.pageSize!==void 0?{perPage:r.pageSize}:{},startCursor:r.startKey??null,fetch:async n=>{let s=new URL(r.url);return n.cursor&&s.searchParams.set(r.keyParam,n.cursor),r.pageSize&&s.searchParams.set(e,String(r.pageSize)),(await t(s.toString(),{...r.headers!==void 0?{headers:r.headers}:{},...r.signal!==void 0?{signal:r.signal}:{}})).json()},getItems:n=>r.getItems(n),hasNext:(n,s)=>{let o=r.getItems(n);return r.hasMore?r.hasMore(o,n):r.pageSize?o.length>=r.pageSize:o.length>0},getNext:(n,s)=>{let o=r.getItems(n),i=r.getLastKey(o);return i?{cursor:i}:null}},"keyset")}async function*Du(r,e="page",t=2){let n=[],s=q(r,e),o=!1;async function i(){if(o)return;let{value:a,done:c}=await s.next();o=c??!1,n.push(Promise.resolve(a??null))}for(let a=0;a<t+1;a++)await i();for(;n.length>0;){let a=await n.shift();if(a==null)break;await i(),yield a}}function ko(r){return btoa(JSON.stringify(r))}function Ao(r){try{return M(JSON.parse(atob(r)))}catch{throw new Error("Invalid pagination state string")}}function Nu(r,e){return new Promise(t=>{if(e?.aborted){t();return}let n=setTimeout(t,r);e&&e.addEventListener("abort",()=>{clearTimeout(n),t()},{once:!0})})}function Co(r){let e=r[Symbol.asyncIterator]();return{next:()=>e.next(),return:t=>e.return?.(t)??Promise.resolve({value:t,done:!0}),throw:t=>e.throw?.(t)??Promise.reject(t),[Symbol.asyncIterator](){return this}}}async function*vo(...r){let e=r.map(n=>n[Symbol.asyncIterator]()),t=new Set(e.map((n,s)=>s));for(;t.size>0;)for(let n of[...t]){let{value:s,done:o}=await e[n].next();if(o){t.delete(n);continue}yield s}}var ln=F(()=>{"use strict";z()});var mh={};fe(mh,{AbortError:()=>xr,AuthError:()=>_r,BatchQueue:()=>hn,BatchingTransport:()=>kt,CircuitBreaker:()=>Ze,CircuitBreakerRegistry:()=>Le,CircuitOpenError:()=>Ye,CloudflareKVAdapter:()=>at,ConsoleTransport:()=>Ke,ContentTypeError:()=>Se,CookieJar:()=>Te,DedupMap:()=>Ie,FetchTransport:()=>qe,FluentRequest:()=>ir,GraphQLClient:()=>te,GraphQLClientError:()=>N,HAS_NATIVE_FETCH:()=>qs,HTTPCache:()=>ie,HTTPError:()=>lr,HTTPLogger:()=>ke,HTTPResponseError:()=>je,HTTPStatusError:()=>ot,HeaderName:()=>w,HookEmitter:()=>ar,HookRegistry:()=>fn,HttpHeaders:()=>ce,IS_NODE:()=>Be,InterceptorManager:()=>zt,JSONTransport:()=>Rt,Kinetex:()=>Lt,KinetexError:()=>S,LogLevel:()=>Tt,MemoryStorageAdapter:()=>be,MultiPartProgressAggregator:()=>fr,MultiTransport:()=>Ct,NetworkError:()=>Z,NodeHTTP2Transport:()=>mt,ProgressTracker:()=>W,ProxyError:()=>Sr,RUNTIME:()=>me,RateLimitError:()=>lt,Redactor:()=>vt,RedirectError:()=>Er,RedirectTracker:()=>dn,RemoteTransport:()=>At,ResponseDecodeError:()=>ze,ResponseSizeLimitError:()=>_e,ResponseValidationError:()=>ur,RichHeaders:()=>xe,SSEClient:()=>Ve,SSEError:()=>he,SSEMaxReconnectsError:()=>Je,SSEParser:()=>Ae,SSERouter:()=>rr,SSEServerResponse:()=>Pt,SSETransformStream:()=>tr,SigV4Signer:()=>ae,SizeLimitError:()=>st,Socks5Error:()=>I,TimeoutError:()=>Q,TooManyRedirectsError:()=>cr,TwoTierStorageAdapter:()=>ct,URLBuilder:()=>ve,ValidationError:()=>J,WSClient:()=>De,WSConnectTimeoutError:()=>nt,WSError:()=>K,WSMaxReconnectsError:()=>Ht,WSRateLimitError:()=>br,WebStorageAdapter:()=>Ue,applyDecompression:()=>Vt,assertOk:()=>Ms,assertOkJSON:()=>Os,authLink:()=>ao,buildDataURL:()=>Dc,cachingCredentials:()=>Gn,canonicalizeDomainFull:()=>ue,chainCredentials:()=>Bi,clearAPQCache:()=>po,collectAll:()=>go,collectPages:()=>yo,collectStream:()=>ri,compilePattern:()=>Ec,composeAround:()=>rc,composeBeforeRequest:()=>ec,composeBeforeResponse:()=>tc,computeBodySize:()=>Kn,computeDigestResponse:()=>os,concatUint8Arrays:()=>mr,connectWS:()=>Pi,corsHeaders:()=>pa,createAPIGatewaySigner:()=>Qi,createAbortHook:()=>ic,createAuthInterceptor:()=>Hn,createBodyNormalizationHook:()=>oc,createCacheInterceptor:()=>qn,createCircuitBreaker:()=>ai,createCircuitBreakerRegistry:()=>ci,createCookieJar:()=>Xr,createCursorPaginator:()=>_o,createDedupMap:()=>ii,createDedupeInterceptor:()=>Bn,createDevelopmentLogger:()=>Ys,createDigestAuthorization:()=>Cr,createDynamoDBSigner:()=>Xi,createGraphQLClient:()=>ho,createHARInterceptor:()=>Fn,createHeaders:()=>ma,createHookContext:()=>ac,createImmutableHeaders:()=>wa,createInterceptorSuite:()=>ji,createJSONSSEStream:()=>eo,createKVCache:()=>vn,createKeysetPaginator:()=>Ro,createLimitedReader:()=>Hs,createLinkHeaderPaginator:()=>Eo,createLocalStorageCache:()=>An,createLogger:()=>Gs,createLoggingHooks:()=>nc,createLoggingInterceptor:()=>zn,createMemoryCache:()=>kn,createMethodCircuitBreakerKey:()=>Ja,createMetricsInterceptor:()=>Wn,createOffsetPaginator:()=>bo,createPagePaginator:()=>xo,createProductionLogger:()=>Xs,createRateLimitInterceptor:()=>qt,createRelayPaginator:()=>So,createRequestHeaders:()=>ga,createResponseHeaders:()=>ya,createRetryInterceptor:()=>$n,createS3Signer:()=>Ji,createSSEResponse:()=>to,createSSEStream:()=>Zs,createSTSSigner:()=>Gi,createSessionStorageCache:()=>Cn,createSocks5Tunnel:()=>jo,createStructuredError:()=>_i,createTimeoutInterceptor:()=>jn,createTimingHook:()=>sc,createTokenPaginator:()=>To,createTransport:()=>Qt,createTwoTierCache:()=>Pn,decodeBody:()=>Kt,decodeIDNLabel:()=>er,decompressBodyStream:()=>Xt,decompressStream:()=>Hr,deepClone:()=>et,default:()=>ph,defaultPath:()=>xt,denoTcpConnector:()=>uc,deriveSigningKey:()=>ft,deserializePaginationState:()=>Ao,detectClockSkew:()=>rs,detectOperationType:()=>sn,detectRuntime:()=>Vr,diffResponses:()=>Ds,diffURLs:()=>Nc,domainMatch:()=>bt,encodePathComponent:()=>qo,encodeQueryValue:()=>Qe,envCredentials:()=>qi,errorLink:()=>co,expandTemplate:()=>Sc,extractOperationName:()=>ye,extractServerTiming:()=>Us,extractSetCookieHeaders:()=>Et,fillPathParams:()=>Ko,formatAmzDate:()=>Bt,formatBasic:()=>sa,formatBearer:()=>na,formatBytes:()=>Dt,formatCSP:()=>Nr,formatCacheControl:()=>ys,formatContentDisposition:()=>ms,formatContentType:()=>ds,formatDateStamp:()=>ut,formatDigestAuth:()=>is,formatETA:()=>wn,formatError:()=>Si,formatHSTS:()=>Dr,formatLinkHeader:()=>aa,formatProgress:()=>si,formatRate:()=>yn,formatServerTiming:()=>la,fromNodeHeaders:()=>ua,fromWebHeaders:()=>fa,getAPQMetrics:()=>mo,getAuthFingerprint:()=>$e,getClientIP:()=>Es,getEffectiveRuntime:()=>zs,getOrigin:()=>mn,getPublicSuffix:()=>yt,getRegistrableDomain:()=>Qr,getRuntime:()=>wr,gql:()=>fo,hasNativeFetch:()=>vi,imdsCredentials:()=>Fi,initChunkedSigning:()=>es,injectHeaders:()=>Ga,isAbortError:()=>yr,isAbortSignal:()=>mi,isAbsolute:()=>Vo,isArrayBuffer:()=>fi,isBinary:()=>Is,isBlob:()=>wi,isBlobURL:()=>Lc,isBrowserEnvironment:()=>Ci,isClockSkewError:()=>ns,isDataURL:()=>Ic,isFormData:()=>yi,isHTTP:()=>Pc,isHTTPS:()=>vc,isHeaders:()=>pi,isIPAddress:()=>ge,isJSON:()=>Wt,isLocalhost:()=>Mc,isNodeEnvironment:()=>Ai,isPlainObject:()=>gi,isPublicSuffix:()=>wt,isReadableStream:()=>di,isRelative:()=>Cc,isSafeURL:()=>Oe,isSameOrigin:()=>Tc,isSameSite:()=>Rc,isText:()=>Ur,isURLSearchParams:()=>bi,isUint8Array:()=>hi,isValidHeaderName:()=>Me,isValidHeaderValue:()=>we,joinPath:()=>Fo,jsonSSE:()=>tn,kinetex:()=>Fc,loadCookieJar:()=>Yr,loggingLink:()=>lo,mergePaginators:()=>vo,mergeQuery:()=>gc,mergeSignals:()=>gr,negotiateContentType:()=>ia,nodeTcpConnector:()=>hc,normalizeForwardedHeaders:()=>Or,normalizeHeaders:()=>rt,normalizePath:()=>Wo,normalizeResponse:()=>Ps,normalizeURL:()=>_c,omitQuery:()=>wc,paginate:()=>q,paginateItems:()=>an,parseAccept:()=>Mr,parseAcceptEncoding:()=>ws,parseAcceptLanguage:()=>bs,parseAltSvc:()=>Cs,parseAuthorization:()=>vr,parseBody:()=>gt,parseCSP:()=>ks,parseCacheControl:()=>gs,parseContentDisposition:()=>ps,parseContentLanguage:()=>oa,parseContentRange:()=>_s,parseContentType:()=>Ee,parseCookieDate:()=>Zt,parseDataURL:()=>Oc,parseDigestChallenge:()=>ss,parseForwarded:()=>Ss,parseHSTS:()=>Rs,parseLinkHeader:()=>Ir,parseLinkHeaderNext:()=>cn,parseMultipartResponse:()=>Fr,parseParams:()=>G,parseQuery:()=>Bo,parseRange:()=>xs,parseRetryAfter:()=>Ts,parseSSEText:()=>ro,parseServerTiming:()=>As,parseSetCookieHeader:()=>St,parseSocks5Url:()=>lc,parseUntrustedJSON:()=>ui,parseWWWAuthenticate:()=>Pr,parseWarning:()=>ca,pathMatch:()=>_t,pathSegments:()=>xc,percentDecode:()=>Ce,percentEncode:()=>pn,perfNow:()=>Ti,pickQuery:()=>yc,presignRequest:()=>Zn,readBlob:()=>qr,readBodyWithLimit:()=>$r,readBytes:()=>Jt,readFormData:()=>Ns,readJSON:()=>jr,readJSONStream:()=>Ls,readNDJSON:()=>Br,readRawBody:()=>Gt,readStream:()=>pt,readText:()=>zr,redactURL:()=>Bc,relativeURL:()=>Ac,resolveURL:()=>kc,retryLink:()=>uo,safeJSONParse:()=>de,safeParseURL:()=>Pe,sanitizeParsedJSON:()=>M,sanitizeURL:()=>Ei,securityHeaders:()=>da,sendWithTimeout:()=>Fe,serializePaginationState:()=>ko,setRuntime:()=>js,sigV4UriEncode:()=>Yn,signChunk:()=>Ki,signFinalChunk:()=>Vi,signRequest:()=>kr,signS3PostPolicy:()=>ts,sleep:()=>Ri,socks5Connector:()=>fc,splitSetCookieHeaders:()=>We,staticCredentials:()=>zi,streamWithProgress:()=>ti,stringifyQuery:()=>mc,stripHash:()=>Hc,stripQuery:()=>jc,takeItems:()=>wo,tap:()=>Qa,throttleProgress:()=>oi,throwOnHTTPError:()=>Ya,toNodeHeaders:()=>ha,toOTelSpan:()=>Qs,toPaginationIterator:()=>Co,toRequestId:()=>En,toUint8Array:()=>ki,tryParseJSON:()=>li,uint8ArrayToBase64:()=>$t,urlExtension:()=>zc,urlFilename:()=>qc,validateErrorCode:()=>Ii,validateResponse:()=>Za,withBaseURL:()=>Xa,withBlobUploadProgress:()=>Zo,withDownloadProgress:()=>ei,withTrailingSlash:()=>Uc,withUploadProgress:()=>Nt,withoutTrailingSlash:()=>$c,xhrFetch:()=>ni});var W=class{constructor(e,t={}){h(this,"loaded",0);h(this,"total");h(this,"startMs");h(this,"lastMs");h(this,"lastLoaded",0);h(this,"smoothedRate",0);h(this,"smoothing");h(this,"_done",!1);h(this,"lastEmitMs",0);h(this,"minIntervalMs");h(this,"onProgress");this.total=e,this.startMs=hr(),this.lastMs=this.startMs,this.smoothing=t.smoothingFactor??.3,this.onProgress=t.onProgress??null;let n=t.throttleHz??10;this.minIntervalMs=n>0?1e3/n:0}update(e){this.loaded+=e;let t=this._snapshot();if(this.onProgress){let n=hr();(this.minIntervalMs===0||n-this.lastEmitMs>=this.minIntervalMs)&&(this.lastEmitMs=n,this.onProgress(t))}return t}complete(){this._done=!0;let e=this._snapshot();return this.onProgress?.(e),e}snapshot(){return this._snapshot()}get bytesLoaded(){return this.loaded}get isDone(){return this._done}_snapshot(){let e=hr(),t=e-this.startMs,n=e-this.lastMs;if(n>0){let i=(this.loaded-this.lastLoaded)/n*1e3;this.smoothedRate=this.smoothedRate===0?i:this.smoothedRate*(1-this.smoothing)+i*this.smoothing,this.lastMs=e,this.lastLoaded=this.loaded}let s=this.total!==null&&this.total>0?Math.min(100,this.loaded/this.total*100):null,o=this.total!==null&&this.smoothedRate>0?Math.max(0,(this.total-this.loaded)/this.smoothedRate*1e3):null;return{loaded:this.loaded,total:this.total,percent:this._done?this.total!==null?100:null:s,rate:this.smoothedRate,eta:this._done?0:o,elapsed:t,done:this._done}}};function Nt(r,e,t={}){let n=new W(e,t);if(!r)return n.complete(),{stream:new ReadableStream({start:i=>i.close()}),tracker:n};let s;if(r instanceof ReadableStream)s=r;else if(typeof r=="string"){let i=new TextEncoder().encode(r);s=new ReadableStream({start(a){a.enqueue(i),a.close()}})}else s=new ReadableStream({start(i){i.enqueue(r),i.close()}});return{stream:new ReadableStream({async start(i){let a=s.getReader();if(t.signal?.aborted){a.cancel("aborted").catch(()=>{}),i.error(new DOMException("Upload aborted","AbortError"));return}let c=()=>{a.cancel("aborted").catch(()=>{}),i.error(new DOMException("Upload aborted","AbortError"))};t.signal?.addEventListener("abort",c,{once:!0});try{for(;;){let{done:l,value:u}=await a.read();if(l){n.complete(),i.close();break}n.update(u.byteLength),i.enqueue(u)}}catch(l){n.complete(),i.error(l)}finally{t.signal?.removeEventListener("abort",c)}}}),tracker:n}}function Zo(r,e={}){return Nt(r.stream(),r.size,e)}function ei(r,e={}){let t=r.headers.get("content-length"),n=t?parseInt(t,10):null,s=new W(isNaN(n)?null:n,e);if(!r.body)return s.complete(),{response:r,tracker:s};let o=r.body,i=new ReadableStream({async start(c){let l=o.getReader(),u=!1,f=()=>{u||(u=!0,l.cancel("aborted").catch(()=>{}),c.error(new DOMException("Download aborted","AbortError")))};e.signal?.addEventListener("abort",f,{once:!0});try{for(;;){let{done:p,value:d}=await l.read();if(p){s.complete(),c.close();break}s.update(d.byteLength),c.enqueue(d)}}catch(p){u||s.complete(),c.error(p)}finally{u||e.signal?.removeEventListener("abort",f)}}});return{response:new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers}),tracker:s}}async function*ti(r,e,t={}){let n=new W(e,t),s=r.getReader();try{for(;;){if(t.signal?.aborted)throw new DOMException("Stream aborted","AbortError");let{done:o,value:i}=await s.read();if(o){let c=n.complete();yield{chunk:new Uint8Array(0),progress:c};break}let a=n.update(i.byteLength);yield{chunk:i,progress:a}}}finally{s.releaseLock()}}async function ri(r,e,t={}){let n=new W(e,t),s=[],o=r.getReader();if(t.signal?.aborted)throw o.cancel("aborted").catch(()=>{}),new DOMException("Stream aborted","AbortError");let i=()=>{o.cancel("aborted").catch(()=>{})};t.signal&&t.signal.addEventListener("abort",i,{once:!0});try{for(;;){let{done:u,value:f}=await o.read();if(u)break;s.push(f),n.update(f.byteLength)}}finally{o.releaseLock(),t.signal?.removeEventListener("abort",i)}n.complete();let a=s.reduce((u,f)=>u+f.byteLength,0),c=new Uint8Array(a),l=0;for(let u of s)c.set(u,l),l+=u.byteLength;return{data:c,tracker:n}}var fr=class{constructor(e,t){h(this,"partCount");h(this,"trackers",new Map);h(this,"totals",new Map);h(this,"onOverall");this.partCount=e,this.onOverall=t??null}createPartTracker(e,t,n={}){this.totals.set(e,t);let s=new W(t,{...n,onProgress:o=>{n.onProgress?.(o),this._emit()}});return this.trackers.set(e,s),s}getOverall(){let e=[],t=0,n=0,s=0,o=!0,i=0;for(let f=0;f<this.partCount;f++){let d=this.trackers.get(f)?.snapshot()??{loaded:0,total:this.totals.get(f)??null,percent:0,rate:0,eta:null,elapsed:0,done:!1};e.push(d),t+=d.loaded,d.total!==null&&(n+=d.total),s+=d.rate,d.done||(o=!1),d.elapsed>i&&(i=d.elapsed)}let a=n>0,c=a?Math.min(100,t/n*100):null,l=a&&s>0?Math.max(0,(n-t)/s*1e3):null;return{parts:e,overall:{loaded:t,total:a?n:null,percent:c,rate:s,eta:o?0:l,elapsed:i,done:o}}}_emit(){this.onOverall&&this.onOverall(this.getOverall())}},Xo=globalThis.XMLHttpRequest;function ni(r,e){return new Promise((t,n)=>{if(!Xo){n(new Error("XMLHttpRequest is not available in this runtime. Use fetch() instead."));return}let s=new Xo,o=new W(null,{...e.onUploadProgress!==void 0?{onProgress:e.onUploadProgress}:{},...e.throttleHz!==void 0?{throttleHz:e.throttleHz}:{},...e.smoothingFactor!==void 0?{smoothingFactor:e.smoothingFactor}:{}}),i=new W(null,{...e.onDownloadProgress!==void 0?{onProgress:e.onDownloadProgress}:{},...e.throttleHz!==void 0?{throttleHz:e.throttleHz}:{},...e.smoothingFactor!==void 0?{smoothingFactor:e.smoothingFactor}:{}});s.open(e.method??"GET",r,!0);for(let[a,c]of Object.entries(e.headers??{}))s.setRequestHeader(a,c);e.responseType&&(s.responseType=e.responseType),s.upload&&e.onUploadProgress&&(s.upload.addEventListener("loadstart",a=>{}),s.upload.addEventListener("progress",a=>{o.update(a.loaded-o.bytesLoaded)}),s.upload.addEventListener("load",()=>o.complete())),e.onDownloadProgress&&s.addEventListener("progress",a=>{i.update(a.loaded-i.bytesLoaded)}),e.signal?.addEventListener("abort",()=>{s.abort(),n(new DOMException("Request aborted","AbortError"))},{once:!0}),s.addEventListener("load",()=>{i.complete();let a=s.getAllResponseHeaders(),c={};for(let l of a.trim().split(/[\r\n]+/)){let u=l.indexOf(": ");u!==-1&&(c[l.slice(0,u).toLowerCase()]=l.slice(u+2))}t({status:s.status,statusText:s.statusText,headers:c,body:typeof s.response=="string"?s.response:String(s.response??"")})}),s.addEventListener("error",()=>{n(new TypeError("Network request failed"))}),s.addEventListener("timeout",()=>{n(new TypeError("Request timed out"))}),s.send(e.body??null)})}var Yo=["B","KB","MB","GB","TB"];function Dt(r,e=2){if(r===0)return"0 B";let t=1024,n=Math.max(0,e),s=Math.floor(Math.log(r)/Math.log(t)),o=Yo[Math.min(s,Yo.length-1)];return`${parseFloat((r/Math.pow(t,s)).toFixed(n))} ${o}`}function yn(r){return`${Dt(r)}/s`}function wn(r){if(!isFinite(r)||r<0)return"\u221E";let e=Math.round(r/1e3),t=Math.floor(e/3600),n=Math.floor(e%3600/60),s=e%60;return t>0?`${t}h ${n}m ${s}s`:n>0?`${n}m ${s}s`:`${s}s`}function si(r){let e=Dt(r.loaded),t=r.total!==null?` / ${Dt(r.total)}`:"",n=r.percent!==null?` (${r.percent.toFixed(1)}%)`:"",s=r.rate>0?` @ ${yn(r.rate)}`:"",o=r.eta!==null&&!r.done?` ETA ${wn(r.eta)}`:"";return`${e}${t}${n}${s}${o}`}function oi(r,e=10){let t=e>0?1e3/e:0,n=0;return s=>{let o=hr();(s.done||o-n>=t)&&(n=o,r(s))}}function hr(){return typeof performance<"u"?performance.now():Date.now()}var Ie=class{constructor(e={}){h(this,"inflight",new Map);h(this,"timeouts",new Map);h(this,"windowMs");h(this,"methods");h(this,"keyFn");h(this,"_globalSignal");h(this,"_hits",0);h(this,"_misses",0);this.windowMs=e.windowMs??0,this.methods=new Set((e.methods??["GET","HEAD"]).map(t=>t.toUpperCase())),this.keyFn=e.keyFn??((t,n)=>`${t}::${n}`),this._globalSignal=e.signal??null}execute(e,t,n,s,o,i){let a=o??this.windowMs,c=i??this._globalSignal;if(c?.aborted||!this.methods.has(e.toUpperCase()))return n();let l=this.keyFn(e,t,s),u=this.inflight.get(l);if(u){if(u.resolvedAt!==null&&a>0&&Date.now()-u.resolvedAt<=a)return this._hits++,u.promise;if(u.resolvedAt===null)return this._hits++,u.promise;this.inflight.delete(l)}this._misses++;let f={resolvedAt:null,promise:void 0};return this.inflight.set(l,f),f.promise=(async()=>{let p=c?()=>{this.inflight.delete(l);let d=this.timeouts.get(l);d!==void 0&&(clearTimeout(d),this.timeouts.delete(l))}:null;c&&p&&c.addEventListener("abort",p,{once:!0});try{return await n()}finally{c&&p&&c.removeEventListener("abort",p)}})().then(p=>{if(f.resolvedAt=Date.now(),f.result=p,a<=0)this.inflight.delete(l);else{let d=setTimeout(()=>{this.inflight.delete(l),this.timeouts.delete(l)},a);this.timeouts.set(l,d)}return p},p=>{f.resolvedAt=Date.now(),f.error=p,this.inflight.delete(l);let d=this.timeouts.get(l);throw d!==void 0&&(clearTimeout(d),this.timeouts.delete(l)),p}),f.promise}get hits(){return this._hits}get misses(){return this._misses}get inFlightCount(){let e=0;for(let t of this.inflight.values())t.resolvedAt===null&&e++;return e}get keys(){return[...this.inflight.keys()]}getStats(){let e=this._hits+this._misses;return{hits:this._hits,misses:this._misses,totalRequests:e,hitRate:e===0?0:this._hits/e,inFlightCount:this.inFlightCount,trackedKeys:this.inflight.size}}resetMetrics(){this._hits=0,this._misses=0}clear(){this.inflight.clear();for(let e of this.timeouts.values())clearTimeout(e);this.timeouts.clear()}invalidate(e){let t=this.timeouts.get(e);return t&&(clearTimeout(t),this.timeouts.delete(e)),this.inflight.delete(e)}destroy(){this.clear()}};function ii(r){return new Ie(r)}var Ye=class extends Error{constructor(t,n){super(`Circuit breaker OPEN for "${t}" \u2014 request rejected`);h(this,"code","ECIRCUITOPEN");h(this,"state");this.name="CircuitOpenError",this.state=n}},Ze=class{constructor(e,t={}){h(this,"key");h(this,"failureThreshold");h(this,"windowSize");h(this,"resetTimeoutMs");h(this,"successThreshold");h(this,"halfOpenConcurrency");h(this,"failureFilter");h(this,"cfg");h(this,"_state","CLOSED");h(this,"_window",[]);h(this,"_consecutiveFails",0);h(this,"_consecutiveSucc",0);h(this,"_openedAt",null);h(this,"_halfOpenAt",null);h(this,"_lastFailureAt",null);h(this,"_lastSuccessAt",null);h(this,"_inFlightProbes",0);h(this,"_totalRequests",0);h(this,"_totalFailures",0);h(this,"_totalSuccesses",0);h(this,"_totalRejected",0);this.key=e,this.failureThreshold=t.failureThreshold??5,this.windowSize=t.windowSize??10,this.resetTimeoutMs=t.resetTimeoutMs??3e4,this.successThreshold=t.successThreshold??2,this.halfOpenConcurrency=t.halfOpenConcurrency??1,this.failureFilter={networkErrors:t.failures?.networkErrors??!0,timeouts:t.failures?.timeouts??!0,serverErrors:t.failures?.serverErrors??!1,statusCodes:t.failures?.statusCodes??[]},this.cfg=t}get state(){return this._state}get snapshot(){return{state:this._state,failureCount:this.windowSize>0?this._window.filter(e=>!e).length:this._consecutiveFails,successCount:this._consecutiveSucc,lastFailureAt:this._lastFailureAt,lastSuccessAt:this._lastSuccessAt,openedAt:this._openedAt,halfOpenAt:this._halfOpenAt,totalRequests:this._totalRequests,totalFailures:this._totalFailures,totalSuccesses:this._totalSuccesses,totalRejected:this._totalRejected,inFlightProbes:this._inFlightProbes}}execute(e){if(this._checkTransition(),this._state==="OPEN"){this._totalRejected++;let t=this.snapshot;return this.cfg.onRejected?.(t),Promise.reject(new Ye(this.key,t))}if(this._state==="HALF_OPEN"){if(this._inFlightProbes>=this.halfOpenConcurrency){this._totalRejected++;let t=this.snapshot;return this.cfg.onRejected?.(t),Promise.reject(new Ye(this.key,t))}this._inFlightProbes++}return this._totalRequests++,e().then(t=>(this._state==="HALF_OPEN"&&(this._inFlightProbes=Math.max(0,this._inFlightProbes-1)),this._recordSuccess(),t),t=>{throw this._state==="HALF_OPEN"&&(this._inFlightProbes=Math.max(0,this._inFlightProbes-1)),this._isCountableFailure(t)&&this._recordFailure(),t})}trip(){this._state!=="OPEN"&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))}reset(){this._state="CLOSED",this._window=[],this._consecutiveFails=0,this._consecutiveSucc=0,this._openedAt=null,this._halfOpenAt=null,this._inFlightProbes=0,this.cfg.onClose?.(this.snapshot)}_checkTransition(){this._state==="OPEN"&&this._openedAt!==null&&Date.now()-this._openedAt>=this.resetTimeoutMs&&(this._state="HALF_OPEN",this._halfOpenAt=Date.now(),this._consecutiveSucc=0,this._inFlightProbes=0,this.cfg.onHalfOpen?.(this.snapshot))}_recordSuccess(){if(this._lastSuccessAt=Date.now(),this._totalSuccesses++,this._consecutiveFails=0,this._state==="HALF_OPEN"){this._consecutiveSucc++,this._consecutiveSucc>=this.successThreshold&&this.reset();return}this.windowSize>0&&(this._window.push(!0),this._window.length>this.windowSize&&this._window.shift())}_recordFailure(){if(this._lastFailureAt=Date.now(),this._totalFailures++,this._consecutiveSucc=0,this._consecutiveFails++,this._state==="HALF_OPEN"){this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot);return}this.windowSize>0?(this._window.push(!1),this._window.length>this.windowSize&&this._window.shift(),this._window.filter(t=>!t).length>=this.failureThreshold&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))):this._consecutiveFails>=this.failureThreshold&&(this._openedAt=Date.now(),this._state="OPEN",this.cfg.onOpen?.(this.snapshot))}_isCountableFailure(e){if(!(e instanceof Error))return!1;let t=e.code;if(this.failureFilter.networkErrors&&t==="ENETWORK"||this.failureFilter.timeouts&&t==="ETIMEOUT")return!0;if(this.failureFilter.serverErrors){let n=e.status;if(n&&n>=500)return!0}if(this.failureFilter.statusCodes&&this.failureFilter.statusCodes.length>0){let n=e.status;if(n&&this.failureFilter.statusCodes.includes(n))return!0}return!1}},Le=class{constructor(e={}){h(this,"breakers",new Map);h(this,"defaultConfig");this.defaultConfig=e}get(e,t){return this.breakers.has(e)||this.breakers.set(e,new Ze(e,{...this.defaultConfig,...t})),this.breakers.get(e)}execute(e,t,n){return this.get(e,n).execute(t)}trip(e){this.get(e).trip()}reset(e){this.get(e).reset()}snapshots(){let e={};for(let[t,n]of this.breakers)e[t]=n.snapshot;return e}delete(e){this.breakers.delete(e)}clear(){this.breakers.clear()}get size(){return this.breakers.size}};function ai(r,e){return new Ze(r,e)}function ci(r){return new Le(r)}z();var K=class extends Error{constructor(t,n){super(t,n!=null?{cause:n}:void 0);h(this,"code","EWSCONNECT");h(this,"originalCause");this.name="WSError",this.originalCause=n}},Ht=class extends Error{constructor(t){super(`WebSocket gave up after ${t} reconnect attempts`);h(this,"attempts");h(this,"code","EWSMAXRECONNECTS");this.attempts=t,this.name="WSMaxReconnectsError"}},nt=class extends Error{constructor(t,n){super(`WebSocket connect to ${t} timed out after ${n}ms`);h(this,"code","EWSCONNECTTIMEOUT");this.name="WSConnectTimeoutError"}},br=class extends Error{constructor(t){super(`WebSocket send rate limited; retry in ${t}ms`);h(this,"delayMs");h(this,"code","EWSRATELIMIT");this.delayMs=t,this.name="WSRateLimitError"}},De=class{constructor(e){h(this,"_url");h(this,"_protocols");h(this,"_headers");h(this,"_maxReconnects");h(this,"_reconnectBaseMs");h(this,"_reconnectMaxMs");h(this,"_reconnectJitter");h(this,"_pingIntervalMs");h(this,"_pingPayload");h(this,"_pongMatcher");h(this,"_pongTimeoutMs");h(this,"_connectTimeoutMs");h(this,"_bufferMessages");h(this,"_maxBufferSize");h(this,"_cbOpen");h(this,"_cbMessage");h(this,"_cbClose");h(this,"_cbError");h(this,"_cbReconnect");h(this,"_cbGiveUp");h(this,"_ws",null);h(this,"_state","CLOSED");h(this,"_reconnAttempt",0);h(this,"_buffer",[]);h(this,"_pingTimer",null);h(this,"_pongTimer",null);h(this,"_reconnTimer",null);h(this,"_msgListeners",[]);h(this,"_closeListeners",[]);h(this,"_openWaiters",[]);h(this,"_correlations",new Map);h(this,"_aborted",!1);h(this,"_externalSignal",null);h(this,"_onExternalAbort",()=>this.close(1e3,"AbortSignal aborted"));h(this,"_iterQueue",[]);h(this,"_iterWaiter",null);h(this,"_iterDone",!1);h(this,"_rooms",[]);h(this,"_keepRooms");h(this,"_highWaterMark");h(this,"_lowWaterMark");h(this,"_bufferedBytes",0);h(this,"_drainWaiters",[]);h(this,"_cbBackpressure");h(this,"_wasBackpressured",!1);h(this,"_maxSendRate");h(this,"_tokens",0);h(this,"_lastToken",0);h(this,"_serverEndpoint",null);h(this,"_mx",{messagesSent:0,messagesReceived:0,bytesSent:0,bytesReceived:0,reconnectCount:0,totalConnectAttempts:0,connectedAt:null,closedAt:null,uptimeMs:0});h(this,"_openedAt",null);if(this._url=e.url,this._protocols=e.protocols,this._headers=e.headers,this._maxReconnects=e.maxReconnects??10,this._reconnectBaseMs=e.reconnectBaseMs??1e3,this._reconnectMaxMs=e.reconnectMaxMs??3e4,this._reconnectJitter=e.reconnectJitter??.3,this._pingIntervalMs=e.pingIntervalMs??3e4,this._pingPayload=e.pingPayload??"ping",this._pongMatcher=e.pongMatcher,this._pongTimeoutMs=e.pongTimeoutMs??1e4,this._connectTimeoutMs=e.connectTimeoutMs??3e4,this._bufferMessages=e.bufferMessages??!0,this._maxBufferSize=e.maxBufferSize??100,this._cbOpen=e.onOpen,this._cbMessage=e.onMessage,this._cbClose=e.onClose,this._cbError=e.onError,this._cbReconnect=e.onReconnect,this._cbGiveUp=e.onGiveUp,this._cbBackpressure=e.onBackpressure,this._highWaterMark=e.highWaterMark??65536,this._lowWaterMark=e.lowWaterMark??16384,this._maxSendRate=e.maxSendRate??0,this._keepRooms=e.keepRooms??!0,e.rooms&&e.rooms.length>0)for(let t of e.rooms)this._rooms.push({room:t,joinedAt:0});this._externalSignal=e.signal??null,this._externalSignal?.addEventListener("abort",this._onExternalAbort,{once:!0})}get state(){return this._state}get connected(){return this._state==="OPEN"}get bufferedCount(){return this._buffer.length}get metrics(){return{...this._mx,uptimeMs:this._mx.uptimeMs+(this._openedAt!=null?Date.now()-this._openedAt:0)}}connect(){return this._state==="OPEN"?Promise.resolve():this._state==="CONNECTING"||this._state==="RECONNECTING"?new Promise((e,t)=>this._openWaiters.push({resolve:e,reject:t})):this._doConnect(!1)}waitForOpen(e=6e4){return this._state==="OPEN"?Promise.resolve():new Promise((t,n)=>{let s=e>0?setTimeout(()=>{let o=this._openWaiters.findIndex(i=>i.resolve===t);o!==-1&&this._openWaiters.splice(o,1),n(new nt(this._url,e))},e):null;this._openWaiters.push({resolve:()=>{s&&clearTimeout(s),t()},reject:o=>{s&&clearTimeout(s),n(o)}})})}close(e=1e3,t="Client closed"){this._aborted=!0,this._externalSignal?.removeEventListener("abort",this._onExternalAbort),this._externalSignal=null,this._stopAll();for(let s of this._drainWaiters.splice(0))s();this._state="CLOSING";let n=this._ws;if(n){if(n.onopen=n.onmessage=n.onerror=n.onclose=null,n.readyState<2)try{n.close(e,t)}catch{}this._ws=null}this._buffer=[],this._bufferedBytes=0,this._iterQueue=[],this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null);for(let s of this._openWaiters.splice(0))s.reject(new Error("Client closed"));this._rooms=[];for(let s of this._correlations.values())s.timer&&clearTimeout(s.timer),s.reject(new Error("Client closed"));this._correlations.clear(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now(),this._state="CLOSED";for(let s of this._closeListeners)try{s({code:e,reason:t})}catch{}this._closeListeners=[],this._msgListeners=[],this._cbClose?.(e,t,!1)}destroy(){this._aborted=!0,this._stopAll();for(let t of this._drainWaiters.splice(0))t();this._state="CLOSING";let e=this._ws;if(e){if(e.onopen=e.onmessage=e.onerror=e.onclose=null,e.readyState<2)try{e.close(1e3,"Destroyed")}catch{}this._ws=null}this._buffer=[],this._bufferedBytes=0,this._iterQueue=[],this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null),this._msgListeners=[];for(let t of this._openWaiters.splice(0))t.reject(new Error("Client destroyed"));this._rooms=[];for(let t of this._correlations.values())t.timer&&clearTimeout(t.timer),t.reject(new Error("Client destroyed"));this._correlations.clear(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now(),this._state="CLOSED";for(let t of this._closeListeners)try{t({code:1e3,reason:"Destroyed"})}catch{}this._closeListeners=[],this._cbClose?.(1e3,"Destroyed",!1)}send(e){this._tx(e)&&this._mx.messagesSent++}sendBinary(e){let t=e instanceof Uint8Array?e.slice().buffer:e;this._tx(t)&&this._mx.messagesSent++}sendJSON(e){this.send(JSON.stringify(e))}request(e,t,n=o=>o.json??o.data,s=1e4){return new Promise((o,i)=>{let a=`${Date.now()}-${Math.random()}`,c=s>0?setTimeout(()=>{let l=this._correlations.get(a);l?.timer&&clearTimeout(l.timer),this._correlations.delete(a),i(new K(`request() timed out after ${s}ms waiting for reply`))},s):null;this._correlations.set(a,{matcher:t,extract:n,resolve:o,reject:i,timer:c}),typeof e=="string"?this.send(e):this.sendJSON(e)})}onMessage(e){return this._msgListeners.push(e),()=>{let t=this._msgListeners.indexOf(e);t!==-1&&this._msgListeners.splice(t,1)}}onClose(e){return this._closeListeners.push(e),()=>{let t=this._closeListeners.indexOf(e);t!==-1&&this._closeListeners.splice(t,1)}}drainBuffer(){let e=this._buffer.splice(0);return this._bufferedBytes=0,this._updateBackpressure(),e}join(e,t){this._rooms.some(n=>n.room===e&&n.namespace===t)||(this._rooms.push({room:e,namespace:t,joinedAt:Date.now()}),this.sendJSON({type:"room:join",room:e,namespace:t??null}))}leave(e,t){let n=this._rooms.findIndex(s=>s.room===e&&s.namespace===t);n!==-1&&(this._rooms.splice(n,1),this.sendJSON({type:"room:leave",room:e,namespace:t??null}))}get rooms(){return this._rooms}get backpressure(){return{bufferedBytes:this._bufferedBytes,highWaterMark:this._highWaterMark,lowWaterMark:this._lowWaterMark,isBackpressured:this._bufferedBytes>=this._highWaterMark}}drain(e=3e4){return this._state==="CLOSED"?Promise.reject(new K("Cannot drain \u2014 socket is CLOSED")):this._bufferedBytes<this._lowWaterMark?Promise.resolve():new Promise((t,n)=>{let s=e>0?setTimeout(()=>n(new K(`drain() timed out after ${e}ms`)),e):null;this._drainWaiters.push(()=>{s&&clearTimeout(s),t()})})}async drainAndClose(e=3e4){if(this._state!=="CLOSED"){try{await this.drain(e)}catch{}this.close(1e3,"Graceful shutdown")}}get serverEndpoint(){return this._serverEndpoint}[Symbol.asyncIterator](){return{next:()=>this._iterQueue.length>0?Promise.resolve({done:!1,value:this._iterQueue.shift()}):this._iterDone?Promise.resolve({done:!0,value:void 0}):new Promise(e=>{this._iterWaiter=e}),return:()=>(this.close(1e3,"Iterator returned"),Promise.resolve({done:!0,value:void 0}))}}_doConnect(e){return this._mx.totalConnectAttempts++,this._state="CONNECTING",new Promise((t,n)=>{let s=!1,o=null;this._connectTimeoutMs>0&&(o=setTimeout(()=>{if(s)return;s=!0;let u=new nt(this._url,this._connectTimeoutMs);n(u),this._cbError?.(u);let f=this._ws;if(f&&(f.onopen=f.onmessage=f.onerror=f.onclose=null,f.close(),this._ws=null),!this._aborted&&this._canRecon())this._scheduleRecon();else{this._state="CLOSED";for(let p of this._openWaiters.splice(0))p.reject(u);this._rejectCorrelations("Connection timeout")}},this._connectTimeoutMs));let i=()=>{o&&(clearTimeout(o),o=null)},a=this._url,c=(()=>{try{let u=globalThis;if(typeof globalThis.Deno<"u"||typeof globalThis.Bun<"u"||u.process?.versions?.node||typeof window>"u")return!1;let f=window;return typeof f.navigator<"u"&&typeof f.document<"u"}catch{return!1}})();if(this._headers&&c){let u=new URL(a);for(let[f,p]of Object.entries(this._headers))u.searchParams.set(f,p);a=u.href}let l;try{l=this._protocols?new WebSocket(a,this._protocols):new WebSocket(a)}catch(u){i(),this._state="CLOSED",n(new K("Failed to construct WebSocket",u instanceof Error?u:void 0));return}if(this._headers&&!c){let u=l;if(typeof u.setHeader=="function")for(let[f,p]of Object.entries(this._headers))u.setHeader(f,p)}this._ws=l,l.binaryType="arraybuffer",l.onopen=()=>{if(i(),!s){if(s=!0,this._state="OPEN",this._openedAt=Date.now(),this._mx.connectedAt=this._openedAt,e&&this._mx.reconnectCount++,this._serverEndpoint=l.url??this._url,this._reconnAttempt=0,this._rooms.length>0&&this._keepRooms)for(let u of this._rooms)try{l.send(JSON.stringify({type:"room:join",room:u.room,namespace:u.namespace??null}))}catch{}this._startPing(),this._flushBuf(),this._cbOpen?.(this._mx.reconnectCount),t();for(let u of this._openWaiters.splice(0))u.resolve()}},l.onmessage=async u=>{if(this._aborted)return;let f,p,d;if(typeof u.data=="string"){f=u.data,d=new TextEncoder().encode(f).byteLength;try{p=M(JSON.parse(f))}catch{}}else if(u.data instanceof ArrayBuffer)f=new Uint8Array(u.data),d=f.byteLength;else if(typeof Blob<"u"&&u.data instanceof Blob){let m=await u.data.arrayBuffer();f=new Uint8Array(m),d=f.byteLength}else f=new Uint8Array(u.data),d=f.byteLength;this._mx.messagesReceived++,this._mx.bytesReceived+=d;let g={data:f,json:p,timestamp:Date.now()};if(this._pongMatcher&&typeof f=="string"&&(typeof this._pongMatcher=="string"?f===this._pongMatcher:this._pongMatcher.test(f))){this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null);return}for(let[m,y]of this._correlations)if(y.matcher(g)){this._correlations.delete(m),y.timer&&clearTimeout(y.timer);try{y.resolve(y.extract(g))}catch(b){y.reject(b)}return}for(let m of this._msgListeners)try{m(g)}catch{}if(this._cbMessage?.(g),this._iterWaiter){let m=this._iterWaiter;this._iterWaiter=null,m({done:!1,value:g})}else this._iterQueue.length>=this._maxBufferSize&&this._iterQueue.shift(),this._iterQueue.push(g)},l.onerror=u=>{this._cbError?.(new K(u.message??"WebSocket error",u.error))},l.onclose=u=>{i(),this._stopPing(),this._openedAt!=null&&(this._mx.uptimeMs+=Date.now()-this._openedAt,this._openedAt=null),this._mx.closedAt=Date.now();for(let p of this._closeListeners)try{p({code:u.code,reason:u.reason})}catch{}if(s||(s=!0,n(new K(`Socket closed before open (code ${u.code}: ${u.reason})`))),this._aborted||u.code===1e3||u.code===1001){this._state="CLOSED",this._cbClose?.(u.code,u.reason,!1),this._terminateIter();for(let p of this._openWaiters.splice(0))p.reject(new K(`Socket closed (code ${u.code})`));this._rejectCorrelations(`Socket closed (code ${u.code})`);return}let f=this._canRecon();if(this._cbClose?.(u.code,u.reason,f),f)this._scheduleRecon();else{this._cbGiveUp?.(this._reconnAttempt),this._state="CLOSED",this._terminateIter();let p=new Ht(this._reconnAttempt);for(let d of this._openWaiters.splice(0))d.reject(p);this._rejectCorrelations("Max reconnects exceeded")}}})}_canRecon(){return this._maxReconnects===0||this._reconnAttempt<this._maxReconnects}_scheduleRecon(){this._state="RECONNECTING",this._reconnAttempt++;let e=this._reconnectBaseMs*Math.pow(2,this._reconnAttempt-1),t=Math.min(e,this._reconnectMaxMs),n=Math.floor(t*(1+this._reconnectJitter*Math.random()));this._cbReconnect?.(this._reconnAttempt,n),this._reconnTimer=setTimeout(()=>{this._aborted||this._doConnect(!0).catch(()=>{})},n),typeof this._reconnTimer=="object"&&this._reconnTimer!==null&&"unref"in this._reconnTimer&&this._reconnTimer.unref()}_tx(e){let t=this._ws,n=typeof e=="string"?new TextEncoder().encode(e).byteLength:e.byteLength;if(this._maxSendRate>0){let s=Date.now();this._lastToken===0&&(this._lastToken=s,this._tokens=this._maxSendRate);let o=s-this._lastToken;if(this._tokens=Math.min(this._maxSendRate,this._tokens+o*this._maxSendRate/1e3),this._lastToken=s,this._tokens<1)return this._bufferMessage(e,n),!1;this._tokens--}if(this._bufferedBytes>=this._highWaterMark)return this._bufferMessage(e,n),!1;if(t&&t.readyState===1)try{return t.send(e),this._mx.bytesSent+=n,!0}catch(s){if(this._cbError?.(new K(`WebSocket send failed: ${s instanceof Error?s.message:String(s)}`,s)),t.readyState===1)try{t.close(4001,"Send error")}catch{}return this._ws=null,!this._aborted&&this._canRecon()&&this._scheduleRecon(),!1}return this._bufferMessage(e,n),!1}_bufferMessage(e,t){if(this._bufferMessages&&!this._aborted){let n=this._buffer.length>=this._maxBufferSize?this._buffer.shift():void 0;n!==void 0&&(this._bufferedBytes-=typeof n=="string"?new TextEncoder().encode(n).byteLength:n.byteLength),this._buffer.push(e),this._bufferedBytes+=t,this._updateBackpressure()}}_flushBuf(){let e=this._buffer.splice(0);for(let t of e)try{this._ws?.send(t),this._mx.messagesSent++,this._mx.bytesSent+=typeof t=="string"?new TextEncoder().encode(t).byteLength:t.byteLength}catch{}this._bufferedBytes=0,this._updateBackpressure()}_updateBackpressure(){let e=this._bufferedBytes>=this._highWaterMark;if(e!==this._wasBackpressured&&(this._wasBackpressured=e,this._cbBackpressure?.(e,this.backpressure)),!e&&this._bufferedBytes<this._lowWaterMark&&this._drainWaiters.length>0)for(let t of this._drainWaiters.splice(0))t()}_startPing(){this._pingIntervalMs<=0||(this._pingTimer=setInterval(()=>{let e=this._ws;if(!(!e||e.readyState!==1)){try{e.send(this._pingPayload),this._mx.messagesSent++,this._mx.bytesSent+=new TextEncoder().encode(this._pingPayload).byteLength}catch{}this._pongMatcher&&this._pongTimeoutMs>0&&(this._pongTimer&&clearTimeout(this._pongTimer),this._pongTimer=setTimeout(()=>{this._pongTimer=null;let t=this._ws;t&&(t.onopen=t.onmessage=t.onerror=t.onclose=null,t.close(4e3,"Pong timeout"),this._ws=null),!this._aborted&&this._canRecon()?(this._cbClose?.(4e3,"Pong timeout",!0),this._scheduleRecon()):this._state="CLOSED"},this._pongTimeoutMs),typeof this._pongTimer=="object"&&this._pongTimer!==null&&"unref"in this._pongTimer&&this._pongTimer.unref())}},this._pingIntervalMs),typeof this._pingTimer=="object"&&this._pingTimer!==null&&"unref"in this._pingTimer&&this._pingTimer.unref())}_stopPing(){this._pingTimer&&(clearInterval(this._pingTimer),this._pingTimer=null),this._pongTimer&&(clearTimeout(this._pongTimer),this._pongTimer=null)}_stopAll(){this._stopPing(),this._reconnTimer&&(clearTimeout(this._reconnTimer),this._reconnTimer=null)}_terminateIter(){this._iterDone=!0,this._iterWaiter&&(this._iterWaiter({done:!0,value:void 0}),this._iterWaiter=null)}_rejectCorrelations(e){for(let t of this._correlations.values())t.timer&&clearTimeout(t.timer),t.reject(new K(e));this._correlations.clear()}};async function Pi(r){let e=new De(r);return await e.connect(),e}Ne();z();jt();var ml=0;function In(){return`interceptor_${++ml}`}function Ln(r){return[...r].sort((e,t)=>e.priority-t.priority)}var zt=class{constructor(){h(this,"requestInterceptors",[]);h(this,"responseInterceptors",[]);h(this,"errorInterceptors",[])}useRequest(e,t={}){let n=t.id??In();return this.requestInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}useResponse(e,t={}){let n=t.id??In();return this.responseInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}useError(e,t={}){let n=t.id??In();return this.errorInterceptors.push({id:n,priority:t.priority??0,once:t.once??!1,condition:t.condition??null,fn:e}),n}use(e,t,n={}){let s=e?this.useRequest(e,n):null,o=t?this.useResponse(t,n):null;return{requestId:s,responseId:o}}eject(e){let t=this.requestInterceptors.length+this.responseInterceptors.length+this.errorInterceptors.length;return this.requestInterceptors=this.requestInterceptors.filter(s=>s.id!==e),this.responseInterceptors=this.responseInterceptors.filter(s=>s.id!==e),this.errorInterceptors=this.errorInterceptors.filter(s=>s.id!==e),this.requestInterceptors.length+this.responseInterceptors.length+this.errorInterceptors.length<t}ejectAll(){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[]}has(e){return this.requestInterceptors.some(t=>t.id===e)||this.responseInterceptors.some(t=>t.id===e)||this.errorInterceptors.some(t=>t.id===e)}get requestCount(){return this.requestInterceptors.length}get responseCount(){return this.responseInterceptors.length}get errorCount(){return this.errorInterceptors.length}async execute(e,t){let n={request:e,response:null,error:null,startedAt:ee(),attempt:0,aborted:!1,store:new Map};return await this._run(n,t)}async _run(e,t){e.attempt++;let n=new Set;for(let s of Ln(this.requestInterceptors)){if(e.aborted)break;if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){e.error=i;for(let a of n)this.eject(a);return this._runErrorPhase(e,t)}if(s.once&&n.add(s.id),o!=null){if(Mn(o)){e.response=o;for(let i of n)this.eject(i);return this._runResponsePhase(e,t)}Ni(o)&&(e.request=o)}}for(let s of n)this.eject(s);try{e.response=await t(e.request)}catch(s){return e.error=s,this._runErrorPhase(e,t)}return this._runResponsePhase(e,t)}async _runResponsePhase(e,t){let n=new Set;for(let s of Ln(this.responseInterceptors)){if(e.aborted)break;if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){e.error=i;for(let a of n)this.eject(a);return this._runErrorPhase(e,t)}if(s.once&&n.add(s.id),o!=null){if(Ni(o)){e.request=o,e.response=null,e.error=null;for(let i of n)this.eject(i);return this._run(e,t)}Mn(o)&&(e.response=o)}}for(let s of n)this.eject(s);if(!e.response)throw new Error("Pipeline produced no response");return e.response}async _runErrorPhase(e,t){let n=new Set;for(let s of Ln(this.errorInterceptors)){if(s.condition&&!s.condition(e))continue;let o;try{o=await s.fn(e)}catch(i){if(i.__retrySignal){for(let a of n)this.eject(a);return e.error=null,e.response=null,this._run(e,t)}e.error=i;continue}if(s.once&&n.add(s.id),o!=null&&Mn(o)){e.response=o,e.error=null;for(let i of n)this.eject(i);return this._runResponsePhase(e,t)}}for(let s of n)this.eject(s);throw e.error}};function Mn(r){return r!==null&&typeof r=="object"&&typeof r.status=="number"&&"headers"in r&&"request"in r}function Ni(r){return r!==null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.method=="string"&&!("status"in r)}var gl={maxRetries:3,baseDelayMs:300,maxDelayMs:3e4,jitter:.3,retryStatuses:[408,429,500,502,503,504],retryOnError:!0,retryMethods:["GET","HEAD","PUT","DELETE","OPTIONS","TRACE","POST"],shouldRetry:null,onRetry:null};function $n(r={}){let e={...gl,...r};function t(a,c){if(c!==null)return Math.min(c,e.maxDelayMs);let l=e.baseDelayMs*Math.pow(2,a-1),u=Math.min(l,e.maxDelayMs),f=u*e.jitter*Math.random();return Math.floor(u+f)}function n(a){return a.attempt>e.maxRetries||!e.retryMethods.includes(a.request.method.toUpperCase())?!1:e.shouldRetry?e.shouldRetry(a):a.error?e.retryOnError:a.response?e.retryStatuses.includes(a.response.status):!1}function s(a){let c=a.response?.headers["retry-after"]??a.response?.headers["Retry-After"];if(!c)return null;if(/^\d+$/.test(c.trim()))return parseInt(c,10)*1e3;let l=Date.parse(c);return isNaN(l)?null:Math.max(0,l-Date.now())}return{responseInterceptor:async a=>{if(!n(a))return;let c=t(a.attempt,s(a));return e.onRetry?.(a,c),await Hi(c),{...a.request}},errorInterceptor:async a=>{if(!n(a))return;let c=t(a.attempt,null);throw e.onRetry?.(a,c),await Hi(c),a.error=null,new Nn(a.request)}}}var Nn=class{constructor(e){h(this,"request");h(this,"__retrySignal",!0);this.request=e}},yl={getToken:()=>null,refreshToken:null,headerName:"authorization",scheme:"Bearer ",refreshOnStatuses:[401],maxQueue:50,refreshRetryDelay:3e4};function Hn(r){let e={...yl,...r},t=null,n=[],s=null,o=e.refreshRetryDelay??3e4;async function i(){if(s!==null){let l=Date.now()-s;if(l<o)throw new Error(`Auth refresh circuit breaker: last failure ${Math.round(l/1e3)}s ago, retry after ${Math.round((o-l)/1e3)}s`)}if(t){if(n.length>=e.maxQueue)throw new Error("Auth refresh queue full");return await new Promise((l,u)=>n.push({resolve:l,reject:u}))}return e.refreshToken?(t=e.refreshToken().then(l=>{for(let u of n)u.resolve(l);return n.length=0,t=null,s=null,l},l=>{for(let u of n)u.reject(l);throw n.length=0,t=null,s=Date.now(),l}),t):null}return{requestInterceptor:async l=>{let u=await e.getToken();u&&(l.request.headers[e.headerName]=`${e.scheme}${u}`)},responseInterceptor:async l=>{if(!l.response||!e.refreshOnStatuses.includes(l.response.status)||!e.refreshToken||l.request.meta.__authRetried)return;let u=await i();return u?{...l.request,headers:{...l.request.headers,[e.headerName]:`${e.scheme}${u}`},meta:{...l.request.meta,__authRetried:!0}}:void 0}}}var wl={timeoutMs:3e4,methodTimeouts:{},message:"Request timed out"};function jn(r={}){let e={...wl,...r},t=i=>{let a=e.methodTimeouts[i.request.method.toUpperCase()]??e.timeoutMs;if(a<=0)return;let c=new AbortController,l=setTimeout(()=>{i.aborted=!0,c.abort(new Un(e.message,a))},a),u=i.request.signal;if(u){let f=()=>{clearTimeout(l),c.abort(u.reason)};u.addEventListener("abort",f,{once:!0}),i.store.set(Dn,{existing:u,onExistingAbort:f})}i.request={...i.request,signal:c.signal},i.store.set(On,l)},n=i=>{let a=i.store.get(On);a&&(clearTimeout(a),i.store.delete(On));let c=i.store.get(Dn);c&&(c.existing.removeEventListener("abort",c.onExistingAbort),i.store.delete(Dn))};return{id:"timeout",requestInterceptor:t,responseInterceptor:i=>{n(i)},errorInterceptor:i=>{n(i)}}}var On=Symbol("timeoutTimer"),Dn=Symbol("timeoutSignal"),Un=class extends Error{constructor(t,n){super(t);h(this,"timeoutMs");h(this,"code","ETIMEDOUT");this.timeoutMs=n,this.name="TimeoutError"}},bl={logger:r=>console.log(JSON.stringify(r)),redactHeaders:["authorization","cookie","set-cookie","proxy-authorization"],logRequests:!0,logResponses:!0,logErrors:!0},Ui=Symbol("requestId"),xl=0;function zn(r={}){let e={...bl,...r},t=new Set(e.redactHeaders.map(c=>c.toLowerCase()));function n(c){let l={};for(let[u,f]of Object.entries(c))l[u]=t.has(u.toLowerCase())?"**REDACTED**":f;return l}function s(c,l){let u=l.store.get(Ui)??"unknown";return{type:c,timestamp:Date.now(),requestId:u,method:l.request.method,url:l.request.url,status:l.response?.status??null,durationMs:c!=="request"?ee()-l.startedAt:null,attempt:l.attempt,error:l.error instanceof Error?l.error.message:null}}return{requestInterceptor:c=>{let l=`req_${++xl}`;c.store.set(Ui,l),e.logRequests&&e.logger(s("request",c))},responseInterceptor:c=>{e.logResponses&&e.logger(s("response",c))},errorInterceptor:c=>{e.logErrors&&e.logger(s("error",c))}}}var _l={maxEntries:500,defaultTtlMs:6e4,cacheMethods:["GET","HEAD"],cacheKey:null,honorCacheControl:!0};function qn(r={}){let e={..._l,...r},t=new Map,n=[];function s(l){return e.cacheKey?e.cacheKey(l):`${l.method}:${l.url}`}function o(l){let u=n.indexOf(l);for(u!==-1&&n.splice(u,1),n.unshift(l);n.length>e.maxEntries;){let f=n.pop();t.delete(f)}}function i(l){let u=l.headers["cache-control"]??l.headers["Cache-Control"]??"",f=u.match(/max-age=(\d+)/)?.[1],p=u.match(/stale-while-revalidate=(\d+)/)?.[1],d=/no-store/i.test(u),g=/no-cache/i.test(u);if(e.honorCacheControl&&(d||g))return{ttlMs:0,swrMs:0};let m=f?parseInt(f,10)*1e3:e.defaultTtlMs,y=p?parseInt(p,10)*1e3:0;return{ttlMs:m,swrMs:y}}return{requestInterceptor:l=>{if(!e.cacheMethods.includes(l.request.method.toUpperCase()))return;let u=s(l.request),f=t.get(u);if(!f)return;let p=ee();if(f.expiresAt>p)return o(u),l.store.set(Sl,!0),{...f.response,request:l.request};f.staleUntil>p&&(o(u),l.store.set($i,f),f.etag?l.request={...l.request,headers:{...l.request.headers,"if-none-match":f.etag}}:f.lastModified&&(l.request={...l.request,headers:{...l.request.headers,"if-modified-since":f.lastModified}}))},responseInterceptor:l=>{if(!l.response||!e.cacheMethods.includes(l.request.method.toUpperCase()))return;let u=s(l.request);if(l.response.status===304){let m=l.store.get($i);if(m){let{ttlMs:y,swrMs:b}=i(m.response),x=ee(),E={...m,createdAt:x,expiresAt:x+y,staleUntil:x+y+b};t.set(u,E),o(u),l.response={...m.response,request:l.request};return}}let{ttlMs:f,swrMs:p}=i(l.response);if(f<=0)return;let d=ee(),g={response:l.response,createdAt:d,expiresAt:d+f,staleUntil:d+f+p,etag:l.response.headers.etag??l.response.headers.ETag??null,lastModified:l.response.headers["last-modified"]??null};t.set(u,g),o(u)},store:t}}var Sl=Symbol("cacheHit"),$i=Symbol("cacheStale");function Bn(){let r=new Map;function e(o){return`${o.method.toUpperCase()}:${o.url}`}return{requestInterceptor:o=>{if(o.request.method.toUpperCase()!=="GET"&&o.request.method.toUpperCase()!=="HEAD")return;let i=e(o.request),a=r.get(i);if(!a){r.set(i,{promise:void 0,waiters:[]});return}return o.store.set(El,i),new Promise((c,l)=>{a.waiters.push({resolve:u=>c(u),reject:u=>l(u)})})},responseInterceptor:o=>{if(!o.response)return;let i=e(o.request),a=r.get(i);if(a){r.delete(i);for(let c of a.waiters)c.resolve(o.response)}},errorInterceptor:o=>{let i=e(o.request),a=r.get(i);if(a){r.delete(i);for(let c of a.waiters)c.reject(o.error)}}}}var El=Symbol("dedupeQueued"),Tl={limit:60,windowMs:6e4,queue:!0,maxQueue:100};function qt(r={}){let e={...Tl,...r},t=e.limit,n=ee(),s=[],o=null;function i(){let l=ee(),u=(l-n)/e.windowMs;t=Math.min(e.limit,t+u*e.limit),n=l}function a(){o===null&&(o=setInterval(()=>{for(i();t>=1&&s.length>0;)t--,s.shift()();s.length===0&&o!==null&&(clearInterval(o),o=null)},Math.ceil(e.windowMs/e.limit)),typeof o=="object"&&o!==null&&"unref"in o&&o.unref())}async function c(){if(i(),t>=1){t--;return}if(!e.queue)throw new lt("Rate limit exceeded");if(s.length>=e.maxQueue)throw new lt("Rate limit queue full");await new Promise(l=>{s.push(()=>l()),a()})}return async()=>{await c()}}var lt=class extends Error{constructor(t){super(t);h(this,"code","ERATELIMIT");this.name="RateLimitError"}};function Fn(){let r=[],e=Symbol("harStart");function t(i){return Object.entries(i).map(([a,c])=>({name:a,value:c}))}function n(i){try{let a=new URL(i);return Array.from(a.searchParams.entries()).map(([c,l])=>({name:c,value:l}))}catch{return[]}}return{requestInterceptor:i=>{i.store.set(e,ee())},responseInterceptor:i=>{if(!i.response)return;let a=i.store.get(e)??i.startedAt,c=ee()-a,l=i.response.headers["content-type"]??i.response.headers["Content-Type"]??"application/octet-stream",u=i.response.body,f=u instanceof Uint8Array?u.byteLength:typeof u=="string"?u.length:0;r.push({startedDateTime:new Date(Date.now()-c).toISOString(),time:c,request:{method:i.request.method.toUpperCase(),url:i.request.url,httpVersion:"HTTP/1.1",headers:t(i.request.headers),queryString:n(i.request.url),bodySize:Kn(i.request.body)},response:{status:i.response.status,statusText:i.response.statusText,httpVersion:"HTTP/1.1",headers:t(i.response.headers),content:{size:f,mimeType:l,...typeof u=="string"?{text:u}:{}},bodySize:f,redirectURL:i.response.headers.location??""},timings:{send:0,wait:Math.floor(c*.9),receive:Math.floor(c*.1)}})},getHAR:()=>({version:"1.2",creator:{name:"kinetex",version:"0.0.3"},entries:[...r]}),clearHAR:()=>{r.length=0}}}function Wn(){let r=Symbol("metricsStart"),e=0,t=0,n=0,s={"2xx":0,"3xx":0,"4xx":0,"5xx":0},o=1e4,i=[],a=d=>{d.store.set(r,ee()),e++,d.attempt>1&&n++},c=d=>{if(!d.response)return;let g=d.store.get(r);if(g!==void 0){let y=ee()-g;i.length>=o&&i.shift(),i.push(y)}let m=`${Math.floor(d.response.status/100)}xx`;if(m in s){let y=s;y[m]=(y[m]??0)+1}},l=()=>{t++};function u(d,g){if(d.length===0)return 0;let m=Math.ceil(g/100*d.length)-1,y=Math.min(Math.max(0,m),d.length-1);return d[y]}return{requestInterceptor:a,responseInterceptor:c,errorInterceptor:l,snapshot:()=>{let d=[...i].sort((m,y)=>m-y),g=d.length?d.reduce((m,y)=>m+y,0)/d.length:0;return{totalRequests:e,totalErrors:t,totalRetries:n,statusBuckets:{...s},avgDurationMs:Math.round(g),p50DurationMs:u(d,50),p95DurationMs:u(d,95),p99DurationMs:u(d,99)}},reset:()=>{e=0,t=0,n=0;for(let d of Object.keys(s))s[d]=0;i.length=0}}}function ee(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Hi(r){return new Promise(e=>setTimeout(e,r))}function Kn(r){return r?typeof r=="string"?r.length:r instanceof Uint8Array||r instanceof ArrayBuffer?r.byteLength:-1:0}function ji(r={}){let e=new zt,t=jn(r.timeout);e.useRequest(t.requestInterceptor,{priority:-100,id:"timeout-req"}),e.useResponse(t.responseInterceptor,{priority:-100,id:"timeout-res"}),e.useError(t.errorInterceptor,{priority:-100,id:"timeout-err"}),r.rateLimit&&e.useRequest(qt(r.rateLimit),{priority:-90,id:"ratelimit"});let n=Bn();e.useRequest(n.requestInterceptor,{priority:-80,id:"dedupe-req"}),e.useResponse(n.responseInterceptor,{priority:-80,id:"dedupe-res"}),e.useError(n.errorInterceptor,{priority:-80,id:"dedupe-err"});let s=qn(r.cache);e.useRequest(s.requestInterceptor,{priority:-70,id:"cache-req"}),e.useResponse(s.responseInterceptor,{priority:-70,id:"cache-res"});let o=null;r.auth&&(o=Hn(r.auth),e.useRequest(o.requestInterceptor,{priority:-50,id:"auth-req"}),e.useResponse(o.responseInterceptor,{priority:-50,id:"auth-res"}));let i=$n(r.retry);e.useResponse(i.responseInterceptor,{priority:50,id:"retry-res"}),e.useError(i.errorInterceptor,{priority:50,id:"retry-err"});let a=zn(r.logging);e.useRequest(a.requestInterceptor,{priority:90,id:"log-req"}),e.useResponse(a.responseInterceptor,{priority:90,id:"log-res"}),e.useError(a.errorInterceptor,{priority:90,id:"log-err"});let c=Fn();e.useRequest(c.requestInterceptor,{priority:95,id:"har-req"}),e.useResponse(c.responseInterceptor,{priority:95,id:"har-res"});let l=Wn();return e.useRequest(l.requestInterceptor,{priority:100,id:"metrics-req"}),e.useResponse(l.responseInterceptor,{priority:100,id:"metrics-res"}),e.useError(l.errorInterceptor,{priority:100,id:"metrics-err"}),{manager:e,retry:i,auth:o,timeout:{id:t.id},logging:a,cache:s,dedupe:n,har:c,metrics:l}}Ne();function zi(r){return()=>Promise.resolve(r)}function qi(){return()=>{let r=Vn("AWS_ACCESS_KEY_ID"),e=Vn("AWS_SECRET_ACCESS_KEY"),t=Vn("AWS_SESSION_TOKEN");return!r||!e?Promise.reject(new Z("AWS credentials not found in environment. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.")):Promise.resolve({accessKeyId:r,secretAccessKey:e,...t!==void 0?{sessionToken:t}:{}})}}function Bi(...r){return async()=>{let e=[];for(let t of r)try{return await t()}catch(n){e.push(n instanceof Error?n:new Error(String(n)))}throw new Z(`All credential providers failed:
|
|
75
75
|
${e.map(t=>` - ${t.message}`).join(`
|
|
76
|
-
`)}`)}}function
|
|
77
|
-
`)[0]?.trim();if(!a)throw new
|
|
76
|
+
`)}`)}}function Gn(r,e=300*1e3){let t=null,n=null;return()=>{let s=Date.now();return t&&(!t.expiration||new Date(t.expiration).getTime()-s>e)?Promise.resolve(t):n||(n=r().then(o=>(t=o,n=null,o),o=>{throw n=null,o}),n)}}var Rl=new Set(["http://169.254.169.254","http://169.254.170.2","http://fd00:ec2::254"]);function kl(r){try{let e=new URL(r),t=e.hostname;t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));let n=`${e.protocol}//${t}`;return Rl.has(n)}catch{return!1}}function Fi(r={}){let e=r.endpoint??"http://169.254.169.254",t=r.timeout??5e3;if(!kl(e))throw new Error(`Invalid IMDS endpoint: ${e}. Only AWS metadata service endpoints are allowed.`);return Gn(async()=>{let n=await Jn(`${e}/latest/api/token`,{method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}},t);if(!n.ok)throw new Z(`IMDS token fetch failed: ${n.status}`);let s=await n.text(),o=await Jn(`${e}/latest/meta-data/iam/security-credentials/`,{headers:{"x-aws-ec2-metadata-token":s}},t);if(!o.ok)throw new Z(`IMDS role fetch failed: ${o.status}`);let a=(await o.text()).trim().split(`
|
|
77
|
+
`)[0]?.trim();if(!a)throw new Z("No IAM role found in IMDS response");let c=await Jn(`${e}/latest/meta-data/iam/security-credentials/${a}`,{headers:{"x-aws-ec2-metadata-token":s}},t);if(!c.ok)throw new Z(`IMDS credentials fetch failed: ${c.status}`);let l=await c.json();return{accessKeyId:l.AccessKeyId,secretAccessKey:l.SecretAccessKey,sessionToken:l.Token,expiration:l.Expiration}})}function Bt(r){return r.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,"")}function ut(r){return r.toISOString().slice(0,10).replace(/-/g,"")}function Rr(r){if(r.signingDate){let t=r.signingDate instanceof Date?r.signingDate:new Date(r.signingDate);return r.clockSkewSecs?new Date(t.getTime()+r.clockSkewSecs*1e3):t}let e=new Date;return r.clockSkewSecs?new Date(e.getTime()+r.clockSkewSecs*1e3):e}async function pe(r,e){let t=new TextEncoder,n=typeof r=="string"?t.encode(r):r,s=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),o=await crypto.subtle.importKey("raw",s,{name:"HMAC",hash:"SHA-256"},!1,["sign"]),i=await crypto.subtle.sign("HMAC",o,t.encode(e));return new Uint8Array(i)}async function Xn(r){let e=new TextEncoder,t=typeof r=="string"?e.encode(r):r,n=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),s=await crypto.subtle.digest("SHA-256",n);return ht(new Uint8Array(s))}function ht(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}var Al=new Set(["user-agent","x-forwarded-for","x-forwarded-host","x-forwarded-proto","accept-encoding","connection","expect","transfer-encoding"]),Cl=new Set(["host","content-type","content-md5"]);function Yn(r,e=!0){let t=encodeURIComponent(r).replace(/[!'()*]/g,n=>"%"+n.charCodeAt(0).toString(16).toUpperCase());return e?t.replace(/%/g,"%25").replace(/%2525/g,"%25"):t}function vl(r,e){if(!r||r==="/")return"/";let n=r.split("/").map(i=>i===""||i==="."||i===".."?i:Yn(decodeURIComponent(i.replace(/\+/g," ")),e)),s=[];for(let i of n)if(i!=="."){if(i===".."){s.pop();continue}s.push(i)}let o=s.join("/");return o.startsWith("/")?o:"/"+o}function Pl(r){let e=[];for(let[t,n]of r.entries())e.push([encodeURIComponent(t).replace(/[!'()*]/g,s=>"%"+s.charCodeAt(0).toString(16).toUpperCase()),encodeURIComponent(n).replace(/[!'()*]/g,s=>"%"+s.charCodeAt(0).toString(16).toUpperCase())]);return e.sort(([t,n],[s,o])=>t<s?-1:t>s?1:n<o?-1:n>o?1:0),e.map(([t,n])=>`${t}=${n}`).join("&")}function Il(r,e){let t=new Set([...Al,...e.map(a=>a.toLowerCase())]),n=[];for(let[a,c]of Object.entries(r)){let l=a.toLowerCase();if(t.has(l)&&!Cl.has(l))continue;let u=c.trim().replace(/\s+/g," ");n.push([l,u])}n.sort(([a],[c])=>a<c?-1:a>c?1:0);let s=new Map;for(let[a,c]of n){let l=s.get(a);s.set(a,l?`${l},${c}`:c)}let o=Array.from(s.entries()).map(([a,c])=>`${a}:${c}`).join(`
|
|
78
78
|
`)+`
|
|
79
|
-
`,i=Array.from(s.keys()).join(";");return{canonicalHeaders:o,signedHeaders:i}}async function
|
|
80
|
-
`),signedHeaders:
|
|
81
|
-
`)}async function
|
|
82
|
-
`),i=await
|
|
83
|
-
`,newState:{...e,previousSignature:a}}}async function
|
|
84
|
-
`),n=await
|
|
79
|
+
`,i=Array.from(s.keys()).join(";");return{canonicalHeaders:o,signedHeaders:i}}async function Qn(r,e,t,n,s,o,i){let a=r.toUpperCase(),c=vl(e.pathname,o),l=Pl(e.searchParams),u;s?u="UNSIGNED-PAYLOAD":n?u=await Xn(n):u="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";let{canonicalHeaders:f,signedHeaders:p}=Il(t,i);return{canonicalRequest:[a,c,l,f,p,u].join(`
|
|
80
|
+
`),signedHeaders:p,payloadHash:u}}async function ft(r,e,t,n){let s=new TextEncoder,o=s.encode("AWS4"),i=s.encode(r),a=new Uint8Array(o.length+i.length);a.set(o),a.set(i,o.length),i.fill(0);let c=await pe(a,e),l=await pe(c,t),u=await pe(l,n),f=await pe(u,"aws4_request");return a.fill(0),f}async function Wi(r,e,t){let n=await Xn(t);return["AWS4-HMAC-SHA256",r,e,n].join(`
|
|
81
|
+
`)}async function kr(r,e){let t=await Ar(e.credentials),n=Rr(e),s=Bt(n),o=ut(n),i=new URL(r.url),a={...r.headers,host:i.host,"x-amz-date":s};e.unsignedPayload&&(a["x-amz-content-sha256"]="UNSIGNED-PAYLOAD"),t.sessionToken&&(a["x-amz-security-token"]=t.sessionToken);let c=e.doubleEncodeUri!==!1,l=e.unsignedHeaders??[],{canonicalRequest:u,signedHeaders:f,payloadHash:p}=await Qn(r.method,i,a,r.body,e.unsignedPayload??!1,c,l);!a["x-amz-content-sha256"]&&!e.unsignedPayload&&(a["x-amz-content-sha256"]=p);let d=`${o}/${e.region}/${e.service}/aws4_request`,g=await Wi(s,d,u),m=await ft(t.secretAccessKey,o,e.region,e.service),y=await pe(m,g),b=ht(y),x=`AWS4-HMAC-SHA256 Credential=${t.accessKeyId}/${d}, SignedHeaders=${f}, Signature=${b}`;return{method:r.method,url:r.url,headers:{...a,authorization:x},body:r.body,authorization:x,amzDate:s,signature:b,canonicalRequest:u,stringToSign:g}}async function Zn(r,e,t={}){let n=await Ar(e.credentials),s=Rr(e),o=Bt(s),i=ut(s),a=t.expiresIn??3600,c=e.service==="s3"?604800:3600;(a<1||a>c)&&console.warn(`[aws-sigv4] presignRequest: expiresIn should be 1-${c} seconds for ${e.service}, got ${a}`);let l=new URL(r.url),u=`${i}/${e.region}/${e.service}/aws4_request`;if(l.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),l.searchParams.set("X-Amz-Credential",`${n.accessKeyId}/${u}`),l.searchParams.set("X-Amz-Date",o),l.searchParams.set("X-Amz-Expires",String(a)),n.sessionToken&&!t.omitSessionToken&&l.searchParams.set("X-Amz-Security-Token",n.sessionToken),t.extraParams)for(let[R,A]of Object.entries(t.extraParams))l.searchParams.set(R,A);let f={...r.headers,host:l.host},p=e.unsignedHeaders??[],{canonicalRequest:d,signedHeaders:g}=await Qn(r.method,l,f,null,!0,e.doubleEncodeUri!==!1,p);l.searchParams.set("X-Amz-SignedHeaders",g);let{canonicalRequest:m}=await Qn(r.method,l,f,null,!0,e.doubleEncodeUri!==!1,p),y=await Wi(o,u,m),b=await ft(n.secretAccessKey,i,e.region,e.service),x=await pe(b,y),E=ht(x);return l.searchParams.set("X-Amz-Signature",E),l.toString()}async function es(r,e){let t={...r,body:null};t.headers={...t.headers,"x-amz-content-sha256":"STREAMING-AWS4-HMAC-SHA256-PAYLOAD","content-encoding":"aws-chunked"};let n=await kr(t,{...e,unsignedPayload:!1}),s=await Ar(e.credentials),o=Rr(e),i=ut(o),a=Bt(o),c=await ft(s.secretAccessKey,i,e.region,e.service),l=`${i}/${e.region}/${e.service}/aws4_request`;return{signedRequest:n,state:{previousSignature:n.signature,signingKey:c,scope:l,signingDate:a}}}async function Ki(r,e){let t=typeof r=="string"?new TextEncoder().encode(r):r,n=await Xn(t),o=["AWS4-HMAC-SHA256-PAYLOAD",e.signingDate,e.scope,e.previousSignature,"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",n].join(`
|
|
82
|
+
`),i=await pe(e.signingKey,o),a=ht(i);return{chunkHeader:`${t.byteLength.toString(16)};chunk-signature=${a}\r
|
|
83
|
+
`,newState:{...e,previousSignature:a}}}async function Vi(r){let e="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",t=["AWS4-HMAC-SHA256-PAYLOAD",r.signingDate,r.scope,r.previousSignature,e,e].join(`
|
|
84
|
+
`),n=await pe(r.signingKey,t);return`0;chunk-signature=${ht(n)}\r
|
|
85
85
|
\r
|
|
86
|
-
`}async function Xn(r,e){let t=await kr(e.credentials),n=Er(e),s=lt(n),o=`${s}/${e.region}/${e.service}/aws4_request`,i=`${t.accessKeyId}/${o}`,a=JSON.stringify(r),c=btoa(a),l=await ht(t.secretAccessKey,s,e.region,e.service),u=await de(l,c),f=ut(u),d={policy:c,signature:f,credential:i,date:s};return t.sessionToken&&(d.securityToken=t.sessionToken),d}function Yn(r){let e=r.date??r.Date;if(!e)return 0;let t=new Date(e).getTime();return isNaN(t)?0:Math.round((t-Date.now())/1e3)}function Zn(r,e){return r!==403&&r!==400?!1:e.includes("RequestTimeTooSkewed")||e.includes("RequestExpired")||e.includes("InvalidSignatureException")||e.includes("AuthFailure")||e.includes("SignatureDoesNotMatch")}var oe=class{constructor(e){h(this,"config");h(this,"clockSkewSecs",0);this.config=e}async sign(e){return await Rr(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}async presign(e,t){return await Qn(e,{...this.config,clockSkewSecs:this.clockSkewSecs},t)}async signPostPolicy(e){return await Xn(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}async initChunked(e){return await Gn(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}updateClockSkew(e){let t=Yn(e);t!==0&&(this.clockSkewSecs=t)}handleClockSkewError(e,t,n){return Zn(e,t)?(this.updateClockSkew(n),!0):!1}};async function kr(r){return await(typeof r=="function"?r():Promise.resolve(r))}function Bn(r){let e=globalThis.Deno;if(typeof e<"u")try{return e.env.get(r)}catch{}try{return globalThis.process?.env?.[r]}catch{}}async function Fn(r,e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let o=e.signal&&typeof AbortSignal<"u"&&"any"in AbortSignal?AbortSignal.any([e.signal,n.signal]):n.signal,i=await fetch(r,{...e,signal:o});return clearTimeout(s),i}catch(o){throw n.signal.aborted?new re(t):o}finally{clearTimeout(s)}}function zi(r){return new oe({credentials:r.credentials,region:r.region,service:"s3",doubleEncodeUri:!1,unsignedPayload:r.unsignedPayload??!1})}function Bi(r){return new oe({credentials:r.credentials,region:r.region,service:"execute-api"})}function Fi(r){return new oe({credentials:r.credentials,region:r.region,service:"sts"})}function Wi(r){return new oe({credentials:r.credentials,region:r.region,service:"dynamodb"})}fe();function Tl(r){let e=[];for(let u=0;u<r.length;u++){let f=r.charCodeAt(u);if(f<128)e.push(f);else if(f<2048)e.push(192|f>>6,128|f&63);else if(f<55296||f>=57344)e.push(224|f>>12,128|f>>6&63,128|f&63);else{u++;let d=r.charCodeAt(u),p=65536+((f&1023)<<10|d&1023);e.push(240|p>>18,128|p>>12&63,128|p>>6&63,128|p&63)}}let t=e.length*8;for(e.push(128);e.length*8%512!==448;)e.push(0);for(let u=0;u<4;u++)e.push(t>>>u*8&255);for(let u=4;u<8;u++)e.push(0);let n=[3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],s=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],o=1732584193,i=4023233417,a=2562383102,c=271733878;for(let u=0;u<e.length;u+=64){let f=[];for(let y=0;y<16;y++){let b=e[u+y*4],x=e[u+y*4+1],S=e[u+y*4+2],R=e[u+y*4+3];f[y]=(b|x<<8|S<<16|R<<24)>>>0}let d=o,p=i,g=a,m=c;for(let y=0;y<64;y++){let b,x;y<16?(b=p&g|~p&m,x=y):y<32?(b=m&p|~m&g,x=(5*y+1)%16):y<48?(b=p^g^m,x=(3*y+5)%16):(b=g^(p|~m),x=7*y%16),b=b+d+n[y]+f[x]>>>0,d=m,m=g,g=p,p=p+(b<<s[y]|b>>>32-s[y])>>>0}o=o+d>>>0,i=i+p>>>0,a=a+g>>>0,c=c+m>>>0}function l(u){let f="";for(let d=0;d<4;d++)f+=(u>>>d*8&255).toString(16).padStart(2,"0");return f}return l(o)+l(i)+l(a)+l(c)}function es(r){let e={algorithm:"MD5"},t=r.replace(/^Digest\s+/i,"").trim(),n=/(\w+)\s*=\s*(?:"([^"]*)"|([^,\s]+))/g,s;for(;(s=n.exec(t))!==null;){let o=s[1].toLowerCase(),i=s[2]??s[3];switch(o){case"realm":e.realm=i;break;case"nonce":e.nonce=i;break;case"opaque":e.opaque=i;break;case"algorithm":e.algorithm=i.toUpperCase();break;case"qop":e.qop=i;break;case"domain":e.domain=i;break;case"charset":e.charset=i;break;case"userhash":e.userhash=i==="true";break;case"stale":e.stale=i==="true";break}}if(!e.realm)throw new Error("Digest challenge missing 'realm'");if(!e.nonce)throw new Error("Digest challenge missing 'nonce'");return e}async function El(r){let e=new TextEncoder,t=await crypto.subtle.digest("SHA-256",e.encode(r)),n=new Uint8Array(t);return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}function Rl(r){let e=[0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n],t=[0x22312194fc2bf72cn,0x9f555fa3c84c64c2n,0x2393b86b6f53b151n,0x963877195940eabdn,0x96283ee2a88effe3n,0xbe5e1e2553863992n,0x2b0199fc2c85b8aan,0x0eb72ddc81c52ca2n],n=[];for(let c=0;c<r.length;c++){let l=r.charCodeAt(c);if(l<128)n.push(l);else if(l<2048)n.push(192|l>>6,128|l&63);else if(l<55296||l>=57344)n.push(224|l>>12,128|l>>6&63,128|l&63);else{c++;let u=r.charCodeAt(c),f=65536+((l&1023)<<10|u&1023);n.push(240|f>>18,128|f>>12&63,128|f>>6&63,128|f&63)}}let s=BigInt(n.length*8);for(n.push(128);n.length*8%1024!==896;)n.push(0);for(let c=15;c>=0;c--)n.push(Number(s>>BigInt(c*8)&0xffn));function o(c,l){return c>>l|c<<64n-l&0xffffffffffffffffn}let i=t.slice();for(let c=0;c<n.length;c+=128){let l=new Array(80);for(let x=0;x<16;x++){let S=0n;for(let R=0;R<8;R++)S=S<<8n|BigInt(n[c+x*8+R]);l[x]=S}for(let x=16;x<80;x++){let S=o(l[x-15],1n)^o(l[x-15],8n)^l[x-15]>>7n,R=o(l[x-2],19n)^o(l[x-2],61n)^l[x-2]>>6n;l[x]=l[x-16]+S+l[x-7]+R&0xffffffffffffffffn}let u=i[0],f=i[1],d=i[2],p=i[3],g=i[4],m=i[5],y=i[6],b=i[7];for(let x=0;x<80;x++){let S=o(g,14n)^o(g,18n)^o(g,41n),R=g&m^~g&y,C=b+S+R+e[x]+l[x]&0xffffffffffffffffn,T=o(u,28n)^o(u,34n)^o(u,39n),A=u&f^u&d^f&d,M=T+A&0xffffffffffffffffn;b=y,y=m,m=g,g=p+C&0xffffffffffffffffn,p=d,d=f,f=u,u=C+M&0xffffffffffffffffn}i=[i[0]+u&0xffffffffffffffffn,i[1]+f&0xffffffffffffffffn,i[2]+d&0xffffffffffffffffn,i[3]+p&0xffffffffffffffffn,i[4]+g&0xffffffffffffffffn,i[5]+m&0xffffffffffffffffn,i[6]+y&0xffffffffffffffffn,i[7]+b&0xffffffffffffffffn]}let a="";for(let c=0;c<4;c++)a+=i[c].toString(16).padStart(16,"0");return a}async function ts(r,e,t,n,s,o,i){let a=r.qop||"",c=r.nonce,l=r.realm,u=o||nt(5),f=i||"00000001",d=kl(r.algorithm);async function p(x){return d==="MD5"?Tl(x):d==="SHA-512-256"?Rl(x):await El(x)}let g=await p(`${e}:${l}:${t}`),m=await p(`${n}:${s}`),y,b=a.split(/\s*,\s*/).filter(Boolean);return b.includes("auth")||b.includes("auth-int")?y=await p(`${g}:${c}:${f}:${u}:${b[0]}:${m}`):y=await p(`${g}:${c}:${m}`),y}function kl(r){let e=r.toUpperCase().replace(/-/g,"");return e==="SHA256"?"SHA-256":e==="SHA512256"?"SHA-512-256":"MD5"}function rs(r,e,t,n,s,o){let i=[],a=s||nt(5),c=o||"00000001";return i.push(`username="${e}"`),i.push(`realm="${r.realm}"`),i.push(`nonce="${r.nonce}"`),i.push(`uri="${n}"`),i.push(`response="${t}"`),r.opaque&&i.push(`opaque="${r.opaque}"`),r.algorithm&&r.algorithm!=="MD5"&&i.push(`algorithm=${r.algorithm}`),r.qop&&(i.push(`qop=${r.qop.split(/\s*,\s*/)[0]}`),i.push(`nc=${c}`),i.push(`cnonce="${a}"`)),`Digest ${i.join(", ")}`}async function Ar(r,e,t,n,s){let o=es(r),i=nt(5),a="00000001",c=await ts(o,e,t,n,s,i,a);return rs(o,e,c,s,i,a)}Xt();var Cu={maxRetries:3,baseDelayMs:300,maxDelayMs:3e4,jitter:.3,statuses:[408,429,500,502,503,504],onNetworkError:!0,onTimeout:!1,methods:["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]},Co=class{constructor(){h(this,"_req",new Map);h(this,"_res",new Map);h(this,"_err",new Map);h(this,"_seq",0)}get request(){return Array.from(this._req.values())}get response(){return Array.from(this._res.values())}get error(){return Array.from(this._err.values())}addRequest(e){let t=++this._seq;return this._req.set(t,e),()=>{this._req.delete(t)}}addResponse(e){let t=++this._seq;return this._res.set(t,e),()=>{this._res.delete(t)}}addError(e){let t=++this._seq;return this._err.set(t,e),()=>{this._err.delete(t)}}clear(){this._req.clear(),this._res.clear(),this._err.clear()}};function vu(r){if(r){let n=r.spanContext(),s=n.traceFlags.toString(16).padStart(2,"0");return{traceparent:`00-${n.traceId}-${n.spanId}-${s}`,traceId:n.traceId,spanId:n.spanId}}let e=vo(32),t=vo(16);return{traceparent:`00-${e}-${t}-01`,traceId:e,spanId:t}}function vo(r){return nt(r/2)}var Po=class{constructor(e=1e4){h(this,"_buf",new Map);h(this,"_head",0);h(this,"_tail",0);h(this,"maxEntries");this.maxEntries=e}get entries(){return Array.from(this._buf.values())}record(e,t,n){let s=t.durationMs,o=0,i=s,a=0;try{if(typeof performance<"u"&&typeof performance.getEntriesByType=="function"){let u=performance.getEntriesByType("resource").filter(f=>f.name===t.url).pop();u&&u.requestStart>0&&(o=Math.max(0,u.responseStart-u.requestStart),a=Math.max(0,u.responseEnd-u.responseStart),i=Math.max(0,s-o-a))}}catch{}let c={startedDateTime:new Date(n).toISOString(),time:s,request:{method:e.method,url:e.url,httpVersion:t.httpVersion,headers:Object.entries(e.headers).map(([l,u])=>({name:l,value:u})),queryString:(()=>{try{return Array.from(new URL(e.url).searchParams.entries()).map(([l,u])=>({name:l,value:u}))}catch{return[]}})(),bodySize:e.body?typeof e.body=="string"?new TextEncoder().encode(e.body).byteLength:e.body instanceof Uint8Array||e.body instanceof ArrayBuffer?e.body.byteLength:-1:0},response:{status:t.status,statusText:t.statusText,httpVersion:t.httpVersion,headers:Object.entries(t.headers).map(([l,u])=>({name:l,value:u})),content:{size:t.rawBody?.byteLength??0,mimeType:t.headers["content-type"]??"application/octet-stream",...typeof t.data=="string"?{text:t.data}:{}},redirectURL:t.headers.location??"",bodySize:t.rawBody?.byteLength??0},timings:{send:o,wait:i,receive:a},cache:{}};this._buf.set(this._tail++,c),this._buf.size>this.maxEntries&&this._buf.delete(this._head++)}getHAR(){return{version:"1.2",creator:{name:"kinetex",version:"1.0.0",comment:`runtime:${pe}`},entries:[...this.entries]}}clear(){this._buf.clear(),this._head=0,this._tail=0}get count(){return this._buf.size}};async function Ha(r,e){let t={...r.headers};switch(e.type){case"bearer":{let n=typeof e.token=="function"?await e.token():e.token;t.authorization=`Bearer ${n}`;break}case"basic":{let n=new TextEncoder,s=n.encode(e.username),o=n.encode(e.password),i=s.length+1+o.length,a=new Uint8Array(i);a.set(s),a.set(n.encode(":"),s.length),a.set(o,s.length+1);let c=Ut(a);t.authorization=`Basic ${c}`,s.fill(0),o.fill(0),a.fill(0);break}case"apikey":{let n=typeof e.key=="function"?await e.key():e.key;t[e.header.toLowerCase()]=n;break}case"digest":break;case"custom":{let n=e.apply(r);if(!n)throw new Error("Custom auth 'apply' must return a KinetexRequest");return n}default:{let n=e;throw new Error(`Unknown auth type: ${n.type}`)}}return{...r,headers:t}}function sr(r,e,t){let o;if(/^https?:\/\//i.test(e))o=e;else{let i=r??"";try{let a=i.replace(/\/$/,""),c=e.startsWith("/")?e.slice(1):e;o=new URL(c,a+"/").href}catch{let a=i.endsWith("/")?i:i+"/",c=e.startsWith("/")?e.slice(1):e;o=a+c}}if(!t||Object.keys(t).length===0){if(!rt(o))throw new _(`URL "${o}" failed safety check \u2014 blocked private/loopback address or forbidden scheme`,"EVALIDATION");return o}try{let i=new URL(o),a=0;for(let[l,u]of Object.entries(t)){if(u==null)continue;let f=String(u);if(Array.isArray(u)){for(let d of u)if(d!=null){if(a++,a>100)throw new _(`Query parameter count ${a} exceeds limit of 100`,"EVALIDATION");i.searchParams.append(l,String(d))}}else{if(a++,a>100)throw new _(`Query parameter count ${a} exceeds limit of 100`,"EVALIDATION");i.searchParams.set(l,f)}}let c=i.toString();if(c.length>8192)throw new _(`URL length ${c.length} bytes exceeds limit of 8192 bytes`,"EVALIDATION");if(!rt(c))throw new _(`URL "${c}" failed safety check \u2014 blocked private/loopback address or forbidden scheme`,"EVALIDATION");return c}catch(i){if(i instanceof _)throw i;o.includes("?")?o+="&":o+="?";let a=[],c=0;for(let[u,f]of Object.entries(t??{}))if(f!=null)if(Array.isArray(f)){for(let d of f)if(d!=null){if(c++,c>100)throw new _(`Query parameter count ${c} exceeds limit of 100`,"EVALIDATION");a.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(d))}`)}}else{if(c++,c>100)throw new _(`Query parameter count ${c} exceeds limit of 100`,"EVALIDATION");a.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(f))}`)}let l=o+a.join("&");if(l.length>8192)throw new _(`URL length ${l.length} bytes exceeds limit of 8192 bytes`,"EVALIDATION");return l}}function Pt(...r){let e=Object.create(null);for(let t of r){if(!t)continue;let n=Object.keys(t);for(let s of n){if(s==="__proto__"||s==="constructor"||s==="prototype")continue;if(!et(s))throw new _(`Invalid header name: "${s}" \u2014 contains forbidden characters`,"EVALIDATION");let o=t[s];if(o==null)continue;let i=Array.isArray(o)?o.map(String).join(", "):String(o);if(!tt(i))throw new _(`Invalid header value for ${s}: contains forbidden characters`,"EVALIDATION");e[s.toLowerCase()]=i}}return e}function ja(r,e){if(e.attempt>r.maxRetries||!r.methods.includes(e.request.method))return!1;if(r.shouldRetry)return r.shouldRetry(e);if(e.error){let t=e.error,n=t.code;switch(n){case"EHTTPSTATUS":return r.statuses.includes(t.status??0);case"ETIMEOUT":return r.onTimeout===!0;case"ENETWORK":return r.onNetworkError;case"EABORT":return!1;case"ESIZELIMIT":return!1;case"EPARSE":return!1;case"EVALIDATION":return!1;case"EAUTH":return!1;case"EPROXY":return!1;case"EREDIRECT":return!1;case"EUNKNOWN":return!1;default:return!1}}return e.response?r.statuses.includes(e.response.status):!1}function ko(r,e,t){if(t!==null)return Math.min(t,r.maxDelayMs);let n=Math.min(e,31),s=r.baseDelayMs*Math.pow(2,n-1);if(!isFinite(s)||s>r.maxDelayMs)return r.maxDelayMs;let o=Math.min(s,r.maxDelayMs);return Math.floor(o+o*r.jitter*Math.random())}function Pu(r){let e=r["retry-after"];if(!e)return null;if(/^\d+$/.test(e.trim())){let n=parseInt(e,10);return!isFinite(n)||n<0?null:Math.min(n,86400)*1e3}let t=Date.parse(e);return isNaN(t)?null:Math.max(0,Math.min(t-Date.now(),864e5))}var It=class r{constructor(e={}){h(this,"cfg");h(this,"transport");h(this,"interceptors");h(this,"harRecorder");h(this,"retryConfig");h(this,"_cache",null);h(this,"_cookieJar",null);h(this,"_logger",null);h(this,"_cacheInitLock",null);h(this,"_cookieJarInitLock",null);h(this,"_loggerInitLock",null);h(this,"_otelTracer",null);h(this,"_dedup",null);h(this,"_circuitBreakers",null);h(this,"_circuitBreakerKeyFn",null);h(this,"_wsClients",new Set);if(this.cfg=e,this.interceptors=new Co,this.harRecorder=e.har===!0?new Po:null,this.retryConfig={...Cu,...e.retry},e.circuitBreakerKeyFn&&(this._circuitBreakerKeyFn=e.circuitBreakerKeyFn),e.rateLimit){let t=qt(e.rateLimit);this.interceptors.addRequest(t)}if(e.awsSigning){let t=new oe(e.awsSigning);this.interceptors.addRequest(async n=>{let s=n.request,o=null;(s.body instanceof Uint8Array||typeof s.body=="string")&&(o=s.body);let i=await t.sign({method:s.method,url:s.url,headers:{...s.headers},body:o});n.request={...s,headers:i.headers}})}if(this.transport=Jt(e.fetch,e.httpVersion!=="HTTP/1.1",void 0,e.strictHeaders?{strict:!0}:void 0),e.interceptors&&(e.interceptors.request?.forEach(t=>this.interceptors.addRequest(t)),e.interceptors.response?.forEach(t=>this.interceptors.addResponse(t)),e.interceptors.error?.forEach(t=>this.interceptors.addError(t))),e.auth?.type==="digest"){let t=e.auth;this.interceptors.addResponse(async n=>{if(!n.response||n.response.status!==401)return;let s=n.response.headers["www-authenticate"];if(!s||!s.toLowerCase().startsWith("digest")||n.request.meta.__digestRetried)return;let o=n.request.method,i=new URL(n.request.url).pathname+new URL(n.request.url).search,a=await Ar(s,t.username,t.password,o,i);return{...n.request,headers:{...n.request.headers,authorization:a},meta:{...n.request.meta,__digestRetried:!0}}})}}useRequest(e){return this.interceptors.addRequest(e)}attachHookRegistry(e){let t=this.useRequest(async o=>{let i={url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta},a={request:i,response:null,error:null,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta},c=await e.runBeforeRequest(i,a);c!==i&&(o.request={...o.request,...c})}),n=this.useResponse(async o=>{if(!o.response)return;let i={status:o.response.status,statusText:o.response.statusText,headers:o.response.headers,body:o.response.rawBody??null,request:{url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta}},a={request:i.request,response:i,error:null,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta};await e.runAfterResponse(i,a)}),s=this.useError(async o=>{if(!o.error)return;let i={error:o.error,request:{url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta},response:null,attempt:o.attempt},a={request:i.request,response:null,error:o.error,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta};await e.runOnError(i,a)});return()=>{t(),n(),s()}}useResponse(e){return this.interceptors.addResponse(e)}useError(e){return this.interceptors.addError(e)}getHAR(){if(!this.harRecorder)throw new _("HAR recording not enabled. Pass `har: true` in config.","EUNKNOWN");return this.harRecorder.getHAR()}clearHAR(){this.harRecorder?.clear()}async getCache(){if(this._cache)return this._cache;if(!this.cfg.cache)return null;if(this._cacheInitLock)return await this._cacheInitLock,this._cache;let e=()=>{};this._cacheInitLock=new Promise(t=>{e=t});try{let{HTTPCache:t}=await Promise.resolve().then(()=>($t(),vi));return this._cache=new t(this.cfg.cache),this._cache}finally{e(),this._cacheInitLock=null}}async getCookieJar(){if(this._cookieJar)return this._cookieJar;if(!this.cfg.cookieJar)return null;if(this._cookieJarInitLock)return await this._cookieJarInitLock,this._cookieJar;if(this.cfg.cookieJar instanceof Object&&"setCookie"in this.cfg.cookieJar)return this._cookieJar=this.cfg.cookieJar,this._cookieJar;let e=()=>{};this._cookieJarInitLock=new Promise(t=>{e=t});try{let{CookieJar:t}=await Promise.resolve().then(()=>(Fs(),Ra));return this._cookieJar=new t,this._cookieJar}finally{e(),this._cookieJarInitLock=null}}async getLogger(){if(this._logger)return this._logger;if(!this.cfg.logger)return null;if(this._loggerInitLock)return await this._loggerInitLock,this._logger;let e=()=>{};this._loggerInitLock=new Promise(t=>{e=t});try{let{createLogger:t}=await Promise.resolve().then(()=>(Zr(),Ca));return this._logger=t(this.cfg.logger),this._logger}finally{e(),this._loggerInitLock=null}}extend(e){let t=this.cfg.interceptors?.request??[],n=this.cfg.interceptors?.response??[],s=this.cfg.interceptors?.error??[],o=e.interceptors?.request??[],i=e.interceptors?.response??[],a=e.interceptors?.error??[],c=new r({...this.cfg,...e,headers:Pt(this.cfg.headers,e.headers),params:{...this.cfg.params,...e.params},interceptors:{request:[...t,...o],response:[...n,...i],error:[...s,...a]}}),l=new Set([...t,...o]),u=new Set([...n,...i]),f=new Set([...s,...a]);for(let d of this.interceptors.request)l.has(d)||c.useRequest(d);for(let d of this.interceptors.response)u.has(d)||c.useResponse(d);for(let d of this.interceptors.error)f.has(d)||c.useError(d);return this._circuitBreakers&&!c._circuitBreakers&&(c._circuitBreakers=this._circuitBreakers),this._dedup&&!c._dedup&&(c._dedup=this._dedup),this._otelTracer&&!c._otelTracer&&(c._otelTracer=this._otelTracer),c}setTracer(e){return this._otelTracer=e,this}enableDedup(e){return this._dedup=new ve(e),this}disableDedup(){return this._dedup=null,this}get dedupMetrics(){return this._dedup?{hits:this._dedup.hits,misses:this._dedup.misses,inFlightCount:this._dedup.inFlightCount}:null}enableCircuitBreaker(e){return this._circuitBreakers=new Pe(e),this}disableCircuitBreaker(){return this._circuitBreakers=null,this}tripCircuit(e){return this._circuitBreakers?.trip(e),this}resetCircuit(e){return this._circuitBreakers?.reset(e),this}get circuitSnapshots(){return this._circuitBreakers?.snapshots()??{}}async ws(e,t={}){let n=sr(this.cfg.baseURL,e,this.cfg.params),s=Pt(this.cfg.headers,t.headers),o={},i=this.cfg.auth;if(i){if(i.type==="bearer"){let p=typeof i.token=="function"?await i.token():i.token;o.authorization=`Bearer ${p}`}else if(i.type==="basic"){let p=new TextEncoder,g=p.encode(i.username),m=p.encode(i.password),y=new Uint8Array(g.length+1+m.length);y.set(g),y[g.length]=58,y.set(m,g.length+1);let b=Ut(y);y.fill(0),g.fill(0),m.fill(0),o.authorization=`Basic ${b}`}else if(i.type==="apikey"){let p=typeof i.key=="function"?await i.key():i.key;o[i.header.toLowerCase()]=typeof p=="string"?p:await p}}let a=await this.getCookieJar();if(a){let p=a.getCookieHeader({url:n,http:!1});p&&(s.cookie=p)}try{let p=new URL(n);if(this.cfg.baseURL){let g=new URL(this.cfg.baseURL),m=p.protocol==="wss:",y=g.protocol==="https:";if(m!==y||p.host!==g.host)throw new _(`WebSocket origin ${p.origin} does not match baseURL origin ${g.origin}`,"EVALIDATION")}}catch(p){throw p instanceof _?p:new _(`Invalid WebSocket URL: ${p}`,"EVALIDATION")}if(this._circuitBreakers){let p=this._circuitBreakerKeyFn?this._circuitBreakerKeyFn({url:n,method:"GET",headers:s,body:null,signal:null,meta:{}}):new URL(n).origin;if(this._circuitBreakers.get(p).state==="OPEN")throw new _(`Circuit breaker is open for WebSocket origin ${new URL(n).origin}`,"ENETWORK")}let c=this.cfg.ws,l={...c?.highWaterMark!==void 0?{highWaterMark:c.highWaterMark}:{},...c?.lowWaterMark!==void 0?{lowWaterMark:c.lowWaterMark}:{},...c?.maxSendRate!==void 0?{maxSendRate:c.maxSendRate}:{},...c?.keepRooms!==void 0?{keepRooms:c.keepRooms}:{},...t},u=l.onClose,f=(p,g,m)=>{m||this._wsClients.delete(d),u?.(p,g,m)},d=new Ie({url:n,headers:{...o,...s},...l,onClose:f});return this._wsClients.add(d),await d.connect().catch(p=>{throw this._wsClients.delete(d),p}),d}async send(e,t,n={}){let s=ln(),o=Date.now(),i=n.timeout!==void 0?n.timeout:this.cfg.timeout??3e4,a=n.retry===!1?!1:{...this.retryConfig,...n.retry??{}},c=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE","CONNECT"],l=t.toUpperCase();if(!c.includes(l))throw new _(`Invalid HTTP method '${t}'. Valid methods: ${c.join(", ")}`,"EVALIDATION");let u=sr(n.baseURL??this.cfg.baseURL,e,Iu(this.cfg.params,n.params));if(this.cfg.httpsOnly)try{let T=new URL(u);if(T.protocol!=="https:")throw new _(`HTTPS-only mode enabled but URL uses ${T.protocol}. Use HTTPS URLs only.`,"EVALIDATION")}catch(T){throw T instanceof _?T:new _(`Invalid URL: ${T}`,"EVALIDATION")}let f=n.maxRequestSize??this.cfg.maxRequestSize??0;if(f>0&&n.body){let T=0;if(typeof n.body=="string"?T=new TextEncoder().encode(n.body).byteLength:n.body instanceof Uint8Array||n.body instanceof ArrayBuffer?T=n.body.byteLength:n.body instanceof Blob?T=n.body.size:n.body instanceof FormData||n.body&&typeof n.body=="object"&&(T=JSON.stringify(n.body).length),T>f)throw new _(`Request body size ${T} bytes exceeds limit of ${f} bytes`,"EVALIDATION")}let d={url:u,method:t,headers:Pt(this.cfg.headers,n.headers),body:n.body??null,signal:n.signal??null,meta:{...n.meta},httpVersion:n.httpVersion??this.cfg.httpVersion??"HTTP/2"};d.body!==null&&typeof d.body=="object"&&!(d.body instanceof Uint8Array)&&!(d.body instanceof ArrayBuffer)&&!(d.body instanceof ReadableStream)&&!(d.body instanceof FormData)&&!(d.body instanceof URLSearchParams)&&!(d.body instanceof Blob)&&!d.headers["content-type"]&&(d={...d,headers:{...d.headers,"content-type":"application/json"},body:JSON.stringify(d.body)});let p=n.auth!==!1?n.auth??this.cfg.auth:void 0;p&&(d=await Ha(d,p)),this.cfg.transformRequest&&(d=await this.cfg.transformRequest(d));let g=await this.getCookieJar();if(g){let T=g.getCookieHeader({url:d.url,http:!0});T&&(d={...d,headers:{...d.headers,cookie:T}})}let m=null;if(this._otelTracer){m=this._otelTracer.startSpan(`HTTP ${d.method}`,{kind:3});let{traceparent:T,traceId:A,spanId:M}=vu(m);m.setAttribute("http.request.method",d.method),m.setAttribute("url.full",d.url);try{m.setAttribute("server.address",new URL(d.url).hostname)}catch{}d={...d,headers:{...d.headers,traceparent:T},meta:{...d.meta,traceId:A,spanId:M}}}else if(d.meta.traceId&&!d.headers.traceparent){let T=String(d.meta.traceId),A=vo(16);d={...d,headers:{...d.headers,traceparent:`00-${T}-${A}-01`},meta:{...d.meta,spanId:A}}}let y;if(this._circuitBreakerKeyFn)try{y=this._circuitBreakerKeyFn(d)}catch{y=d.url}else try{y=new URL(d.url).origin}catch{y=d.url}let b=()=>this._executeWithRetry(d,a,i,n,s,o),x=await Oe(d.headers??{}),S=`${d.method}:${d.url}${x?":"+x:""}`,R=this._dedup?()=>this._dedup.execute(d.method,S,b).then(T=>T):b,C=this._circuitBreakers?()=>this._circuitBreakers.execute(y,R).then(T=>T):R;try{let T=await C();return m&&(m.setAttribute("http.response.status_code",T.status),m.setStatus({code:T.status<400?1:2}),m.end()),T}catch(T){throw m&&(m.setStatus({code:2,message:T instanceof Error?T.message:String(T)}),T instanceof Error&&m.recordException(T),m.end()),T}}async _executeWithRetry(e,t,n,s,o,i){let a=0;for(;;){if(a++,e.signal?.aborted)throw Io();try{let c=await this._executeOnce(e,n,s,o,a,i,t);if(t&&a<=t.maxRetries){let l={request:e,response:c,error:null,attempt:a,maxRetries:t.maxRetries};if(t.shouldRetry?await t.shouldRetry(l):ja(t,l)){let f=ko(t,a,Pu(c.headers));await t.onRetry?.(l,f),await this.cfg.hooks?.onRetry?.reduce(async(d,p)=>{await d,await p(l)},Promise.resolve()),await Ao(f,e.signal);continue}}return c}catch(c){if(t&&a<=t.maxRetries){let u={request:e,response:null,error:c,attempt:a,maxRetries:t.maxRetries};if(t.shouldRetry?await t.shouldRetry(u):ja(t,u)){let d=ko(t,a,null);await t.onRetry?.(u,d),await Ao(d,e.signal);continue}}let l=await this._runErrorInterceptors(e,c,a,o);if(l)return l;if(s.onError){let u=c instanceof _?c:new _(String(c),"EUNKNOWN",{request:e,cause:c});throw s.onError(u),u}throw c}}}async _sendFollowingRedirects(e,t,n,s){let i={...e,redirect:"manual"},a=new Set;for(let c=0;c<=20;c++){if(c>0&&s&&(i=await Ha(i,s)),c>0&&this.cfg.hooks?.onBeforeRequest)for(let f of this.cfg.hooks.onBeforeRequest){let d=await f(i,{request:i,response:null,error:null,startedAt:ln(),attempt:1,meta:i.meta});d&&(i={...d,redirect:"manual"})}let l=await je(this.transport,i,t);if(c>0){let f=await this.getLogger();if(f){let d=i.meta.requestId??"redirect";f.logResponse(d,l.status,l.statusText,l.headers,new Uint8Array(0),1,!1)}}if(l.status>=300&&l.status<400&&!!l.headers.location){if(a.has(l.url))throw new _(`Redirect loop detected: ${l.url}`,"ENETWORK",{request:e});if(a.add(l.url),n.processResponseHeaders(l.headers,{url:l.url}),c===20)throw new _("Too many redirects (exceeded 20)","ENETWORK",{request:e});if(l.body)try{await l.body.cancel()}catch{}let f=l.headers.location,d;try{let b=new URL(f,l.url);d=b.href;let x=b.protocol.toLowerCase();if(x!=="http:"&&x!=="https:")throw new _(`Unsafe redirect to ${x} detected \u2014 only HTTP(S) allowed`,"ENETWORK",{request:e})}catch(b){throw b instanceof _?b:new _(`Invalid redirect location: ${f}`,"ENETWORK",{request:e,cause:b})}let p=l.status===301||l.status===302||l.status===303?"GET":i.method,g=p==="GET"||p==="HEAD"?null:i.body,m=n.getCookieHeader({url:d,http:!0}),y={...i.headers};m?y.cookie=m:delete y.cookie,i={...i,url:d,method:p,body:g,headers:y,redirect:"manual"};continue}return l}throw new _("Redirect loop","ENETWORK",{request:e})}async _executeOnce(e,t,n,s,o,i,a){let c={request:e,response:null,error:null,startedAt:s,attempt:o,aborted:!1,store:new Map},l=e.meta.requestId??`req-${o}-${Date.now()}`;if(this._trace(l,"request_interceptors","start",s,o),e=await this._runRequestInterceptors(c),this._trace(l,"request_interceptors","end",s,o),this._trace(l,"lifecycle_before","start",s,o),this.cfg.hooks?.onBeforeRequest)for(let k of this.cfg.hooks.onBeforeRequest){let P=await k(e,this._hookCtx(c));P&&(e=P)}if(this._trace(l,"lifecycle_before","end",s,o),n.cache!==!1&&this.cfg.cache){let k=await this.getCache();if(k){let P={url:e.url,method:e.method,headers:e.headers},v=await k.get(P);if(v&&!v.stale){let L=await this._buildResponse(v.entry.response,e,!0,o,s,n);if(this.cfg.hooks?.onBeforeResponse)for(let W of this.cfg.hooks.onBeforeResponse)await W(L,this._hookCtx(c));return L}if(v?.stale){if(await k.markSWRInFlight(P)){let O={...e,headers:{...e.headers,...k.buildConditionalHeaders(v.entry)}};(async()=>{try{let j=await je(this.transport,O,t),mn=await this.getCache();if(mn)if(j.status===304)await mn.revalidate({url:O.url,method:O.method,headers:O.headers},{status:304,statusText:"Not Modified",headers:j.headers,body:null});else{let{decompressBodyStream:$c,readRawBody:Hc}=await Promise.resolve().then(()=>(Xt(),_a)),jc=await $c(j.body,j.headers),qc=await Hc(jc,0,j.url,O.signal);await mn.set({url:O.url,method:O.method,headers:O.headers},{status:j.status,statusText:j.statusText,headers:j.headers,body:qc},{tags:n.tags??[]})}}catch(j){if(this.cfg.onSWRError)try{this.cfg.onSWRError(j,O)}catch{}}finally{(await this.getCache())?.clearSWRInFlight(P)}})()}return await this._buildResponse(v.entry.response,e,!0,o,s,n)}}}let u=[];n.onUploadProgress&&u.push(n.onUploadProgress),this.cfg.hooks?.onUploadProgress&&u.push(...this.cfg.hooks.onUploadProgress);let f=u.length>0?u:null,d=null;if(f!==null&&e.body!==null){let k=null,P=null;if(e.body instanceof ReadableStream)k=e.body;else if(typeof e.body=="string"){let v=new TextEncoder().encode(e.body);P=v.byteLength,k=new ReadableStream({start:L=>{L.enqueue(v),L.close()}})}else if(e.body instanceof Uint8Array)P=e.body.byteLength,k=new ReadableStream({start:v=>{v.enqueue(e.body),v.close()}});else if(e.body instanceof ArrayBuffer){let v=new Uint8Array(e.body);P=v.byteLength,k=new ReadableStream({start:L=>{L.enqueue(v),L.close()}})}else if(typeof Blob<"u"&&e.body instanceof Blob)P=e.body.size,k=e.body.stream();else if(typeof URLSearchParams<"u"&&e.body instanceof URLSearchParams){let v=new TextEncoder().encode(e.body.toString());P=v.byteLength,k=new ReadableStream({start:L=>{L.enqueue(v),L.close()}})}if(k){let{stream:v}=Dt(k,P,{onProgress:L=>{let W=L;for(let O of u)O(W)},...e.signal!==null?{signal:e.signal}:{}});d=v,e={...e,body:v}}}e.headers["accept-encoding"]||(e={...e,headers:{...e.headers,"accept-encoding":"gzip, deflate, br"}});let p=await this.getCookieJar();this._trace(l,"transport_send","start",s,o);let g;try{g=p?await this._sendFollowingRedirects(e,t,p,n.auth!==!1?n.auth??this.cfg.auth:void 0):await je(this.transport,e,t)}catch(k){if(d)try{d.cancel("Request failed").catch(()=>{})}catch{}throw k}if(this._trace(l,"transport_send","end",s,o),g.status===304){let k=await this.getCache();if(k){let P=await k.revalidate({url:e.url,method:e.method,headers:e.headers},{status:304,statusText:"Not Modified",headers:g.headers,body:null});if(P)return await this._buildResponse(P.response,e,!0,o,s,n)}}g.alreadyDecompressed&&(delete g.headers["content-encoding"],delete g.headers["Content-Encoding"]);let m=await Gt(g.body,g.headers),y=[];n.onDownloadProgress&&y.push(n.onDownloadProgress),this.cfg.hooks?.onDownloadProgress&&y.push(...this.cfg.hooks.onDownloadProgress);let b=y.length>0?y:null,x=m;if(b&&x){let k=g.headers["content-length"],P=k?parseInt(k,10):null,v=new z(P&&!isNaN(P)?P:null,{onProgress:L=>{let W=L;for(let O of y)O(W)},...e.signal!==null?{signal:e.signal}:{}});x=new ReadableStream({async start(L){let W=x.getReader();try{for(;;){let{done:O,value:j}=await W.read();if(O){v.complete(),L.close();break}v.update(j.byteLength),L.enqueue(j)}}catch(O){L.error(O)}finally{W.releaseLock()}},cancel(){x?.cancel()}})}let S=n.maxResponseSize??this.cfg.maxResponseSize??0,R=await Qt(x,S,g.url,e.signal),C=await this.getCookieJar();C&&C.processResponseHeaders(g.headers,{url:g.url});let T=g.headers["content-type"]??null;this._trace(l,"response_parse","start",s,o);let A=await mt(R,T,n.parseResponse,n.parseFailure,g.headers,g.url);this._trace(l,"response_parse","end",s,o);let M=ln()-s,N={status:g.status,statusText:g.statusText,headers:g.headers,data:this.cfg.transformResponse?this.cfg.transformResponse(A,{}):A,rawBody:R,url:g.url,cached:!1,redirected:g.redirected,httpVersion:g.httpVersion,durationMs:M,request:e,attempt:o};if(n.cache!==!1&&this.cfg.cache){let k=await this.getCache();k&&g.status!==304&&await k.set({url:e.url,method:e.method,headers:e.headers},{status:g.status,statusText:g.statusText,headers:g.headers,body:R},{tags:n.tags??[]})}let F=await this.getLogger();if(F){let k=c.store.get("requestId")??e.meta.requestId??"unknown";F.logResponse(k,N.status,N.statusText,N.headers,R,o,!1)}this.harRecorder?.record(e,N,i??Date.now()-N.durationMs),c.response=N,this._trace(l,"response_interceptors","start",s,o);let $=await this._runResponseInterceptors(c,N,e,t,n,s,o,a??!1);if(this._trace(l,"response_interceptors","end",s,o),this.cfg.hooks?.onBeforeResponse){let k=$;for(let P of this.cfg.hooks.onBeforeResponse){let v=await P(k,this._hookCtx(c));v&&(k=v)}}if((n.throwOnError??this.cfg.throwOnError??!0)&&$.status>=400)throw new Ye($,e);if(this.cfg.hooks?.onAfterResponse)for(let k of this.cfg.hooks.onAfterResponse)await k($,this._hookCtx(c));return n.onSuccess?.($),$}async _runRequestInterceptors(e){let t=e.request;for(let n of this.interceptors.request){e.request=t;let s=await n(e);s&&"url"in s&&!("status"in s)?t=s:e.request!==t&&(t=e.request)}return e.request=t,t}async _runResponseInterceptors(e,t,n,s,o,i,a,c){let l=t;for(let u of this.interceptors.response){let f=await u(e);if(f){if("status"in f&&"headers"in f)l=f;else if("url"in f&&"method"in f&&!("status"in f)){if(c&&a<=c.maxRetries){let d={request:n,response:t,error:null,attempt:a,maxRetries:c.maxRetries},p=ko(c,a,0);await c.onRetry?.(d,p),await this.cfg.hooks?.onRetry?.reduce(async(g,m)=>{await g,await m(d)},Promise.resolve()),await Ao(p,n.signal)}return this._executeOnce(f,s,o,i,a+1,void 0,c)}}}return l}async _runErrorInterceptors(e,t,n,s){let o={request:e,response:null,error:t,startedAt:s,attempt:n,aborted:!1,store:new Map};for(let i of this.interceptors.error){let a=await i(o);if(a&&"status"in a)return a}if(this.cfg.hooks?.onError)for(let i of this.cfg.hooks.onError){let a=await i(t,this._hookCtx(o));if(a)return a}return null}async _buildResponse(e,t,n,s,o,i){let a=e.body,c=a instanceof Uint8Array?a:typeof a=="string"?new TextEncoder().encode(a):null,l=c?await mt(c,e.headers["content-type"]??null,i.parseResponse,i.parseFailure,e.headers,"url"in e?e.url:t.url):null,u=ln()-o,f="url"in e?e.url:t.url,d="redirected"in e?e.redirected:!1,p="httpVersion"in e?e.httpVersion:"HTTP/1.1";return{status:e.status,statusText:e.statusText,headers:e.headers,data:l,rawBody:c,url:f,cached:n,redirected:d,httpVersion:p,durationMs:u,request:t,attempt:s}}_hookCtx(e){return{request:e.request,response:e.response,error:e.error,startedAt:e.startedAt,attempt:e.attempt,meta:e.request.meta}}_trace(e,t,n,s,o,i){if(this.cfg.onPipelineTrace)try{console.debug("[kinetex:trace]",e,t,n,o),this.cfg.onPipelineTrace({requestId:e,stage:t,event:n,elapsedMs:typeof performance<"u"?performance.now()-s:Date.now()-s,attempt:o,...i})}catch{}}get(e,t){return this.send(e,"GET",t)}post(e,t,n){return this.send(e,"POST",{...n,...t!==void 0?{body:t}:{}})}put(e,t,n){return this.send(e,"PUT",{...n,...t!==void 0?{body:t}:{}})}patch(e,t,n){return this.send(e,"PATCH",{...n,...t!==void 0?{body:t}:{}})}delete(e,t){return this.send(e,"DELETE",t)}head(e,t){return this.send(e,"HEAD",t)}options(e,t){return this.send(e,"OPTIONS",t)}request(e,t){return new or(this,e,t)}GET(e){return this.request("GET",e)}POST(e){return this.request("POST",e)}PUT(e){return this.request("PUT",e)}PATCH(e){return this.request("PATCH",e)}DELETE(e){return this.request("DELETE",e)}async sse(e,t={}){let{SSEClient:n}=await Promise.resolve().then(()=>(rr(),Zs)),s=Pt(this.cfg.headers,t.headers),o=sr(this.cfg.baseURL,e,this.cfg.params),i=async(a,c)=>{let l=typeof a=="string"?a:a.url,u=c,f=await this.send(l,u.method??"GET",{headers:u.headers,body:u.body,signal:u.signal,throwOnError:!1,parseResponse:p=>p}),d={...f.headers};return delete d["content-encoding"],delete d["Content-Encoding"],new Response(f.rawBody?.buffer??null,{status:f.status,headers:d})};return new n({url:o,headers:s,fetch:i,...t})}async graphql(e,t={}){let{GraphQLClient:n}=await Promise.resolve().then(()=>(sn(),Ua)),s=Pt(this.cfg.headers,t.headers),o=sr(this.cfg.baseURL,e,this.cfg.params),i=async(a,c)=>{let l=typeof a=="string"?a:a.url,u=c,f=await this.send(l,u.method??"POST",{headers:u.headers,body:u.body,signal:u.signal,throwOnError:!1,parseResponse:p=>p}),d={...f.headers};return delete d["content-encoding"],delete d["Content-Encoding"],new Response(f.rawBody?.buffer??null,{status:f.status,headers:d})};return new n({url:o,headers:s,fetch:i,...t})}async paginate(e,t){let{createPagePaginator:n}=await Promise.resolve().then(()=>(cn(),$a)),s=sr(this.cfg.baseURL,e,this.cfg.params);return n({url:s,fetch:async(i,a)=>{let c=typeof i=="string"?i:i.url,l=a,u=await this.send(c,l.method??"GET",{headers:l.headers,body:l.body,signal:l.signal,throwOnError:!1,parseResponse:d=>d}),f={...u.headers};return delete f["content-encoding"],delete f["Content-Encoding"],new Response(u.rawBody?.buffer??null,{status:u.status,headers:f})},headers:Pt(this.cfg.headers),...t})}async destroy(){for(let e of this._wsClients)try{e.close(1e3,"Client destroyed")}catch{}if(this._wsClients.clear(),this._cache)try{await this._cache.clear()}catch{}He&&this.transport&&"destroy"in this.transport&&this.transport.destroy(),this._cookieJar=null,this._logger=null,this._dedup?.clear(),this._circuitBreakers?.clear?.(),this._otelTracer=null,this.interceptors.clear()}},or=class{constructor(e,t,n){h(this,"client");h(this,"method");h(this,"_options",{});h(this,"_url");this.client=e,this.method=t,this._url=n}header(e,t){return this._options.headers={...this._options.headers,[e.toLowerCase()]:t},this}headers(e){return this._options.headers={...this._options.headers,...e},this}param(e,t){return this._options.params={...this._options.params,[e]:t},this}params(e){return this._options.params={...this._options.params,...e},this}withBody(e){return this._options.body=e,this}withJSON(e){return this._options.body=JSON.stringify(e),this._options.headers={...this._options.headers,"content-type":"application/json"},this}withForm(e){return this._options.body=e,this}bearer(e){return this._options.auth={type:"bearer",token:e},this}basic(e,t){return this._options.auth={type:"basic",username:e,password:t},this}apiKey(e,t){return this._options.auth={type:"apikey",header:e,key:t},this}digest(e,t){return this._options.auth={type:"digest",username:e,password:t},this}noAuth(){return this._options.auth=!1,this}retry(e,t){return this._options.retry={maxRetries:e,...t},this}noRetry(){return this._options.retry=!1,this}timeout(e){return this._options.timeout=e,this}proxy(e){return this._options.proxy=e,this}cache(e){return this._options.cache=e,this}noCache(){return this._options.cache={forceRefresh:!0},this}onUploadProgress(e){return this._options.onUploadProgress=e,this}onDownloadProgress(e){return this._options.onDownloadProgress=e,this}signal(e){return this._options.signal=e,this}maxSize(e){return this._options.maxResponseSize=e,this}http2(){return this._options.httpVersion="HTTP/2",this}http1(){return this._options.httpVersion="HTTP/1.1",this}noThrow(){return this._options.throwOnError=!1,this}tags(...e){return this._options.tags=e,this}meta(e){return this._options.meta={...this._options.meta,...e},this}send(){return this.client.send(this._url,this.method,this._options)}async data(){return(await this.client.send(this._url,this.method,this._options)).data}async json(){let e={...this._options};return e.headers={...e.headers,accept:"application/json"},(await this.client.send(this._url,this.method,e)).data}async text(){let e={...this._options};return e.parseResponse=n=>new TextDecoder("utf-8").decode(n),(await this.client.send(this._url,this.method,e)).data}async bytes(){let e={...this._options};return e.parseResponse=n=>n,(await this.client.send(this._url,this.method,e)).data}async blob(){let e=await this.bytes(),t="application/octet-stream";if(typeof Blob>"u")throw new _("Blob is not available in this runtime","EUNKNOWN");return new Blob([e.buffer],{type:t})}subscribe(e,t){this.client.send(this._url,this.method,{...this._options,onSuccess:e,...t!==void 0?{onError:t}:{}}).catch(n=>t?.(n instanceof _?n:new _(String(n),"EUNKNOWN")))}};function Io(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let r=new Error("Aborted");return r.name="AbortError",r}function Iu(r,e){if(!(!r&&!e))return{...r,...e}}function Ao(r,e){return new Promise((t,n)=>{if(e?.aborted){n(Io());return}let s=()=>{clearTimeout(o),n(Io())},o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);e?.addEventListener("abort",s,{once:!0})})}function ln(){return typeof performance<"u"?performance.now():Date.now()}function qa(r){try{return`${r.method}:${new URL(r.url).origin}`}catch{return`${r.method}:${r.url}`}}var un=class{constructor(e,t={}){h(this,"_client");h(this,"_maxBatch");h(this,"_flushMs");h(this,"_queue",[]);h(this,"_timer",null);this._client=e,this._maxBatch=t.maxBatch??100,this._flushMs=t.flushMs??0}enqueue(e,t="GET",n={}){return new Promise((s,o)=>{let i={url:e,method:t,options:n,resolve:s,reject:o};this._queue.push(i);let a=n.signal;if(a){let c=()=>{let l=this._queue.indexOf(i);l!==-1&&(this._queue.splice(l,1),o(new _("Request aborted while queued","EABORT")))};if(i._abortCleanup=()=>a.removeEventListener("abort",c),a.addEventListener("abort",c,{once:!0}),a.aborted){a.removeEventListener("abort",c);let l=this._queue.indexOf(i);l!==-1&&this._queue.splice(l,1),o(new _("Request aborted before flush","EABORT"));return}}this._queue.length>=this._maxBatch?this._flushNow():this._timer||(this._flushMs===0?queueMicrotask(()=>{this._timer=null,this._flushNow()}):this._timer=setTimeout(()=>this._flushNow(),this._flushMs))})}flush(){for(;this._queue.length>0;)this._flushNow()}get pendingCount(){return this._queue.length}_flushNow(){if(this._timer!==null&&(clearTimeout(this._timer),this._timer=null),this._queue.length===0)return;let e=this._queue.splice(0,this._maxBatch);for(let t of e){let n=o=>{t._abortCleanup?.(),t.resolve(o)},s=o=>{t._abortCleanup?.(),t.reject(o)};try{this._client.send(t.url,t.method,t.options).then(n,s)}catch(o){s(o)}}}};$t();Qr();Xt();sn();Bt();var ir=class{constructor(){h(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e)??[];return n.push({fn:t,once:!1}),this.listeners.set(e,n),this}once(e,t){let n=this.listeners.get(e)??[];return n.push({fn:t,once:!0}),this.listeners.set(e,n),this}off(e,t){let n=this.listeners.get(e);return n?(this.listeners.set(e,n.filter(s=>s.fn!==t)),this):this}async emit(e,t){let n=this.listeners.get(e);if(!n||n.length===0)return;let s=new Set;for(let o=0;o<n.length;o++){let i=n[o];try{await i.fn(t)}catch{}i.once&&s.add(o)}if(s.size>0){let o=n.filter((i,a)=>!s.has(a));this.listeners.set(e,o)}}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}},Lu=0;function Mu(){return`hook_${++Lu}`}function V(r){return[...r].sort((e,t)=>e.priority-t.priority)}var hn=class{constructor(){h(this,"beforeRequest",[]);h(this,"afterRequest",[]);h(this,"beforeResponse",[]);h(this,"afterResponse",[]);h(this,"onError",[]);h(this,"onRetry",[]);h(this,"onRedirect",[]);h(this,"onUploadProgress",[]);h(this,"onDownloadProgress",[]);h(this,"onCancel",[]);h(this,"onConnection",[]);h(this,"aroundHooks",[]);h(this,"emitter",new ir)}addBeforeRequest(e,t={}){return this._add(this.beforeRequest,e,t)}addAfterRequest(e,t={}){return this._add(this.afterRequest,e,t)}addBeforeResponse(e,t={}){return this._add(this.beforeResponse,e,t)}addAfterResponse(e,t={}){return this._add(this.afterResponse,e,t)}addOnError(e,t={}){return this._add(this.onError,e,t)}addOnRetry(e,t={}){return this._add(this.onRetry,e,t)}addOnRedirect(e,t={}){return this._add(this.onRedirect,e,t)}addOnUploadProgress(e,t={}){return this._add(this.onUploadProgress,e,t)}addOnDownloadProgress(e,t={}){return this._add(this.onDownloadProgress,e,t)}addOnCancel(e,t={}){return this._add(this.onCancel,e,t)}addOnConnection(e,t={}){return this._add(this.onConnection,e,t)}addAround(e,t={}){return this._add(this.aroundHooks,e,t)}remove(e){let t=!1,n=[this.beforeRequest,this.afterRequest,this.beforeResponse,this.afterResponse,this.onError,this.onRetry,this.onRedirect,this.onUploadProgress,this.onDownloadProgress,this.onCancel,this.onConnection,this.aroundHooks];for(let s of n){let o=s.length,i=s.filter(a=>a.id!==e);i.length<o&&(s.length=0,s.push(...i),t=!0)}return t}removeAll(){this.beforeRequest.length=0,this.afterRequest.length=0,this.beforeResponse.length=0,this.afterResponse.length=0,this.onError.length=0,this.onRetry.length=0,this.onRedirect.length=0,this.onUploadProgress.length=0,this.onDownloadProgress.length=0,this.onCancel.length=0,this.onConnection.length=0,this.aroundHooks.length=0}has(e){return[this.beforeRequest,this.afterRequest,this.beforeResponse,this.afterResponse,this.onError,this.onRetry,this.onRedirect,this.onUploadProgress,this.onDownloadProgress,this.onCancel,this.onConnection,this.aroundHooks].some(n=>n.some(s=>s.id===e))}async runBeforeRequest(e,t){let n=e;for(let s of V(this.beforeRequest)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(n,t));o&&typeof o=="object"&&"url"in o&&(n=o),this._maybeEject(s,this.beforeRequest)}return await this.emitter.emit("before:request",n),n}async runAfterRequest(e,t){for(let n of V(this.afterRequest))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.afterRequest));await this.emitter.emit("after:request",e)}async runBeforeResponse(e,t){let n=e;for(let s of V(this.beforeResponse)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(n,t));o&&typeof o=="object"&&"status"in o&&(n=o),this._maybeEject(s,this.beforeResponse)}return await this.emitter.emit("before:response",n),n}async runAfterResponse(e,t){for(let n of V(this.afterResponse))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.afterResponse));await this.emitter.emit("after:response",e)}async runOnError(e,t){for(let n of V(this.onError)){if(!this._shouldRun(n,t))continue;let s=await this._safeRun(n,()=>n.fn(e,t));if(this._maybeEject(n,this.onError),s&&typeof s=="object"&&"status"in s)return s}return await this.emitter.emit("error",e),null}async runOnRetry(e,t){for(let n of V(this.onRetry))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.onRetry));await this.emitter.emit("retry",e)}async runOnRedirect(e,t){let n=!0;for(let s of V(this.onRedirect)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(e,t));if(this._maybeEject(s,this.onRedirect),o===!1){n=!1;break}}return await this.emitter.emit("redirect",e),n}runOnUploadProgress(e,t){for(let n of V(this.onUploadProgress))if(this._shouldRun(n,t)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onUploadProgress)}this.emitter.emit("upload:progress",e)}runOnDownloadProgress(e,t){for(let n of V(this.onDownloadProgress))if(this._shouldRun(n,t)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onDownloadProgress)}this.emitter.emit("download:progress",e)}runOnCancel(e,t){for(let n of V(this.onCancel)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onCancel)}this.emitter.emit("cancel",e)}runOnConnection(e){for(let t of V(this.onConnection)){try{t.fn(e)}catch{}this._maybeEject(t,this.onConnection)}this.emitter.emit("connection",e)}wrapWithAround(e,t){let n=V(this.aroundHooks).reverse(),s=t;for(let o of n){let i=s;s=()=>{if(!this._shouldRun(o,e))return i();let a=o.fn(e,i);return this._maybeEject(o,this.aroundHooks),a}}return s}_add(e,t,n){let s=n.id??Mu();return e.push({id:s,priority:n.priority??0,once:n.once??!1,condition:n.condition??null,safe:n.safe??!1,fn:t}),s}_shouldRun(e,t){return e.condition?e.condition(t):!0}async _safeRun(e,t){try{return await t()}catch(n){if(!e.safe)throw n;console.error(`[lifecycle] Hook "${e.id}" threw:`,n);return}}_maybeEject(e,t){if(!e.once)return;let n=t.indexOf(e);n!==-1&&t.splice(n,1)}};var fn=class{constructor(e=10){h(this,"maxRedirects");h(this,"count",0);this.maxRedirects=e}record(e,t,n,s){if(this.count++,this.count>this.maxRedirects)throw new ar(this.count,e);return{from:e,to:t,status:n,count:this.count,request:s}}get redirectCount(){return this.count}reset(){this.count=0}},ar=class extends Error{constructor(t,n){super(`Too many redirects (${t}) at ${n}`);h(this,"count");h(this,"url");h(this,"code","ETOOMANYREDIRECTS");this.count=t,this.url=n,this.name="TooManyRedirectsError"}};function za(r){return async e=>(await r(e),e)}function Ba(r){return async e=>({...e,headers:{...e.headers,...typeof r=="function"?await r():r}})}function Fa(r){return e=>{if(/^https?:\/\//i.test(e.url))return;let t=r.endsWith("/")||e.url.startsWith("/")?"":"/";return{...e,url:`${r}${t}${e.url}`}}}function Wa(r=e=>e>=400){return e=>{if(e.response&&r(e.response.status))throw new cr(e.response.status,e.response.statusText,e.response)}}function Ka(r){return e=>{let t=r(e);if(t===!0)return;let n=typeof t=="string"?t:`Response validation failed (status ${e.status})`;throw new lr(n,e)}}var cr=class extends Error{constructor(t,n,s){super(`HTTP ${t}: ${n}`);h(this,"status");h(this,"statusText");h(this,"response");h(this,"code","EHTTPERROR");this.status=t,this.statusText=n,this.response=s,this.name="HTTPError"}},lr=class extends Error{constructor(t,n){super(t);h(this,"response");h(this,"code","EVALIDATION");this.response=n,this.name="ResponseValidationError"}};function Va(...r){return async(e,t)=>{let n=e;for(let s of r){let o=await s(n,t);o&&typeof o=="object"&&"url"in o&&(n=o)}return n}}function Ja(...r){return async(e,t)=>{let n=e;for(let s of r){let o=await s(n,t);o&&typeof o=="object"&&"status"in o&&(n=o)}return n}}function Qa(...r){return(e,t)=>r.reduceRight((s,o)=>()=>o(e,s),t)()}function Ga(r={}){let e=r.logger??((s,o)=>console.log(s,JSON.stringify(o))),t=new Set((r.redactHeaders??["authorization","cookie"]).map(s=>s.toLowerCase()));function n(s){let o={};for(let[i,a]of Object.entries(s))o[i]=t.has(i.toLowerCase())?"***":a;return o}return{beforeRequest:s=>{e("\u2192 request",{method:s.method,url:s.url,headers:n(s.headers)})},afterResponse:s=>{e("\u2190 response",{status:s.status,url:s.request.url,headers:n(s.headers)})},onError:s=>{e("\u2717 error",{url:s.request.url,error:s.error instanceof Error?s.error.message:String(s.error),status:s.response?.status??null})}}}function Xa(){let r="__kinetex_timing__";return{beforeRequest:(e,t)=>{t.meta[r]=Lo()},afterResponse:(e,t)=>{let n=t.meta[r],s=n!==void 0?Lo()-n:null;s!==null&&(t.meta.durationMs=s)}}}function Ya(r="utf-8"){return e=>{if(e.body instanceof Uint8Array)return{...e,body:new TextDecoder(r).decode(e.body)}}}function Za(){return{beforeRequest:(r,e)=>{if(r.signal?.aborted)throw e.meta.aborted=!0,Ou("Request aborted before sending")},onCancel:r=>{console.debug(`[lifecycle] Request cancelled: ${r.request.url}`,r.reason)}}}function Ou(r){if(typeof DOMException<"u")return new DOMException(r,"AbortError");let e=new Error(r);return e.name="AbortError",e}function Lo(){return typeof performance<"u"?performance.now():Date.now()}function ec(r,e={}){return{request:r,response:null,error:null,startedAt:Lo(),attempt:1,meta:{},...e}}Zr();cn();Fr();var Lt={NoAuth:0,GSSAPI:1,UserPassword:2,NoAcceptable:255},Y={IPv4:1,Domain:3,IPv6:4},Du={Connect:1,Bind:2,UdpAssociate:3},J={Succeeded:0,GeneralFailure:1,ConnNotAllowed:2,NetworkUnreachable:3,HostUnreachable:4,ConnRefused:5,TtlExpired:6,CmdNotSupported:7,AddrTypeNotSupported:8},Nu={[J.Succeeded]:"Succeeded",[J.GeneralFailure]:"General SOCKS server failure",[J.ConnNotAllowed]:"Connection not allowed by ruleset",[J.NetworkUnreachable]:"Network unreachable",[J.HostUnreachable]:"Host unreachable",[J.ConnRefused]:"Connection refused",[J.TtlExpired]:"TTL expired",[J.CmdNotSupported]:"Command not supported",[J.AddrTypeNotSupported]:"Address type not supported"},I=class extends Error{constructor(t,n,s=!1){super(t);h(this,"code");h(this,"retriable");this.code=n,this.retriable=s,this.name="Socks5Error"}};function Uu(r){let e=Nu[r]??`Unknown reply code 0x${r.toString(16)}`,t=r===J.NetworkUnreachable||r===J.TtlExpired;return new I(`SOCKS5 proxy error: ${e}`,`SOCKS5_REPLY_${r}`,t)}var Oo=class{constructor(e,t){h(this,"conn");h(this,"timeoutMs");h(this,"buf",new Uint8Array(0));this.conn=e,this.timeoutMs=t}async readExact(e){for(;this.buf.length<e;){let n=new Uint8Array(4096),o=await tc(this.conn.read(n),this.timeoutMs,"SOCKS5 handshake read timed out");if(o===null||o===0)throw new I("Connection closed during SOCKS5 handshake","SOCKS5_EOF");let i=new Uint8Array(this.buf.length+o);i.set(this.buf),i.set(n.subarray(0,o),this.buf.length),this.buf=i}let t=this.buf.slice(0,e);return this.buf=this.buf.slice(e),t}};function tc(r,e,t){return new Promise((n,s)=>{let o=setTimeout(()=>s(new I(t,"SOCKS5_TIMEOUT",!0)),e);r.then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),s(i)})})}function $u(r,e){let t=r.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(t){let o=t.slice(1).map(Number);if(o.every(i=>i>=0&&i<=255))return new Uint8Array([Y.IPv4,...o])}let n=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(Hu(n)){let o=ju(n);return new Uint8Array([Y.IPv6,...o])}e||console.warn("[socks5] remoteDns=false but got a hostname; sending as DOMAINNAME");let s=new TextEncoder().encode(r);if(s.length>255)throw new I("Hostname too long for SOCKS5 (max 255 bytes)","SOCKS5_ADDR_TOO_LONG");return new Uint8Array([Y.Domain,s.length,...s])}function Hu(r){return r.includes(":")}function ju(r){let e=r.split("::"),t=o=>o?o.split(":").map(i=>parseInt(i||"0",16)):[],n;if(e.length===2){let o=t(e[0]),i=t(e[1]),a=new Array(8-o.length-i.length).fill(0);n=[...o,...a,...i]}else n=t(r);if(n.length!==8)throw new I(`Invalid IPv6 address: ${r}`,"SOCKS5_INVALID_ADDR");for(let o of n)if(o<0||o>65535)throw new I(`Invalid IPv6 group: ${o} out of range (0-65535)`,"SOCKS5_INVALID_ADDR");let s=[];for(let o of n)s.push(o>>8&255,o&255);return s}function Mo(r,e){if(r===Y.IPv4)return Array.from(e).join(".");if(r===Y.IPv6){let t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return t.join(":")}return new TextDecoder().decode(e)}async function qu(r,e,t){let n=new Oo(r,t.handshakeTimeoutMs),s=!!(t.username&&t.password),o=s?[Lt.NoAuth,Lt.UserPassword]:[Lt.NoAuth],i=new Uint8Array([5,o.length,...o]);await r.write(i);let a=await n.readExact(2);if(a[0]!==5)throw new I(`Unexpected SOCKS version in method response: ${a[0]}`,"SOCKS5_BAD_VERSION");let c=a[1];if(c===Lt.NoAcceptable)throw new I("SOCKS5 proxy rejected all authentication methods","SOCKS5_NO_ACCEPTABLE_METHOD");if(c===Lt.UserPassword){if(!s)throw new I("SOCKS5 proxy requires username/password but none provided","SOCKS5_AUTH_REQUIRED");await zu(r,n,t.username,t.password)}else if(c!==Lt.NoAuth)throw new I(`SOCKS5 proxy chose unsupported auth method: 0x${c.toString(16)}`,"SOCKS5_UNSUPPORTED_METHOD");let l=$u(e.host,t.remoteDns),u=e.port,f=[u>>8&255,u&255],d=new Uint8Array([5,Du.Connect,0,...l,...f]);await r.write(d);let p=await n.readExact(4);if(p[0]!==5)throw new I(`Unexpected SOCKS version in reply: ${p[0]}`,"SOCKS5_BAD_VERSION");if(p[1]!==J.Succeeded)throw Uu(p[1]);let g=p[3],m,y;if(g===Y.IPv4)y=await n.readExact(4),m=Mo(Y.IPv4,y);else if(g===Y.IPv6)y=await n.readExact(16),m=Mo(Y.IPv6,y);else if(g===Y.Domain){let S=await n.readExact(1);y=await n.readExact(S[0]),m=Mo(Y.Domain,y)}else throw new I(`Unsupported bound address type in reply: 0x${g.toString(16)}`,"SOCKS5_UNSUPPORTED_ADDR_TYPE");let b=await n.readExact(2),x=b[0]<<8|b[1];return{boundAddr:m,boundPort:x}}async function zu(r,e,t,n){let s=new TextEncoder,o=s.encode(t),i=s.encode(n);if(o.length>255||i.length>255)throw new I("Username or password too long (max 255 bytes)","SOCKS5_AUTH_TOO_LONG");let a=new Uint8Array([1,o.length,...o,i.length,...i]);await r.write(a);let c=await e.readExact(2);if(c[0]!==1&&c[0]!==5)throw new I(`Unexpected auth sub-negotiation version: ${c[0]}`,"SOCKS5_BAD_AUTH_VERSION");if(c[1]!==0)throw new I("SOCKS5 authentication failed (invalid credentials)","SOCKS5_AUTH_FAILED")}async function Bu(r,e,t){let n;for(let s=0;s<=e;s++)try{return await r()}catch(o){if(n=o,!(o instanceof I&&o.retriable)||s===e)break;await Fu(t*Math.pow(2,s))}throw n}function Fu(r){return new Promise(e=>setTimeout(e,r))}function Wu(r){return{host:r.host,port:r.port??1080,username:r.username??"",password:r.password??"",remoteDns:r.remoteDns??!0,connectTimeoutMs:r.connectTimeoutMs??1e4,handshakeTimeoutMs:r.handshakeTimeoutMs??1e4,maxRetries:r.maxRetries??2,retryDelayMs:r.retryDelayMs??300}}async function Do(r,e,t){let n=Wu(r);return await Bu(async()=>{let s=await tc(t(n.host,n.port,n.connectTimeoutMs),n.connectTimeoutMs,`TCP connection to SOCKS5 proxy ${n.host}:${n.port} timed out`);try{let{boundAddr:o,boundPort:i}=await qu(s,e,n);return{conn:s,boundAddr:o,boundPort:i}}catch(o){throw s.close(),o}},n.maxRetries,n.retryDelayMs)}function rc(r){let e;try{Ku(r),e=new URL(r)}catch{throw new I("Invalid SOCKS5 proxy URL: malformed URL","SOCKS5_BAD_URL")}if(e.protocol!=="socks5:"&&e.protocol!=="socks5h:")throw new I(`Expected socks5:// or socks5h:// scheme, got: ${e.protocol}`,"SOCKS5_BAD_SCHEME");let t=e.protocol==="socks5h:",n=e.hostname,s=e.port?parseInt(e.port,10):1080;if(!Number.isFinite(s)||s<1||s>65535)throw new I("Invalid SOCKS5 proxy URL: port must be between 1 and 65535","SOCKS5_BAD_URL");if(!n)throw new I("Invalid SOCKS5 proxy URL: no hostname specified (e.g., socks5://host:port)","SOCKS5_BAD_URL");let o={host:n,port:s,remoteDns:t};return e.username&&(o.username=decodeURIComponent(e.username)),e.password&&(o.password=decodeURIComponent(e.password)),o}function Ku(r){try{let e=new URL(r);return`${e.protocol}//${e.host}${e.pathname}${e.search}${e.hash}`}catch{return"[redacted]"}}var nc=async(r,e,t)=>{let n=globalThis,s;return t&&t>0?s=await Promise.race([n.Deno.connect({hostname:r,port:e,transport:"tcp"}),new Promise((i,a)=>setTimeout(()=>a(new I("TCP connect to proxy timed out","SOCKS5_TIMEOUT",!0)),t))]):s=await n.Deno.connect({hostname:r,port:e,transport:"tcp"}),{read:async i=>{if(t&&t>0)return Promise.race([s.read(i).catch(()=>null),new Promise((a,c)=>setTimeout(()=>c(new I("TCP read timed out","SOCKS5_TIMEOUT",!0)),t))]);try{return await s.read(i)}catch{return null}},write:i=>s.write(i),close:()=>{try{s.close()}catch{}}}},sc=(r,e,t)=>new Promise((n,s)=>{import("node:net").then(({createConnection:o})=>{let i=o({host:r,port:e}),a=setTimeout(()=>{i.destroy(),s(new I("TCP connect to proxy timed out","SOCKS5_TIMEOUT",!0))},t),c=new Uint8Array(0),l=null,u=null,f=null,d=null;function p(){if(!l||!f||c.length===0)return;let m=Math.min(c.length,f.length);f.set(c.subarray(0,m)),c=c.slice(m);let y=l;l=null,u=null,f=null,y(m)}function g(m){if(u){let y=u;l=null,u=null,f=null,y(m)}}i.on("data",m=>{let y=new Uint8Array(c.length+m.length);y.set(c),y.set(m,c.length),c=y,p()}),i.on("end",()=>{l&&(l(null),l=null,u=null,f=null)}),i.once("error",m=>{clearTimeout(a),d=m,g(m),s(m)}),i.once("connect",()=>{clearTimeout(a),i.on("error",m=>{d=m,g(m)}),n({read:m=>new Promise((y,b)=>{if(d){b(d);return}if(c.length>0){let x=Math.min(c.length,m.length);m.set(c.subarray(0,x)),c=c.slice(x),y(x);return}l=y,u=b,f=m}),write:m=>new Promise((y,b)=>{i.write(m,x=>x?b(x):y(m.length))}),close:()=>i.destroy()})})}).catch(s)});function oc(r,e){return async(t,n,s)=>(await Do({connectTimeoutMs:s,...r},{host:t,port:n},e)).conn}rr();Le();Le();Xt();$t();Fs();rr();sn();cn();Zr();Fr();Bt();var No=class extends Error{constructor(t){super(t);h(this,"code","URL_VALIDATION_ERROR");this.name="URLValidationError"}},Vu=/^[A-Za-z0-9\-._~]$/,Ju=/^[:/?#\[\]@!$&'()*+,;=]$/;function dn(r,e=!1){return Array.from(r).map(t=>{if(Vu.test(t)||e&&Ju.test(t))return t;let n=t.codePointAt(0);if(n>65535){let s=new TextEncoder().encode(t);return Array.from(s).map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join("")}if(n>127){let s=new TextEncoder().encode(t);return Array.from(s).map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join("")}return"%"+n.toString(16).toUpperCase().padStart(2,"0")}).join("")}function ke(r){try{return decodeURIComponent(r.replace(/\+/g,"%20"))}catch{return r.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}}function Uo(r){return encodeURIComponent(r).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function We(r){return encodeURIComponent(r).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function cc(r,e={}){let{sort:t=!1,arrayFormat:n="repeat"}=e,s=[];for(let[o,i]of Object.entries(r)){if(i==null)continue;let a=We(o);if(Array.isArray(i)){let c=i.filter(l=>l!=null);if(c.length===0)continue;if(n==="comma")s.push([a,c.map(l=>We(String(l))).join(",")]);else if(n==="bracket")for(let l of c)s.push([`${a}[]`,We(String(l))]);else for(let l of c)s.push([a,We(String(l))])}else s.push([a,We(String(i))])}return t&&s.sort(([o],[i])=>o<i?-1:o>i?1:0),s.map(([o,i])=>`${o}=${i}`).join("&")}function $o(r){let e=r.startsWith("?")?r.slice(1):r,t={};if(!e)return t;for(let n of e.split("&")){if(!n)continue;let s=n.indexOf("="),o=ke(s===-1?n:n.slice(0,s)),i=s===-1?"":ke(n.slice(s+1)),a=t[o];a===void 0?t[o]=i:Array.isArray(a)?a.push(i):t[o]=[a,i]}return t}function lc(r,e){let t={...r};for(let[n,s]of Object.entries(e))s==null?delete t[n]:t[n]=s;return t}function uc(r,...e){let t={};for(let n of e)n in r&&(t[n]=r[n]);return t}function hc(r,...e){let t=new Set(e),n={};for(let[s,o]of Object.entries(r))t.has(s)||(n[s]=o);return n}function Ho(...r){if(r.length===0)return"/";let e=[];for(let i of r)i&&e.push(...i.split("/").filter((a,c)=>a!==""||c===0));let n=fc(e).join("/"),o=r[r.length-1]?.endsWith("/")&&n!=="/"?"/":"";return(n.startsWith("/")?"":"/")+n+o}function fc(r){let e=[];for(let t of r)t!=="."&&(t===".."?e.pop():e.push(t));return e}function jo(r,e={}){let{trailingSlash:t="preserve"}=e,n=r.endsWith("/")&&r!=="/",s=r.split("/").filter(Boolean),i="/"+fc(s).join("/");return t==="add"&&i!=="/"?i+="/":t==="remove"||t==="preserve"&&n&&i!=="/"&&(i+="/"),i}function dc(r){return r.split("/").filter(Boolean).map(ke)}function qo(r,e){return r.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g,(t,n)=>{let s=e[n];if(s===void 0)throw new No(`Missing path param: "${n}"`);return Uo(String(s))})}var Qu={"http:":"80","https:":"443","ftp:":"21","ws:":"80","wss:":"443"};function pc(r,e={}){let t=Ce(r);if(!t)throw new TypeError(`Invalid URL: ${r}`);let n=Qu[t.protocol],s=t.port===n?"":t.port,o=jo(t.pathname,{trailingSlash:e.trailingSlash??"preserve"});e.sortParams&&t.searchParams.sort();let i=t.searchParams.toString()?`?${t.searchParams}`:"",a=e.removeFragment?"":t.hash,c=t.username?`${encodeURIComponent(t.username)}${t.password?":"+encodeURIComponent(t.password):""}@`:"",l=s?`${t.hostname}:${s}`:t.hostname;return`${t.protocol}//${c}${l}${o}${i}${a}`}var Ae=class r{constructor(e,t){h(this,"_url");try{this._url=new URL(String(e),t)}catch{throw new TypeError(`Invalid URL: "${e}"${t?` (base: "${t}")`:""}`)}}static from(e,t){return new r(e,t)}static https(e,t){return new r(`https://${e}${t??"/"}`)}static http(e,t){return new r(`http://${e}${t??"/"}`)}withProtocol(e){let t=this._clone();return t._url.protocol=e.endsWith(":")?e:e+":",t}withHostname(e){let t=this._clone();return t._url.hostname=e,t}withHost(e){let t=this._clone();return t._url.host=e,t}withPort(e){let t=this._clone();return t._url.port=String(e),t}withUsername(e){let t=this._clone();return t._url.username=encodeURIComponent(e),t}withPassword(e){let t=this._clone();return t._url.password=encodeURIComponent(e),t}withPathname(e){let t=this._clone();return t._url.pathname=e,t}appendPath(...e){let t=this._clone(),n=t._url.pathname.replace(/\/$/,""),s=e.map(o=>o.replace(/^\/|\/$/g,"")).filter(Boolean);return t._url.pathname=n+"/"+s.join("/"),t}path(...e){let t=this._clone();return t._url.pathname=Ho(...e),t}params(e){let t=this._clone();t._url.pathname=qo(t._url.pathname,e);for(let[n,s]of Object.entries(e))t._url.searchParams.set(n,String(s));return t}addTrailingSlash(){let e=this._clone();return e._url.pathname.endsWith("/")||(e._url.pathname+="/"),e}removeTrailingSlash(){let e=this._clone();return e._url.pathname!=="/"&&e._url.pathname.endsWith("/")&&(e._url.pathname=e._url.pathname.slice(0,-1)),e}setParam(e,t){let n=this._clone();return t==null?n._url.searchParams.delete(e):n._url.searchParams.set(e,String(t)),n}appendParam(e,t){if(t==null)return this;let n=this._clone();return n._url.searchParams.append(e,String(t)),n}deleteParam(e){let t=this._clone();return t._url.searchParams.delete(e),t}query(e){let t=this._clone();for(let[n,s]of Object.entries(e))if(s==null)t._url.searchParams.delete(n);else if(Array.isArray(s)){t._url.searchParams.delete(n);for(let o of s)o!=null&&t._url.searchParams.append(n,String(o))}else t._url.searchParams.set(n,String(s));return t}setQuery(e){let t=this._clone();return t._url.search="",t.query(e)}pickParams(...e){let t=this._clone(),n=new Set(e),s=[];for(let[o,i]of t._url.searchParams.entries())n.has(o)&&s.push([o,i]);t._url.search="";for(let[o,i]of s)t._url.searchParams.append(o,i);return t}omitParams(...e){let t=this._clone(),n=new Set(e);for(let s of n)t._url.searchParams.delete(s);return t}sortParams(){let e=this._clone();return e._url.searchParams.sort(),e}redactParams(...e){let t=this._clone();for(let n of e)t._url.searchParams.has(n)&&(t=t.setParam(n,"REDACTED"));return t}withHash(e){let t=this._clone();return t._url.hash=e.startsWith("#")?e:"#"+e,t}removeHash(){let e=this._clone();return e._url.hash="",e}toString(){return this._url.toString()}toURL(){return new URL(this._url.toString())}get href(){return this._url.href}get protocol(){return this._url.protocol}get hostname(){return this._url.hostname}get host(){return this._url.host}get port(){return this._url.port}get pathname(){return this._url.pathname}get search(){return this._url.search}get hash(){return this._url.hash}get origin(){return this._url.origin}get searchParams(){return new URLSearchParams(this._url.searchParams)}get queryObject(){return $o(this._url.search)}_clone(){return new r(this._url.toString())}};function mc(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let s=n[0],o="+#./;?&".includes(s),i=(o?n.slice(1):n).split(",");return Gu(o?s:"",i,e)})}function Gu(r,e,t){let n=Zu(r),s=eh(r),o=th(r),i=rh(r),a=r==="+"||r==="#",c=[];for(let l of e){let{name:u,explode:f,maxLength:d}=Xu(l.trim()),p=t[u];if(p==null)continue;let g=Yu(p,u,o,f,d,a,n,i);g!==null&&c.push(g)}return c.length===0?"":s+c.join(n)}function Xu(r){if(r.endsWith("*"))return{name:r.slice(0,-1),explode:!0,maxLength:null};let e=r.lastIndexOf(":");if(e!==-1){let t=parseInt(r.slice(e+1),10);return{name:r.slice(0,e),explode:!1,maxLength:isNaN(t)?null:t}}return{name:r,explode:!1,maxLength:null}}function Yu(r,e,t,n,s,o,i,a){let c=l=>o?dn(l,!0):dn(l);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean"){let l=String(r);s!==null&&(l=l.slice(0,s));let u=c(l);return t?`${e}${u===""?a:"="+u}`:u}if(Array.isArray(r)){if(r.length===0)return null;if(n)return r.map(u=>{let f=c(String(u));return t?`${e}=${f}`:f}).join(i);let l=r.map(u=>c(String(u))).join(",");return t?`${e}=${l}`:l}if(typeof r=="object"&&r!==null){let l=Object.entries(r);if(l.length===0)return null;if(n)return l.map(([f,d])=>`${c(f)}=${c(d)}`).join(i);let u=l.flatMap(([f,d])=>[c(f),c(d)]).join(",");return t?`${e}=${u}`:u}return null}function Zu(r){switch(r){case".":return".";case"/":return"/";case";":return";";case"?":case"&":return"&";default:return","}}function eh(r){switch(r){case"#":return"#";case".":return".";case"/":return"/";case";":return";";case"?":return"?";case"&":return"&";default:return""}}function th(r){return r===";"||r==="?"||r==="&"}function rh(r){return r===";"?"":"="}function gc(r){let e=[],t={n:0},n=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,"*").replace(/\*\*/g,()=>"(.+?)").replace(/\*(?!\*)/g,()=>(t.n++,"([^/]+)")).replace(/:([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]+)\))?/g,(o,i,a)=>(e.push(i),`(${a??"[^/]+"})`)),s=new RegExp(`^${n}\\/?$`);return{match(o){let i=ic(o),a=s.exec(i);if(!a)return null;let c={},l=[],u={},f=1;for(let d of e)c[d]=ke(a[f++]??"");for(;f<=a.length-1;){let d=a[f++]??"";l.push(...d.split("/").filter(Boolean).map(ke))}return{params:c,wildcards:l,groups:u}},test(o){return s.test(ic(o))}}}function ic(r){try{return new URL(r).pathname}catch{return r}}function pn(r){let e=Ce(r);return e?["file:","data:","blob:"].includes(e.protocol)?"null":e.origin:null}function yc(r,e){let t=pn(r),n=pn(e);return!t||!n?!1:t===n}function wc(r,e){let t=Ce(r),n=Ce(e);return!t||!n||t.protocol!==n.protocol?!1:ac(t.hostname)===ac(n.hostname)}function ac(r){let e=new Set(["co.uk","co.jp","co.kr","co.nz","co.za","co.in","com.au","com.br","com.mx","com.cn","com.tw","com.hk","com.sg","com.my","com.ph","com.vn","com.tr","net.au","net.uk","net.br","org.uk","org.au","org.nz","org.cn","org.in","ac.uk","gov.uk","gov.au","gov.cn","or.kr","pe.kr","go.jp","ne.jp","ac.jp","github.io","herokuapp.com","cloudfront.net"]),t=r.split(".");if(t.length>=3){let n=t.slice(-2).join(".");if(e.has(n))return t.slice(-3).join(".")}return t.slice(-2).join(".")}function bc(r,e){try{return new URL(r,e).toString()}catch{throw new TypeError(`Cannot resolve "${r}" against base "${e}"`)}}function xc(r,e){try{let t=new URL(r),n=new URL(e);return t.origin!==n.origin||!t.pathname.startsWith(n.pathname)?null:t.pathname.slice(n.pathname.length)+t.search+t.hash}catch{return null}}function zo(r){try{if(/^[A-Za-z][A-Za-z0-9+\-.]*:\/\//.test(r))return!0;let e=new URL(r);return e.protocol!==""&&e.protocol!=="file:"}catch{return!1}}function _c(r){return!zo(r)}function Sc(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function Tc(r){try{let e=new URL(r).protocol;return e==="http:"||e==="https:"}catch{return!1}}function Ec(r){return r.trimStart().startsWith("data:")}function Rc(r){return r.trimStart().startsWith("blob:")}function kc(r){try{let e=new URL(r).hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}catch{return!1}}function Ac(r){let e=r.match(/^data:([^;,]+)?(;base64)?,(.*)$/s);return e?{mediaType:e[1]??"text/plain",isBase64:!!e[2],data:e[3]??""}:null}function Cc(r,e,t=!0){if(typeof r=="string")return t?`data:${e};base64,${btoa(r)}`:`data:${e},${encodeURIComponent(r)}`;let n=new TextDecoder("iso-8859-1").decode(r);return`data:${e};base64,${btoa(n)}`}function vc(r,e){let t=Ce(r),n=Ce(e);if(!t||!n)throw new TypeError(`Cannot diff invalid URLs: "${r}" vs "${e}"`);let s={addedParams:{},removedParams:{},changedParams:{}};t.protocol!==n.protocol&&(s.protocol=[t.protocol,n.protocol]),t.hostname!==n.hostname&&(s.hostname=[t.hostname,n.hostname]),t.port!==n.port&&(s.port=[t.port,n.port]),t.pathname!==n.pathname&&(s.pathname=[t.pathname,n.pathname]),t.hash!==n.hash&&(s.hash=[t.hash,n.hash]);for(let[o,i]of t.searchParams.entries()){let a=n.searchParams.get(o);a===null?s.removedParams[o]=i:a!==i&&(s.changedParams[o]=[i,a])}for(let[o,i]of n.searchParams.entries())t.searchParams.has(o)||(s.addedParams[o]=i);return t.search!==n.search&&!Object.keys(s.changedParams).length&&!Object.keys(s.addedParams).length&&!Object.keys(s.removedParams).length&&(s.search=[t.search,n.search]),s}function Ce(r){try{return new URL(r)}catch{return null}}function Pc(r){return Ae.from(r).addTrailingSlash().toString()}function Ic(r){return Ae.from(r).removeTrailingSlash().toString()}function Lc(r){return Ae.from(r).removeHash().toString()}function Mc(r){try{let e=new URL(r);return e.search="",e.toString()}catch{return r}}function Oc(r){try{let t=new URL(r).pathname.split("/").pop()??"",n=t.lastIndexOf(".");return n===-1?"":t.slice(n+1).toLowerCase()}catch{return""}}function Dc(r){try{let e=new URL(r).pathname;return ke(e.split("/").filter(Boolean).pop()??"")}catch{return""}}function Nc(r,...e){return Ae.from(r).redactParams(...e).toString()}fe();function Uc(r={}){return new It(r)}var nh=Uc;return Jc(sh);})();
|
|
86
|
+
`}async function ts(r,e){let t=await Ar(e.credentials),n=Rr(e),s=ut(n),o=`${s}/${e.region}/${e.service}/aws4_request`,i=`${t.accessKeyId}/${o}`,a=JSON.stringify(r),c=btoa(a),l=await ft(t.secretAccessKey,s,e.region,e.service),u=await pe(l,c),f=ht(u),p={policy:c,signature:f,credential:i,date:s};return t.sessionToken&&(p.securityToken=t.sessionToken),p}function rs(r){let e=r.date??r.Date;if(!e)return 0;let t=new Date(e).getTime();return isNaN(t)?0:Math.round((t-Date.now())/1e3)}function ns(r,e){return r!==403&&r!==400?!1:e.includes("RequestTimeTooSkewed")||e.includes("RequestExpired")||e.includes("InvalidSignatureException")||e.includes("AuthFailure")||e.includes("SignatureDoesNotMatch")}var ae=class{constructor(e){h(this,"config");h(this,"clockSkewSecs",0);this.config=e}async sign(e){return await kr(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}async presign(e,t){return await Zn(e,{...this.config,clockSkewSecs:this.clockSkewSecs},t)}async signPostPolicy(e){return await ts(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}async initChunked(e){return await es(e,{...this.config,clockSkewSecs:this.clockSkewSecs})}updateClockSkew(e){let t=rs(e);t!==0&&(this.clockSkewSecs=t)}handleClockSkewError(e,t,n){return ns(e,t)?(this.updateClockSkew(n),!0):!1}};async function Ar(r){return await(typeof r=="function"?r():Promise.resolve(r))}function Vn(r){let e=globalThis.Deno;if(typeof e<"u")try{return e.env.get(r)}catch{}try{return globalThis.process?.env?.[r]}catch{}}async function Jn(r,e,t){let n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let o=e.signal&&typeof AbortSignal<"u"&&"any"in AbortSignal?AbortSignal.any([e.signal,n.signal]):n.signal,i=await fetch(r,{...e,signal:o});return clearTimeout(s),i}catch(o){throw n.signal.aborted?new Q(t):o}finally{clearTimeout(s)}}function Ji(r){return new ae({credentials:r.credentials,region:r.region,service:"s3",doubleEncodeUri:!1,unsignedPayload:r.unsignedPayload??!1})}function Qi(r){return new ae({credentials:r.credentials,region:r.region,service:"execute-api"})}function Gi(r){return new ae({credentials:r.credentials,region:r.region,service:"sts"})}function Xi(r){return new ae({credentials:r.credentials,region:r.region,service:"dynamodb"})}z();function Ll(r){let e=[];for(let u=0;u<r.length;u++){let f=r.charCodeAt(u);if(f<128)e.push(f);else if(f<2048)e.push(192|f>>6,128|f&63);else if(f<55296||f>=57344)e.push(224|f>>12,128|f>>6&63,128|f&63);else{u++;let p=r.charCodeAt(u),d=65536+((f&1023)<<10|p&1023);e.push(240|d>>18,128|d>>12&63,128|d>>6&63,128|d&63)}}let t=e.length*8;for(e.push(128);e.length*8%512!==448;)e.push(0);for(let u=0;u<4;u++)e.push(t>>>u*8&255);for(let u=4;u<8;u++)e.push(0);let n=[3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],s=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],o=1732584193,i=4023233417,a=2562383102,c=271733878;for(let u=0;u<e.length;u+=64){let f=[];for(let y=0;y<16;y++){let b=e[u+y*4],x=e[u+y*4+1],E=e[u+y*4+2],R=e[u+y*4+3];f[y]=(b|x<<8|E<<16|R<<24)>>>0}let p=o,d=i,g=a,m=c;for(let y=0;y<64;y++){let b,x;y<16?(b=d&g|~d&m,x=y):y<32?(b=m&d|~m&g,x=(5*y+1)%16):y<48?(b=d^g^m,x=(3*y+5)%16):(b=g^(d|~m),x=7*y%16),b=b+p+n[y]+f[x]>>>0,p=m,m=g,g=d,d=d+(b<<s[y]|b>>>32-s[y])>>>0}o=o+p>>>0,i=i+d>>>0,a=a+g>>>0,c=c+m>>>0}function l(u){let f="";for(let p=0;p<4;p++)f+=(u>>>p*8&255).toString(16).padStart(2,"0");return f}return l(o)+l(i)+l(a)+l(c)}function ss(r){let e={algorithm:"MD5"},t=r.replace(/^Digest\s+/i,"").trim(),n=/(\w+)\s*=\s*(?:"([^"]*)"|([^,\s]+))/g,s;for(;(s=n.exec(t))!==null;){let o=s[1].toLowerCase(),i=s[2]??s[3];switch(o){case"realm":e.realm=i;break;case"nonce":e.nonce=i;break;case"opaque":e.opaque=i;break;case"algorithm":e.algorithm=i.toUpperCase();break;case"qop":e.qop=i;break;case"domain":e.domain=i;break;case"charset":e.charset=i;break;case"userhash":e.userhash=i==="true";break;case"stale":e.stale=i==="true";break}}if(!e.realm)throw new Error("Digest challenge missing 'realm'");if(!e.nonce)throw new Error("Digest challenge missing 'nonce'");return e}async function Ml(r){let e=new TextEncoder,t=await crypto.subtle.digest("SHA-256",e.encode(r)),n=new Uint8Array(t);return Array.from(n).map(s=>s.toString(16).padStart(2,"0")).join("")}function Ol(r){let e=[0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n],t=[0x22312194fc2bf72cn,0x9f555fa3c84c64c2n,0x2393b86b6f53b151n,0x963877195940eabdn,0x96283ee2a88effe3n,0xbe5e1e2553863992n,0x2b0199fc2c85b8aan,0x0eb72ddc81c52ca2n],n=[];for(let c=0;c<r.length;c++){let l=r.charCodeAt(c);if(l<128)n.push(l);else if(l<2048)n.push(192|l>>6,128|l&63);else if(l<55296||l>=57344)n.push(224|l>>12,128|l>>6&63,128|l&63);else{c++;let u=r.charCodeAt(c),f=65536+((l&1023)<<10|u&1023);n.push(240|f>>18,128|f>>12&63,128|f>>6&63,128|f&63)}}let s=BigInt(n.length*8);for(n.push(128);n.length*8%1024!==896;)n.push(0);for(let c=15;c>=0;c--)n.push(Number(s>>BigInt(c*8)&0xffn));function o(c,l){return c>>l|c<<64n-l&0xffffffffffffffffn}let i=t.slice();for(let c=0;c<n.length;c+=128){let l=new Array(80);for(let x=0;x<16;x++){let E=0n;for(let R=0;R<8;R++)E=E<<8n|BigInt(n[c+x*8+R]);l[x]=E}for(let x=16;x<80;x++){let E=o(l[x-15],1n)^o(l[x-15],8n)^l[x-15]>>7n,R=o(l[x-2],19n)^o(l[x-2],61n)^l[x-2]>>6n;l[x]=l[x-16]+E+l[x-7]+R&0xffffffffffffffffn}let u=i[0],f=i[1],p=i[2],d=i[3],g=i[4],m=i[5],y=i[6],b=i[7];for(let x=0;x<80;x++){let E=o(g,14n)^o(g,18n)^o(g,41n),R=g&m^~g&y,A=b+E+R+e[x]+l[x]&0xffffffffffffffffn,U=o(u,28n)^o(u,34n)^o(u,39n),_=u&f^u&p^f&p,v=U+_&0xffffffffffffffffn;b=y,y=m,m=g,g=d+A&0xffffffffffffffffn,d=p,p=f,f=u,u=A+v&0xffffffffffffffffn}i=[i[0]+u&0xffffffffffffffffn,i[1]+f&0xffffffffffffffffn,i[2]+p&0xffffffffffffffffn,i[3]+d&0xffffffffffffffffn,i[4]+g&0xffffffffffffffffn,i[5]+m&0xffffffffffffffffn,i[6]+y&0xffffffffffffffffn,i[7]+b&0xffffffffffffffffn]}let a="";for(let c=0;c<4;c++)a+=i[c].toString(16).padStart(16,"0");return a}async function os(r,e,t,n,s,o,i){let a=r.qop||"",c=r.nonce,l=r.realm,u=o||tt(5),f=i||"00000001",p=Dl(r.algorithm);async function d(x){return p==="MD5"?Ll(x):p==="SHA-512-256"?Ol(x):await Ml(x)}let g=await d(`${e}:${l}:${t}`),m=await d(`${n}:${s}`),y,b=a.split(/\s*,\s*/).filter(Boolean);return b.includes("auth")||b.includes("auth-int")?y=await d(`${g}:${c}:${f}:${u}:${b[0]}:${m}`):y=await d(`${g}:${c}:${m}`),y}function Dl(r){let e=r.toUpperCase().replace(/-/g,"");return e==="SHA256"?"SHA-256":e==="SHA512256"?"SHA-512-256":"MD5"}function is(r,e,t,n,s,o){let i=[],a=s||tt(5),c=o||"00000001";return i.push(`username="${e}"`),i.push(`realm="${r.realm}"`),i.push(`nonce="${r.nonce}"`),i.push(`uri="${n}"`),i.push(`response="${t}"`),r.opaque&&i.push(`opaque="${r.opaque}"`),r.algorithm&&r.algorithm!=="MD5"&&i.push(`algorithm=${r.algorithm}`),r.qop&&(i.push(`qop=${r.qop.split(/\s*,\s*/)[0]}`),i.push(`nc=${c}`),i.push(`cnonce="${a}"`)),`Digest ${i.join(", ")}`}async function Cr(r,e,t,n,s){let o=ss(r),i=tt(5),a="00000001",c=await os(o,e,t,n,s,i,a);return is(o,e,c,s,i,a)}Yt();var Uu={maxRetries:3,baseDelayMs:300,maxDelayMs:3e4,jitter:.3,statuses:[408,429,500,502,503,504],onNetworkError:!0,onTimeout:!1,methods:["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]},Mo=class{constructor(){h(this,"_req",new Map);h(this,"_res",new Map);h(this,"_err",new Map);h(this,"_seq",0)}get request(){return Array.from(this._req.values())}get response(){return Array.from(this._res.values())}get error(){return Array.from(this._err.values())}addRequest(e){let t=++this._seq;return this._req.set(t,e),()=>{this._req.delete(t)}}addResponse(e){let t=++this._seq;return this._res.set(t,e),()=>{this._res.delete(t)}}addError(e){let t=++this._seq;return this._err.set(t,e),()=>{this._err.delete(t)}}clear(){this._req.clear(),this._res.clear(),this._err.clear()}};function $u(r){if(r){let n=r.spanContext(),s=n.traceFlags.toString(16).padStart(2,"0");return{traceparent:`00-${n.traceId}-${n.spanId}-${s}`,traceId:n.traceId,spanId:n.spanId}}let e=Oo(32),t=Oo(16);return{traceparent:`00-${e}-${t}-01`,traceId:e,spanId:t}}function Oo(r){return tt(r/2)}var Hu=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-access-token","x-refresh-token","x-csrf-token","x-session-id","x-session-token","x-secret","x-secret-key","x-private-key","api-key","apikey","bearer","token","authentication","credentials","password","passwd","secret"]);function Wa(r,e){return Hu.has(r.toLowerCase())?{name:r,value:"***REDACTED***"}:{name:r,value:e}}var Do=class{constructor(e=1e4){h(this,"_buf",new Map);h(this,"_head",0);h(this,"_tail",0);h(this,"maxEntries");this.maxEntries=e}get entries(){return Array.from(this._buf.values())}record(e,t,n){let s=t.durationMs,o=0,i=s,a=0;try{if(typeof performance<"u"&&typeof performance.getEntriesByType=="function"){let u=performance.getEntriesByType("resource").filter(f=>f.name===t.url).pop();u&&u.requestStart>0&&(o=Math.max(0,u.responseStart-u.requestStart),a=Math.max(0,u.responseEnd-u.responseStart),i=Math.max(0,s-o-a))}}catch{}let c={startedDateTime:new Date(n).toISOString(),time:s,request:{method:e.method,url:e.url,httpVersion:t.httpVersion,headers:Object.entries(e.headers).map(([l,u])=>Wa(l,u)),queryString:(()=>{try{return Array.from(new URL(e.url).searchParams.entries()).map(([l,u])=>({name:l,value:u}))}catch{return[]}})(),bodySize:e.body?typeof e.body=="string"?new TextEncoder().encode(e.body).byteLength:e.body instanceof Uint8Array||e.body instanceof ArrayBuffer?e.body.byteLength:-1:0},response:{status:t.status,statusText:t.statusText,httpVersion:t.httpVersion,headers:Object.entries(t.headers).map(([l,u])=>Wa(l,u)),content:{size:t.rawBody?.byteLength??0,mimeType:t.headers["content-type"]??"application/octet-stream",...typeof t.data=="string"?{text:t.data}:{}},redirectURL:t.headers.location??"",bodySize:t.rawBody?.byteLength??0},timings:{send:o,wait:i,receive:a},cache:{}};this._buf.set(this._tail++,c),this._buf.size>this.maxEntries&&this._buf.delete(this._head++)}getHAR(){return{version:"1.2",creator:{name:"kinetex",version:"1.0.0",comment:`runtime:${me}`},entries:[...this.entries]}}clear(){this._buf.clear(),this._head=0,this._tail=0}get count(){return this._buf.size}};async function Ka(r,e){let t={...r.headers};switch(e.type){case"bearer":{let s=`Bearer ${typeof e.token=="function"?await e.token():e.token}`;if(!we(s))throw new S("Invalid bearer token \u2014 contains forbidden characters (CRLF/CTL)","EVALIDATION");t.authorization=s;break}case"basic":{let n=new TextEncoder,s=n.encode(e.username),o=n.encode(e.password),i=s.length+1+o.length,a=new Uint8Array(i);a.set(s),a.set(n.encode(":"),s.length),a.set(o,s.length+1);let c=$t(a);t.authorization=`Basic ${c}`,s.fill(0),o.fill(0),a.fill(0);break}case"apikey":{let n=typeof e.key=="function"?await e.key():e.key;if(!Me(e.header))throw new S(`Invalid apikey auth header name: "${e.header}"`,"EVALIDATION");if(!we(String(n)))throw new S(`Invalid apikey value for "${e.header}" \u2014 contains forbidden characters`,"EVALIDATION");t[e.header.toLowerCase()]=String(n);break}case"digest":break;case"custom":{let n=e.apply(r);if(!n)throw new Error("Custom auth 'apply' must return a KinetexRequest");return n}default:{let n=e;throw new Error(`Unknown auth type: ${n.type}`)}}return{...r,headers:t}}var ju=new Set(["authorization","cookie","proxy-authorization","x-api-key","x-auth-token","x-access-token","x-refresh-token","x-csrf-token","x-session-id","x-session-token","x-secret","x-secret-key","x-private-key","api-key","apikey","www-authenticate"]);function Po(r){try{let e=new URL(r);return e.username||e.password?(e.username="",e.password="",e.toString()):r}catch{return r.replace(/\/\/[^/@]*@/,"//")}}function or(r,e,t){let o;if(/^https?:\/\//i.test(e))o=e;else{let i=r??"";try{let a=i.replace(/\/$/,""),c=e.startsWith("/")?e.slice(1):e;o=new URL(c,a+"/").href}catch{let a=i.endsWith("/")?i:i+"/",c=e.startsWith("/")?e.slice(1):e;o=a+c}}if(!t||Object.keys(t).length===0){if(!Oe(o))throw new S(`URL "${Po(o)}" failed safety check \u2014 blocked private/loopback address or forbidden scheme`,"EVALIDATION");return o}try{let i=new URL(o),a=0;for(let[l,u]of Object.entries(t)){if(u==null)continue;let f=String(u);if(Array.isArray(u)){for(let p of u)if(p!=null){if(a++,a>100)throw new S(`Query parameter count ${a} exceeds limit of 100`,"EVALIDATION");i.searchParams.append(l,String(p))}}else{if(a++,a>100)throw new S(`Query parameter count ${a} exceeds limit of 100`,"EVALIDATION");i.searchParams.set(l,f)}}let c=i.toString();if(c.length>8192)throw new S(`URL length ${c.length} bytes exceeds limit of 8192 bytes`,"EVALIDATION");if(!Oe(c))throw new S(`URL "${Po(c)}" failed safety check \u2014 blocked private/loopback address or forbidden scheme`,"EVALIDATION");return c}catch(i){if(i instanceof S)throw i;o.includes("?")?o+="&":o+="?";let a=[],c=0;for(let[u,f]of Object.entries(t??{}))if(f!=null)if(Array.isArray(f)){for(let p of f)if(p!=null){if(c++,c>100)throw new S(`Query parameter count ${c} exceeds limit of 100`,"EVALIDATION");a.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(p))}`)}}else{if(c++,c>100)throw new S(`Query parameter count ${c} exceeds limit of 100`,"EVALIDATION");a.push(`${encodeURIComponent(u)}=${encodeURIComponent(String(f))}`)}let l=o+a.join("&");if(l.length>8192)throw new S(`URL length ${l.length} bytes exceeds limit of 8192 bytes`,"EVALIDATION");if(!Oe(l))throw new S(`URL "${Po(l)}" failed safety check \u2014 blocked private/loopback address or forbidden scheme`,"EVALIDATION");return l}}function It(...r){let e=Object.create(null);for(let t of r){if(!t)continue;let n=Object.keys(t);for(let s of n){if(s==="__proto__"||s==="constructor"||s==="prototype")continue;if(!Me(s))throw new S(`Invalid header name: "${s}" \u2014 contains forbidden characters`,"EVALIDATION");let o=t[s];if(o==null)continue;let i=Array.isArray(o)?o.map(String).join(", "):String(o);if(!we(i))throw new S(`Invalid header value for ${s}: contains forbidden characters`,"EVALIDATION");e[s.toLowerCase()]=i}}return e}function Va(r,e){if(e.attempt>r.maxRetries||!r.methods.includes(e.request.method))return!1;if(r.shouldRetry)return r.shouldRetry(e);if(e.error){let t=e.error,n=t.code;switch(n){case"EHTTPSTATUS":return r.statuses.includes(t.status??0);case"ETIMEOUT":return r.onTimeout===!0;case"ENETWORK":return r.onNetworkError;case"EABORT":return!1;case"ESIZELIMIT":return!1;case"EPARSE":return!1;case"EVALIDATION":return!1;case"EAUTH":return!1;case"EPROXY":return!1;case"EREDIRECT":return!1;case"EUNKNOWN":return!1;default:return!1}}return e.response?r.statuses.includes(e.response.status):!1}function Io(r,e,t){if(t!==null)return Math.min(t,r.maxDelayMs);let n=Math.min(e,31),s=r.baseDelayMs*Math.pow(2,n-1);if(!isFinite(s)||s>r.maxDelayMs)return r.maxDelayMs;let o=Math.min(s,r.maxDelayMs);return Math.floor(o+o*r.jitter*Math.random())}function zu(r){let e=r["retry-after"];if(!e)return null;if(/^\d+$/.test(e.trim())){let n=parseInt(e,10);return!isFinite(n)||n<0?null:Math.min(n,86400)*1e3}let t=Date.parse(e);return isNaN(t)?null:Math.max(0,Math.min(t-Date.now(),864e5))}var Lt=class r{constructor(e={}){h(this,"cfg");h(this,"transport");h(this,"interceptors");h(this,"harRecorder");h(this,"retryConfig");h(this,"_cache",null);h(this,"_cookieJar",null);h(this,"_logger",null);h(this,"_cacheInitLock",null);h(this,"_cookieJarInitLock",null);h(this,"_loggerInitLock",null);h(this,"_otelTracer",null);h(this,"_dedup",null);h(this,"_circuitBreakers",null);h(this,"_circuitBreakerKeyFn",null);h(this,"_wsClients",new Set);if(this.cfg=e,this.interceptors=new Mo,this.harRecorder=e.har===!0?new Do:null,this.retryConfig={...Uu,...e.retry},e.circuitBreakerKeyFn&&(this._circuitBreakerKeyFn=e.circuitBreakerKeyFn),e.rateLimit){let t=qt(e.rateLimit);this.interceptors.addRequest(t)}if(e.awsSigning){let t=new ae(e.awsSigning);this.interceptors.addRequest(async n=>{let s=n.request,o=null;(s.body instanceof Uint8Array||typeof s.body=="string")&&(o=s.body);let i=await t.sign({method:s.method,url:s.url,headers:{...s.headers},body:o});n.request={...s,headers:i.headers}})}if(this.transport=Qt(e.fetch,e.httpVersion!=="HTTP/1.1",void 0,e.strictHeaders?{strict:!0}:void 0),e.interceptors&&(e.interceptors.request?.forEach(t=>this.interceptors.addRequest(t)),e.interceptors.response?.forEach(t=>this.interceptors.addResponse(t)),e.interceptors.error?.forEach(t=>this.interceptors.addError(t))),e.auth?.type==="digest"){let t=e.auth;this.interceptors.addResponse(async n=>{if(!n.response||n.response.status!==401)return;let s=n.response.headers["www-authenticate"];if(!s||!s.toLowerCase().startsWith("digest")||n.request.meta.__digestRetried)return;let o=n.request.method,i=new URL(n.request.url).pathname+new URL(n.request.url).search,a=await Cr(s,t.username,t.password,o,i);return{...n.request,headers:{...n.request.headers,authorization:a},meta:{...n.request.meta,__digestRetried:!0}}})}}useRequest(e){return this.interceptors.addRequest(e)}attachHookRegistry(e){let t=this.useRequest(async o=>{let i={url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta},a={request:i,response:null,error:null,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta},c=await e.runBeforeRequest(i,a);c!==i&&(o.request={...o.request,...c})}),n=this.useResponse(async o=>{if(!o.response)return;let i={status:o.response.status,statusText:o.response.statusText,headers:o.response.headers,body:o.response.rawBody??null,request:{url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta}},a={request:i.request,response:i,error:null,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta};await e.runAfterResponse(i,a)}),s=this.useError(async o=>{if(!o.error)return;let i={error:o.error,request:{url:o.request.url,method:o.request.method,headers:o.request.headers,body:o.request.body,signal:o.request.signal,meta:o.request.meta},response:null,attempt:o.attempt},a={request:i.request,response:null,error:o.error,startedAt:o.startedAt,attempt:o.attempt,meta:o.request.meta};await e.runOnError(i,a)});return()=>{t(),n(),s()}}useResponse(e){return this.interceptors.addResponse(e)}useError(e){return this.interceptors.addError(e)}getHAR(){if(!this.harRecorder)throw new S("HAR recording not enabled. Pass `har: true` in config.","EUNKNOWN");return this.harRecorder.getHAR()}clearHAR(){this.harRecorder?.clear()}async getCache(){if(this._cache)return this._cache;if(!this.cfg.cache)return null;if(this._cacheInitLock)return await this._cacheInitLock,this._cache;let e=()=>{};this._cacheInitLock=new Promise(t=>{e=t});try{let{HTTPCache:t}=await Promise.resolve().then(()=>(jt(),Di));return this._cache=new t(this.cfg.cache),this._cache}finally{e(),this._cacheInitLock=null}}async getCookieJar(){if(this._cookieJar)return this._cookieJar;if(!this.cfg.cookieJar)return null;if(this._cookieJarInitLock)return await this._cookieJarInitLock,this._cookieJar;if(this.cfg.cookieJar instanceof Object&&"setCookie"in this.cfg.cookieJar)return this._cookieJar=this.cfg.cookieJar,this._cookieJar;let e=()=>{};this._cookieJarInitLock=new Promise(t=>{e=t});try{let{CookieJar:t}=await Promise.resolve().then(()=>(Js(),Ia));return this._cookieJar=new t,this._cookieJar}finally{e(),this._cookieJarInitLock=null}}async getLogger(){if(this._logger)return this._logger;if(!this.cfg.logger)return null;if(this._loggerInitLock)return await this._loggerInitLock,this._logger;let e=()=>{};this._loggerInitLock=new Promise(t=>{e=t});try{let{createLogger:t}=await Promise.resolve().then(()=>(en(),Oa));return this._logger=t(this.cfg.logger),this._logger}finally{e(),this._loggerInitLock=null}}extend(e){let t=this.cfg.interceptors?.request??[],n=this.cfg.interceptors?.response??[],s=this.cfg.interceptors?.error??[],o=e.interceptors?.request??[],i=e.interceptors?.response??[],a=e.interceptors?.error??[],c=new r({...this.cfg,...e,headers:It(this.cfg.headers,e.headers),params:{...this.cfg.params,...e.params},interceptors:{request:[...t,...o],response:[...n,...i],error:[...s,...a]}}),l=new Set([...t,...o]),u=new Set([...n,...i]),f=new Set([...s,...a]);for(let p of this.interceptors.request)l.has(p)||c.useRequest(p);for(let p of this.interceptors.response)u.has(p)||c.useResponse(p);for(let p of this.interceptors.error)f.has(p)||c.useError(p);return this._circuitBreakers&&!c._circuitBreakers&&(c._circuitBreakers=this._circuitBreakers),this._dedup&&!c._dedup&&(c._dedup=this._dedup),this._otelTracer&&!c._otelTracer&&(c._otelTracer=this._otelTracer),c}setTracer(e){return this._otelTracer=e,this}enableDedup(e){return this._dedup=new Ie(e),this}disableDedup(){return this._dedup=null,this}get dedupMetrics(){return this._dedup?{hits:this._dedup.hits,misses:this._dedup.misses,inFlightCount:this._dedup.inFlightCount}:null}enableCircuitBreaker(e){return this._circuitBreakers=new Le(e),this}disableCircuitBreaker(){return this._circuitBreakers=null,this}tripCircuit(e){return this._circuitBreakers?.trip(e),this}resetCircuit(e){return this._circuitBreakers?.reset(e),this}get circuitSnapshots(){return this._circuitBreakers?.snapshots()??{}}async ws(e,t={}){let n=or(this.cfg.baseURL,e,this.cfg.params),s=It(this.cfg.headers,t.headers),o={},i=this.cfg.auth;if(i){if(i.type==="bearer"){let d=typeof i.token=="function"?await i.token():i.token;o.authorization=`Bearer ${d}`}else if(i.type==="basic"){let d=new TextEncoder,g=d.encode(i.username),m=d.encode(i.password),y=new Uint8Array(g.length+1+m.length);y.set(g),y[g.length]=58,y.set(m,g.length+1);let b=$t(y);y.fill(0),g.fill(0),m.fill(0),o.authorization=`Basic ${b}`}else if(i.type==="apikey"){let d=typeof i.key=="function"?await i.key():i.key;o[i.header.toLowerCase()]=typeof d=="string"?d:await d}}let a=await this.getCookieJar();if(a){let d=a.getCookieHeader({url:n,http:!1});d&&(s.cookie=d)}try{let d=new URL(n);if(this.cfg.baseURL){let g=new URL(this.cfg.baseURL),m=d.protocol==="wss:",y=g.protocol==="https:";if(m!==y||d.host!==g.host)throw new S(`WebSocket origin ${d.origin} does not match baseURL origin ${g.origin}`,"EVALIDATION")}}catch(d){throw d instanceof S?d:new S(`Invalid WebSocket URL: ${d}`,"EVALIDATION")}if(this._circuitBreakers){let d=this._circuitBreakerKeyFn?this._circuitBreakerKeyFn({url:n,method:"GET",headers:s,body:null,signal:null,meta:{}}):new URL(n).origin;if(this._circuitBreakers.get(d).state==="OPEN")throw new S(`Circuit breaker is open for WebSocket origin ${new URL(n).origin}`,"ENETWORK")}let c=this.cfg.ws,l={...c?.highWaterMark!==void 0?{highWaterMark:c.highWaterMark}:{},...c?.lowWaterMark!==void 0?{lowWaterMark:c.lowWaterMark}:{},...c?.maxSendRate!==void 0?{maxSendRate:c.maxSendRate}:{},...c?.keepRooms!==void 0?{keepRooms:c.keepRooms}:{},...t},u=l.onClose,f=(d,g,m)=>{m||this._wsClients.delete(p),u?.(d,g,m)},p=new De({url:n,headers:{...o,...s},...l,onClose:f});return this._wsClients.add(p),await p.connect().catch(d=>{throw this._wsClients.delete(p),d}),p}async send(e,t,n={}){let s=un(),o=Date.now(),i=n.timeout!==void 0?n.timeout:this.cfg.timeout??3e4,a=n.retry===!1?!1:{...this.retryConfig,...n.retry??{}},c=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS","TRACE","CONNECT"],l=t.toUpperCase();if(!c.includes(l))throw new S(`Invalid HTTP method '${t}'. Valid methods: ${c.join(", ")}`,"EVALIDATION");let u=or(n.baseURL??this.cfg.baseURL,e,qu(this.cfg.params,n.params));if(n.proxy??this.cfg.proxy)throw new S("proxy is configured but kinetex's built-in transports cannot route through it: HTTP(S) proxies require a custom fetch with a proxy agent (e.g. undici ProxyAgent passed via the `fetch` option), and SOCKS5 requires createSocks5Tunnel() from kinetex/socks5. Set up one of those instead of relying on `proxy` silently doing nothing.","EVALIDATION");if(this.cfg.httpsOnly)try{let _=new URL(u);if(_.protocol!=="https:")throw new S(`HTTPS-only mode enabled but URL uses ${_.protocol}. Use HTTPS URLs only.`,"EVALIDATION")}catch(_){throw _ instanceof S?_:new S(`Invalid URL: ${_}`,"EVALIDATION")}let p=n.maxRequestSize??this.cfg.maxRequestSize??0;if(p>0&&n.body){let _=0;if(typeof n.body=="string")_=new TextEncoder().encode(n.body).byteLength;else if(n.body instanceof Uint8Array)_=n.body.byteLength;else if(n.body instanceof ArrayBuffer)_=n.body.byteLength;else if(n.body instanceof Blob)_=n.body.size;else if(ArrayBuffer.isView(n.body))_=n.body.byteLength;else if(n.body instanceof URLSearchParams)_=new TextEncoder().encode(n.body.toString()).byteLength;else if(n.body instanceof FormData){for(let[O,H]of n.body)_+=new TextEncoder().encode(O).byteLength+76,typeof H=="string"?_+=new TextEncoder().encode(H).byteLength:_+=H.size;_+=76}else{if(n.body instanceof ReadableStream)throw new S("maxRequestSize cannot be enforced for ReadableStream bodies \u2014 pass maxRequestSize: 0 to opt out, or buffer the body first","EVALIDATION");n.body&&typeof n.body=="object"&&(_=new TextEncoder().encode(JSON.stringify(n.body)).byteLength)}if(_>p)throw new S(`Request body size ${_} bytes exceeds limit of ${p} bytes`,"EVALIDATION")}let d={url:u,method:t,headers:It(this.cfg.headers,n.headers),body:n.body??null,signal:n.signal??null,meta:{...n.meta},httpVersion:n.httpVersion??this.cfg.httpVersion??"HTTP/2"};d.body!==null&&typeof d.body=="object"&&!(d.body instanceof Uint8Array)&&!(d.body instanceof ArrayBuffer)&&!(d.body instanceof ReadableStream)&&!(d.body instanceof FormData)&&!(d.body instanceof URLSearchParams)&&!(d.body instanceof Blob)&&!d.headers["content-type"]&&(d={...d,headers:{...d.headers,"content-type":"application/json"},body:JSON.stringify(d.body)});let g=n.auth!==!1?n.auth??this.cfg.auth:void 0;g&&(d=await Ka(d,g)),this.cfg.transformRequest&&(d=await this.cfg.transformRequest(d));let m=await this.getCookieJar();if(m){let _=m.getCookieHeader({url:d.url,http:!0});_&&(d={...d,headers:{...d.headers,cookie:_}})}let y=null;if(this._otelTracer){y=this._otelTracer.startSpan(`HTTP ${d.method}`,{kind:3});let{traceparent:_,traceId:v,spanId:O}=$u(y);y.setAttribute("http.request.method",d.method),y.setAttribute("url.full",d.url);try{y.setAttribute("server.address",new URL(d.url).hostname)}catch{}d={...d,headers:{...d.headers,traceparent:_},meta:{...d.meta,traceId:v,spanId:O}}}else if(d.meta.traceId&&!d.headers.traceparent){let _=String(d.meta.traceId),v=Oo(16);d={...d,headers:{...d.headers,traceparent:`00-${_}-${v}-01`},meta:{...d.meta,spanId:v}}}let b;if(this._circuitBreakerKeyFn)try{b=this._circuitBreakerKeyFn(d)}catch{b=d.url}else try{b=new URL(d.url).origin}catch{b=d.url}let x=()=>this._executeWithRetry(d,a,i,n,s,o),E=await $e(d.headers??{}),R=`${d.method}:${d.url}${E?":"+E:""}`,A=this._dedup?()=>this._dedup.execute(d.method,R,x).then(_=>_):x,U=this._circuitBreakers?()=>this._circuitBreakers.execute(b,A).then(_=>_):A;try{let _=await U();return y&&(y.setAttribute("http.response.status_code",_.status),y.setStatus({code:_.status<400?1:2}),y.end()),_}catch(_){throw y&&(y.setStatus({code:2,message:_ instanceof Error?_.message:String(_)}),_ instanceof Error&&y.recordException(_),y.end()),_}}async _executeWithRetry(e,t,n,s,o,i){let a=0;for(;;){if(a++,e.signal?.aborted)throw No();try{let c=await this._executeOnce(e,n,s,o,a,i,t);if(t&&a<=t.maxRetries){let l={request:e,response:c,error:null,attempt:a,maxRetries:t.maxRetries};if(t.shouldRetry?await t.shouldRetry(l):Va(t,l)){let f=Io(t,a,zu(c.headers));await t.onRetry?.(l,f),await this.cfg.hooks?.onRetry?.reduce(async(p,d)=>{await p,await d(l)},Promise.resolve()),await Lo(f,e.signal);continue}}return c}catch(c){if(t&&a<=t.maxRetries){let u={request:e,response:null,error:c,attempt:a,maxRetries:t.maxRetries};if(t.shouldRetry?await t.shouldRetry(u):Va(t,u)){let p=Io(t,a,null);await t.onRetry?.(u,p),await Lo(p,e.signal);continue}}let l=await this._runErrorInterceptors(e,c,a,o);if(l)return l;if(s.onError){let u=c instanceof S?c:new S(String(c),"EUNKNOWN",{request:e,cause:c});throw s.onError(u),u}throw c}}}async _sendFollowingRedirects(e,t,n,s){let i={...e,redirect:"manual"},a=(()=>{try{return new URL(e.url).origin}catch{return null}})(),c=new Set;for(let l=0;l<=20;l++){if(l>0&&s&&(()=>{try{return new URL(i.url).origin===a}catch{return!1}})()&&(i=await Ka(i,s)),l>0&&this.cfg.hooks?.onBeforeRequest)for(let p of this.cfg.hooks.onBeforeRequest){let d=await p(i,{request:i,response:null,error:null,startedAt:un(),attempt:1,meta:i.meta});d&&(i={...d,redirect:"manual"})}let u=await Fe(this.transport,i,t);if(l>0){let p=await this.getLogger();if(p){let d=i.meta.requestId??"redirect";p.logResponse(d,u.status,u.statusText,u.headers,new Uint8Array(0),1,!1)}}if(u.status>=300&&u.status<400&&!!u.headers.location){if(c.has(u.url))throw new S(`Redirect loop detected: ${u.url}`,"ENETWORK",{request:e});if(c.add(u.url),n.processResponseHeaders(u.headers,{url:u.url}),l===20)throw new S("Too many redirects (exceeded 20)","ENETWORK",{request:e});if(u.body)try{await u.body.cancel()}catch{}let p=u.headers.location,d;try{let x=new URL(p,u.url);d=x.href;let E=x.protocol.toLowerCase();if(E!=="http:"&&E!=="https:")throw new S(`Unsafe redirect to ${E} detected \u2014 only HTTP(S) allowed`,"ENETWORK",{request:e})}catch(x){throw x instanceof S?x:new S(`Invalid redirect location: ${p}`,"ENETWORK",{request:e,cause:x})}let g=u.status===301||u.status===302||u.status===303?"GET":i.method,m=g==="GET"||g==="HEAD"?null:i.body,y=n.getCookieHeader({url:d,http:!0}),b={...i.headers};y?b.cookie=y:delete b.cookie;try{if(new URL(d).origin!==new URL(i.url).origin)for(let x of ju)delete b[x]}catch{}i={...i,url:d,method:g,body:m,headers:b,redirect:"manual"};continue}return u}throw new S("Redirect loop","ENETWORK",{request:e})}async _executeOnce(e,t,n,s,o,i,a){let c={request:e,response:null,error:null,startedAt:s,attempt:o,aborted:!1,store:new Map},l=e.meta.requestId??`req-${o}-${Date.now()}`;if(this._trace(l,"request_interceptors","start",s,o),e=await this._runRequestInterceptors(c),this._trace(l,"request_interceptors","end",s,o),this._trace(l,"lifecycle_before","start",s,o),this.cfg.hooks?.onBeforeRequest)for(let k of this.cfg.hooks.onBeforeRequest){let P=await k(e,this._hookCtx(c));P&&(e=P)}if(this._trace(l,"lifecycle_before","end",s,o),n.cache!==!1&&this.cfg.cache){let k=await this.getCache();if(k){let P={url:e.url,method:e.method,headers:e.headers},C=await k.get(P);if(C&&!C.stale){let L=await this._buildResponse(C.entry.response,e,!0,o,s,n);if(this.cfg.hooks?.onBeforeResponse)for(let V of this.cfg.hooks.onBeforeResponse)await V(L,this._hookCtx(c));return L}if(C?.stale){if(await k.markSWRInFlight(P)){let D={...e,headers:{...e.headers,...k.buildConditionalHeaders(C.entry)}};(async()=>{try{let B=await Fe(this.transport,D,t),gn=await this.getCache();if(gn)if(B.status===304)await gn.revalidate({url:D.url,method:D.method,headers:D.headers},{status:304,statusText:"Not Modified",headers:B.headers,body:null});else{let{decompressBodyStream:Wc,readRawBody:Kc}=await Promise.resolve().then(()=>(Yt(),Aa)),Vc=await Wc(B.body,B.headers),Jc=await Kc(Vc,0,B.url,D.signal);await gn.set({url:D.url,method:D.method,headers:D.headers},{status:B.status,statusText:B.statusText,headers:B.headers,body:Jc},{tags:n.tags??[]})}}catch(B){if(this.cfg.onSWRError)try{this.cfg.onSWRError(B,D)}catch{}}finally{(await this.getCache())?.clearSWRInFlight(P)}})()}return await this._buildResponse(C.entry.response,e,!0,o,s,n)}}}let u=[];n.onUploadProgress&&u.push(n.onUploadProgress),this.cfg.hooks?.onUploadProgress&&u.push(...this.cfg.hooks.onUploadProgress);let f=u.length>0?u:null,p=null;if(f!==null&&e.body!==null){let k=null,P=null;if(e.body instanceof ReadableStream)k=e.body;else if(typeof e.body=="string"){let C=new TextEncoder().encode(e.body);P=C.byteLength,k=new ReadableStream({start:L=>{L.enqueue(C),L.close()}})}else if(e.body instanceof Uint8Array)P=e.body.byteLength,k=new ReadableStream({start:C=>{C.enqueue(e.body),C.close()}});else if(e.body instanceof ArrayBuffer){let C=new Uint8Array(e.body);P=C.byteLength,k=new ReadableStream({start:L=>{L.enqueue(C),L.close()}})}else if(typeof Blob<"u"&&e.body instanceof Blob)P=e.body.size,k=e.body.stream();else if(typeof URLSearchParams<"u"&&e.body instanceof URLSearchParams){let C=new TextEncoder().encode(e.body.toString());P=C.byteLength,k=new ReadableStream({start:L=>{L.enqueue(C),L.close()}})}if(k){let{stream:C}=Nt(k,P,{onProgress:L=>{let V=L;for(let D of u)D(V)},...e.signal!==null?{signal:e.signal}:{}});p=C,e={...e,body:C}}}e.headers["accept-encoding"]||(e={...e,headers:{...e.headers,"accept-encoding":"gzip, deflate, br"}});let d=await this.getCookieJar();this._trace(l,"transport_send","start",s,o);let g;try{g=d?await this._sendFollowingRedirects(e,t,d,n.auth!==!1?n.auth??this.cfg.auth:void 0):await Fe(this.transport,e,t)}catch(k){if(p)try{p.cancel("Request failed").catch(()=>{})}catch{}throw k}if(this._trace(l,"transport_send","end",s,o),g.status===304){let k=await this.getCache();if(k){let P=await k.revalidate({url:e.url,method:e.method,headers:e.headers},{status:304,statusText:"Not Modified",headers:g.headers,body:null});if(P)return await this._buildResponse(P.response,e,!0,o,s,n)}}g.alreadyDecompressed&&(delete g.headers["content-encoding"],delete g.headers["Content-Encoding"]);let m=await Xt(g.body,g.headers),y=[];n.onDownloadProgress&&y.push(n.onDownloadProgress),this.cfg.hooks?.onDownloadProgress&&y.push(...this.cfg.hooks.onDownloadProgress);let b=y.length>0?y:null,x=m;if(b&&x){let k=g.headers["content-length"],P=k?parseInt(k,10):null,C=new W(P&&!isNaN(P)?P:null,{onProgress:L=>{let V=L;for(let D of y)D(V)},...e.signal!==null?{signal:e.signal}:{}});x=new ReadableStream({async start(L){let V=x.getReader();try{for(;;){let{done:D,value:B}=await V.read();if(D){C.complete(),L.close();break}C.update(B.byteLength),L.enqueue(B)}}catch(D){L.error(D)}finally{V.releaseLock()}},cancel(){x?.cancel()}})}let E=n.maxResponseSize??this.cfg.maxResponseSize??0,R=await Gt(x,E,g.url,e.signal),A=await this.getCookieJar();A&&A.processResponseHeaders(g.headers,{url:g.url});let U=g.headers["content-type"]??null;this._trace(l,"response_parse","start",s,o);let _=await gt(R,U,n.parseResponse,n.parseFailure,g.headers,g.url);this._trace(l,"response_parse","end",s,o);let v=un()-s,O={status:g.status,statusText:g.statusText,headers:g.headers,data:this.cfg.transformResponse?this.cfg.transformResponse(_,{}):_,rawBody:R,url:g.url,cached:!1,redirected:g.redirected,httpVersion:g.httpVersion,durationMs:v,request:e,attempt:o};if(n.cache!==!1&&this.cfg.cache){let k=await this.getCache();k&&g.status!==304&&await k.set({url:e.url,method:e.method,headers:e.headers},{status:g.status,statusText:g.statusText,headers:g.headers,body:R},{tags:n.tags??[]})}let H=await this.getLogger();if(H){let k=c.store.get("requestId")??e.meta.requestId??"unknown";H.logResponse(k,O.status,O.statusText,O.headers,R,o,!1)}this.harRecorder?.record(e,O,i??Date.now()-O.durationMs),c.response=O,this._trace(l,"response_interceptors","start",s,o);let j=await this._runResponseInterceptors(c,O,e,t,n,s,o,a??!1);if(this._trace(l,"response_interceptors","end",s,o),this.cfg.hooks?.onBeforeResponse){let k=j;for(let P of this.cfg.hooks.onBeforeResponse){let C=await P(k,this._hookCtx(c));C&&(k=C)}}if((n.throwOnError??this.cfg.throwOnError??!0)&&j.status>=400)throw new ot(j,e);if(this.cfg.hooks?.onAfterResponse)for(let k of this.cfg.hooks.onAfterResponse)await k(j,this._hookCtx(c));return n.onSuccess?.(j),j}async _runRequestInterceptors(e){let t=e.request;for(let n of this.interceptors.request){e.request=t;let s=await n(e);s&&"url"in s&&!("status"in s)?t=s:e.request!==t&&(t=e.request)}return e.request=t,t}async _runResponseInterceptors(e,t,n,s,o,i,a,c){let l=t;for(let u of this.interceptors.response){let f=await u(e);if(f){if("status"in f&&"headers"in f)l=f;else if("url"in f&&"method"in f&&!("status"in f)){if(c&&a<=c.maxRetries){let p={request:n,response:t,error:null,attempt:a,maxRetries:c.maxRetries},d=Io(c,a,0);await c.onRetry?.(p,d),await this.cfg.hooks?.onRetry?.reduce(async(g,m)=>{await g,await m(p)},Promise.resolve()),await Lo(d,n.signal)}return this._executeOnce(f,s,o,i,a+1,void 0,c)}}}return l}async _runErrorInterceptors(e,t,n,s){let o={request:e,response:null,error:t,startedAt:s,attempt:n,aborted:!1,store:new Map};for(let i of this.interceptors.error){let a=await i(o);if(a&&"status"in a)return a}if(this.cfg.hooks?.onError)for(let i of this.cfg.hooks.onError){let a=await i(t,this._hookCtx(o));if(a)return a}return null}async _buildResponse(e,t,n,s,o,i){let a=e.body,c=a instanceof Uint8Array?a:typeof a=="string"?new TextEncoder().encode(a):null,l=c?await gt(c,e.headers["content-type"]??null,i.parseResponse,i.parseFailure,e.headers,"url"in e?e.url:t.url):null,u=un()-o,f="url"in e?e.url:t.url,p="redirected"in e?e.redirected:!1,d="httpVersion"in e?e.httpVersion:"HTTP/1.1";return{status:e.status,statusText:e.statusText,headers:e.headers,data:l,rawBody:c,url:f,cached:n,redirected:p,httpVersion:d,durationMs:u,request:t,attempt:s}}_hookCtx(e){return{request:e.request,response:e.response,error:e.error,startedAt:e.startedAt,attempt:e.attempt,meta:e.request.meta}}_trace(e,t,n,s,o,i){if(this.cfg.onPipelineTrace)try{console.debug("[kinetex:trace]",e,t,n,o),this.cfg.onPipelineTrace({requestId:e,stage:t,event:n,elapsedMs:typeof performance<"u"?performance.now()-s:Date.now()-s,attempt:o,...i})}catch{}}get(e,t){return this.send(e,"GET",t)}post(e,t,n){return this.send(e,"POST",{...n,...t!==void 0?{body:t}:{}})}put(e,t,n){return this.send(e,"PUT",{...n,...t!==void 0?{body:t}:{}})}patch(e,t,n){return this.send(e,"PATCH",{...n,...t!==void 0?{body:t}:{}})}delete(e,t){return this.send(e,"DELETE",t)}head(e,t){return this.send(e,"HEAD",t)}options(e,t){return this.send(e,"OPTIONS",t)}request(e,t){return new ir(this,e,t)}GET(e){return this.request("GET",e)}POST(e){return this.request("POST",e)}PUT(e){return this.request("PUT",e)}PATCH(e){return this.request("PATCH",e)}DELETE(e){return this.request("DELETE",e)}async sse(e,t={}){let{SSEClient:n}=await Promise.resolve().then(()=>(nr(),no)),s=It(this.cfg.headers,t.headers),o=or(this.cfg.baseURL,e,this.cfg.params),i=async(a,c)=>{let l=typeof a=="string"?a:a.url,u=c,f=await this.send(l,u.method??"GET",{headers:u.headers,body:u.body,signal:u.signal,throwOnError:!1,parseResponse:d=>d}),p={...f.headers};return delete p["content-encoding"],delete p["Content-Encoding"],new Response(f.rawBody?.buffer??null,{status:f.status,headers:p})};return new n({url:o,headers:s,fetch:i,...t})}async graphql(e,t={}){let{GraphQLClient:n}=await Promise.resolve().then(()=>(on(),Ba)),s=It(this.cfg.headers,t.headers),o=or(this.cfg.baseURL,e,this.cfg.params),i=async(a,c)=>{let l=typeof a=="string"?a:a.url,u=c,f=await this.send(l,u.method??"POST",{headers:u.headers,body:u.body,signal:u.signal,throwOnError:!1,parseResponse:d=>d}),p={...f.headers};return delete p["content-encoding"],delete p["Content-Encoding"],new Response(f.rawBody?.buffer??null,{status:f.status,headers:p})};return new n({url:o,headers:s,fetch:i,...t})}async paginate(e,t){let{createPagePaginator:n}=await Promise.resolve().then(()=>(ln(),Fa)),s=or(this.cfg.baseURL,e,this.cfg.params);return n({url:s,fetch:async(i,a)=>{let c=typeof i=="string"?i:i.url,l=a,u=await this.send(c,l.method??"GET",{headers:l.headers,body:l.body,signal:l.signal,throwOnError:!1,parseResponse:p=>p}),f={...u.headers};return delete f["content-encoding"],delete f["Content-Encoding"],new Response(u.rawBody?.buffer??null,{status:u.status,headers:f})},headers:It(this.cfg.headers),...t})}async destroy(){for(let e of this._wsClients)try{e.close(1e3,"Client destroyed")}catch{}if(this._wsClients.clear(),this._cache)try{await this._cache.clear()}catch{}Be&&this.transport&&"destroy"in this.transport&&this.transport.destroy(),this._cookieJar=null,this._logger=null,this._dedup?.clear(),this._circuitBreakers?.clear?.(),this._otelTracer=null,this.interceptors.clear()}},ir=class{constructor(e,t,n){h(this,"client");h(this,"method");h(this,"_options",{});h(this,"_url");this.client=e,this.method=t,this._url=n}header(e,t){return this._options.headers={...this._options.headers,[e.toLowerCase()]:t},this}headers(e){return this._options.headers={...this._options.headers,...e},this}param(e,t){return this._options.params={...this._options.params,[e]:t},this}params(e){return this._options.params={...this._options.params,...e},this}withBody(e){return this._options.body=e,this}withJSON(e){return this._options.body=JSON.stringify(e),this._options.headers={...this._options.headers,"content-type":"application/json"},this}withForm(e){return this._options.body=e,this}bearer(e){return this._options.auth={type:"bearer",token:e},this}basic(e,t){return this._options.auth={type:"basic",username:e,password:t},this}apiKey(e,t){return this._options.auth={type:"apikey",header:e,key:t},this}digest(e,t){return this._options.auth={type:"digest",username:e,password:t},this}noAuth(){return this._options.auth=!1,this}retry(e,t){return this._options.retry={maxRetries:e,...t},this}noRetry(){return this._options.retry=!1,this}timeout(e){return this._options.timeout=e,this}proxy(e){return this._options.proxy=e,this}cache(e){return this._options.cache=e,this}noCache(){return this._options.cache={forceRefresh:!0},this}onUploadProgress(e){return this._options.onUploadProgress=e,this}onDownloadProgress(e){return this._options.onDownloadProgress=e,this}signal(e){return this._options.signal=e,this}maxSize(e){return this._options.maxResponseSize=e,this}http2(){return this._options.httpVersion="HTTP/2",this}http1(){return this._options.httpVersion="HTTP/1.1",this}noThrow(){return this._options.throwOnError=!1,this}tags(...e){return this._options.tags=e,this}meta(e){return this._options.meta={...this._options.meta,...e},this}send(){return this.client.send(this._url,this.method,this._options)}async data(){return(await this.client.send(this._url,this.method,this._options)).data}async json(){let e={...this._options};return e.headers={...e.headers,accept:"application/json"},(await this.client.send(this._url,this.method,e)).data}async text(){let e={...this._options};return e.parseResponse=n=>new TextDecoder("utf-8").decode(n),(await this.client.send(this._url,this.method,e)).data}async bytes(){let e={...this._options};return e.parseResponse=n=>n,(await this.client.send(this._url,this.method,e)).data}async blob(){let e=await this.bytes(),t="application/octet-stream";if(typeof Blob>"u")throw new S("Blob is not available in this runtime","EUNKNOWN");return new Blob([e.buffer],{type:t})}subscribe(e,t){this.client.send(this._url,this.method,{...this._options,onSuccess:e,...t!==void 0?{onError:t}:{}}).catch(n=>t?.(n instanceof S?n:new S(String(n),"EUNKNOWN")))}};function No(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let r=new Error("Aborted");return r.name="AbortError",r}function qu(r,e){if(!(!r&&!e))return{...r,...e}}function Lo(r,e){return new Promise((t,n)=>{if(e?.aborted){n(No());return}let s=()=>{clearTimeout(o),n(No())},o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);e?.addEventListener("abort",s,{once:!0})})}function un(){return typeof performance<"u"?performance.now():Date.now()}function Ja(r){try{return`${r.method}:${new URL(r.url).origin}`}catch{return`${r.method}:${r.url}`}}var hn=class{constructor(e,t={}){h(this,"_client");h(this,"_maxBatch");h(this,"_flushMs");h(this,"_queue",[]);h(this,"_timer",null);this._client=e,this._maxBatch=t.maxBatch??100,this._flushMs=t.flushMs??0}enqueue(e,t="GET",n={}){return new Promise((s,o)=>{let i={url:e,method:t,options:n,resolve:s,reject:o};this._queue.push(i);let a=n.signal;if(a){let c=()=>{let l=this._queue.indexOf(i);l!==-1&&(this._queue.splice(l,1),o(new S("Request aborted while queued","EABORT")))};if(i._abortCleanup=()=>a.removeEventListener("abort",c),a.addEventListener("abort",c,{once:!0}),a.aborted){a.removeEventListener("abort",c);let l=this._queue.indexOf(i);l!==-1&&this._queue.splice(l,1),o(new S("Request aborted before flush","EABORT"));return}}this._queue.length>=this._maxBatch?this._flushNow():this._timer||(this._flushMs===0?queueMicrotask(()=>{this._timer=null,this._flushNow()}):this._timer=setTimeout(()=>this._flushNow(),this._flushMs))})}flush(){for(;this._queue.length>0;)this._flushNow()}get pendingCount(){return this._queue.length}_flushNow(){if(this._timer!==null&&(clearTimeout(this._timer),this._timer=null),this._queue.length===0)return;let e=this._queue.splice(0,this._maxBatch);for(let t of e){let n=o=>{t._abortCleanup?.(),t.resolve(o)},s=o=>{t._abortCleanup?.(),t.reject(o)};try{this._client.send(t.url,t.method,t.options).then(n,s)}catch(o){s(o)}}}};jt();Gr();Yt();on();Ft();var ar=class{constructor(){h(this,"listeners",new Map)}on(e,t){let n=this.listeners.get(e)??[];return n.push({fn:t,once:!1}),this.listeners.set(e,n),this}once(e,t){let n=this.listeners.get(e)??[];return n.push({fn:t,once:!0}),this.listeners.set(e,n),this}off(e,t){let n=this.listeners.get(e);return n?(this.listeners.set(e,n.filter(s=>s.fn!==t)),this):this}async emit(e,t){let n=this.listeners.get(e);if(!n||n.length===0)return;let s=new Set;for(let o=0;o<n.length;o++){let i=n[o];try{await i.fn(t)}catch{}i.once&&s.add(o)}if(s.size>0){let o=n.filter((i,a)=>!s.has(a));this.listeners.set(e,o)}}removeAllListeners(e){return e?this.listeners.delete(e):this.listeners.clear(),this}},Bu=0;function Fu(){return`hook_${++Bu}`}function X(r){return[...r].sort((e,t)=>e.priority-t.priority)}var fn=class{constructor(){h(this,"beforeRequest",[]);h(this,"afterRequest",[]);h(this,"beforeResponse",[]);h(this,"afterResponse",[]);h(this,"onError",[]);h(this,"onRetry",[]);h(this,"onRedirect",[]);h(this,"onUploadProgress",[]);h(this,"onDownloadProgress",[]);h(this,"onCancel",[]);h(this,"onConnection",[]);h(this,"aroundHooks",[]);h(this,"emitter",new ar)}addBeforeRequest(e,t={}){return this._add(this.beforeRequest,e,t)}addAfterRequest(e,t={}){return this._add(this.afterRequest,e,t)}addBeforeResponse(e,t={}){return this._add(this.beforeResponse,e,t)}addAfterResponse(e,t={}){return this._add(this.afterResponse,e,t)}addOnError(e,t={}){return this._add(this.onError,e,t)}addOnRetry(e,t={}){return this._add(this.onRetry,e,t)}addOnRedirect(e,t={}){return this._add(this.onRedirect,e,t)}addOnUploadProgress(e,t={}){return this._add(this.onUploadProgress,e,t)}addOnDownloadProgress(e,t={}){return this._add(this.onDownloadProgress,e,t)}addOnCancel(e,t={}){return this._add(this.onCancel,e,t)}addOnConnection(e,t={}){return this._add(this.onConnection,e,t)}addAround(e,t={}){return this._add(this.aroundHooks,e,t)}remove(e){let t=!1,n=[this.beforeRequest,this.afterRequest,this.beforeResponse,this.afterResponse,this.onError,this.onRetry,this.onRedirect,this.onUploadProgress,this.onDownloadProgress,this.onCancel,this.onConnection,this.aroundHooks];for(let s of n){let o=s.length,i=s.filter(a=>a.id!==e);i.length<o&&(s.length=0,s.push(...i),t=!0)}return t}removeAll(){this.beforeRequest.length=0,this.afterRequest.length=0,this.beforeResponse.length=0,this.afterResponse.length=0,this.onError.length=0,this.onRetry.length=0,this.onRedirect.length=0,this.onUploadProgress.length=0,this.onDownloadProgress.length=0,this.onCancel.length=0,this.onConnection.length=0,this.aroundHooks.length=0}has(e){return[this.beforeRequest,this.afterRequest,this.beforeResponse,this.afterResponse,this.onError,this.onRetry,this.onRedirect,this.onUploadProgress,this.onDownloadProgress,this.onCancel,this.onConnection,this.aroundHooks].some(n=>n.some(s=>s.id===e))}async runBeforeRequest(e,t){let n=e;for(let s of X(this.beforeRequest)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(n,t));o&&typeof o=="object"&&"url"in o&&(n=o),this._maybeEject(s,this.beforeRequest)}return await this.emitter.emit("before:request",n),n}async runAfterRequest(e,t){for(let n of X(this.afterRequest))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.afterRequest));await this.emitter.emit("after:request",e)}async runBeforeResponse(e,t){let n=e;for(let s of X(this.beforeResponse)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(n,t));o&&typeof o=="object"&&"status"in o&&(n=o),this._maybeEject(s,this.beforeResponse)}return await this.emitter.emit("before:response",n),n}async runAfterResponse(e,t){for(let n of X(this.afterResponse))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.afterResponse));await this.emitter.emit("after:response",e)}async runOnError(e,t){for(let n of X(this.onError)){if(!this._shouldRun(n,t))continue;let s=await this._safeRun(n,()=>n.fn(e,t));if(this._maybeEject(n,this.onError),s&&typeof s=="object"&&"status"in s)return s}return await this.emitter.emit("error",e),null}async runOnRetry(e,t){for(let n of X(this.onRetry))this._shouldRun(n,t)&&(await this._safeRun(n,()=>n.fn(e,t)),this._maybeEject(n,this.onRetry));await this.emitter.emit("retry",e)}async runOnRedirect(e,t){let n=!0;for(let s of X(this.onRedirect)){if(!this._shouldRun(s,t))continue;let o=await this._safeRun(s,()=>s.fn(e,t));if(this._maybeEject(s,this.onRedirect),o===!1){n=!1;break}}return await this.emitter.emit("redirect",e),n}runOnUploadProgress(e,t){for(let n of X(this.onUploadProgress))if(this._shouldRun(n,t)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onUploadProgress)}this.emitter.emit("upload:progress",e)}runOnDownloadProgress(e,t){for(let n of X(this.onDownloadProgress))if(this._shouldRun(n,t)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onDownloadProgress)}this.emitter.emit("download:progress",e)}runOnCancel(e,t){for(let n of X(this.onCancel)){try{n.fn(e,t)}catch{}this._maybeEject(n,this.onCancel)}this.emitter.emit("cancel",e)}runOnConnection(e){for(let t of X(this.onConnection)){try{t.fn(e)}catch{}this._maybeEject(t,this.onConnection)}this.emitter.emit("connection",e)}wrapWithAround(e,t){let n=X(this.aroundHooks).reverse(),s=t;for(let o of n){let i=s;s=()=>{if(!this._shouldRun(o,e))return i();let a=o.fn(e,i);return this._maybeEject(o,this.aroundHooks),a}}return s}_add(e,t,n){let s=n.id??Fu();return e.push({id:s,priority:n.priority??0,once:n.once??!1,condition:n.condition??null,safe:n.safe??!1,fn:t}),s}_shouldRun(e,t){return e.condition?e.condition(t):!0}async _safeRun(e,t){try{return await t()}catch(n){if(!e.safe)throw n;console.error(`[lifecycle] Hook "${e.id}" threw:`,n);return}}_maybeEject(e,t){if(!e.once)return;let n=t.indexOf(e);n!==-1&&t.splice(n,1)}};var dn=class{constructor(e=10){h(this,"maxRedirects");h(this,"count",0);this.maxRedirects=e}record(e,t,n,s){if(this.count++,this.count>this.maxRedirects)throw new cr(this.count,e);return{from:e,to:t,status:n,count:this.count,request:s}}get redirectCount(){return this.count}reset(){this.count=0}},cr=class extends Error{constructor(t,n){super(`Too many redirects (${t}) at ${n}`);h(this,"count");h(this,"url");h(this,"code","ETOOMANYREDIRECTS");this.count=t,this.url=n,this.name="TooManyRedirectsError"}};function Qa(r){return async e=>(await r(e),e)}function Ga(r){return async e=>({...e,headers:{...e.headers,...typeof r=="function"?await r():r}})}function Xa(r){return e=>{if(/^https?:\/\//i.test(e.url))return;let t=r.endsWith("/")||e.url.startsWith("/")?"":"/";return{...e,url:`${r}${t}${e.url}`}}}function Ya(r=e=>e>=400){return e=>{if(e.response&&r(e.response.status))throw new lr(e.response.status,e.response.statusText,e.response)}}function Za(r){return e=>{let t=r(e);if(t===!0)return;let n=typeof t=="string"?t:`Response validation failed (status ${e.status})`;throw new ur(n,e)}}var lr=class extends Error{constructor(t,n,s){super(`HTTP ${t}: ${n}`);h(this,"status");h(this,"statusText");h(this,"response");h(this,"code","EHTTPERROR");this.status=t,this.statusText=n,this.response=s,this.name="HTTPError"}},ur=class extends Error{constructor(t,n){super(t);h(this,"response");h(this,"code","EVALIDATION");this.response=n,this.name="ResponseValidationError"}};function ec(...r){return async(e,t)=>{let n=e;for(let s of r){let o=await s(n,t);o&&typeof o=="object"&&"url"in o&&(n=o)}return n}}function tc(...r){return async(e,t)=>{let n=e;for(let s of r){let o=await s(n,t);o&&typeof o=="object"&&"status"in o&&(n=o)}return n}}function rc(...r){return(e,t)=>r.reduceRight((s,o)=>()=>o(e,s),t)()}function nc(r={}){let e=r.logger??((s,o)=>console.log(s,JSON.stringify(o))),t=new Set((r.redactHeaders??["authorization","cookie"]).map(s=>s.toLowerCase()));function n(s){let o={};for(let[i,a]of Object.entries(s))o[i]=t.has(i.toLowerCase())?"***":a;return o}return{beforeRequest:s=>{e("\u2192 request",{method:s.method,url:s.url,headers:n(s.headers)})},afterResponse:s=>{e("\u2190 response",{status:s.status,url:s.request.url,headers:n(s.headers)})},onError:s=>{e("\u2717 error",{url:s.request.url,error:s.error instanceof Error?s.error.message:String(s.error),status:s.response?.status??null})}}}function sc(){let r="__kinetex_timing__";return{beforeRequest:(e,t)=>{t.meta[r]=Uo()},afterResponse:(e,t)=>{let n=t.meta[r],s=n!==void 0?Uo()-n:null;s!==null&&(t.meta.durationMs=s)}}}function oc(r="utf-8"){return e=>{if(e.body instanceof Uint8Array)return{...e,body:new TextDecoder(r).decode(e.body)}}}function ic(){return{beforeRequest:(r,e)=>{if(r.signal?.aborted)throw e.meta.aborted=!0,Wu("Request aborted before sending")},onCancel:r=>{console.debug(`[lifecycle] Request cancelled: ${r.request.url}`,r.reason)}}}function Wu(r){if(typeof DOMException<"u")return new DOMException(r,"AbortError");let e=new Error(r);return e.name="AbortError",e}function Uo(){return typeof performance<"u"?performance.now():Date.now()}function ac(r,e={}){return{request:r,response:null,error:null,startedAt:Uo(),attempt:1,meta:{},...e}}en();ln();Wr();var Mt={NoAuth:0,GSSAPI:1,UserPassword:2,NoAcceptable:255},re={IPv4:1,Domain:3,IPv6:4},Ku={Connect:1,Bind:2,UdpAssociate:3},Y={Succeeded:0,GeneralFailure:1,ConnNotAllowed:2,NetworkUnreachable:3,HostUnreachable:4,ConnRefused:5,TtlExpired:6,CmdNotSupported:7,AddrTypeNotSupported:8},Vu={[Y.Succeeded]:"Succeeded",[Y.GeneralFailure]:"General SOCKS server failure",[Y.ConnNotAllowed]:"Connection not allowed by ruleset",[Y.NetworkUnreachable]:"Network unreachable",[Y.HostUnreachable]:"Host unreachable",[Y.ConnRefused]:"Connection refused",[Y.TtlExpired]:"TTL expired",[Y.CmdNotSupported]:"Command not supported",[Y.AddrTypeNotSupported]:"Address type not supported"},I=class extends Error{constructor(t,n,s=!1){super(t);h(this,"code");h(this,"retriable");this.code=n,this.retriable=s,this.name="Socks5Error"}};function Ju(r){let e=Vu[r]??`Unknown reply code 0x${r.toString(16)}`,t=r===Y.NetworkUnreachable||r===Y.TtlExpired;return new I(`SOCKS5 proxy error: ${e}`,`SOCKS5_REPLY_${r}`,t)}var Ho=class{constructor(e,t){h(this,"conn");h(this,"timeoutMs");h(this,"buf",new Uint8Array(0));this.conn=e,this.timeoutMs=t}async readExact(e){for(;this.buf.length<e;){let n=new Uint8Array(4096),o=await cc(this.conn.read(n),this.timeoutMs,"SOCKS5 handshake read timed out");if(o===null||o===0)throw new I("Connection closed during SOCKS5 handshake","SOCKS5_EOF");let i=new Uint8Array(this.buf.length+o);i.set(this.buf),i.set(n.subarray(0,o),this.buf.length),this.buf=i}let t=this.buf.slice(0,e);return this.buf=this.buf.slice(e),t}};function cc(r,e,t){return new Promise((n,s)=>{let o=setTimeout(()=>s(new I(t,"SOCKS5_TIMEOUT",!0)),e);r.then(i=>{clearTimeout(o),n(i)},i=>{clearTimeout(o),s(i)})})}function Qu(r,e){let t=r.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(t){let o=t.slice(1).map(Number);if(o.every(i=>i>=0&&i<=255))return new Uint8Array([re.IPv4,...o])}let n=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r;if(Gu(n)){let o=Xu(n);return new Uint8Array([re.IPv6,...o])}e||console.warn("[socks5] remoteDns=false but got a hostname; sending as DOMAINNAME");let s=new TextEncoder().encode(r);if(s.length>255)throw new I("Hostname too long for SOCKS5 (max 255 bytes)","SOCKS5_ADDR_TOO_LONG");return new Uint8Array([re.Domain,s.length,...s])}function Gu(r){return r.includes(":")}function Xu(r){let e=r.split("::"),t=o=>o?o.split(":").map(i=>parseInt(i||"0",16)):[],n;if(e.length===2){let o=t(e[0]),i=t(e[1]),a=new Array(8-o.length-i.length).fill(0);n=[...o,...a,...i]}else n=t(r);if(n.length!==8)throw new I(`Invalid IPv6 address: ${r}`,"SOCKS5_INVALID_ADDR");for(let o of n)if(o<0||o>65535)throw new I(`Invalid IPv6 group: ${o} out of range (0-65535)`,"SOCKS5_INVALID_ADDR");let s=[];for(let o of n)s.push(o>>8&255,o&255);return s}function $o(r,e){if(r===re.IPv4)return Array.from(e).join(".");if(r===re.IPv6){let t=[];for(let n=0;n<16;n+=2)t.push((e[n]<<8|e[n+1]).toString(16));return t.join(":")}return new TextDecoder().decode(e)}async function Yu(r,e,t){let n=new Ho(r,t.handshakeTimeoutMs),s=!!(t.username&&t.password),o=s?[Mt.NoAuth,Mt.UserPassword]:[Mt.NoAuth],i=new Uint8Array([5,o.length,...o]);await r.write(i);let a=await n.readExact(2);if(a[0]!==5)throw new I(`Unexpected SOCKS version in method response: ${a[0]}`,"SOCKS5_BAD_VERSION");let c=a[1];if(c===Mt.NoAcceptable)throw new I("SOCKS5 proxy rejected all authentication methods","SOCKS5_NO_ACCEPTABLE_METHOD");if(c===Mt.UserPassword){if(!s)throw new I("SOCKS5 proxy requires username/password but none provided","SOCKS5_AUTH_REQUIRED");await Zu(r,n,t.username,t.password)}else if(c!==Mt.NoAuth)throw new I(`SOCKS5 proxy chose unsupported auth method: 0x${c.toString(16)}`,"SOCKS5_UNSUPPORTED_METHOD");let l=Qu(e.host,t.remoteDns),u=e.port,f=[u>>8&255,u&255],p=new Uint8Array([5,Ku.Connect,0,...l,...f]);await r.write(p);let d=await n.readExact(4);if(d[0]!==5)throw new I(`Unexpected SOCKS version in reply: ${d[0]}`,"SOCKS5_BAD_VERSION");if(d[1]!==Y.Succeeded)throw Ju(d[1]);let g=d[3],m,y;if(g===re.IPv4)y=await n.readExact(4),m=$o(re.IPv4,y);else if(g===re.IPv6)y=await n.readExact(16),m=$o(re.IPv6,y);else if(g===re.Domain){let E=await n.readExact(1);y=await n.readExact(E[0]),m=$o(re.Domain,y)}else throw new I(`Unsupported bound address type in reply: 0x${g.toString(16)}`,"SOCKS5_UNSUPPORTED_ADDR_TYPE");let b=await n.readExact(2),x=b[0]<<8|b[1];return{boundAddr:m,boundPort:x}}async function Zu(r,e,t,n){let s=new TextEncoder,o=s.encode(t),i=s.encode(n);if(o.length>255||i.length>255)throw new I("Username or password too long (max 255 bytes)","SOCKS5_AUTH_TOO_LONG");let a=new Uint8Array([1,o.length,...o,i.length,...i]);await r.write(a);let c=await e.readExact(2);if(c[0]!==1&&c[0]!==5)throw new I(`Unexpected auth sub-negotiation version: ${c[0]}`,"SOCKS5_BAD_AUTH_VERSION");if(c[1]!==0)throw new I("SOCKS5 authentication failed (invalid credentials)","SOCKS5_AUTH_FAILED")}async function eh(r,e,t){let n;for(let s=0;s<=e;s++)try{return await r()}catch(o){if(n=o,!(o instanceof I&&o.retriable)||s===e)break;await th(t*Math.pow(2,s))}throw n}function th(r){return new Promise(e=>setTimeout(e,r))}function rh(r){return{host:r.host,port:r.port??1080,username:r.username??"",password:r.password??"",remoteDns:r.remoteDns??!0,connectTimeoutMs:r.connectTimeoutMs??1e4,handshakeTimeoutMs:r.handshakeTimeoutMs??1e4,maxRetries:r.maxRetries??2,retryDelayMs:r.retryDelayMs??300}}async function jo(r,e,t){let n=rh(r);return await eh(async()=>{let s=await cc(t(n.host,n.port,n.connectTimeoutMs),n.connectTimeoutMs,`TCP connection to SOCKS5 proxy ${n.host}:${n.port} timed out`);try{let{boundAddr:o,boundPort:i}=await Yu(s,e,n);return{conn:s,boundAddr:o,boundPort:i}}catch(o){throw s.close(),o}},n.maxRetries,n.retryDelayMs)}function lc(r){let e;try{nh(r),e=new URL(r)}catch{throw new I("Invalid SOCKS5 proxy URL: malformed URL","SOCKS5_BAD_URL")}if(e.protocol!=="socks5:"&&e.protocol!=="socks5h:")throw new I(`Expected socks5:// or socks5h:// scheme, got: ${e.protocol}`,"SOCKS5_BAD_SCHEME");let t=e.protocol==="socks5h:",n=e.hostname,s=e.port?parseInt(e.port,10):1080;if(!Number.isFinite(s)||s<1||s>65535)throw new I("Invalid SOCKS5 proxy URL: port must be between 1 and 65535","SOCKS5_BAD_URL");if(!n)throw new I("Invalid SOCKS5 proxy URL: no hostname specified (e.g., socks5://host:port)","SOCKS5_BAD_URL");let o={host:n,port:s,remoteDns:t};return e.username&&(o.username=decodeURIComponent(e.username)),e.password&&(o.password=decodeURIComponent(e.password)),o}function nh(r){try{let e=new URL(r);return`${e.protocol}//${e.host}${e.pathname}${e.search}${e.hash}`}catch{return"[redacted]"}}var uc=async(r,e,t)=>{let n=globalThis,s;return t&&t>0?s=await Promise.race([n.Deno.connect({hostname:r,port:e,transport:"tcp"}),new Promise((i,a)=>setTimeout(()=>a(new I("TCP connect to proxy timed out","SOCKS5_TIMEOUT",!0)),t))]):s=await n.Deno.connect({hostname:r,port:e,transport:"tcp"}),{read:async i=>{if(t&&t>0)return Promise.race([s.read(i).catch(()=>null),new Promise((a,c)=>setTimeout(()=>c(new I("TCP read timed out","SOCKS5_TIMEOUT",!0)),t))]);try{return await s.read(i)}catch{return null}},write:i=>s.write(i),close:()=>{try{s.close()}catch{}}}},hc=(r,e,t)=>new Promise((n,s)=>{import("node:net").then(({createConnection:o})=>{let i=o({host:r,port:e}),a=setTimeout(()=>{i.destroy(),s(new I("TCP connect to proxy timed out","SOCKS5_TIMEOUT",!0))},t),c=new Uint8Array(0),l=null,u=null,f=null,p=null;function d(){if(!l||!f||c.length===0)return;let m=Math.min(c.length,f.length);f.set(c.subarray(0,m)),c=c.slice(m);let y=l;l=null,u=null,f=null,y(m)}function g(m){if(u){let y=u;l=null,u=null,f=null,y(m)}}i.on("data",m=>{let y=new Uint8Array(c.length+m.length);y.set(c),y.set(m,c.length),c=y,d()}),i.on("end",()=>{l&&(l(null),l=null,u=null,f=null)}),i.once("error",m=>{clearTimeout(a),p=m,g(m),s(m)}),i.once("connect",()=>{clearTimeout(a),i.on("error",m=>{p=m,g(m)}),n({read:m=>new Promise((y,b)=>{if(p){b(p);return}if(c.length>0){let x=Math.min(c.length,m.length);m.set(c.subarray(0,x)),c=c.slice(x),y(x);return}l=y,u=b,f=m}),write:m=>new Promise((y,b)=>{i.write(m,x=>x?b(x):y(m.length))}),close:()=>i.destroy()})})}).catch(s)});function fc(r,e){return async(t,n,s)=>(await jo({connectTimeoutMs:s,...r},{host:t,port:n},e)).conn}nr();Ne();Ne();Yt();jt();Js();nr();on();ln();en();Wr();Ft();var zo=class extends Error{constructor(t){super(t);h(this,"code","URL_VALIDATION_ERROR");this.name="URLValidationError"}},sh=/^[A-Za-z0-9\-._~]$/,oh=/^[:/?#\[\]@!$&'()*+,;=]$/;function pn(r,e=!1){return Array.from(r).map(t=>{if(sh.test(t)||e&&oh.test(t))return t;let n=t.codePointAt(0);if(n>65535){let s=new TextEncoder().encode(t);return Array.from(s).map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join("")}if(n>127){let s=new TextEncoder().encode(t);return Array.from(s).map(o=>"%"+o.toString(16).toUpperCase().padStart(2,"0")).join("")}return"%"+n.toString(16).toUpperCase().padStart(2,"0")}).join("")}function Ce(r){try{return decodeURIComponent(r.replace(/\+/g,"%20"))}catch{return r.replace(/%([0-9A-Fa-f]{2})/g,(e,t)=>String.fromCharCode(parseInt(t,16)))}}function qo(r){return encodeURIComponent(r).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function Qe(r){return encodeURIComponent(r).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A")}function mc(r,e={}){let{sort:t=!1,arrayFormat:n="repeat"}=e,s=[];for(let[o,i]of Object.entries(r)){if(i==null)continue;let a=Qe(o);if(Array.isArray(i)){let c=i.filter(l=>l!=null);if(c.length===0)continue;if(n==="comma")s.push([a,c.map(l=>Qe(String(l))).join(",")]);else if(n==="bracket")for(let l of c)s.push([`${a}[]`,Qe(String(l))]);else for(let l of c)s.push([a,Qe(String(l))])}else s.push([a,Qe(String(i))])}return t&&s.sort(([o],[i])=>o<i?-1:o>i?1:0),s.map(([o,i])=>`${o}=${i}`).join("&")}function Bo(r){let e=r.startsWith("?")?r.slice(1):r,t={};if(!e)return t;for(let n of e.split("&")){if(!n)continue;let s=n.indexOf("="),o=Ce(s===-1?n:n.slice(0,s)),i=s===-1?"":Ce(n.slice(s+1)),a=t[o];a===void 0?t[o]=i:Array.isArray(a)?a.push(i):t[o]=[a,i]}return t}function gc(r,e){let t={...r};for(let[n,s]of Object.entries(e))s==null?delete t[n]:t[n]=s;return t}function yc(r,...e){let t={};for(let n of e)n in r&&(t[n]=r[n]);return t}function wc(r,...e){let t=new Set(e),n={};for(let[s,o]of Object.entries(r))t.has(s)||(n[s]=o);return n}function Fo(...r){if(r.length===0)return"/";let e=[];for(let i of r)i&&e.push(...i.split("/").filter((a,c)=>a!==""||c===0));let n=bc(e).join("/"),o=r[r.length-1]?.endsWith("/")&&n!=="/"?"/":"";return(n.startsWith("/")?"":"/")+n+o}function bc(r){let e=[];for(let t of r)t!=="."&&(t===".."?e.pop():e.push(t));return e}function Wo(r,e={}){let{trailingSlash:t="preserve"}=e,n=r.endsWith("/")&&r!=="/",s=r.split("/").filter(Boolean),i="/"+bc(s).join("/");return t==="add"&&i!=="/"?i+="/":t==="remove"||t==="preserve"&&n&&i!=="/"&&(i+="/"),i}function xc(r){return r.split("/").filter(Boolean).map(Ce)}function Ko(r,e){return r.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g,(t,n)=>{let s=e[n];if(s===void 0)throw new zo(`Missing path param: "${n}"`);return qo(String(s))})}var ih={"http:":"80","https:":"443","ftp:":"21","ws:":"80","wss:":"443"};function _c(r,e={}){let t=Pe(r);if(!t)throw new TypeError(`Invalid URL: ${r}`);let n=ih[t.protocol],s=t.port===n?"":t.port,o=Wo(t.pathname,{trailingSlash:e.trailingSlash??"preserve"});e.sortParams&&t.searchParams.sort();let i=t.searchParams.toString()?`?${t.searchParams}`:"",a=e.removeFragment?"":t.hash,c=t.username?`${encodeURIComponent(t.username)}${t.password?":"+encodeURIComponent(t.password):""}@`:"",l=s?`${t.hostname}:${s}`:t.hostname;return`${t.protocol}//${c}${l}${o}${i}${a}`}var ve=class r{constructor(e,t){h(this,"_url");try{this._url=new URL(String(e),t)}catch{throw new TypeError(`Invalid URL: "${e}"${t?` (base: "${t}")`:""}`)}}static from(e,t){return new r(e,t)}static https(e,t){return new r(`https://${e}${t??"/"}`)}static http(e,t){return new r(`http://${e}${t??"/"}`)}withProtocol(e){let t=this._clone();return t._url.protocol=e.endsWith(":")?e:e+":",t}withHostname(e){let t=this._clone();return t._url.hostname=e,t}withHost(e){let t=this._clone();return t._url.host=e,t}withPort(e){let t=this._clone();return t._url.port=String(e),t}withUsername(e){let t=this._clone();return t._url.username=encodeURIComponent(e),t}withPassword(e){let t=this._clone();return t._url.password=encodeURIComponent(e),t}withPathname(e){let t=this._clone();return t._url.pathname=e,t}appendPath(...e){let t=this._clone(),n=t._url.pathname.replace(/\/$/,""),s=e.map(o=>o.replace(/^\/|\/$/g,"")).filter(Boolean);return t._url.pathname=n+"/"+s.join("/"),t}path(...e){let t=this._clone();return t._url.pathname=Fo(...e),t}params(e){let t=this._clone();t._url.pathname=Ko(t._url.pathname,e);for(let[n,s]of Object.entries(e))t._url.searchParams.set(n,String(s));return t}addTrailingSlash(){let e=this._clone();return e._url.pathname.endsWith("/")||(e._url.pathname+="/"),e}removeTrailingSlash(){let e=this._clone();return e._url.pathname!=="/"&&e._url.pathname.endsWith("/")&&(e._url.pathname=e._url.pathname.slice(0,-1)),e}setParam(e,t){let n=this._clone();return t==null?n._url.searchParams.delete(e):n._url.searchParams.set(e,String(t)),n}appendParam(e,t){if(t==null)return this;let n=this._clone();return n._url.searchParams.append(e,String(t)),n}deleteParam(e){let t=this._clone();return t._url.searchParams.delete(e),t}query(e){let t=this._clone();for(let[n,s]of Object.entries(e))if(s==null)t._url.searchParams.delete(n);else if(Array.isArray(s)){t._url.searchParams.delete(n);for(let o of s)o!=null&&t._url.searchParams.append(n,String(o))}else t._url.searchParams.set(n,String(s));return t}setQuery(e){let t=this._clone();return t._url.search="",t.query(e)}pickParams(...e){let t=this._clone(),n=new Set(e),s=[];for(let[o,i]of t._url.searchParams.entries())n.has(o)&&s.push([o,i]);t._url.search="";for(let[o,i]of s)t._url.searchParams.append(o,i);return t}omitParams(...e){let t=this._clone(),n=new Set(e);for(let s of n)t._url.searchParams.delete(s);return t}sortParams(){let e=this._clone();return e._url.searchParams.sort(),e}redactParams(...e){let t=this._clone();for(let n of e)t._url.searchParams.has(n)&&(t=t.setParam(n,"REDACTED"));return t}withHash(e){let t=this._clone();return t._url.hash=e.startsWith("#")?e:"#"+e,t}removeHash(){let e=this._clone();return e._url.hash="",e}toString(){return this._url.toString()}toURL(){return new URL(this._url.toString())}get href(){return this._url.href}get protocol(){return this._url.protocol}get hostname(){return this._url.hostname}get host(){return this._url.host}get port(){return this._url.port}get pathname(){return this._url.pathname}get search(){return this._url.search}get hash(){return this._url.hash}get origin(){return this._url.origin}get searchParams(){return new URLSearchParams(this._url.searchParams)}get queryObject(){return Bo(this._url.search)}_clone(){return new r(this._url.toString())}};function Sc(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let s=n[0],o="+#./;?&".includes(s),i=(o?n.slice(1):n).split(",");return ah(o?s:"",i,e)})}function ah(r,e,t){let n=uh(r),s=hh(r),o=fh(r),i=dh(r),a=r==="+"||r==="#",c=[];for(let l of e){let{name:u,explode:f,maxLength:p}=ch(l.trim()),d=t[u];if(d==null)continue;let g=lh(d,u,o,f,p,a,n,i);g!==null&&c.push(g)}return c.length===0?"":s+c.join(n)}function ch(r){if(r.endsWith("*"))return{name:r.slice(0,-1),explode:!0,maxLength:null};let e=r.lastIndexOf(":");if(e!==-1){let t=parseInt(r.slice(e+1),10);return{name:r.slice(0,e),explode:!1,maxLength:isNaN(t)?null:t}}return{name:r,explode:!1,maxLength:null}}function lh(r,e,t,n,s,o,i,a){let c=l=>o?pn(l,!0):pn(l);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean"){let l=String(r);s!==null&&(l=l.slice(0,s));let u=c(l);return t?`${e}${u===""?a:"="+u}`:u}if(Array.isArray(r)){if(r.length===0)return null;if(n)return r.map(u=>{let f=c(String(u));return t?`${e}=${f}`:f}).join(i);let l=r.map(u=>c(String(u))).join(",");return t?`${e}=${l}`:l}if(typeof r=="object"&&r!==null){let l=Object.entries(r);if(l.length===0)return null;if(n)return l.map(([f,p])=>`${c(f)}=${c(p)}`).join(i);let u=l.flatMap(([f,p])=>[c(f),c(p)]).join(",");return t?`${e}=${u}`:u}return null}function uh(r){switch(r){case".":return".";case"/":return"/";case";":return";";case"?":case"&":return"&";default:return","}}function hh(r){switch(r){case"#":return"#";case".":return".";case"/":return"/";case";":return";";case"?":return"?";case"&":return"&";default:return""}}function fh(r){return r===";"||r==="?"||r==="&"}function dh(r){return r===";"?"":"="}function Ec(r){let e=[],t={n:0},n=r.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,"*").replace(/\*\*/g,()=>"(.+?)").replace(/\*(?!\*)/g,()=>(t.n++,"([^/]+)")).replace(/:([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]+)\))?/g,(o,i,a)=>(e.push(i),`(${a??"[^/]+"})`)),s=new RegExp(`^${n}\\/?$`);return{match(o){let i=dc(o),a=s.exec(i);if(!a)return null;let c={},l=[],u={},f=1;for(let p of e)c[p]=Ce(a[f++]??"");for(;f<=a.length-1;){let p=a[f++]??"";l.push(...p.split("/").filter(Boolean).map(Ce))}return{params:c,wildcards:l,groups:u}},test(o){return s.test(dc(o))}}}function dc(r){try{return new URL(r).pathname}catch{return r}}function mn(r){let e=Pe(r);return e?["file:","data:","blob:"].includes(e.protocol)?"null":e.origin:null}function Tc(r,e){let t=mn(r),n=mn(e);return!t||!n?!1:t===n}function Rc(r,e){let t=Pe(r),n=Pe(e);return!t||!n||t.protocol!==n.protocol?!1:pc(t.hostname)===pc(n.hostname)}function pc(r){let e=new Set(["co.uk","co.jp","co.kr","co.nz","co.za","co.in","com.au","com.br","com.mx","com.cn","com.tw","com.hk","com.sg","com.my","com.ph","com.vn","com.tr","net.au","net.uk","net.br","org.uk","org.au","org.nz","org.cn","org.in","ac.uk","gov.uk","gov.au","gov.cn","or.kr","pe.kr","go.jp","ne.jp","ac.jp","github.io","herokuapp.com","cloudfront.net"]),t=r.split(".");if(t.length>=3){let n=t.slice(-2).join(".");if(e.has(n))return t.slice(-3).join(".")}return t.slice(-2).join(".")}function kc(r,e){try{return new URL(r,e).toString()}catch{throw new TypeError(`Cannot resolve "${r}" against base "${e}"`)}}function Ac(r,e){try{let t=new URL(r),n=new URL(e);return t.origin!==n.origin||!t.pathname.startsWith(n.pathname)?null:t.pathname.slice(n.pathname.length)+t.search+t.hash}catch{return null}}function Vo(r){try{if(/^[A-Za-z][A-Za-z0-9+\-.]*:\/\//.test(r))return!0;let e=new URL(r);return e.protocol!==""&&e.protocol!=="file:"}catch{return!1}}function Cc(r){return!Vo(r)}function vc(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function Pc(r){try{let e=new URL(r).protocol;return e==="http:"||e==="https:"}catch{return!1}}function Ic(r){return r.trimStart().startsWith("data:")}function Lc(r){return r.trimStart().startsWith("blob:")}function Mc(r){try{let e=new URL(r).hostname;return e==="localhost"||e==="127.0.0.1"||e==="::1"||e.endsWith(".localhost")}catch{return!1}}function Oc(r){let e=r.match(/^data:([^;,]+)?(;base64)?,(.*)$/s);return e?{mediaType:e[1]??"text/plain",isBase64:!!e[2],data:e[3]??""}:null}function Dc(r,e,t=!0){if(typeof r=="string")return t?`data:${e};base64,${btoa(r)}`:`data:${e},${encodeURIComponent(r)}`;let n=new TextDecoder("iso-8859-1").decode(r);return`data:${e};base64,${btoa(n)}`}function Nc(r,e){let t=Pe(r),n=Pe(e);if(!t||!n)throw new TypeError(`Cannot diff invalid URLs: "${r}" vs "${e}"`);let s={addedParams:{},removedParams:{},changedParams:{}};t.protocol!==n.protocol&&(s.protocol=[t.protocol,n.protocol]),t.hostname!==n.hostname&&(s.hostname=[t.hostname,n.hostname]),t.port!==n.port&&(s.port=[t.port,n.port]),t.pathname!==n.pathname&&(s.pathname=[t.pathname,n.pathname]),t.hash!==n.hash&&(s.hash=[t.hash,n.hash]);for(let[o,i]of t.searchParams.entries()){let a=n.searchParams.get(o);a===null?s.removedParams[o]=i:a!==i&&(s.changedParams[o]=[i,a])}for(let[o,i]of n.searchParams.entries())t.searchParams.has(o)||(s.addedParams[o]=i);return t.search!==n.search&&!Object.keys(s.changedParams).length&&!Object.keys(s.addedParams).length&&!Object.keys(s.removedParams).length&&(s.search=[t.search,n.search]),s}function Pe(r){try{return new URL(r)}catch{return null}}function Uc(r){return ve.from(r).addTrailingSlash().toString()}function $c(r){return ve.from(r).removeTrailingSlash().toString()}function Hc(r){return ve.from(r).removeHash().toString()}function jc(r){try{let e=new URL(r);return e.search="",e.toString()}catch{return r}}function zc(r){try{let t=new URL(r).pathname.split("/").pop()??"",n=t.lastIndexOf(".");return n===-1?"":t.slice(n+1).toLowerCase()}catch{return""}}function qc(r){try{let e=new URL(r).pathname;return Ce(e.split("/").filter(Boolean).pop()??"")}catch{return""}}function Bc(r,...e){return ve.from(r).redactParams(...e).toString()}z();function Fc(r={}){return new Lt(r)}var ph=Fc;return tl(mh);})();
|