var ne=new Set([0,1,7,9,11,13,15,17,19,20,21,22,23,25,37,42,43,53,69,77,79,87,95,101,102,103,104,109,110,111,113,115,117,119,123,135,137,139,143,161,179,389,427,465,512,513,514,515,526,530,531,532,540,548,554,556,563,587,601,636,989,990,993,995,1719,1720,1723,2049,3659,4045,4190,5060,5061,6e3,6566,6665,6666,6667,6668,6669,6679,6697,10080]);function X(t){return t.port!==""&&ne.has(Number(t.port))}var ie=["localhost","local","internal","intranet","lan","home","test","invalid","example","onion","arpa","cors.dev"],oe=new Set(["accept","accept-language","if-none-match","if-modified-since","range"]),se=new Set(["content-type","x-requested-with","traceparent","tracestate","baggage","sentry-trace","save-data"]),ae=new Set(["origin","host","user-agent","referer","accept-encoding","cache-control","pragma","priority","connection","content-length","dnt","te","true-client-ip","cdn-loop","x-forwarded-for","x-forwarded-proto","x-real-ip","cookie","cookie2","set-cookie","transfer-encoding","trailer","upgrade","keep-alive","forwarded","expect","via"]),le=/^(?:https?|capacitor|tauri|ionic|chrome-extension|moz-extension):\/\//,de=new Set(["GET","HEAD","POST","PUT","PATCH","DELETE"]);function $(t){return t.length<=253&&t.includes(".")&&/^[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?(?:\.[a-z0-9_](?:[a-z0-9_-]{0,61}[a-z0-9_])?)+$/.test(t)&&/[a-z]/.test(t.split(".").at(-1))&&!ie.some(e=>t===e||t.endsWith(`.${e}`))}function ce(t){let e=t.toLowerCase();if(!$(e))throw new TypeError("Auto hosts must be exact public hostnames");return e}function z(t){let e=t.mode??"native-first";if(!["native-first","proxy-first","proxy-only","native-only"].includes(e))throw new TypeError("Invalid Auto mode");let n=new URL(t.proxyOrigin??"https://proxy.cors.dev");if(n.protocol!=="https:"||n.username||n.password||n.pathname!=="/"||n.search||n.hash)throw new TypeError("proxyOrigin must be an HTTPS origin");if(t.key!==void 0&&!/^[A-Za-z0-9_-]{16,256}$/.test(t.key))throw new TypeError("Invalid publishable key");if(t.cacheSeconds!==void 0&&(!Number.isInteger(t.cacheSeconds)||t.cacheSeconds<1||t.cacheSeconds>300))throw new TypeError("cacheSeconds must be an integer from 1 to 300");let i=s=>s?.map(ce);return{...t,mode:e,xhr:t.xhr??!0,hosts:i(t.hosts),nativeHosts:i(t.nativeHosts),proxyOrigin:n.origin}}function F(t,e,n){let i=t.url;if(!le.test(n)||!t.supported||!de.has(t.method)||i.origin===n||i.origin===e.proxyOrigin||i.protocol!=="https:"&&i.protocol!=="http:"||i.username||i.password||X(i)||i.hash||i.href.length+e.proxyOrigin.length+1>8192||!$(i.hostname)||t.credentials==="include"||t.mode!=="cors"||t.redirect!=="follow"||e.nativeHosts?.includes(i.hostname)||e.hosts&&!e.hosts.includes(i.hostname))return!1;let s=0;for(let[r,o]of t.headers)if(s+=new TextEncoder().encode(r+o).byteLength+4,s>16384||/[\u0000-\u001f\u007f]/.test(o)||ae.has(r)||/^(?:cf-|sec-|proxy-|x-cors|x-forwarded-|access-control-)/.test(r))return!1;return!0}function K(t){return R(t)&&t.bodyBytes===0&&!_(t)}function _(t){return[...t.headers.keys()].some(e=>!oe.has(e)&&!se.has(e))}function R(t){return t.method==="GET"||t.method==="HEAD"}function q(t){return t==null?0:typeof t=="string"?new TextEncoder().encode(t).byteLength:t instanceof URLSearchParams?new TextEncoder().encode(t.toString()).byteLength:t instanceof Blob?t.size:t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:null}var ue=Object.getOwnPropertyDescriptor(Request.prototype,"url").get;function C(t){try{return ue.call(t),t}catch{return}}function V(t,e,n){try{let i=C(t),s=new URL(i?.url??String(t),n),o=e?.body!=null?q(e.body):i&&!R(i)&&i.body!==null?null:0,d=O(e?.method??i?.method??"GET"),c=new Headers(e?.headers??i?.headers),y=e?.credentials??i?.credentials??"same-origin",h=e?.mode??i?.mode??"cors",u=e?.redirect??i?.redirect??"follow",a=e?.signal!==void 0?e.signal:i?.signal,f=e?.cache??i?.cache??"default",b=e?.integrity??i?.integrity??"",m=e?.keepalive??i?.keepalive??!1,w=o!==null&&!i?.bodyUsed&&!b&&!m&&f==="default"&&!(e&&["duplex","attributionReporting","browsingTopics"].some(l=>l in e))&&(!R({method:d})||o===0);return new Request(s,{method:d,headers:c,credentials:y,mode:h,redirect:u,cache:f,integrity:b,keepalive:m,signal:a,...e,body:void 0}),{url:s,method:d,headers:c,credentials:y,mode:h,redirect:u,signal:a??void 0,bodyBytes:o,supported:w,context:JSON.stringify([f,e?.referrer??i?.referrer??"about:client",e?.referrerPolicy??i?.referrerPolicy??"",b])}}catch{return null}}function k(t){return t instanceof URLSearchParams?new URLSearchParams(t):t instanceof ArrayBuffer?t.slice(0):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice().buffer:t}function Y(t){if(!t)return t;let e={...t};for(let n of["body","cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","window","priority","duplex","attributionReporting","browsingTopics"])!Object.hasOwn(e,n)&&n in t&&(e[n]=Reflect.get(t,n));return e.headers!==void 0&&(e.headers=new Headers(e.headers)),e.body=k(e.body),e}function O(t){return/^(?:delete|get|head|options|post|put)$/i.test(t)?t.toUpperCase():t}var he=3e4,H=5e3,fe=6e4,pe=3e5,ye=6e5,me=6e4,j=128,ge=new Map([["rate_limited","This IP or target host is over the keyless rate limit; a key gets its own allocation."],["quota_exceeded","The request allowance is exhausted."],["owner_opted_out","The API owner opted out of cors.dev."],["origin_not_allowed","This page origin is not registered on the Connection."],["target_not_allowed","This host is not allowed for the Connection or access tier."],["invalid_key","The publishable key is invalid or revoked."]]);function v(t){return t.reason??new DOMException("The operation was aborted","AbortError")}function G(t,e){return e?e.aborted?Promise.reject(v(e)):new Promise((n,i)=>{let s=()=>i(v(e));e.addEventListener("abort",s,{once:!0}),t.then(n,i).finally(()=>e.removeEventListener("abort",s))}):t}function S(t,e){return!!e?.aborted||t instanceof Error&&["AbortError","TimeoutError"].includes(t.name)}function W(t,e){let n=t.get("retry-after")??"",i=/^\d+$/.test(n)?Number(n)*1e3:Date.parse(n)-Date.now();return Math.max(H,Math.min(Number.isNaN(i)?0:i,e))}function be(t){return typeof t=="number"?t:t.until}function J(){return{until:Date.now()+H,code:null}}function we(t){let e=Math.ceil((t.until-Date.now())/1e3);return new TypeError(`Auto proxy route is backed off after ${t.code??"a failed proxy request"}; retry in ${e} s`)}var L=class{constructor(e,n,i){this.options=e;this.nativeFetch=n;this.pageOrigin=i}options;nativeFetch;pageOrigin;routes=new Map;backoff=new Map;warnedUntil=new Map;capability=null;pendingCapability=null;capabilityRetryAt=0;generation=0;clearRoutes(){this.routes.clear(),this.backoff.clear(),this.capability=null,this.pendingCapability=null,this.capabilityRetryAt=0,this.generation++}remember(e,n,i){if(!n)return;let s=Date.now();for(let[r,o]of e)be(o)<=s&&e.delete(r);for(e.delete(n);e.size>=j;)e.delete(e.keys().next().value);e.set(n,i)}held(e){let n=this.backoff.get(e);return n&&n.until>Date.now()?n:void 0}warn(e,n){let i=Date.now();(this.warnedUntil.get(e)??0)>i||(this.warnedUntil.size>=j&&this.warnedUntil.clear(),this.warnedUntil.set(e,i+me),console.warn(`[cors.dev auto] ${n}`))}async routeKey(e){if(!globalThis.crypto?.subtle)return"";let n=JSON.stringify([e.method,e.url.href,[...e.headers],e.credentials,e.mode,e.redirect,e.context,this.options.key??"",this.options.cacheSeconds??0]),i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(i),s=>s.toString(16).padStart(2,"0")).join("")}async getCapability(){if(!this.options.key)return null;if(this.capability&&this.capability.expiresAt>Date.now())return this.capability;if(this.pendingCapability)return this.pendingCapability;if(this.capabilityRetryAt>Date.now())return null;let e=this.generation;return this.pendingCapability=this.loadCapability().then(({config:n,retryIn:i})=>e!==this.generation?n:n?(this.capability?.configVersion!==n.configVersion&&this.routes.clear(),this.capability=n,n):(this.capabilityRetryAt=Date.now()+i,this.capability=null,null)).finally(()=>{e===this.generation&&(this.pendingCapability=null)}),this.pendingCapability}async loadCapability(){let e=new AbortController,n=setTimeout(()=>e.abort(),2500);try{let i=await this.nativeFetch(`${this.options.proxyOrigin}/_auto/config`,{headers:{"X-Cors-Key":this.options.key},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",signal:e.signal});if(!i.ok)return this.capabilityRefused(i);let s=await i.json(),r=s;return!s||typeof s!="object"||r.version!==1||!Number.isSafeInteger(r.configVersion)||r.configVersion<0||typeof r.managed!="boolean"||!Array.isArray(r.targetHosts)||r.targetHosts.length>1e3||!r.targetHosts.every(o=>typeof o=="string"&&o.length<=253)||!Array.isArray(r.methods)||r.methods.length>6||!r.methods.every(o=>typeof o=="string")||!Number.isSafeInteger(r.maxRequestBytes)||r.maxRequestBytes<0||r.maxRequestBytes>1048576||!Number.isFinite(r.expiresAt)||r.expiresAt<=Date.now()?this.capabilityFailed("invalid response"):{config:{...r,expiresAt:Math.min(r.expiresAt,Date.now()+6e4)},retryIn:0}}catch(i){return this.capabilityFailed(e.signal.aborted?"timed out":String(i))}finally{clearTimeout(n)}}capabilityRefused(e){let n=e.headers.get("x-cors-error"),i=`HTTP ${e.status}${n?` ${n}`:""}`;if(e.status===401||e.status===403)return this.warn("capability",`Connection lookup refused (${i}): key revoked or origin not registered on this Connection. Continuing keyless; retrying in 5 min.`),{config:null,retryIn:pe};let s=e.status===429||e.status===503;return this.capabilityFailed(i,s?W(e.headers,ye):H)}capabilityFailed(e,n=H){return this.warn("capability",`Connection lookup failed (${e}). Continuing keyless; retrying in ${Math.ceil(n/1e3)} s.`),{config:null,retryIn:n}}async proxyRoute(e){let n=await G(this.getCapability(),e.signal);if(e.signal?.aborted)throw v(e.signal);let i=n&&n.expiresAt>Date.now()&&n.targetHosts.includes(e.url.hostname)&&n.methods.includes(e.method),s=!_(e)||this.options.hosts?.includes(e.url.hostname),r=i&&n.managed&&s&&e.bodyBytes!==null&&e.bodyBytes<=n.maxRequestBytes;if(!r&&!K(e))return null;let o=!!(r&&this.options.cacheSeconds&&e.method==="GET"),d=new Headers(e.headers);return r&&d.set("X-Cors-Key",this.options.key),o&&d.set("X-Cors-Cache",String(this.options.cacheSeconds)),{url:`${this.options.proxyOrigin}/${e.url.href}`,headers:d,cached:o}}refusal(e,n){let i=n.headers.get("x-cors-error");if(n.headers.get("x-cors-source")!=="gateway"||i===null)return null;let s=n.headers.get("retry-after");return this.warn(`gateway:${i}`,[`Proxy refused ${e.method} ${e.url.hostname} with ${i} (HTTP ${n.status}${s?`, Retry-After ${s}`:""}).`,ge.get(i),"See https://cors.dev/docs#errors"].filter(Boolean).join(" ")),{until:Date.now()+W(n.headers,fe),code:i}}observe(e,n,i){let s=this.refusal(n,i);s?(this.routes.delete(e),this.remember(this.backoff,e,s)):i.headers.get("x-cors-source")==="upstream"&&i.status>=200&&i.status<300&&(this.remember(this.routes,e,Date.now()+he),this.backoff.delete(e))}async execute(e,n,i){if(!e||this.options.mode==="native-only"||!F(e,this.options,this.pageOrigin))return n();if(e.signal?.aborted)throw v(e.signal);let s=this.options.mode==="proxy-only";if(!R(e)){let a=await this.proxyRoute(e);if(e.signal?.aborted)throw v(e.signal);if(!a&&s)throw new TypeError("Auto proxy route is unavailable for this request");if(!a)return n();let f=await i(a);return this.refusal(e,f),f}let r=await G(this.routeKey(e),e.signal),o=this.held(r);if(o){if(s)throw we(o);return n()}let d=this.options.cacheSeconds&&e.method==="GET"?await this.proxyRoute(e):void 0,c=!!d?.cached;if(!(s||c||this.options.mode==="proxy-first"||(this.routes.get(r)??0)>Date.now()))try{return await n()}catch(a){if(S(a,e.signal)||(d===void 0&&(d=await this.proxyRoute(e)),!d))throw a;try{let f=await i(d);return this.observe(r,e,f),f}catch(f){throw S(f,e.signal)?f:(this.remember(this.backoff,r,J()),a)}}if(d===void 0&&(d=await this.proxyRoute(e)),!d){if(s)throw new TypeError("Auto proxy route is unavailable for this request");return n()}let h;try{h=await i(d)}catch(a){if(S(a,e.signal)||(this.routes.delete(r),this.remember(this.backoff,r,J()),s))throw a;return n()}this.observe(r,e,h);let u=h.headers.get("x-cors-source")==="gateway"&&h.headers.get("x-cors-error")!==null;if(!s&&u)try{return await n()}catch(a){if(S(a,e.signal))throw a;return h}return h}};var A="X-Cors-Stream";var D="X-Cors-Stream-Limit",P="X-Cors-Content-Type",Q="application/octet-stream";function I(t,e,n){let i=new Response(e,{status:t.status,statusText:t.statusText,headers:n}),s=i.clone.bind(i);return Object.defineProperties(i,{url:{value:t.url},type:{value:t.type},redirected:{value:t.redirected},clone:{value:()=>{let r=s();return I(t,r.body,new Headers(r.headers))}}}),i}function Z(t,e){if(e==="HEAD"||[204,205,304].includes(t.status)||t.status>=400&&t.headers.get("x-cors-source")==="gateway"&&t.headers.has("x-cors-error"))return t;let n=()=>new TypeError("Incomplete or invalid cors.dev response stream"),i=t.headers.get(D),s=Number(i);if(!(t.headers.get(A)==="v1"&&t.headers.get("content-type")===Q&&["1048576",String(6291456)].includes(i??"")&&t.body!==null))return t.body?.cancel().catch(()=>{}),I(t,new ReadableStream({start(l){l.error(n())}}),new Headers(t.headers));let o=t.body.getReader(),d=new Uint8Array,c=0,y=0,h=0,u=0,a=!1,f=async l=>{let p=new Uint8Array(l),g=0;for(;g<l;){if(a)throw n();if(c===d.byteLength){let T=await o.read();if(T.done||a||(d=T.value,!d.byteLength&&++u>1e5))throw n();c=0}let E=Math.min(l-g,d.byteLength-c);p.set(d.subarray(c,c+E),g),g+=E,c+=E}return p},b=new ReadableStream({async pull(l){if(!a)try{if(++h>1e5)throw n();let p=await f(5),g=new DataView(p.buffer).getUint32(1);if(p[0]===1&&g>0&&g<=65536&&y+g<=s){let E=await f(g);if(a)return;y+=g,l.enqueue(E)}else if(p[0]===0&&g===4){if(new DataView((await f(4)).buffer).getUint32(0)!==y||c!==d.byteLength)throw n();for(;;){let T=await o.read();if(a)return;if(T.done)break;if(T.value.byteLength||++u>1e5)throw n()}if(a)return;a=!0,d=new Uint8Array,o.releaseLock(),l.close()}else throw n()}catch(p){if(a)return;a=!0,d=new Uint8Array,o.cancel(p).catch(()=>{}),l.error(p)}},cancel(l){return a=!0,d=new Uint8Array,o.cancel(l)}},{highWaterMark:0}),m=new Headers(t.headers),w=m.get(P);w===null?m.delete("content-type"):m.set("content-type",w);for(let l of[A,D,P,"content-length","content-encoding"])m.delete(l);return I(t,b,m)}var ee=["loadstart","progress","abort","error","load","timeout","loadend"],N=new WeakMap;function te(t,e){for(let n of e)Object.defineProperty(t,`on${n}`,{configurable:!0,enumerable:!0,get(){return N.get(this)?.get(n)??null},set(i){let s=N.get(this);s||(s=new Map,N.set(this,s));let r=s.get(n);r&&this.removeEventListener(n,r),s.delete(n),typeof i=="function"&&(s.set(n,i),this.addEventListener(n,i))}})}var M=class extends EventTarget{observed=!1;addEventListener(e,n,i){this.observed=!0,super.addEventListener(e,n,i)}used(){return this.observed||["loadstart","progress","abort","error","load","timeout","loadend"].some(e=>this[`on${e}`]!==null)}emit(e,n){let i=new ProgressEvent(e,{loaded:n.loaded,total:n.total,lengthComputable:n.lengthComputable});this.dispatchEvent(i)}};te(M.prototype,ee);function re(t,e,n){class i extends EventTarget{static UNSENT=0;static OPENED=1;static HEADERS_RECEIVED=2;static LOADING=3;static DONE=4;static[Symbol.hasInstance](r){return Function.prototype[Symbol.hasInstance].call(this,r)||this===i&&r instanceof t}UNSENT=0;OPENED=1;HEADERS_RECEIVED=2;LOADING=3;DONE=4;upload=new M;initial=null;selected=null;activeAttempt=null;state=0;sent=!1;asynchronous=!0;method="";url="";username;password;headers=new Headers;responseKind="";credentials=!1;timeoutMs=0;mime=null;controller=null;timer=null;generation=0;startedAt=0;get readyState(){return this.selected?.readyState??this.state}get status(){return this.selected?.status??0}get statusText(){return this.selected?.statusText??""}get responseURL(){return this.selected?.responseURL??""}get response(){return this.selected?.response??(this.responseKind===""||this.responseKind==="text"?"":null)}get responseText(){if(this.responseKind!==""&&this.responseKind!=="text")throw new DOMException("responseText requires a text responseType","InvalidStateError");return this.selected?.responseText??""}get responseXML(){return this.selected?.responseXML??null}get responseType(){return this.responseKind}set responseType(r){if(this.readyState>=3)throw new DOMException("The response has started","InvalidStateError");["","text","json","arraybuffer","blob","document"].includes(r)&&(!this.asynchronous&&this.initial&&(this.initial.responseType=r),this.activeAttempt&&this.activeAttempt.readyState<3&&(this.activeAttempt.responseType=r),this.responseKind=r)}get withCredentials(){return this.credentials}set withCredentials(r){if(this.sent||this.readyState>1)throw new DOMException("The request has started","InvalidStateError");this.credentials=!!r}get timeout(){return this.timeoutMs}set timeout(r){!this.asynchronous&&this.initial&&(this.initial.timeout=r),this.timeoutMs=Number(r)>>>0,this.sent&&this.armTimeout()}emit(r,o){let d=r==="readystatechange"?new Event(r):new ProgressEvent(r,o?{loaded:o.loaded,total:o.total,lengthComputable:o.lengthComputable}:void 0);this.dispatchEvent(d)}open(r,o,d=!0,c,y){let h=new t;h.open(r,String(o),d,c,y),this.mime&&h.overrideMimeType(this.mime);let u=this.readyState!==1;this.generation++,this.controller?.abort(),this.stopTimer(),this.initial=h,this.selected=null,this.activeAttempt=null,this.state=1,this.sent=!1,this.asynchronous=d,this.method=O(r),this.url=new URL(String(o),n()).href,this.username=c,this.password=y,this.headers=new Headers,u&&this.emit("readystatechange")}setRequestHeader(r,o){if(!this.initial||this.readyState!==1||this.sent)throw new DOMException("Call open before setting headers","InvalidStateError");this.initial.setRequestHeader(r,o),this.headers.append(r,o)}getAllResponseHeaders(){return this.selected?.getAllResponseHeaders()??""}getResponseHeader(r){return this.selected?.getResponseHeader(r)??null}overrideMimeType(r){if(this.readyState>=3)throw new DOMException("The response has started","InvalidStateError");this.initial&&this.initial.readyState<3&&this.initial.overrideMimeType(r),this.activeAttempt&&this.activeAttempt!==this.initial&&this.activeAttempt.readyState<3&&this.activeAttempt.overrideMimeType(r),this.mime=r}stopTimer(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}armTimeout(){if(this.stopTimer(),!this.timeoutMs)return;let r=this.generation,o=Math.max(0,this.timeoutMs-(performance.now()-this.startedAt));this.timer=setTimeout(()=>{r!==this.generation||!this.sent||(this.generation++,this.controller?.abort(new DOMException("The operation timed out","TimeoutError")),this.fail("timeout"))},o)}fail(r){if(!this.sent)return;this.sent=!1,this.stopTimer(),this.selected=null,this.activeAttempt=null,this.state=4;let o=this.generation;this.emit("readystatechange"),this.emit(r),this.emit("loadend"),r==="abort"&&o===this.generation&&(this.state=0)}abort(){if(!this.asynchronous&&this.initial){this.initial.abort();return}let r=this.readyState,o=r===4;this.generation++,this.controller?.abort(),this.sent&&!o?this.fail("abort"):(this.sent=!1,this.stopTimer(),this.selected=null,this.activeAttempt=null,this.state=o?0:r)}send(r=null){if(!this.initial||this.readyState!==1||this.sent)throw new DOMException("The request is not open","InvalidStateError");if(!this.asynchronous){this.selected=this.initial,this.responseKind&&(this.initial.responseType=this.responseKind),this.initial.withCredentials=this.credentials,this.timeoutMs&&(this.initial.timeout=this.timeoutMs),this.initial.onreadystatechange=()=>this.emit("readystatechange");for(let u of["loadstart","progress","abort","error","load","timeout","loadend"])this.initial.addEventListener(u,a=>this.emit(u,a));this.initial.send(r);return}this.sent=!0,this.startedAt=performance.now();let o=this.generation;this.controller=new AbortController;let d=this.controller.signal,c=["GET","HEAD"].includes(this.method)?null:typeof Document<"u"&&r instanceof Document?r:k(r),y=typeof Document<"u"&&c instanceof Document?null:q(c),h={url:new URL(this.url),method:this.method,headers:new Headers(this.headers),credentials:this.credentials?"include":"same-origin",mode:"cors",redirect:"follow",signal:d,bodyBytes:y,supported:y!==null&&!this.username&&!this.password&&this.responseKind!=="document",context:JSON.stringify(["xhr",this.responseKind,this.mime])};this.armTimeout(),this.emit("loadstart"),!(o!==this.generation||!this.sent)&&e.execute(h,()=>this.attempt(this.initial,null,c,d,o),u=>this.attempt(new t,u,c,d,o)).then(u=>{if(o!==this.generation||!this.sent)return;this.selected=u.xhr;let a=u.xhr.readyState===4;a&&(this.sent=!1,this.stopTimer()),this.emit("readystatechange"),o===this.generation&&a&&(this.emit("load"),this.emit("loadend"))}).catch(()=>{o===this.generation&&this.sent&&this.fail(d.aborted?"abort":"error")})}attempt(r,o,d,c,y){return new Promise((h,u)=>{if(c.aborted){u(v(c));return}if(o){r.open(this.method,o.url,!0);for(let[l,p]of o.headers)r.setRequestHeader(l,p)}this.activeAttempt=r,r.withCredentials=o?!1:this.credentials,r.responseType=this.responseKind,this.mime&&r.overrideMimeType(this.mime);let a=!1,f=()=>{if(a)return;a=!0;let l=new Headers;for(let p of r.getAllResponseHeaders().trim().split(/[\r\n]+/)){let g=p.indexOf(":");g>0&&l.append(p.slice(0,g),p.slice(g+1).trim())}h({xhr:r,status:r.status,headers:l})},b=!1,m=()=>y===this.generation&&this.selected===r,w=()=>{r.abort(),a||(a=!0,u(v(c)))};c.addEventListener("abort",w,{once:!0}),r.addEventListener("readystatechange",()=>{r.readyState>=2&&r.status!==0&&f(),m()&&(r.readyState===4&&(b=!0,this.sent=!1,this.stopTimer()),this.emit("readystatechange"))});for(let l of["loadstart","progress","abort","error","load","timeout","loadend"])r.addEventListener(l,p=>{l==="load"&&f(),["error","abort","timeout"].includes(l)&&!a&&(a=!0,u(l==="abort"?v(c):new TypeError(`XMLHttpRequest ${l}`))),l!=="loadstart"&&(m()||b&&l!=="progress")&&this.emit(l,p),l==="loadend"&&c.removeEventListener("abort",w)}),this.upload.used()&&r.upload.addEventListener(l,p=>{y===this.generation&&this.sent&&this.upload.emit(l,p)});try{r.send(d)}catch(l){c.removeEventListener("abort",w),u(l)}})}}return te(i.prototype,["readystatechange",...ee]),i}var x=Symbol.for("cors.dev.auto");function Ie(t={}){let e=window;if(e[x])return e[x];let n=z(t),i=e.fetch,s=i.bind(e),r=e.XMLHttpRequest,o=new L(n,s,e.location.origin),d=()=>e.document?.baseURI??e.location.href,c=(a,f)=>{let b=a,m=f;try{m=Y(f)}catch(l){return Promise.reject(l)}try{let l=C(a);l?(R(l)||l.body===null)&&(b=l.clone()):b=new URL(String(a),d()).href}catch{return s(a,m)}let w=V(b,m,d());return o.execute(w,()=>s(b,m),l=>(l.headers.set(A,"v1"),s(l.url,{method:w.method,headers:l.headers,body:m?.body,signal:w.signal,credentials:"omit",mode:"cors",redirect:"error",referrerPolicy:"no-referrer"}).then(p=>Z(p,w.method))))},y=n.xhr?re(r,o,d):r,h=!0,u={nativeFetch:s,clearRoutes:()=>o.clearRoutes(),uninstall(){h&&(h=!1,e.fetch===c&&(e.fetch=i),e.XMLHttpRequest===y&&(e.XMLHttpRequest=r),e[x]===u&&delete e[x],o.clearRoutes())}};return e[x]=u,e.fetch=c,n.xhr&&(e.XMLHttpRequest=y),u}export{Ie as installAuto};
