@serve.zone/dcrouter 18.8.1 → 18.8.3
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/deno.json
CHANGED
package/dist_serve/bundle.js
CHANGED
|
@@ -11,7 +11,7 @@ ${s}
|
|
|
11
11
|
`)},"stripIndent"),PNt=i((r,e)=>{let t=r;return(!e||e.stripIndent)&&(t=ENt(t)),(!e||e.normalizeNewline)&&(t=t.replace(/\r\n/g,`
|
|
12
12
|
`)),(!e||e.replaceTabs)&&(t=Cnt(t," /"," ")),(!e||e.stripLeadingTrailingEmptyLines)&&(t=t.replace(/^\s*[\r\n]/gm,"").replace(/\s*[\r\n]$/gm,"")),(!e||e.stripAllEmptyLines)&&(t=t.replace(/^\s*[\r\n]/gm,"")),t},"standard")});var She,pee,N2,_he=h(()=>{She={encode:i(r=>{if(typeof Buffer<"u")return Buffer.from(r,"utf8").toString("base64");if(typeof btoa<"u"){let e=new TextEncoder().encode(r),t=Array.from(e,a=>String.fromCharCode(a)).join("");return btoa(t)}else{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=new TextEncoder().encode(r),a="",s=0;for(;s<t.length;){let o=t[s++],n=s<t.length?t[s++]:0,l=s<t.length?t[s++]:0,c=o<<16|n<<8|l;a+=e.charAt(c>>18&63),a+=e.charAt(c>>12&63),a+=s-2<t.length?e.charAt(c>>6&63):"=",a+=s-1<t.length?e.charAt(c&63):"="}return a}},"encode"),decode:i(r=>{let e=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"=");if(typeof Buffer<"u")return Buffer.from(e,"base64").toString("utf8");if(typeof atob<"u"){let t=atob(e),a=new Uint8Array(t.length);for(let s=0;s<t.length;s++)a[s]=t.charCodeAt(s);return new TextDecoder().decode(a)}else{let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=[],s=0;for(;s<e.length;){let o=t.indexOf(e.charAt(s++)),n=t.indexOf(e.charAt(s++)),l=t.indexOf(e.charAt(s++)),c=t.indexOf(e.charAt(s++)),d=o<<18|n<<12|l<<6|c;a.push(d>>16&255),l!==64&&a.push(d>>8&255),c!==64&&a.push(d&255)}return new TextDecoder().decode(new Uint8Array(a))}},"decode")},pee=class{static{i(this,"Base64")}constructor(e,t){switch(t){case"string":this.refString=e;break;case"base64":this.refString=N2.decode(e);break;case"base64uri":this.refString=N2.decode(e)}}get simpleString(){return this.refString}get base64String(){return N2.encode(this.refString)}get base64UriString(){return N2.encodeUri(this.refString)}},N2={encode:i(r=>She.encode(r),"encode"),encodeUri:i(r=>She.encode(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),"encodeUri"),decode:i(r=>She.decode(r),"decode"),isBase64:i(r=>/^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$/.test(r),"isBase64")}});var hee={};St(hee,{isBase64:()=>RNt,isUtf8:()=>ANt});var ANt,RNt,Mnt=h(()=>{t4();_he();ANt=i(r=>{let t=new TextEncoder().encode(r),a=0;for(;a<t.length;){if(t[a]===9||t[a]===10||t[a]===13||32<=t[a]&&t[a]<=126){a+=1;continue}if(194<=t[a]&&t[a]<=223&&128<=t[a+1]&&t[a+1]<=191){a+=2;continue}if(t[a]===224&&160<=t[a+1]&&t[a+1]<=191&&128<=t[a+2]&&t[a+2]<=191||(225<=t[a]&&t[a]<=236||t[a]===238||t[a]===239)&&128<=t[a+1]&&t[a+1]<=191&&128<=t[a+2]&&t[a+2]<=191||t[a]===237&&128<=t[a+1]&&t[a+1]<=159&&128<=t[a+2]&&t[a+2]<=191){a+=3;continue}if(t[a]===240&&144<=t[a+1]&&t[a+1]<=191&&128<=t[a+2]&&t[a+2]<=191&&128<=t[a+3]&&t[a+3]<=191||241<=t[a]&&t[a]<=243&&128<=t[a+1]&&t[a+1]<=191&&128<=t[a+2]&&t[a+2]<=191&&128<=t[a+3]&&t[a+3]<=191||t[a]===244&&128<=t[a+1]&&t[a+1]<=143&&128<=t[a+2]&&t[a+2]<=191&&128<=t[a+3]&&t[a+3]<=191){a+=4;continue}return!1}return!0},"isUtf8"),RNt=i(r=>{let e=/[^A-Z0-9+\/=]/i,t=r.length;if(!t||t%4!==0||e.test(r))return!1;let a=r.indexOf("=");return a===-1||a===t-1||a===t-2&&r[t-1]==="="},"isBase64")});var fee,Int=h(()=>{fee=class{static{i(this,"Domain")}constructor(e){this.protocol=this._protocolRegex(e),this.protocol||(e=`https://${e}`),this.nodeParsedUrl=new URL(e),this.port=this.nodeParsedUrl.port;let t=this._domainRegex(e.replace(this.nodeParsedUrl.pathname,""));[this.level1,this.level2,this.level3,this.level4,this.level5]=t,this.fullName="";for(let a of t)this.fullName===""?this.fullName=a:this.fullName=a+"."+this.fullName;this.zoneName=[this.level2,this.level1].filter(Boolean).join("."),this.topLevel=this.level1,this.domainName=this.level2,this.subDomain=this.level3}_domainRegex(e){let a=/([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}([a-zA-Z0-9\-\_]*)\.{0,1}$/.exec(e);if(!a)return[];let s=[...a].reverse();return s.pop(),s.filter(function(n){return n!==""})}_protocolRegex(e){let a=/^([a-zA-Z0-9]*):\/\//.exec(e);if(a)return a[1]}_portRegex(e){let a=/^([a-zA-Z0-9]*):\/\//.exec(e);if(a)return a[1]}}});var mee,zNt,$nt,Dnt=h(()=>{mee=class{static{i(this,"GitRepo")}constructor(e,t){let a=zNt(e);if(!a)throw new Error(`Invalid git repository URL: ${e}`);this.host=a[1],this.user=a[2],this.repo=a[3],this.accessToken=t,this.sshUrl=$nt(this.host,this.user,this.repo,this.accessToken,"ssh"),this.httpsUrl=$nt(this.host,this.user,this.repo,this.accessToken,"https")}},zNt=i(function(r){return/([a-zA-Z0-9\-_\.]*)(?:\/|\:)([a-zA-Z0-9\-_\.]*)(?:\/)([a-zA-Z0-9\-_\.]*)(?:\.git)/.exec(r)},"gitRegex"),$nt=i(function(r,e,t,a="",s){switch(a!==""&&(a=a+"@"),s){case"https":return"https://"+a+r+"/"+e+"/"+t+".git";case"ssh":return"git@"+r+":"+e+"/"+t+".git"}},"gitLink")});var uo={};St(uo,{Base64:()=>pee,Domain:()=>fee,GitRepo:()=>mee,base64:()=>N2,create:()=>cee,docker:()=>dee,indent:()=>B2,normalize:()=>uee,type:()=>hee});var r4=h(()=>{knt();Snt();_nt();Tnt();Mnt();_he();Int();Dnt()});var Pnt=dr((tKr,Ent)=>{"use strict";Ent.exports=function(r,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var t=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&(function(o){return function(n){return function(l,c){var d={key:l,value:n[l]},u={key:c,value:n[c]};return o(d,u)}}})(e.cmp),s=[];return i((function o(n){if(n&&n.toJSON&&typeof n.toJSON=="function"&&(n=n.toJSON()),n!==void 0){if(typeof n=="number")return isFinite(n)?""+n:"null";if(typeof n!="object")return JSON.stringify(n);var l,c;if(Array.isArray(n)){for(c="[",l=0;l<n.length;l++)l&&(c+=","),c+=o(n[l])||"null";return c+"]"}if(n===null)return"null";if(s.indexOf(n)!==-1){if(t)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var d=s.push(n)-1,u=Object.keys(n).sort(a&&a(n));for(c="",l=0;l<u.length;l++){var p=u[l],m=o(n[p]);m&&(c&&(c+=","),c+=JSON.stringify(p)+":"+m)}return s.splice(d,1),"{"+c+"}"}}),"stringify")(r)}});var Ant,gee,Che=h(()=>{e4();r4();Ant=rl(Pnt(),1),gee=Ant.default});function ONt(r){let e=Rnt();return e?e.from(r).toString("base64"):btoa(String.fromCharCode(...r))}function BNt(r){let e=Rnt();if(e){let t=e.from(r,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}return new Uint8Array(Array.from(atob(r)).map(t=>t.charCodeAt(0)))}function Mhe(r,e){return JSON.stringify(r,bee,e)}function Ihe(r){return JSON.parse(r,znt)}function NNt(r){return Ont(r)&&r.type==="EncodedBuffer"&&The(r.data)}function FNt(r){return Ont(r)&&r.type==="Buffer"&&(Lnt(r.data)||The(r.data))||r instanceof Uint8Array}function Lnt(r){return Array.isArray(r)}function The(r){return typeof r=="string"}function Ont(r){return typeof r=="object"&&r!==null}var Rnt,bee,znt,Bnt=h(()=>{Che();Rnt=i(()=>globalThis.Buffer,"getNodeBuffer");i(ONt,"base64Encode");i(BNt,"base64Decode");i(Mhe,"stringify");i(Ihe,"parse");bee=i((r,e)=>{if(FNt(e)){let t;if("data"in e&&Lnt(e.data))t=new Uint8Array(e.data);else if(e instanceof Uint8Array)t=e;else return e;return{type:"EncodedBuffer",data:"base64:"+ONt(t)}}return e},"replacer"),znt=i((r,e)=>{if(NNt(e)&&The(e.data)&&e.data.startsWith("base64:")){let t=e.data.slice(7);return BNt(t)}return e},"reviver");i(NNt,"isEncodedBuffer");i(FNt,"isBufferLike");i(Lnt,"isArray");i(The,"isString");i(Ont,"isObject")});var wa={};St(wa,{Smartjson:()=>Dhe,deepEqualJsonLStrings:()=>KNt,deepEqualObjects:()=>Nnt,foldDec:()=>GNt,parse:()=>vee,parseBase64:()=>WNt,parseJsonL:()=>$he,stableOneWayStringify:()=>VNt,stringify:()=>ag,stringifyBase64:()=>UNt,stringifyJsonL:()=>HNt,stringifyPretty:()=>jNt});var vee,$he,HNt,VNt,ag,jNt,UNt,WNt,Dhe,GNt,Nnt,KNt,sg=h(()=>{Che();Bnt();vee=Ihe,$he=i(r=>r.split(`
|
|
13
13
|
`).reduce((a,s)=>{let o=s.trim();return o.length>0&&a.push(vee(o)),a},[]),"parseJsonL"),HNt=i(r=>r.map(e=>ag(e)).join(`
|
|
14
|
-
`),"stringifyJsonL"),VNt=i((r,e,t={})=>{let a=new WeakSet,s=i(l=>{if(l===null||typeof l!="object")return l;let c=bee("",l);if(c&&c.type==="EncodedBuffer"&&typeof c.data=="string")return c;if(a.has(l))return"__cycle__";if(a.add(l),Array.isArray(l))return l.map(u=>s(u));let d={};for(let u of Object.keys(l))try{d[u]=s(l[u])}catch{d[u]="__unserializable__"}return d},"sanitize"),o=s(r),n={...t,cycles:!0};if(e&&!n.cmp){let l=new Map;e.forEach((c,d)=>l.set(c,d)),n.cmp=(c,d)=>{let u=l.has(c.key)?l.get(c.key):Number.POSITIVE_INFINITY,p=l.has(d.key)?l.get(d.key):Number.POSITIVE_INFINITY;return u!==p?u-p:c.key<d.key?-1:c.key>d.key?1:0}}return gee(o,n)},"stableOneWayStringify"),ag=i((r,e,t={})=>{let a=Mhe(r);r=JSON.parse(a);let s={...t};if(e&&!s.cmp){let n=new Map;e.forEach((l,c)=>n.set(l,c)),s.cmp=(l,c)=>{let d=n.has(l.key)?n.get(l.key):Number.POSITIVE_INFINITY,u=n.has(c.key)?n.get(c.key):Number.POSITIVE_INFINITY;return d!==u?d-u:l.key<c.key?-1:l.key>c.key?1:0}}return gee(r,s)},"stringify"),jNt=i(r=>{let e=ag(r),t=JSON.parse(e);return JSON.stringify(t,null,2)},"stringifyPretty"),UNt=i((...r)=>{let e=ag(...r);return uo.base64.encodeUri(e)},"stringifyBase64"),WNt=i(r=>{let e=uo.base64,a=(e.decodeUri||e.decode)(r);return vee(a)},"parseBase64"),Dhe=class r{static{i(this,"Smartjson")}static enfoldFromObject(e){let t=new this,a=t.saveableProperties||[];for(let s in e)a.indexOf(s)!==-1&&(t[s]=e[s]);return t}static enfoldFromJson(e){let t=vee(e);return this.enfoldFromObject(t)}saveableProperties=[];foldToObject(){let e=new Set;return e.add(this),this.foldToObjectInternal(e)}foldToObjectInternal(e){let t={},a=i(o=>{if(o instanceof r){if(e.has(o))throw new Error("cycle detected");return e.add(o),o.foldToObjectInternal(e)}return Array.isArray(o)?o.map(n=>a(n)):structuredClone(o)},"foldValue"),s=this.saveableProperties||[];for(let o of s){let n=this[o];t[o]=a(n)}return t}foldToJson(){let e=this.foldToObject();return ag(e)}},GNt=i(()=>(r,e)=>{let t=String(e.name);e.addInitializer(function(){this.saveableProperties||(this.saveableProperties=[]),this.saveableProperties.includes(t)||this.saveableProperties.push(t)})},"foldDec"),Nnt=i((r,e)=>{let t=ag(r),a=ag(e);return t===a},"deepEqualObjects"),KNt=i((r,e)=>{let t=$he(r),a=$he(e);return Nnt(t,a)},"deepEqualJsonLStrings")});var Fnt={};var qnt=h(()=>{});var Ehe=h(()=>{H_();e4();sg();Po();cd();qnt()});var yee,Vnt,YNt,ZNt,xee,jnt,Unt,QNt,a4,Phe=h(()=>{Ehe();yee=class{static{i(this,"WebStoreDb")}constructor(e){this.nativeDb=e}async get(e,t,a={}){return this.runObjectStoreRequest(e,"readonly",s=>s.get(t),a)}async getKey(e,t,a={}){return this.runObjectStoreRequest(e,"readonly",s=>s.getKey(t),a)}async put(e,t,a,s={}){return this.runObjectStoreRequest(e,"readwrite",o=>a===void 0?o.put(t):o.put(t,a),s)}async delete(e,t,a={}){await this.runObjectStoreRequest(e,"readwrite",s=>s.delete(t),a)}async clear(e,t={}){await this.runObjectStoreRequest(e,"readwrite",a=>a.clear(),t)}async getAllKeys(e,t={}){return this.runObjectStoreRequest(e,"readonly",a=>a.getAllKeys(),t)}close(){this.nativeDb.close()}async runObjectStoreRequest(e,t,a,s){s.signal?.throwIfAborted();let o=this.nativeDb.transaction(e,t),n=o.objectStore(e),l=a(n),c,d=new Promise((p,m)=>{c=m}),u=i(()=>{try{o.abort()}catch(p){if(!(p instanceof DOMException)||p.name!=="InvalidStateError"){c(p);return}}s.signal&&c(s.signal.reason)},"abortTransaction");s.signal?.addEventListener("abort",u,{once:!0});try{let[p]=await Promise.race([Promise.all([YNt(l),ZNt(o)]),d]);return p}catch(p){throw s.signal?.aborted?s.signal.reason:p}finally{s.signal?.removeEventListener("abort",u)}}},Vnt=i(async(r,e)=>{if(e?.throwIfAborted(),!e)return r;let t,a=new Promise((o,n)=>{t=n}),s=i(()=>{t(e.reason)},"abortListener");e.addEventListener("abort",s,{once:!0});try{return await Promise.race([r,a])}finally{e.removeEventListener("abort",s)}},"awaitWithSignal"),YNt=i(r=>new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(xee("IndexedDB request failed",r.error))}),"indexedDbRequestToPromise"),ZNt=i(r=>new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(xee("IndexedDB transaction aborted",r.error)),r.onerror=()=>t(xee("IndexedDB transaction failed",r.error))}),"indexedDbTransactionToPromise"),xee=i((r,e)=>e?new Error(`${r}: ${e.message}`,{cause:e}):new Error(r),"createIndexedDbError"),jnt=i((r,e)=>{r.objectStoreNames.contains(e)||r.createObjectStore(e)},"ensureObjectStore"),Unt=i(async(r,e,t)=>{if(!globalThis.indexedDB)throw new Error("IndexedDB is not available in this runtime");return new Promise((a,s)=>{let o=!1,n=typeof e=="number"?globalThis.indexedDB.open(r,e):globalThis.indexedDB.open(r),l=i(c=>{o||(o=!0,s(c instanceof Error?c:new Error(String(c))))},"rejectOnce");n.onupgradeneeded=()=>{if(t)try{t(n.result)}catch(c){n.transaction?.abort(),l(c)}},n.onsuccess=()=>{if(o){n.result.close();return}o=!0;let c=n.result;c.onversionchange=()=>c.close(),a(c)},n.onerror=()=>l(xee(`Failed to open IndexedDB database "${r}"`,n.error)),n.onblocked=()=>l(new Error(`Opening IndexedDB database "${r}" was blocked by another connection`))})},"openNativeDb"),QNt=i(async(r,e)=>{let t=await Unt(r,void 0,s=>jnt(s,e));if(t.objectStoreNames.contains(e))return new yee(t);let a=t.version+1;if(t.close(),t=await Unt(r,a,s=>jnt(s,e)),!t.objectStoreNames.contains(e))throw t.close(),new Error(`Failed to create IndexedDB object store "${e}" in database "${r}"`);return new yee(t)},"openWebStoreDb"),a4=class{static{i(this,"WebStore")}constructor(e){this.lifecycleGeneration=0,this.closeCoveredGeneration=0,this.activeOperations=new Set,this.options=e}trackOperation(e){this.lifecycleGeneration+=1;let t;return t=(async()=>e())().finally(()=>{this.activeOperations.delete(t)}),this.activeOperations.add(t),t}init(e={}){return this.trackOperation(()=>this.initForOperation(e.signal))}async initForOperation(e){e?.throwIfAborted();let t=this.closePromise;return t&&(await Vnt(t,e),e?.throwIfAborted()),this.initPromise||(this.initPromise=this.runInit().catch(a=>{throw this.initPromise=void 0,a})),Vnt(this.initPromise,e)}async runInit(){let e=new ic.Smartenv;if(!e.isBrowser&&!globalThis.indexedDB&&(await e.getSafeNodeModule("fake-indexeddb/auto"),!globalThis.indexedDB)){let t=await e.getSafeNodeModule("fake-indexeddb");globalThis.indexedDB=new t.IDBFactory}this.db=await QNt(this.options.dbName,this.options.storeName)}runDataOperation(e,t){return this.trackOperation(async()=>(await this.initForOperation(t.signal),t.signal?.throwIfAborted(),e(this.db)))}close(){let e=this.lifecycleGeneration;if(this.closePromise&&e<=this.closeCoveredGeneration)return this.closePromise;let t=this.closePromise,a=[...this.activeOperations];if(!t&&!this.initPromise&&a.length===0)return Promise.resolve();let s;return s=(async()=>{try{if(t)try{await t}catch{}await Promise.allSettled(a);let o=this.initPromise;if(!o)return;try{await o}catch{return}finally{this.initPromise===o&&(this.initPromise=void 0)}this.db.close()}finally{this.closePromise===s&&(this.closePromise=void 0)}})(),this.closePromise=s,this.closeCoveredGeneration=e,s}async get(e,t={}){return this.runDataOperation(a=>a.get(this.options.storeName,e,t),t)}async check(e,t={}){return this.runDataOperation(async a=>await a.getKey(this.options.storeName,e,t)!==void 0,t)}async set(e,t,a={}){return this.runDataOperation(s=>s.put(this.options.storeName,t,e,a),a)}async delete(e,t={}){return this.runDataOperation(a=>a.delete(this.options.storeName,e,t),t)}async clear(e={}){return this.runDataOperation(t=>t.clear(this.options.storeName,e),e)}async keys(e={}){return this.runDataOperation(t=>t.getAllKeys(this.options.storeName,e),e)}}});var Ahe,Wnt=h(()=>{Phe();Ehe();Ahe=class{static{i(this,"TypedrequestCache")}constructor(e="default"){this.webstore=new a4({dbName:"trStore",storeName:`trStore-${e}`})}buildKey(e){return wa.stringify({method:e.method,request:e.request})}async setByRequest(e){if(!e.response)throw new Error("You cannot store requests without a response present");await this.webstore.set(this.buildKey(e),e)}async getByRequest(e){return await this.webstore.get(this.buildKey(e))}}});var oc={};St(oc,{TypedrequestCache:()=>Ahe,WebStore:()=>a4});var wee=h(()=>{Wnt();Phe()});var s4=h(()=>{wh();e4();sg();Po();wee()});var i4,F2,XNt,o4=h(()=>{s4();i4=256,F2=class{static{i(this,"CacheStore")}constructor(e="webrequest-v4",t="cache"){this.lifecycleController=new AbortController,this.closeReason=new Error("Webrequest cache store is closed"),this.disposed=!1,this.pruneGeneration=0,this.pruneWaiters=new Set,this.activeOwnedOperations=new Set,this.webstore=new oc.WebStore({dbName:e,storeName:t}),this.initPromise=this.init()}async init(){}generateCacheKey(e){let t=e.url,a=e.method;return a==="GET"?t:`${a}:${t}`}async set(e,t,a={}){await this.initPromise;let s=this.getOperationSignal(a.signal),o=a.maxEntries??i4;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError("webrequest cache maxEntries must be a positive safe integer");await this.webstore.set(e,t,{signal:s}),await this.schedulePrune(o,s)}async get(e,t={}){await this.initPromise;let a=this.getOperationSignal(t.signal);try{let s=await this.webstore.get(e,{signal:a});return s===void 0?null:this.isCacheEntry(s)?s:(await this.webstore.delete(e,{signal:a}),null)}catch{if(a.aborted)throw a.reason;return null}}async has(e,t={}){return await this.get(e,t)!==null}async delete(e,t={}){await this.initPromise;let a=this.getOperationSignal(t.signal);await this.webstore.delete(e,{signal:a})}async clear(e={}){await this.initPromise;let t=this.getOperationSignal(e.signal);await this.webstore.clear({signal:t})}responseFromCacheEntry(e){let t=new Headers(e.headers);return new Response(e.response,{status:e.status,statusText:e.statusText,headers:t})}cacheEntryFromResponse(e,t,a,s={}){return this.trackOwnedOperation(async()=>{let o=this.getOperationSignal(s.signal),n=s.preserveResponse!==!1,l=n?t.clone():t,c=await this.consumeArrayBuffer(l,o,n?t.body:void 0,s.responseSignal),d={};return l.headers.forEach((u,p)=>{d[p]=u}),{response:c,headers:d,timestamp:Date.now(),etag:a?.etag||l.headers.get("etag")||void 0,lastModified:a?.lastModified||l.headers.get("last-modified")||void 0,maxAge:a?.maxAge,url:e,status:l.status,statusText:l.statusText}})}async pruneExpired(e={}){await this.initPromise;let t=this.getOperationSignal(e.signal),a=await this.collectEntries(t),s=0;for(let o of a)t.throwIfAborted(),!(o.valid&&!this.isExpired(o))&&(await this.webstore.delete(o.key,{signal:t}),s+=1);return s}async schedulePrune(e,t){t?.throwIfAborted();let a=++this.pruneGeneration;this.pendingPruneMaxEntries=this.pendingPruneMaxEntries===void 0?e:Math.min(this.pendingPruneMaxEntries,e);let s,o,n=new Promise((c,d)=>{s=c,o=d}),l={generation:a,resolve:s,reject:o};this.pruneWaiters.add(l),this.ensurePruneLoop();try{await XNt(n,t)}finally{this.pruneWaiters.delete(l)}}ensurePruneLoop(){if(this.pruneLoopPromise)return this.pruneLoopPromise;let e;return e=this.runPruneLoop().catch(t=>{this.pendingPruneMaxEntries=void 0,this.settlePruneWaiters(this.pruneGeneration,t)}).finally(()=>{this.pruneLoopPromise===e&&(this.pruneLoopPromise=void 0,this.pendingPruneMaxEntries!==void 0&&!this.disposed&&this.ensurePruneLoop())}),this.pruneLoopPromise=e,e}async runPruneLoop(){for(;this.pendingPruneMaxEntries!==void 0;){let e=this.pendingPruneMaxEntries;this.pendingPruneMaxEntries=void 0;let t=this.pruneGeneration;await this.pruneToLimit(e,this.lifecycleController.signal),this.settlePruneWaiters(t)}}settlePruneWaiters(e,t){for(let a of this.pruneWaiters)a.generation>e||(this.pruneWaiters.delete(a),t===void 0?a.resolve():a.reject(t))}async pruneToLimit(e,t){let a=await this.collectEntries(t),s=a.filter(l=>!l.valid||this.isExpired(l));for(let l of s)t?.throwIfAborted(),await this.webstore.delete(l.key,{signal:t});let o=a.filter(l=>l.valid&&!this.isExpired(l)).sort((l,c)=>l.timestamp===c.timestamp?l.key.localeCompare(c.key):(l.timestamp??0)-(c.timestamp??0)),n=Math.max(0,o.length-e);for(let l of o.slice(0,n))t?.throwIfAborted(),await this.webstore.delete(l.key,{signal:t})}async collectEntries(e){e?.throwIfAborted();let t=await this.webstore.keys({signal:e}),a=[];for(let s of t)if(e?.throwIfAborted(),typeof s=="string")try{let o=await this.webstore.get(s,{signal:e});a.push(this.isCacheEntry(o)?{key:s,valid:!0,timestamp:o.timestamp,maxAge:o.maxAge}:{key:s,valid:!1,timestamp:0})}catch{if(e?.aborted)throw e.reason;continue}return a}isCacheEntry(e){if(!e||typeof e!="object")return!1;let t=Reflect.get(e,"response"),a=Reflect.get(e,"headers"),s=Reflect.get(e,"timestamp"),o=Reflect.get(e,"url"),n=Reflect.get(e,"status"),l=Reflect.get(e,"statusText");return t instanceof ArrayBuffer&&typeof a=="object"&&a!==null&&Number.isFinite(s)&&typeof o=="string"&&Number.isInteger(n)&&typeof l=="string"}isExpired(e){return e.maxAge!==void 0&&e.maxAge>0&&Date.now()-e.timestamp>=e.maxAge}getOperationSignal(e){if(this.disposed)throw this.closeReason;return e?.throwIfAborted(),e?AbortSignal.any([e,this.lifecycleController.signal]):this.lifecycleController.signal}trackOwnedOperation(e){let t;return t=e().finally(()=>{this.activeOwnedOperations.delete(t)}),this.activeOwnedOperations.add(t),t}close(){if(this.closePromise)return this.closePromise;this.disposed=!0,this.lifecycleController.abort(this.closeReason);let e=this.pruneLoopPromise,t=[...this.activeOwnedOperations];return this.closePromise=(async()=>{await Promise.allSettled([...t,...e?[e]:[]]),await this.webstore.close()})(),this.closePromise}async consumeArrayBuffer(e,t,a,s){if(t?.throwIfAborted(),!t)return e.arrayBuffer();let o=e.body?.getReader();if(!o)return new ArrayBuffer(0);let n=[],l=0,c,d=new Promise((v,f)=>{c=f}),u,p=i(()=>{c(t.reason),s?.aborted||(u=Promise.all([o.cancel(t.reason).catch(()=>{}),a?.cancel(t.reason).catch(()=>{})]).then(()=>{}))},"abortListener");t.addEventListener("abort",p,{once:!0});try{for(;;){let v=await Promise.race([o.read(),d]);if(v.done)break;n.push(v.value),l+=v.value.byteLength}}finally{t.removeEventListener("abort",p),u&&await u;try{o.releaseLock()}catch{}}let m=new Uint8Array(l),b=0;for(let v of n)m.set(v,b),b+=v.byteLength;return m.buffer}},XNt=i(async(r,e)=>{if(e?.throwIfAborted(),!e)return r;let t,a=new Promise((o,n)=>{t=n}),s=i(()=>{t(e.reason)},"abortListener");e.addEventListener("abort",s,{once:!0});try{return await Promise.race([r,a])}finally{e.removeEventListener("abort",s)}},"awaitWithSignal")});function JNt(r){let e={maxAge:0,immutable:!1,noCache:!1,noStore:!1,mustRevalidate:!1};if(!r)return e;let t=r.toLowerCase().split(",").map(a=>a.trim());for(let a of t)if(a==="no-cache")e.noCache=!0;else if(a==="no-store")e.noStore=!0;else if(a==="immutable")e.immutable=!0;else if(a==="must-revalidate")e.mustRevalidate=!0;else if(a.startsWith("max-age=")){let s=parseInt(a.split("=")[1],10);isNaN(s)||(e.maxAge=s*1e3)}return e}function eFt(r){if(r)try{return new Date(r).getTime()}catch{return}}function wd(r){let e=r.get("cache-control"),t=r.get("expires"),a=r.get("etag"),s=r.get("last-modified"),o=JNt(e);if(o.maxAge===0&&t){let n=eFt(t);n&&(o.maxAge=Math.max(0,n-Date.now()))}return{maxAge:o.maxAge||0,etag:a||void 0,lastModified:s||void 0,immutable:o.immutable||!1,noCache:o.noCache||!1,noStore:o.noStore||!1,mustRevalidate:o.mustRevalidate||!1}}function See(r,e){if(e.noStore)return!1;if(e.immutable)return!0;let t=Date.now()-r.timestamp,a=r.maxAge||e.maxAge||0;return a===0?!1:t<a}function q2(r){return r.noCache||r.mustRevalidate}function _ee(r){let e={};return r.etag&&(e["if-none-match"]=r.etag),r.lastModified&&(e["if-modified-since"]=r.lastModified),e}function Cee(r){let e={};return r.forEach((t,a)=>{e[a]=t}),e}function Gnt(r){let e=new Headers;return Object.entries(r).forEach(([t,a])=>{e.set(t,a)}),e}var Rhe=h(()=>{i(JNt,"parseCacheControl");i(eFt,"parseExpires");i(wd,"extractCacheMetadata");i(See,"isFresh");i(q2,"requiresRevalidation");i(_ee,"createConditionalHeaders");i(Cee,"headersToObject");i(Gnt,"objectToHeaders")});function tFt(r){let e=new AbortController,t=!1,a=!1,s=new sr.Timeout(r,null);return s.promise.then(()=>{t=!0,e.abort()}),{controller:e,cleanup:i(()=>{a||(a=!0,s.cancel())},"cleanup"),didTimeout:i(()=>t,"didTimeout")}}async function zhe(r,e,t){let a=r instanceof Request?r.url:String(r),{controller:s,cleanup:o,didTimeout:n}=tFt(t),l=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal;try{let c=await fetch(r,{...e,signal:l});return o(),c}catch(c){throw o(),n()?Hh(a,t):c}}async function Znt(r,e){if(e.signal?.aborted){let u=Ynt(e.signal);throw await r.body?.cancel(u).catch(()=>{}),u}if(e.bodyTimeoutMs!==void 0&&e.bodyTimeoutMs<=0){let u=Hh(e.url,e.reportedTimeoutMs??e.bodyTimeoutMs);throw await r.body?.cancel(u).catch(()=>{}),u}if(e.bodyTimeoutMs===void 0&&!e.signal)return await r.json();let t=r.body?.getReader();if(!t)return JSON.parse("");let a,s,o,n=new Promise((u,p)=>{o=p}),l=i(u=>{a||(a=u,t.cancel(u).catch(()=>{}),o(u))},"terminate"),c=i(()=>{e.signal&&l(Ynt(e.signal))},"abortListener");if(e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c,{once:!0})),e.bodyTimeoutMs!==void 0){let u=e.reportedTimeoutMs??e.bodyTimeoutMs;s=setTimeout(()=>{l(Hh(e.url,u))},e.bodyTimeoutMs)}let d=i(async()=>{let u=new TextDecoder,p="";for(;;){let m;try{m=await t.read()}catch(b){throw a||b}if(a)throw a;if(m.done)break;p+=u.decode(m.value,{stream:!0})}if(p+=u.decode(),a)throw a;return JSON.parse(p)},"readBody");try{return await Promise.race([d(),n])}finally{s!==void 0&&clearTimeout(s),e.signal?.removeEventListener("abort",c);try{t.releaseLock()}catch{}}}var Knt,Hh,n4,Ynt,l4=h(()=>{s4();i(tFt,"createTimeoutController");Knt=Symbol("webrequestTimeoutError"),Hh=i((r,e)=>{let t=new Error(`Request timeout after ${e}ms: ${r}`);return Object.defineProperty(t,Knt,{configurable:!1,enumerable:!1,value:!0,writable:!1}),t},"createTimeoutError"),n4=i(r=>r instanceof Error&&Reflect.get(r,Knt)===!0,"isWebrequestTimeoutError");i(zhe,"fetchWithTimeout");Ynt=i(r=>{if(r.reason instanceof Error)return r.reason;let e=new Error("The request was aborted");return e.name="AbortError",e},"normalizeAbortReason");i(Znt,"consumeJsonWithTimeout")});function Xnt(r){switch(r){case"network-first":return new Tee;case"cache-first":return new Lhe;case"stale-while-revalidate":return new Ohe;case"network-only":return new Bhe;case"cache-only":return new Nhe;default:return new Tee}}var Tee,Lhe,Ohe,Bhe,Nhe,c4,Qnt,H2,Jnt=h(()=>{o4();Rhe();l4();Tee=class{static{i(this,"NetworkFirstStrategy")}async execute(e){let t;try{return t=await e.fetchFn(e.request),t.ok&&await this.cacheResponse(e,t),{response:t,fromCache:!1,revalidated:!1}}catch(a){if(await H2(t,a,e.request.signal),e.signal?.aborted)throw e.signal.reason;if(n4(a))throw a;e.logging&&console.log("[webrequest] Network failed, trying cache:",a);let s=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(s)return{response:e.cacheStore.responseFromCacheEntry(s),fromCache:!0,revalidated:!1};throw a}}async cacheResponse(e,t){let a=wd(t.headers);if(a.maxAge=c4(a.maxAge,e.cacheMaxAge),a.noStore)return;let s=await e.cacheStore.cacheEntryFromResponse(e.request.url,t,a,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,s,{signal:e.signal,maxEntries:e.cacheMaxEntries})}},Lhe=class{static{i(this,"CacheFirstStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(t){let o=wd(new Headers(t.headers));if(Qnt(e,t,o)&&!q2(o))return e.logging&&console.log("[webrequest] Cache hit (fresh):",e.request.url),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1};if(q2(o)&&(t.etag||t.lastModified))return await this.revalidate(e,t)}e.logging&&console.log("[webrequest] Cache miss, fetching:",e.request.url);let a=await e.fetchFn(e.request),s=wd(a.headers);if(s.maxAge=c4(s.maxAge,e.cacheMaxAge),!s.noStore)try{let o=await e.cacheStore.cacheEntryFromResponse(e.request.url,a,s,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,o,{signal:e.signal,maxEntries:e.cacheMaxEntries})}catch(o){throw await H2(a,o,e.request.signal),o}return{response:a,fromCache:!1,revalidated:!1}}async revalidate(e,t){let a=_ee(t),s=new Request(e.request.url,{method:e.request.method,headers:{...Cee(e.request.headers),...a},signal:e.signal}),o;try{if(o=await e.fetchFn(s),o.status===304)return e.logging&&console.log("[webrequest] Cache revalidated (304):",e.request.url),t.timestamp=Date.now(),await e.cacheStore.set(e.cacheKey,t,{signal:e.signal,maxEntries:e.cacheMaxEntries}),await H2(o,"304 response replaced by cached response",s.signal),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!0};if(o.ok){let n=wd(o.headers);if(n.maxAge=c4(n.maxAge,e.cacheMaxAge),!n.noStore){let l=await e.cacheStore.cacheEntryFromResponse(e.request.url,o,n,{signal:e.signal,responseSignal:s.signal});await e.cacheStore.set(e.cacheKey,l,{signal:e.signal,maxEntries:e.cacheMaxEntries})}}return{response:o,fromCache:!1,revalidated:!0}}catch(n){if(await H2(o,n,s.signal),e.signal?.aborted)throw e.signal.reason;if(n4(n))throw n;return e.logging&&console.log("[webrequest] Revalidation failed, using cache:",n),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1}}}},Ohe=class{static{i(this,"StaleWhileRevalidateStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(t){let o=e.cacheStore.responseFromCacheEntry(t);return e.scheduleBackgroundRevalidation(async n=>{let l={...e,request:new Request(e.request,{signal:n}),signal:n};await this.revalidateInBackground(l,t)}),{response:o,fromCache:!0,revalidated:!1}}let a=await e.fetchFn(e.request),s=wd(a.headers);if(s.maxAge=c4(s.maxAge,e.cacheMaxAge),!s.noStore&&a.ok)try{let o=await e.cacheStore.cacheEntryFromResponse(e.request.url,a,s,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,o,{signal:e.signal,maxEntries:e.cacheMaxEntries})}catch(o){throw await H2(a,o,e.request.signal),o}return{response:a,fromCache:!1,revalidated:!1}}async revalidateInBackground(e,t){let a=wd(new Headers(t.headers));if(Qnt(e,t,a)&&!q2(a))return;let s;try{if(e.signal?.throwIfAborted(),s=await e.fetchFn(e.request),s.ok){let o=wd(s.headers);if(o.maxAge=c4(o.maxAge,e.cacheMaxAge),!o.noStore){let n=await e.cacheStore.cacheEntryFromResponse(e.request.url,s,o,{signal:e.signal,responseSignal:e.request.signal,preserveResponse:!1});await e.cacheStore.set(e.cacheKey,n,{signal:e.signal,maxEntries:e.cacheMaxEntries}),e.logging&&console.log("[webrequest] Background revalidation complete:",e.request.url)}}}catch(o){if(e.signal?.aborted)return;e.logging&&console.warn("[webrequest] Background revalidation failed:",o)}finally{await H2(s,"background revalidation response discarded",e.request.signal)}}},Bhe=class{static{i(this,"NetworkOnlyStrategy")}async execute(e){return{response:await e.fetchFn(e.request),fromCache:!1,revalidated:!1}}},Nhe=class{static{i(this,"CacheOnlyStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(!t)throw new Error(`Cache miss for ${e.request.url} (cache-only mode)`);return{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1}}},c4=i((r,e)=>e===void 0?r:Math.min(r,e),"resolveEffectiveMaxAge"),Qnt=i((r,e,t)=>See(e,t)?r.cacheMaxAge===void 0?!0:Date.now()-e.timestamp<r.cacheMaxAge:!1,"isFreshForContext"),H2=i(async(r,e,t)=>{!r?.body||r.bodyUsed||t?.aborted||await r.body.cancel(e).catch(()=>{})},"cancelDiscardedResponse");i(Xnt,"getStrategyHandler")});var V2,Fhe=h(()=>{o4();Jnt();o4();l4();V2=class{static{i(this,"CacheManager")}constructor(e,t,a){this.lifecycleController=new AbortController,this.closeReason=new Error("Webrequest cache manager is closed"),this.disposed=!1,this.backgroundRevalidations=new Map,this.cacheStore=a??new F2(e,t)}async execute(e,t,a){if(this.disposed)throw this.closeReason;e.signal.throwIfAborted();let s=this.determineStrategy(e,t);if(s==="network-only")return{response:await a(e),fromCache:!1,revalidated:!1};let o=t.cacheMaxEntries??i4;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError("webrequest cacheMaxEntries must be a positive safe integer");if(t.cacheMaxAge!==void 0&&(!Number.isSafeInteger(t.cacheMaxAge)||t.cacheMaxAge<0))throw new RangeError("webrequest cacheMaxAge must be a non-negative safe integer");let n=t.timeout??6e4,l=new AbortController,c=setTimeout(()=>{l.abort(Hh(e.url,n))},Math.max(0,n)),d=AbortSignal.any([e.signal,this.lifecycleController.signal,l.signal]);try{let u=this.generateCacheKey(e,t),p=Xnt(s),m={request:e,cacheKey:u,cacheStore:this.cacheStore,fetchFn:a,logging:t.logging,signal:d,cacheMaxAge:t.cacheMaxAge,cacheMaxEntries:o,scheduleBackgroundRevalidation:i(b=>{this.scheduleBackgroundRevalidation(u,e.url,n,b)},"scheduleBackgroundRevalidation")};return await p.execute(m)}finally{clearTimeout(c)}}determineStrategy(e,t){return t.cacheStrategy?t.cacheStrategy:t.cache?this.mapCacheModeToStrategy(t.cache):e.cache?this.mapCacheModeToStrategy(e.cache):"network-first"}mapCacheModeToStrategy(e){switch(e){case"default":return"network-first";case"no-store":case"reload":return"network-only";case"no-cache":return"network-first";case"force-cache":return"cache-first";case"only-if-cached":return"cache-only";default:return"network-first"}}generateCacheKey(e,t){return t.cacheKey?typeof t.cacheKey=="function"?t.cacheKey(e):t.cacheKey:this.cacheStore.generateCacheKey(e)}async clear(){await this.cacheStore.clear()}async delete(e){await this.cacheStore.delete(e)}async has(e){return await this.cacheStore.has(e)}getStore(){return this.cacheStore}scheduleBackgroundRevalidation(e,t,a,s){if(this.disposed||this.backgroundRevalidations.has(e))return;let o=new AbortController,n=AbortSignal.any([this.lifecycleController.signal,o.signal]),l=setTimeout(()=>{o.abort(Hh(t,a))},Math.max(0,a)),c;c=s(n).catch(()=>{}).finally(()=>{clearTimeout(l),this.backgroundRevalidations.get(e)===c&&this.backgroundRevalidations.delete(e)}),this.backgroundRevalidations.set(e,c)}close(){if(this.closePromise)return this.closePromise;this.disposed=!0,this.lifecycleController.abort(this.closeReason);let e=[...this.backgroundRevalidations.values()];return this.closePromise=(async()=>{await Promise.allSettled(e),await this.cacheStore.close()})(),this.closePromise}}});function elt(r){switch(r){case"exponential":return new Mee;case"linear":return new qhe;case"constant":return new Hhe;default:return new Mee}}function tlt(r,e=.1){let t=r*e*Math.random();return r+t}var Mee,qhe,Hhe,rlt=h(()=>{Mee=class{static{i(this,"ExponentialBackoff")}calculate(e,t,a){let s=t*Math.pow(2,e-1);return Math.min(s,a)}},qhe=class{static{i(this,"LinearBackoff")}calculate(e,t,a){let s=t*e;return Math.min(s,a)}},Hhe=class{static{i(this,"ConstantBackoff")}calculate(e,t,a){return Math.min(t,a)}};i(elt,"getBackoffCalculator");i(tlt,"addJitter")});var j2,Vhe=h(()=>{s4();rlt();j2=class{static{i(this,"RetryManager")}constructor(e={},t){this.signal=t,this.options={maxAttempts:e.maxAttempts??3,backoff:e.backoff??"exponential",initialDelay:e.initialDelay??1e3,maxDelay:e.maxDelay??3e4,retryOn:e.retryOn??[408,429,500,502,503,504],onRetry:e.onRetry??(()=>{})}}async execute(e,t){let a;for(let s=1;s<=this.options.maxAttempts;s++){this.throwIfAborted();try{let o=await e();if(o instanceof Response&&this.shouldRetryResponse(o)){if(s===this.options.maxAttempts)return o;await this.cancelResponseBody(o,`Retrying after HTTP ${o.status}`);let n=this.calculateDelay(s);this.options.onRetry(s,new Error(`HTTP ${o.status}`),n),await this.delay(n);continue}return o}catch(o){if(this.signal?.aborted)throw this.getAbortError();a=o instanceof Error?o:new Error(String(o));let n=t?t(o,s):this.shouldRetryError(o);if(s===this.options.maxAttempts||!n)throw a;let l=this.calculateDelay(s);this.options.onRetry(s,a,l),await this.delay(l)}}throw a||new Error("Max retry attempts reached")}async executeWithFallbacks(e,t,a){if(e.length===0)throw new Error("No URLs provided for fallback execution");let s,o=[];for(let n of e){this.throwIfAborted();try{let l=await this.execute(async()=>await a(n,t));if(l.status<400||l.status>=400&&l.status<500&&l.status!==408)return l;await this.cancelResponseBody(l,`Trying fallback after HTTP ${l.status}`),o.push(n),s=new Error(`Request failed with status ${l.status}`)}catch(l){if(this.signal?.aborted)throw this.getAbortError();o.push(n),s=l instanceof Error?l:new Error(String(l))}}throw new Error(`All URLs failed: ${o.join(", ")}. Last error: ${s?.message||"Unknown error"}`)}shouldRetryResponse(e){let t=this.options.retryOn;return typeof t=="function"?t(e):Array.isArray(t)?t.includes(e.status):!1}shouldRetryError(e){if(e instanceof TypeError&&e.message.includes("fetch")||e.name==="AbortError"||e.message.includes("timeout"))return!0;let t=this.options.retryOn;return typeof t=="function"?t(void 0,e):!1}calculateDelay(e){let a=elt(this.options.backoff).calculate(e,this.options.initialDelay,this.options.maxDelay);return tlt(a)}async delay(e){if(!this.signal){await sr.delayFor(e);return}if(this.signal.aborted)throw this.getAbortError();let t=new sr.Timeout(e,null),a,s=new Promise((n,l)=>{a=l}),o=i(()=>{t.cancel(),a(this.getAbortError())},"abortListener");try{this.signal.addEventListener("abort",o,{once:!0}),this.signal.aborted&&o(),await Promise.race([t.promise,s])}finally{t.cancel(),this.signal.removeEventListener("abort",o)}}async cancelResponseBody(e,t){await e.body?.cancel(t).catch(()=>{})}throwIfAborted(){if(this.signal?.aborted)throw this.getAbortError()}getAbortError(){if(this.signal?.reason instanceof Error)return this.signal.reason;let e=new Error("The request was aborted");return e.name="AbortError",e}}});var U2,jhe=h(()=>{s4();U2=class{static{i(this,"RequestDeduplicator")}constructor(){this.inFlightRequests=new Map}generateKey(e){let t=e.url,a=e.method;return a==="GET"||a==="HEAD"?`${a}:${t}`:`${a}:${t}:${Date.now()}`}async execute(e,t){let a=this.inFlightRequests.get(e);if(a){let o=await a.promise;return{response:this.cloneValue(o),wasDeduplicated:!0}}let s=kt.defer();this.inFlightRequests.set(e,s);try{let o=await t();return s.resolve(o),this.inFlightRequests.delete(e),{response:o,wasDeduplicated:!1}}catch(o){throw s.reject(o),this.inFlightRequests.delete(e),o}}isInFlight(e){return this.inFlightRequests.has(e)}getInFlightCount(){return this.inFlightRequests.size}clear(){this.inFlightRequests.clear()}cloneValue(e){return e instanceof Response?e.clone():{...e,response:e.response.clone()}}}});var ig,rFt,Uhe=h(()=>{vhe();Fhe();Vhe();jhe();l4();ig=class{static{i(this,"WebrequestClient")}constructor(e={}){this.closeReason=new Error("Webrequest client is closed"),this.disposed=!1,this.defaultOptions=e,this.interceptorManager=new O2,this.cacheManager=new V2,this.deduplicator=new U2}addRequestInterceptor(e){this.interceptorManager.addRequestInterceptor(e)}addResponseInterceptor(e){this.interceptorManager.addResponseInterceptor(e)}addErrorInterceptor(e){this.interceptorManager.addErrorInterceptor(e)}removeRequestInterceptor(e){this.interceptorManager.removeRequestInterceptor(e)}removeResponseInterceptor(e){this.interceptorManager.removeResponseInterceptor(e)}removeErrorInterceptor(e){this.interceptorManager.removeErrorInterceptor(e)}clearInterceptors(){this.interceptorManager.clearAll()}async clearCache(){await this.cacheManager.clear()}async deleteCache(e){await this.cacheManager.delete(e)}async request(e,t={}){return(await this.requestWithMetadata(e,t)).response}async requestWithMetadata(e,t={}){if(this.disposed)throw this.closeReason;let a={...this.defaultOptions,...t},s;if(typeof e=="string"?s=new Request(e,a):s=e,s=await this.interceptorManager.processRequest(s),a.interceptors?.request)for(let n of a.interceptors.request)s=await n(s);if(a.deduplicate??!1){let n=this.deduplicator.generateKey(s);return(await this.deduplicator.execute(n,async()=>await this.executeRequest(s,a))).response}return await this.executeRequest(s,a)}async executeRequest(e,t){try{let a=typeof t.retry=="object"?t.retry:t.retry?{}:void 0,s=i(async c=>{let d=t.timeout??6e4,u={...t,method:c.method,headers:c.headers,signal:c.signal};return c.body&&(u.body=c.body,u.duplex="half"),await zhe(c.url,u,d)},"fetchFnForRequest"),o=i(async(c,d)=>{let u=t.timeout??6e4;return await zhe(c,d,u)},"fetchFnForFallbacks"),n;if(a){let c=new j2(a,t.signal);if(t.fallbackUrls&&t.fallbackUrls.length>0){let d=[e.url,...t.fallbackUrls];n={response:await c.executeWithFallbacks(d,{method:e.method,headers:e.headers,body:e.body,...t},o),fromCache:!1,revalidated:!1}}else{let d,u=await c.execute(async()=>{let p=await this.cacheManager.execute(e,t,s);return d=p,p.response});n=d?.response===u?d:{response:u,fromCache:!1,revalidated:!1}}}else n=await this.cacheManager.execute(e,t,s);let l=await this.interceptorManager.processResponse(n.response);if(t.interceptors?.response)for(let c of t.interceptors.response)l=await c(l);return rFt(l,n)}catch(a){throw await this.interceptorManager.processError(a instanceof Error?a:new Error(String(a)))}}async close(){return this.closePromise?this.closePromise:(this.disposed=!0,this.closePromise=this.cacheManager.close(),this.closePromise)}async requestJsonWithMetadata(e,t){let a={...this.defaultOptions,...t},s=a.timeout??6e4,o=a.retry?void 0:performance.now()+s,n=o===void 0?void 0:new AbortController,l=n?a.signal?AbortSignal.any([a.signal,n.signal]):n.signal:a.signal,c=n===void 0?void 0:setTimeout(()=>{n.abort(Hh(e,s))},Math.max(0,s));try{let d=await this.requestWithMetadata(e,{...t,signal:l}),u=d.response;if(l?.aborted)throw await u.body?.cancel(l.reason).catch(()=>{}),l.reason instanceof Error?l.reason:new Error("The request was aborted");if(!u.ok)throw await u.body?.cancel(`HTTP ${u.status}`).catch(()=>{}),new Error(`HTTP ${u.status}: ${u.statusText}`);let p=o===void 0?s:o-performance.now(),m=await Znt(u,{bodyTimeoutMs:p,reportedTimeoutMs:s,signal:l,url:e});return Object.freeze({data:m,response:u,metadata:d.metadata})}catch(d){throw l?.aborted&&l.reason instanceof Error?l.reason:d}finally{c!==void 0&&clearTimeout(c)}}async getJson(e,t={}){return(await this.getJsonWithMetadata(e,t)).data}async getJsonWithMetadata(e,t={}){return await this.requestJsonWithMetadata(e,{...t,method:"GET",headers:{Accept:"application/json",...t.headers||{}}})}async postJson(e,t,a={}){return(await this.postJsonWithMetadata(e,t,a)).data}async postJsonWithMetadata(e,t,a={}){return await this.requestJsonWithMetadata(e,{...a,method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers||{}},body:JSON.stringify(t)})}async putJson(e,t,a={}){return(await this.putJsonWithMetadata(e,t,a)).data}async putJsonWithMetadata(e,t,a={}){return await this.requestJsonWithMetadata(e,{...a,method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers||{}},body:JSON.stringify(t)})}async deleteJson(e,t={}){return(await this.deleteJsonWithMetadata(e,t)).data}async deleteJsonWithMetadata(e,t={}){return await this.requestJsonWithMetadata(e,{...t,method:"DELETE",headers:{Accept:"application/json",...t.headers||{}}})}},rFt=i((r,e)=>{let t=Object.freeze({fromCache:e.fromCache,revalidated:e.revalidated});return Object.freeze({response:r,metadata:t})},"createResponseResult")});async function _i(r,e){let t=r instanceof Request?r.url:String(r),a=r instanceof Request?r:new Request(t,e);return await po.request(a,e)}var po,alt=h(()=>{Uhe();po=new ig;i(_i,"webrequest"),_i.requestWithMetadata=async function(r,e){let t=r instanceof Request?r.url:String(r),a=r instanceof Request?r:new Request(t,e);return await po.requestWithMetadata(a,e)},_i.getJson=async function(r,e){return await po.getJson(r,e)},_i.getJsonWithMetadata=async function(r,e){return await po.getJsonWithMetadata(r,e)},_i.postJson=async function(r,e,t){return await po.postJson(r,e,t)},_i.postJsonWithMetadata=async function(r,e,t){return await po.postJsonWithMetadata(r,e,t)},_i.putJson=async function(r,e,t){return await po.putJson(r,e,t)},_i.putJsonWithMetadata=async function(r,e,t){return await po.putJsonWithMetadata(r,e,t)},_i.deleteJson=async function(r,e){return await po.deleteJson(r,e)},_i.deleteJsonWithMetadata=async function(r,e){return await po.deleteJsonWithMetadata(r,e)},_i.addRequestInterceptor=function(r){po.addRequestInterceptor(r)},_i.addResponseInterceptor=function(r){po.addResponseInterceptor(r)},_i.addErrorInterceptor=function(r){po.addErrorInterceptor(r)},_i.clearInterceptors=function(){po.clearInterceptors()},_i.clearCache=async function(){await po.clearCache()},_i.createClient=function(r){return new ig(r)},_i.getDefaultClient=function(){return po}});var Vh={};St(Vh,{CacheManager:()=>V2,CacheStore:()=>F2,InterceptorManager:()=>O2,RequestDeduplicator:()=>U2,RetryManager:()=>j2,WebrequestClient:()=>ig,createConditionalHeaders:()=>_ee,defaultCacheMaxEntries:()=>i4,extractCacheMetadata:()=>wd,headersToObject:()=>Cee,isFresh:()=>See,isWebrequestTimeoutError:()=>n4,objectToHeaders:()=>Gnt,requiresRevalidation:()=>q2,webrequest:()=>_i});var Whe=h(()=>{alt();Uhe();Fhe();o4();Vhe();vhe();jhe();l4();Rhe()});var Pu,og=h(()=>{l2();Pu=rl(sQ(),1);H_();bnt();wh();vnt();Po();Whe()});var dl,W2=h(()=>{dl=class extends Error{static{i(this,"TypedResponseError")}constructor(e,t){super(e),this.name="TypedResponseError",this.errorText=e,this.errorData=t??{}}}});var $ee,slt=h(()=>{W2();og();$ee=class{static{i(this,"TypedTools")}constructor(){this.localData={}}async passGuards(e,t){let a=new J_.GuardSet(e);if(!await a.allGuardsPass(t)){let o=await a.getFailedHint(t);throw new dl(`guard failed: ${o}`,{failedHint:o})}}}});var Ghe,Khe=h(()=>{og();W2();slt();Ghe=class r{static{i(this,"TypedHandler")}static{this.internalErrorMessage="Internal server error"}constructor(e,t){this.method=e,this.handlerFunction=t}async addResponse(e){if(e.method!==this.method)throw new Error("this handler has been given a wrong method to answer to. Please use a TypedRouter to filter requests");let t,a=new $ee;e.localData&&(a.localData=e.localData);let s=await this.handlerFunction(e.request,a).catch(o=>{o instanceof dl?t=o:(console.error(`TypedRequest handler '${this.method}' failed`),t=new dl(r.internalErrorMessage))});return t&&(e.error={text:t.errorText,data:t.errorData}),s&&(e.response=s),e?.correlation?.phase&&(e.correlation.phase="response"),e}}});var G2,Yhe=h(()=>{G2=Object.freeze({redacted:!0})});var ilt,olt,nlt,Eee,aFt,Pee,Aee,K2,clt,dlt,ult,plt,hlt,Dee,Zhe,sFt,llt,Y2,iFt,oFt,nFt,lFt,cFt,Z2,Qhe=h(()=>{Yhe();ilt=Object.freeze(["onOutgoingRequest","onIncomingResponse","onIncomingRequest","onOutgoingResponse"]),olt=Symbol.for("@api.global/typedrequest:global-hooks:3.8"),nlt=i(r=>({payloadProjector:r?.payloadProjector,errorProjector:r?.errorProjector}),"copyProjectionOptions"),Eee=i((r={})=>({hooks:r,projectedRegistrationsByPhase:{}}),"createTypedRouterHookRegistrationState"),aFt=i(r=>ilt.filter(e=>Object.hasOwn(r,e)).map(e=>[e,r[e]]),"getSuppliedHookEntries"),Pee=i((r,e,t)=>{let a=aFt(e);r.hooks={...r.hooks,...e};for(let[s]of a){let o=r.hooks[s];if(typeof o!="function"){delete r.projectedRegistrationsByPhase[s];continue}r.projectedRegistrationsByPhase[s]={callback:o,projectionOptions:nlt(t)}}},"mergeTypedRouterHookRegistrations"),Aee=i((r,e)=>{r.hooks=e;for(let t of ilt)delete r.projectedRegistrationsByPhase[t]},"replaceTypedRouterHookRegistrations"),K2=i(()=>{let r=globalThis[olt];if(r?.version==="3.8"&&r.stateShape==="callback-bound-projections-v1"&&r.subscribers instanceof Map)return r;let e={version:"3.8",stateShape:"callback-bound-projections-v1",legacy:Eee(),subscribers:new Map};return globalThis[olt]=e,e},"getRealmGlobalHookState"),clt=i(()=>K2().legacy.hooks,"getLegacyGlobalHooks"),dlt=i(r=>{Aee(K2().legacy,r)},"replaceLegacyGlobalHooks"),ult=i((r,e)=>{Pee(K2().legacy,r,e)},"mergeLegacyGlobalHooks"),plt=i((r,e)=>{let t=K2(),a=Symbol("typedrequest-hook-subscriber"),s=Eee();Pee(s,r,e),t.subscribers.set(a,s);let o=!1;return()=>{o||(o=!0,t.subscribers.delete(a))}},"addGlobalHookSubscriber"),hlt=i(()=>{let r=K2();Aee(r.legacy,{}),r.subscribers.clear()},"clearGlobalHookRegistrations"),Dee=i(r=>{try{console.error(`TypedRequest hook projection failed (${r})`)}catch{}},"logProjectionFailure"),Zhe=i(r=>{try{console.error(`TypedRequest hook callback failed (${r})`)}catch{}},"logCallbackFailure"),sFt=i((r,e)=>{let t={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0};try{return Object.freeze(t)}catch{Dee(e);return}},"createMetadata"),llt=i(r=>typeof SharedArrayBuffer>"u"?!1:r instanceof SharedArrayBuffer||Object.prototype.toString.call(r)==="[object SharedArrayBuffer]","isSharedArrayBuffer"),Y2=i((r,e=new Set)=>{if(!(r===null||typeof r!="object"&&typeof r!="function")){if(llt(r))throw new TypeError("TypedRequest hook projections cannot contain SharedArrayBuffer");if(ArrayBuffer.isView(r)){if(llt(r.buffer))throw new TypeError("TypedRequest hook projections cannot contain SharedArrayBuffer-backed views");return}if(!e.has(r)){if(e.add(r),r instanceof Map){for(let[t,a]of r)Y2(t,e),Y2(a,e);return}if(r instanceof Set){for(let t of r)Y2(t,e);return}for(let t of Reflect.ownKeys(r)){let a=Reflect.getOwnPropertyDescriptor(r,t);if(a){if(!Object.hasOwn(a,"value"))throw new TypeError("TypedRequest hook projections cannot contain accessor properties");Y2(a.value,e)}}}}},"assertNoSharedArrayBuffer"),iFt=i((r,e,t,a)=>{if(!e||!t.payloadProjector)return{payload:G2,payloadRedacted:!0};try{let s=t.payloadProjector(r,e);Y2(s);let o=structuredClone(s);return Y2(o),o!==null&&(typeof o=="object"||typeof o=="function")&&Object.freeze(o),{payload:o,payloadRedacted:!1}}catch{return Dee(a),{payload:G2,payloadRedacted:!0}}},"snapshotPayload"),oFt=i((r,e,t,a)=>{if(!(!e||r.errorText===void 0||!t.errorProjector))try{let s=t.errorProjector(r.errorText,e);if(s===void 0)return;let o=structuredClone(s);if(typeof o!="string")throw new TypeError("TypedRequest error projector must return a string or undefined");return o}catch{Dee(a);return}},"snapshotError"),nFt=i((r,e,t)=>{let a=sFt(r,t),s=iFt(r.payload,a,e,t),o=oFt(r,a,e,t),n={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0,...s,...o===void 0?{}:{error:o}};try{return Object.freeze(n)}catch{Dee(t);let l={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0,payload:G2,payloadRedacted:!0};try{return Object.freeze(l)}catch{return l}}},"projectLogEntry"),lFt=i((r,e)=>{try{let t=r.hooks[e];if(typeof t!="function")return;let a=r.projectedRegistrationsByPhase[e];return{callback:t,projectionOptions:a?.callback===t?nlt(a.projectionOptions):{}}}catch{Zhe(e);return}},"snapshotDispatchRecipient"),cFt=i((r,e,t)=>{let a=nFt(t,r.projectionOptions,e);try{let s=r.callback(a);s&&typeof s.then=="function"&&Promise.resolve(s).catch(()=>{Zhe(e)})}catch{Zhe(e)}},"dispatchToRecipient"),Z2=i((r,e,t)=>{let a=K2(),o=[a.legacy,...Array.from(a.subscribers.values()),...t?[t]:[]].map(n=>lFt(n,r)).filter(n=>!!n);for(let n of o)cFt(n,r,e)},"dispatchTypedRequestHook")});var d4,Ree=h(()=>{og();zee();Khe();Xhe();W2();Qhe();Yhe();d4=class r{static{i(this,"TypedRouter")}constructor(){this.hookRegistrationState=Eee(),this.routerMap=new Fs.ObjectMap,this.fallbackRouterMap=new Fs.ObjectMap,this.fallbackParentRouters=new Set,this.handlerMap=new Fs.ObjectMap,this.registeredVirtualStreams=new Fs.ObjectMap,this.middlewares=[],this.fireEventInterestMap=new Fs.InterestMap(e=>e)}static{this.internalErrorMessage="Internal server error"}static get globalHooks(){return clt()}static set globalHooks(e){dlt(e)}static setGlobalHooks(e,t){ult(e,t)}static addGlobalHooks(e,t){return plt(e,t)}static clearGlobalHooks(){hlt()}get hooks(){return this.hookRegistrationState.hooks}set hooks(e){Aee(this.hookRegistrationState,e)}setHooks(e,t){Pee(this.hookRegistrationState,e,t)}callHook(e,t){Z2(e,t,this.hookRegistrationState)}setErrorFromCaughtError(e,t,a){if(t instanceof dl){e.error={text:t.errorText,data:t.errorData??{}};return}console.error(`TypedRequest ${a} failed`),e.error={text:r.internalErrorMessage,data:{}}}getRegisteredVirtualStreamById(e){return this.registeredVirtualStreams.findSync(t=>t.streamId===e)}registerVirtualStream(e){let t=this.getRegisteredVirtualStreamById(e.streamId);return t||(this.registeredVirtualStreams.add(e),e)}unregisterVirtualStream(e){this.registeredVirtualStreams.remove(e)}addMiddleware(e){this.middlewares.push(e)}addTypedHandler(e){if(this.getTypedHandlerForMethod(e.method))throw new Error(`a TypedHandler for ${e.method} alredy exists! Can't add another one.`);this.handlerMap.add(e);try{this.validateAffectedCompositionRoots()}catch(a){throw this.handlerMap.remove(e),a}}addTypedRouter(e){if(e===this)throw new Error("A TypedRouter cannot be composed with itself.");if(!this.routerMap.findSync(a=>a===e)){let a=this.canReachRouter(e),s=e.canReachRouter(this);if(a!==s)throw new Error("Cannot add a bidirectional TypedRouter edge across an existing composition boundary.");this.routerMap.add(e),e.routerMap.add(this);try{this.validateAffectedCompositionRoots()}catch(o){throw this.routerMap.remove(e),e.routerMap.remove(this),o}}}addFallbackRouter(e){if(e===this)throw new Error("A TypedRouter cannot use itself as a fallback.");if(this.fallbackRouterMap.findSync(a=>a===e))return()=>{};if(e.canReachRouter(this))throw new Error("Adding this fallback would create a TypedRouter composition cycle.");this.fallbackRouterMap.add(e),e.fallbackParentRouters.add(this);try{this.validateAffectedCompositionRoots()}catch(a){throw this.fallbackRouterMap.remove(e),e.fallbackParentRouters.delete(this),a}let t=!1;return()=>{t||(t=!0,this.fallbackRouterMap.remove(e),e.fallbackParentRouters.delete(this))}}getMethodNames(){return[...this.collectReachableHandlers().keys()].sort()}canReachRouter(e,t=new Set){if(this===e)return!0;if(t.has(this))return!1;t.add(this);for(let a of[...this.routerMap.getArray(),...this.fallbackRouterMap.getArray()])if(a.canReachRouter(e,t))return!0;return!1}collectReachableHandlers(e=new Set,t=new Map){if(e.has(this))return t;e.add(this);for(let a of this.handlerMap.getArray()){let s=t.get(a.method);s||(s=new Set,t.set(a.method,s)),s.add(this)}for(let a of[...this.routerMap.getArray(),...this.fallbackRouterMap.getArray()])a.collectReachableHandlers(e,t);return t}getAffectedCompositionRoots(){let e=new Set,t=[this];for(;t.length>0;){let a=t.pop();e.has(a)||(e.add(a),t.push(...a.routerMap.getArray(),...a.fallbackParentRouters))}return e}validateAffectedCompositionRoots(){for(let e of this.getAffectedCompositionRoots())for(let[t,a]of e.collectReachableHandlers())if(a.size>1)throw new Error(`TypedRouter composition exposes more than one handler for method "${t}".`)}checkForTypedHandler(e){return!!this.getTypedHandlerForMethod(e)}getTypedHandlerForMethod(e,t=[]){t.push(this);let a;return a=this.handlerMap.findSync(s=>s.method===e),a||this.routerMap.getArray().forEach(s=>{!a&&!t.includes(s)&&(a=s.getTypedHandlerForMethod(e,t))}),a||this.fallbackRouterMap.getArray().forEach(s=>{!a&&!t.includes(s)&&(a=s.getTypedHandlerForMethod(e,t))}),a}getTypedHandlerAndRouter(e,t=[]){t.push(this);let a=this.handlerMap.findSync(s=>s.method===e);if(a)return{handler:a,router:this};for(let s of this.routerMap.getArray())if(!t.includes(s)){let o=s.getTypedHandlerAndRouter(e,t);if(o)return o}for(let s of this.fallbackRouterMap.getArray())if(!t.includes(s)){let o=s.getTypedHandlerAndRouter(e,t);if(o)return o}return null}static{this.defaultRouteOptions={localRequest:!1,skipHooks:!1}}async routeAndAddResponse(e,t={}){let a={...r.defaultRouteOptions,...t};if(e=Rn.decodePayloadFromNetwork(e,{typedrouter:this}),e.localData=a.trustedLocalData?{...a.trustedLocalData}:e.localData||{},e.localData.firstTypedrouter=this,e.method==="##VirtualStream##"){let s=await this.handleStreamTypedRequest(e);return s.localData=null,s}if(e?.correlation?.phase==="request"||a.localRequest){let s=Date.now();a.skipHooks||this.callHook("onIncomingRequest",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"incoming",phase:"request",timestamp:s,payload:e.request});let o=this.getTypedHandlerAndRouter(e.method);if(!o)return console.log(`Cannot find handler for methodname ${e.method}`),e.error={text:"There is no available method for this call on the server side",data:{}},e.correlation.phase="response",e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e;let{handler:n,router:l}=o;if(l.middlewares.length>0)try{for(let c of l.middlewares)await c(e)}catch(c){return this.setErrorFromCaughtError(e,c,`middleware for method '${e.method}'`),e.correlation.phase="response",e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e}return e=await n.addResponse(e),e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e}else return e?.correlation?.phase==="response"?(a.skipHooks||this.callHook("onIncomingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"incoming",phase:"response",timestamp:Date.now(),payload:e.response,errorText:e.error?.text}),this.fireEventInterestMap.findInterest(e.correlation.id)?.fullfillInterest(e),null):(console.log("TypedRouter received a malformed request DTO"),null)}async handleStreamTypedRequest(e){let t=this.getRegisteredVirtualStreamById(e.request.streamId);return t?t.handleStreamTr(e):(e.response={streamId:e.request.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:"end",keepAlive:!1,next:!1,backpressure:!1},e)}}});var Q2,jh,u4,Rn,zee=h(()=>{og();Ree();Q2="#############CLOSING BIT#############",jh=class extends Error{static{i(this,"VirtualStreamClosedError")}constructor(e="VirtualStream is closed",t){super(e,t),this.name="VirtualStreamClosedError"}},u4=class{static{i(this,"VirtualStreamActivationScope")}constructor(){this.trackedStreams=new Set,this.settled=!1}track(e){this.settled||this.trackedStreams.add(e)}commit(){let e=[...this.trackedStreams];this.settled=!0,this.trackedStreams.clear();for(let t of e)t.commitActivation()}async rollback(e){if(this.settled)return;this.settled=!0;let t=[...this.trackedStreams];this.trackedStreams.clear(),await Promise.all(t.map(a=>a.abort(e)))}},Rn=class r{static{i(this,"VirtualStream")}constructor(){this.streamId=Pu.uni(),this.lifecycleStateInternal="idle",this.keepAlive=!0,this.sendAdmissionTail=Promise.resolve(),this.frameAdmissionTail=Promise.resolve(),this.closeStarted=!1,this.activationCommitted=!1,this.activationResolvers=new Set,this.respondingDrainResolvers=new Set,this.sendBackpressuredArray=new Fs.BackpressuredArray(16),this.receiveBackpressuredArray=new Fs.BackpressuredArray(16)}static{this.respondingRegistrationIdleTimeoutMs=15e3}static{this.gracefulCloseTimeoutMs=1e4}static encodePayloadForNetwork(e,t,a,s=[]){return!e||rg.isBufferLike(e)?e:e instanceof r?(e.activate(t),!a?.response||s.includes("response")?{_isVirtualStream:!0,streamId:e.streamId}:{_OBMITTED_VIRTUAL_STREAM:!0,reason:"path is under .request: omitted for deduplication reasons in response cycle."}):Array.isArray(e)?e.map((o,n)=>r.encodePayloadForNetwork(o,t,a||e,s.concat(String(n)))):e!==null&&typeof e=="object"?e instanceof Set||e instanceof Map||e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof Promise||typeof e.then=="function"?e:Object.entries(e).reduce((o,[n,l])=>(o[n]=r.encodePayloadForNetwork(l,t,a||e,s.concat(n)),o),{}):e}static decodePayloadFromNetwork(e,t){return r.decodePayloadFromNetworkInternal(e,t,new Map)}static containsNetworkDescriptor(e){return!e||rg.isBufferLike(e)||typeof e!="object"?!1:e._isVirtualStream===!0?!0:Array.isArray(e)?e.some(t=>r.containsNetworkDescriptor(t)):Object.values(e).some(t=>r.containsNetworkDescriptor(t))}static decodePayloadFromNetworkInternal(e,t,a){if(rg.isBufferLike(e)||e instanceof d4||e===null||typeof e!="object"||e instanceof Set||e instanceof Map||e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof Promise||typeof e.then=="function")return e;if(e._isVirtualStream===!0){if(typeof e.streamId!="string"||e.streamId.length===0)throw new TypeError("VirtualStream network descriptor requires a non-empty streamId");let s=a.get(e.streamId);if(s)return s;let o=t.typedrouter?.getRegisteredVirtualStreamById(e.streamId);if(o)return o.refreshRespondingRegistration(),a.set(e.streamId,o),o;let n=new r;return n.streamId=e.streamId,n.activate(t),a.set(e.streamId,n),n}return Array.isArray(e)?e.map(s=>r.decodePayloadFromNetworkInternal(s,t,a)):Object.keys(e).reduce((s,o)=>(s[o]=r.decodePayloadFromNetworkInternal(e[o],t,a),s),{})}get lifecycleState(){return this.lifecycleStateInternal}activate(e){if(this.lifecycleStateInternal==="closed")throw this.getCloseError();let t=e.sendMethod?"requesting":e.typedrouter?"responding":void 0;if(!t)throw new Error("VirtualStream requires a send method or TypedRouter");if(this.lifecycleStateInternal==="active"&&this.side!==t)throw new Error(`VirtualStream ${this.streamId} is already active on the ${this.side} side`);let a=this.lifecycleStateInternal==="idle";if(this.lifecycleStateInternal="active",this.keepAlive=!0,this.side=t,t==="requesting")this.sendMethod=e.sendMethod;else{if(this.typedrouter=e.typedrouter,this.typedrouter.registerVirtualStream(this)!==this)throw this.lifecycleStateInternal="idle",this.typedrouter=void 0,new Error(`VirtualStream ${this.streamId} is already registered on this router`);this.refreshRespondingRegistration()}a&&(e.activationScope?e.activationScope.track(this):this.commitActivation())}commitActivation(){if(this.lifecycleStateInternal==="active"&&this.side==="requesting"){this.activationCommitted=!0;let e=[...this.activationResolvers];this.activationResolvers.clear();for(let t of e)t();this.startKeepAliveLoop(),this.ensureQueueWork()}}getCloseError(e){return this.closeError||(this.closeError=new jh("VirtualStream is closed",e===void 0?void 0:{cause:e})),this.closeError}assertNotClosed(){if(this.lifecycleStateInternal==="closed")throw this.getCloseError()}assertCanSend(){if(this.assertNotClosed(),this.closeStarted)throw new jh("VirtualStream is closing")}async acquireSendAdmission(){let e=this.sendAdmissionTail,t;return this.sendAdmissionTail=new Promise(a=>{t=a}),await e,t}async acquireFrameAdmission(){let e=this.frameAdmissionTail,t;return this.frameAdmissionTail=new Promise(a=>{t=a}),await e,t}async waitForOutboundDrain(){for(;this.sendBackpressuredArray.data.length>0||this.queueWorkPromise;){this.assertNotClosed(),this.ensureQueueWork();let e=this.queueWorkPromise;e?await e:this.activationCommitted||await new Promise(t=>{this.activationResolvers.add(t)})}this.assertNotClosed()}async waitWithinGracefulCloseDeadline(e){let t,a=new Promise((s,o)=>{t=setTimeout(()=>{o(new jh("VirtualStream graceful close timed out"))},r.gracefulCloseTimeoutMs),t.unref?.()});try{await Promise.race([e,a])}finally{t&&clearTimeout(t)}}async waitForRespondingDrain(){this.sendBackpressuredArray.data.length!==0&&await new Promise(e=>{this.respondingDrainResolvers.add(e)})}resolveRespondingDrain(){if(this.sendBackpressuredArray.data.length>0)return;let e=[...this.respondingDrainResolvers];this.respondingDrainResolvers.clear();for(let t of e)t()}static reconstituteBinaryData(e){if(e==null||e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return e;if(typeof e=="object"){if(e.type==="EncodedBuffer"&&typeof e.data=="string"&&e.data.startsWith("base64:")){let a=e.data.slice(7);if(typeof Buffer<"u"){let s=Buffer.from(a,"base64");return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}return new Uint8Array(Array.from(atob(a)).map(s=>s.charCodeAt(0)))}if(e.type==="Buffer"&&Array.isArray(e.data))return new Uint8Array(e.data);let t=Object.keys(e);if(t.length>0&&t.every(a=>/^\d+$/.test(a))){let a=new Array(t.length);for(let s of t)a[Number(s)]=e[s];if(a.every(s=>typeof s=="number"))return new Uint8Array(a)}}return e}ensureQueueWork(){this.lifecycleStateInternal==="closed"||this.side!=="requesting"||!this.activationCommitted||this.queueWorkPromise||(this.queueWorkPromise=this.workOnQueue().catch(async e=>{await this.abort(e)}).finally(()=>{this.queueWorkPromise=void 0,this.lifecycleStateInternal==="active"&&this.side==="requesting"&&this.sendBackpressuredArray.data.length>0&&this.ensureQueueWork()}))}async workOnQueue(){this.assertNotClosed();let e=!this.receiveBackpressuredArray.checkSpaceAvailable(),t=!1,a=!1,s=i(async()=>{let o=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"feedback",next:this.sendBackpressuredArray.data.length>0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable()});this.acceptRemoteResponse(o)&&(a=!!o.response?.backpressure,t=!!o.response?.next)},"getFeedback");for(await s();this.sendBackpressuredArray.data.length>0||t;){for(this.assertNotClosed(),t&&this.sendBackpressuredArray.data.length===0&&!this.receiveBackpressuredArray.checkSpaceAvailable()&&(await this.receiveBackpressuredArray.waitForSpace(),this.assertNotClosed(),e=!this.receiveBackpressuredArray.checkSpaceAvailable());a;)await sr.delayFor(50),this.assertNotClosed(),await s();let o=this.sendBackpressuredArray.data.length>0?this.sendBackpressuredArray.shift():void 0,n=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:o===void 0?"read":"chunk",backpressure:e,next:this.sendBackpressuredArray.data.length>0,...o===void 0?{}:{chunkData:o}});if(!this.acceptRemoteResponse(n))return;a=!!n.response?.backpressure,e=!this.receiveBackpressuredArray.checkSpaceAvailable(),t=!!n.response?.next}}async sendStreamRequest(e){let t=await this.acquireFrameAdmission();try{if(this.assertNotClosed(),!this.sendMethod)throw new Error("VirtualStream is missing a send method");return await this.sendMethod({method:"##VirtualStream##",request:e,response:null})}finally{t()}}acceptRemoteResponse(e){if(this.lifecycleStateInternal==="closed")return!1;let t=e.response?.chunkData;return t!==void 0&&this.receiveBackpressuredArray.push(r.reconstituteBinaryData(t)),e.response?.keepAlive===!1||e.response?.mainPurpose==="end"?(this.terminate(new jh("Remote VirtualStream is closed"),t===Q2),!1):!0}async handleStreamTr(e){if(this.lifecycleStateInternal==="closed")return e.response=this.createClosedResponse(e),e;if(this.refreshRespondingRegistration(),e.request.keepAlive===!1||e.request.mainPurpose==="end")return e.response=this.createClosedResponse(e),await this.abort(),e;let t=e.request.chunkData===Q2;e.request.chunkData!==void 0&&this.receiveBackpressuredArray.push(r.reconstituteBinaryData(e.request.chunkData));let a=!!e.request.backpressure,s=!t&&!a&&this.sendBackpressuredArray.data.length>0?this.sendBackpressuredArray.shift():void 0;this.resolveRespondingDrain();let o=s===Q2;return e.response={streamId:this.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:o?"end":s!==void 0?"chunk":e.request.mainPurpose==="keepAlive"?"keepAlive":"feedback",keepAlive:!o,next:this.sendBackpressuredArray.data.length>0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable(),...s===void 0?{}:{chunkData:s}},(t||o)&&(e.response.mainPurpose="end",e.response.keepAlive=!1,this.terminate(void 0,t)),e}createClosedResponse(e){return{streamId:e.request.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:"end",keepAlive:!1,next:!1,backpressure:!1}}refreshRespondingRegistration(){this.side!=="responding"||this.lifecycleStateInternal!=="active"||(this.respondingExpiryTimer&&clearTimeout(this.respondingExpiryTimer),this.respondingExpiryTimer=setTimeout(()=>{this.abort(new jh("Responding VirtualStream registration expired"))},r.respondingRegistrationIdleTimeoutMs),this.respondingExpiryTimer.unref?.())}async cleanup(){await this.abort()}cleanupRegistration(){if(this.respondingExpiryTimer&&(clearTimeout(this.respondingExpiryTimer),this.respondingExpiryTimer=void 0),this.typedrouter){let e=this.typedrouter;this.typedrouter=void 0,e.unregisterVirtualStream(this)}}startKeepAliveLoop(){this.side!=="requesting"||this.lifecycleStateInternal==="closed"||this.keepAliveLoopPromise||(this.keepAliveLoopPromise=this.runKeepAliveLoop().catch(async e=>{await this.abort(e)}).finally(()=>{this.keepAliveLoopPromise=void 0}))}async runKeepAliveLoop(){for(await sr.delayFor(0);this.keepAlive&&this.lifecycleStateInternal==="active";)await this.triggerKeepAlive(),this.keepAlive&&this.lifecycleStateInternal==="active"&&await sr.delayFor(1e3)}async triggerKeepAlive(){let e=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"keepAlive",keepAlive:!0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable()});this.acceptRemoteResponse(e)&&e.response?.next&&this.ensureQueueWork()}async sendData(e){let t=await this.acquireSendAdmission();try{this.assertCanSend(),await this.sendBackpressuredArray.waitForSpace(),this.assertCanSend(),this.sendBackpressuredArray.push(e),this.ensureQueueWork(),await this.sendBackpressuredArray.waitForSpace(),this.assertCanSend()}finally{t()}}async fetchData(){if(this.receiveBackpressuredArray.checkHasItems())return this.receiveBackpressuredArray.shift();if(this.assertNotClosed(),await this.receiveBackpressuredArray.waitForItems(),!this.receiveBackpressuredArray.checkHasItems())throw this.getCloseError();return this.receiveBackpressuredArray.shift()}async readFromWebstream(e,t=!0){let a=e.getReader();try{let s=!1;for(;!s;){let{value:o,done:n}=await a.read();o!==void 0&&await this.sendData(o),s=n}t&&await this.close(!0)}finally{a.releaseLock()}}async writeToWebstream(e){let t=e.getWriter();try{for(;this.lifecycleStateInternal!=="closed"||this.receiveBackpressuredArray.checkHasItems();){let a=await this.fetchData();if(a===Q2)break;await t.write(a)}await t.close()}finally{t.releaseLock()}}async close(e=!1){if(this.lifecycleStateInternal!=="closed"){if(this.closeStarted=!0,e){if(this.side==="requesting"&&this.sendMethod)try{await this.waitWithinGracefulCloseDeadline(this.waitForOutboundDrain()),await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"chunk",chunkData:Q2,next:!1,backpressure:!1})}catch{}else if(this.side==="responding"){this.sendBackpressuredArray.push(Q2);try{await this.waitWithinGracefulCloseDeadline(this.waitForRespondingDrain())}catch{}}}await this.abort()}}async abort(e){this.terminate(e)}terminate(e,t=!1){if(this.lifecycleStateInternal==="closed")return;this.getCloseError(e),this.lifecycleStateInternal="closed",this.keepAlive=!1,this.activationCommitted=!1,this.sendMethod=void 0,this.sendBackpressuredArray.data.length=0,t||(this.receiveBackpressuredArray.data.length=0),this.sendBackpressuredArray.destroy(),this.receiveBackpressuredArray.destroy();let a=[...this.activationResolvers];this.activationResolvers.clear();for(let o of a)o();let s=[...this.respondingDrainResolvers];this.respondingDrainResolvers.clear();for(let o of s)o();this.cleanupRegistration()}}});var Jhe,efe=h(()=>{Ree();og();Jhe=class{static{i(this,"TypedTarget")}constructor(e){if(this.isAsync=!1,e.postMethodWithTypedRouter&&!e.typedRouterRef)throw new Error("you have to specify a typedrouter when using postmethod with typedrouter");let t=e.responseTimeoutMs??3e4;if(!Number.isSafeInteger(t)||t<=0||t>2147483647)throw new RangeError("TypedTarget responseTimeoutMs must be a positive safe integer no greater than 2147483647");this.options=e,this.responseTimeoutMs=t}async post(e,t={}){if(t.signal&&this.options.supportsAbortSignal!==!0)throw new Error("TypedTarget does not declare AbortSignal transport support");let a=this.options.postMethod||this.options.postMethodWithTypedRouter;if(!a)throw new Error("TypedTarget requires a post method");let s;this.options.typedRouterRef&&(s=await this.options.typedRouterRef.fireEventInterestMap.addInterest(e.correlation.id,e));let o=t.signal;if(o?.aborted)throw s?.destroy(),o.reason??new DOMException("The operation was aborted","AbortError");let n,l=o?new Promise((u,p)=>{n=i(()=>{s?.destroy(),p(o.reason??new DOMException("The operation was aborted","AbortError"))},"abortListener"),o.addEventListener("abort",n,{once:!0})}):void 0,c,d=s?new Promise((u,p)=>{c=setTimeout(()=>{p(new Error(`TypedTarget response timed out after ${this.responseTimeoutMs}ms`))},this.responseTimeoutMs),c.unref?.()}):void 0;try{let u=Promise.resolve(a(e,t)),p=await Promise.race([u,...d?[d]:[],...l?[l]:[]]);return s?await Promise.race([s.interestFullfilled,d,...l?[l]:[]]):p||e}finally{c&&clearTimeout(c),o&&n&&o.removeEventListener("abort",n),s?.destroy()}}}});var flt,Lee,mlt,Oee,Bee,p4,Xhe=h(()=>{og();zee();W2();Qhe();efe();flt=new Vh.WebrequestClient,Lee=2147483647,mlt=1e4,Oee=class extends Error{static{i(this,"TypedRequestTimeoutError")}constructor(e,t){super(`Typed request "${e}" timed out after ${t}ms`),this.name="TypedRequestTimeoutError",this.method=e,this.timeoutMs=t}},Bee=class extends Error{static{i(this,"TypedRequestRetryLimitError")}constructor(e,t){super(`Typed request "${e}" exceeded its ${t} server-directed retries`),this.name="TypedRequestRetryLimitError",this.method=e,this.maxRetries=t}},p4=class{static{i(this,"TypedRequest")}constructor(e,t){this.skipHooks=!1,typeof e=="string"?this.urlEndPoint=e:this.typedTarget=e,this.method=t}async fire(e,t=!1){let a=Date.now(),s=this.resolveFireOptions(t),o=new u4,n={method:this.method,request:e,response:null,correlation:{id:Pu.uni(),phase:"request"}};try{n=Rn.encodePayloadForNetwork(n,{sendMethod:i(p=>this.postStreamTrObject(p),"sendMethod"),activationScope:o});let l=Rn.containsNetworkDescriptor(n);if(l&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("VirtualStreams require TypedTarget AbortSignal transport support");if(s.useCache&&l)throw new Error("TypedRequest response caching is not supported for requests containing VirtualStreams");this.assertDeadline(s),s.useCache&&(s.cacheKey=await this.createCacheKey(n),this.assertDeadline(s)),this.skipHooks||Z2("onOutgoingRequest",{correlationId:n.correlation.id,method:this.method,direction:"outgoing",phase:"request",timestamp:a,payload:e});let c=await this.postTrObject(n,s),d=c.error;if(this.assertDeadline(s),d)throw this.skipHooks||Z2("onIncomingResponse",{correlationId:n.correlation.id,method:this.method,direction:"incoming",phase:"response",timestamp:Date.now(),durationMs:Date.now()-a,payload:c.response,errorText:d.text}),this.assertDeadline(s),new dl(d.text,d.data);let u=Rn.containsNetworkDescriptor(c);if(u&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("VirtualStreams require TypedTarget AbortSignal transport support");return s.useCache&&s.cacheKey&&u&&(await flt.deleteCache(s.cacheKey),this.assertDeadline(s)),c=Rn.decodePayloadFromNetwork(c,{sendMethod:i(p=>this.postStreamTrObject(p),"sendMethod"),activationScope:o}),this.assertDeadline(s),this.skipHooks||Z2("onIncomingResponse",{correlationId:n.correlation.id,method:this.method,direction:"incoming",phase:"response",timestamp:Date.now(),durationMs:Date.now()-a,payload:c?.response}),this.assertDeadline(s),o.commit(),c.response}catch(l){throw await o.rollback(l),l}}async postTrObject(e,t={useCache:!1,maxRetries:3}){let a=0;for(;;){this.assertDeadline(t);let s;if(this.urlEndPoint)try{s=await flt.postJson(this.urlEndPoint,e,{cacheKey:t.cacheKey,cacheStrategy:t.useCache?"cache-first":"network-only",timeout:this.getRemainingTimeout(t)})}catch(o){throw t.timeoutMs!==void 0&&(this.hasDeadlineExpired(t)||Vh.isWebrequestTimeoutError(o))?this.createTimeoutError(t):o}else s=await this.postTypedTarget(e,t);if(this.assertDeadline(t),s.error&&!s.retry||!s.retry)return s;if(console.log(`Server requested a retry for TypedRequest method '${this.method}'`),a>=t.maxRetries)throw new Bee(this.method,t.maxRetries);a+=1,await this.waitForRetry(s.retry.waitForMs,t)}}async postStreamTrObject(e){let t={useCache:!1,maxRetries:3,timeoutMs:mlt,deadlineAt:performance.now()+mlt};return this.postTrObject(e,t)}async postTypedTarget(e,t){let a=this.getRemainingTimeout(t);if(a===void 0)return this.typedTarget.post(e);let s=new AbortController,o=setTimeout(()=>{s.abort(this.createTimeoutError(t))},a);o.unref?.();try{return await this.typedTarget.post(e,{signal:s.signal})}catch(n){throw s.signal.aborted?this.createTimeoutError(t):n}finally{clearTimeout(o)}}resolveFireOptions(e){let t=typeof e=="boolean"?{useCache:e}:e;if(!t||typeof t!="object")throw new TypeError("TypedRequest fire options must be a boolean or an options object");if(t.useCache!==void 0&&typeof t.useCache!="boolean")throw new TypeError("TypedRequest useCache must be a boolean");if(t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0||t.timeoutMs>Lee))throw new RangeError(`TypedRequest timeoutMs must be a positive safe integer no greater than ${Lee}`);if(t.maxRetries!==void 0&&(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0||t.maxRetries>1e3))throw new RangeError("TypedRequest maxRetries must be a safe integer between 0 and 1000");if(t.timeoutMs!==void 0&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("TypedRequest timeoutMs requires an HTTP URL or a TypedTarget with AbortSignal support");return{useCache:t.useCache??!1,timeoutMs:t.timeoutMs,maxRetries:t.maxRetries??3,deadlineAt:t.timeoutMs===void 0?void 0:performance.now()+t.timeoutMs}}getRemainingTimeout(e){if(e.deadlineAt===void 0||e.timeoutMs===void 0)return;let t=Math.ceil(e.deadlineAt-performance.now());if(t<=0)throw this.createTimeoutError(e);return t}assertDeadline(e){this.getRemainingTimeout(e)}hasDeadlineExpired(e){return e.deadlineAt!==void 0&&performance.now()>=e.deadlineAt}createTimeoutError(e){return new Oee(this.method,e.timeoutMs)}async waitForRetry(e,t){if(!Number.isSafeInteger(e)||e<=0||e>Lee)throw new RangeError(`TypedRequest retry waitForMs must be a positive safe integer no greater than ${Lee}`);let a=this.getRemainingTimeout(t);if(a===void 0){await sr.delayFor(e);return}if(e>=a)throw await sr.delayFor(a),this.createTimeoutError(t);await sr.delayFor(e),this.assertDeadline(t)}async createCacheKey(e){let t=JSON.stringify({endpoint:this.urlEndPoint,method:e.method,request:e.request}),a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return`typedrequest:v1:${Array.from(new Uint8Array(a),o=>o.toString(16).padStart(2,"0")).join("")}`}}});var ps={};St(ps,{TYPED_REQUEST_REDACTED_PAYLOAD:()=>G2,TypedHandler:()=>Ghe,TypedRequest:()=>p4,TypedRequestRetryLimitError:()=>Bee,TypedRequestTimeoutError:()=>Oee,TypedResponseError:()=>dl,TypedRouter:()=>d4,TypedTarget:()=>Jhe,VirtualStream:()=>Rn,VirtualStreamActivationScope:()=>u4,VirtualStreamClosedError:()=>jh});var h4=h(()=>{Xhe();Khe();Ree();W2();efe();zee()});function glt(r){return r&&typeof r.then=="function"}function kd(r,e){return r||(r=0),new Promise(function(t){return setTimeout(function(){return t(e)},r)})}function ylt(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function Au(){return Math.random().toString(36).substring(2)}function Ru(){var r=Date.now()*1e3;return r<=tfe&&(r=tfe+1),tfe=r,r}function xlt(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}var blt,vlt,zn,tfe,Uh=h(()=>{i(glt,"isPromise");blt=Promise.resolve(!1),vlt=Promise.resolve(!0),zn=Promise.resolve();i(kd,"sleep");i(ylt,"randomInt");i(Au,"randomToken");tfe=0;i(Ru,"microSeconds");i(xlt,"supportsWebLockAPI")});function pFt(r){var e={time:Ru(),messagesCallback:null,bc:new BroadcastChannel(r),subFns:[]};return e.bc.onmessage=function(t){e.messagesCallback&&e.messagesCallback(t.data)},e}function hFt(r){r.bc.close(),r.subFns=[]}function fFt(r,e){try{return r.bc.postMessage(e,!1),zn}catch(t){return Promise.reject(t)}}function mFt(r,e){r.messagesCallback=e}function gFt(){if(typeof globalThis<"u"&&globalThis.Deno&&globalThis.Deno.args)return!0;if((typeof window<"u"||typeof self<"u")&&typeof BroadcastChannel=="function"){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}else return!1}function bFt(){return 150}var dFt,uFt,wlt,klt=h(()=>{Uh();dFt=Ru,uFt="native";i(pFt,"create");i(hFt,"close");i(fFt,"postMessage");i(mFt,"onMessage");i(gFt,"canBeUsed");i(bFt,"averageResponseTime");wlt={create:pFt,close:hFt,onMessage:mFt,postMessage:fFt,canBeUsed:gFt,type:uFt,averageResponseTime:bFt,microSeconds:dFt}});function vFt(r){let e=rfe()-r.ttl,t=r.map[Symbol.iterator]();for(;;){let a=t.next().value;if(!a)break;let s=a[0];if(a[1]<e)r.map.delete(s);else break}}function rfe(){return Date.now()}var X2,afe=h(()=>{X2=class{static{i(this,"ObliviousSet")}ttl;map=new Map;_to=!1;constructor(e){this.ttl=e}has(e){let t=this.map.get(e);return typeof t>"u"?!1:t<rfe()-this.ttl?(this.map.delete(e),!1):!0}add(e){this.map.delete(e),this.map.set(e,rfe()),this._to||(this._to=!0,setTimeout(()=>{this._to=!1,vFt(this)},0))}clear(){this.map.clear()}};i(vFt,"removeTooOldValues");i(rfe,"now")});function ng(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=JSON.parse(JSON.stringify(r));return typeof e.webWorkerSupport>"u"&&(e.webWorkerSupport=!0),e.idb||(e.idb={}),e.idb.ttl||(e.idb.ttl=1e3*45),e.idb.fallbackInterval||(e.idb.fallbackInterval=150),r.idb&&typeof r.idb.onclose=="function"&&(e.idb.onclose=r.idb.onclose),e.localstorage||(e.localstorage={}),e.localstorage.removeTimeout||(e.localstorage.removeTimeout=1e3*60),r.methods&&(e.methods=r.methods),e.node||(e.node={}),e.node.ttl||(e.node.ttl=1e3*60*2),e.node.maxParallelWrites||(e.node.maxParallelWrites=2048),typeof e.node.useFastPath>"u"&&(e.node.useFastPath=!0),e}var Nee=h(()=>{i(ng,"fillOptionsWithDefaults")});function Slt(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"){if(typeof window.mozIndexedDB<"u")return window.mozIndexedDB;if(typeof window.webkitIndexedDB<"u")return window.webkitIndexedDB;if(typeof window.msIndexedDB<"u")return window.msIndexedDB}return!1}function Fee(r){r.commit&&r.commit()}function kFt(r){var e=Slt(),t=xFt+r,a=e.open(t);return a.onupgradeneeded=function(s){var o=s.target.result;o.createObjectStore(nc,{keyPath:"id",autoIncrement:!0})},new Promise(function(s,o){a.onerror=function(n){return o(n)},a.onsuccess=function(){s(a.result)}})}function SFt(r,e,t){var a=Date.now(),s={uuid:e,time:a,data:t},o=r.transaction([nc],"readwrite",f4);return new Promise(function(n,l){o.oncomplete=function(){return n()},o.onerror=function(d){return l(d)};var c=o.objectStore(nc);c.add(s),Fee(o)})}function oZr(r){var e=r.transaction(nc,"readonly",f4),t=e.objectStore(nc),a=[];return new Promise(function(s){t.openCursor().onsuccess=function(o){var n=o.target.result;n?(a.push(n.value),n.continue()):(Fee(e),s(a))}})}function _Ft(r,e){var t=r.transaction(nc,"readonly",f4),a=t.objectStore(nc),s=[],o=IDBKeyRange.bound(e+1,1/0);if(a.getAll){var n=a.getAll(o);return new Promise(function(c,d){n.onerror=function(u){return d(u)},n.onsuccess=function(u){c(u.target.result)}})}function l(){try{return o=IDBKeyRange.bound(e+1,1/0),a.openCursor(o)}catch{return a.openCursor()}}return i(l,"openCursor"),new Promise(function(c,d){var u=l();u.onerror=function(p){return d(p)},u.onsuccess=function(p){var m=p.target.result;m?m.value.id<e+1?m.continue(e+1):(s.push(m.value),m.continue()):(Fee(t),c(s))}})}function CFt(r,e){if(r.closed)return Promise.resolve([]);var t=r.db.transaction(nc,"readwrite",f4),a=t.objectStore(nc);return Promise.all(e.map(function(s){var o=a.delete(s);return new Promise(function(n){o.onsuccess=function(){return n()}})}))}function TFt(r,e){var t=Date.now()-e,a=r.transaction(nc,"readonly",f4),s=a.objectStore(nc),o=[];return new Promise(function(n){s.openCursor().onsuccess=function(l){var c=l.target.result;if(c){var d=c.value;d.time<t?(o.push(d),c.continue()):(Fee(a),n(o))}else n(o)}})}function MFt(r){return TFt(r.db,r.options.idb.ttl).then(function(e){return CFt(r,e.map(function(t){return t.id}))})}function IFt(r,e){return e=ng(e),kFt(r).then(function(t){var a={closed:!1,lastCursorId:0,channelName:r,options:e,uuid:Au(),eMIs:new X2(e.idb.ttl*2),writeBlockPromise:zn,messagesCallback:null,readQueuePromises:[],db:t};return t.onclose=function(){a.closed=!0,e.idb.onclose&&e.idb.onclose()},_lt(a),a})}function _lt(r){r.closed||Clt(r).then(function(){return kd(r.options.idb.fallbackInterval)}).then(function(){return _lt(r)})}function $Ft(r,e){return!(r.uuid===e.uuid||e.eMIs.has(r.id)||r.data.time<e.messagesCallbackTime)}function Clt(r){return r.closed?zn:r.messagesCallback?_Ft(r.db,r.lastCursorId).then(function(e){var t=e.filter(function(a){return!!a}).map(function(a){return a.id>r.lastCursorId&&(r.lastCursorId=a.id),a}).filter(function(a){return $Ft(a,r)}).sort(function(a,s){return a.time-s.time});return t.forEach(function(a){r.messagesCallback&&(r.eMIs.add(a.id),r.messagesCallback(a.data))}),zn}):zn}function DFt(r){r.closed=!0,r.db.close()}function EFt(r,e){return r.writeBlockPromise=r.writeBlockPromise.then(function(){return SFt(r.db,r.uuid,e)}).then(function(){ylt(0,10)===0&&MFt(r)}),r.writeBlockPromise}function PFt(r,e,t){r.messagesCallbackTime=t,r.messagesCallback=e,Clt(r)}function AFt(){return!!Slt()}function RFt(r){return r.idb.fallbackInterval*2}var yFt,xFt,nc,f4,wFt,Tlt,Mlt=h(()=>{Uh();afe();Nee();yFt=Ru,xFt="pubkey.broadcast-channel-0-",nc="messages",f4={durability:"relaxed"},wFt="idb";i(Slt,"getIdb");i(Fee,"commitIndexedDBTransaction");i(kFt,"createDatabase");i(SFt,"writeMessage");i(oZr,"getAllMessages");i(_Ft,"getMessagesHigherThan");i(CFt,"removeMessagesById");i(TFt,"getOldMessages");i(MFt,"cleanOldMessages");i(IFt,"create");i(_lt,"_readLoop");i($Ft,"_filterMessage");i(Clt,"readNewMessages");i(DFt,"close");i(EFt,"postMessage");i(PFt,"onMessage");i(AFt,"canBeUsed");i(RFt,"averageResponseTime");Tlt={create:IFt,close:DFt,onMessage:PFt,postMessage:EFt,canBeUsed:AFt,type:wFt,averageResponseTime:RFt,microSeconds:yFt}});function Ilt(){var r;if(typeof window>"u")return null;try{r=window.localStorage,r=window["ie8-eventlistener/storage"]||window.localStorage}catch{}return r}function $lt(r){return LFt+r}function BFt(r,e){return new Promise(function(t){kd().then(function(){var a=$lt(r.channelName),s={token:Au(),time:Date.now(),data:e,uuid:r.uuid},o=JSON.stringify(s);Ilt().setItem(a,o);var n=document.createEvent("Event");n.initEvent("storage",!0,!0),n.key=a,n.newValue=o,window.dispatchEvent(n),t()})})}function NFt(r,e){var t=$lt(r),a=i(function(o){o.key===t&&e(JSON.parse(o.newValue))},"listener");return window.addEventListener("storage",a),a}function FFt(r){window.removeEventListener("storage",r)}function qFt(r,e){if(e=ng(e),!Dlt())throw new Error("BroadcastChannel: localstorage cannot be used");var t=Au(),a=new X2(e.localstorage.removeTimeout),s={channelName:r,uuid:t,eMIs:a};return s.listener=NFt(r,function(o){s.messagesCallback&&o.uuid!==t&&(!o.token||a.has(o.token)||o.data.time&&o.data.time<s.messagesCallbackTime||(a.add(o.token),s.messagesCallback(o.data)))}),s}function HFt(r){FFt(r.listener)}function VFt(r,e,t){r.messagesCallbackTime=t,r.messagesCallback=e}function Dlt(){var r=Ilt();if(!r)return!1;try{var e="__broadcastchannel_check";r.setItem(e,"works"),r.removeItem(e)}catch{return!1}return!0}function jFt(){var r=120,e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")?r*2:r}var zFt,LFt,OFt,Elt,Plt=h(()=>{afe();Nee();Uh();zFt=Ru,LFt="pubkey.broadcastChannel-",OFt="localstorage";i(Ilt,"getLocalStorage");i($lt,"storageKey");i(BFt,"postMessage");i(NFt,"addStorageEventListener");i(FFt,"removeStorageEventListener");i(qFt,"create");i(HFt,"close");i(VFt,"onMessage");i(Dlt,"canBeUsed");i(jFt,"averageResponseTime");Elt={create:qFt,close:HFt,onMessage:VFt,postMessage:BFt,canBeUsed:Dlt,type:OFt,averageResponseTime:jFt,microSeconds:zFt}});function WFt(r){var e={time:Alt(),name:r,messagesCallback:null};return sfe.add(e),e}function GFt(r){sfe.delete(r)}function KFt(r,e){return new Promise(function(t){return setTimeout(function(){var a=Array.from(sfe);a.forEach(function(s){s.name===r.name&&s!==r&&s.messagesCallback&&s.time<e.time&&s.messagesCallback(e)}),t()},Rlt)})}function YFt(r,e){r.messagesCallback=e}function ZFt(){return!0}function QFt(){return Rlt}var Alt,UFt,sfe,Rlt,zlt,Llt=h(()=>{Uh();Alt=Ru,UFt="simulate",sfe=new Set;i(WFt,"create");i(GFt,"close");Rlt=5;i(KFt,"postMessage");i(YFt,"onMessage");i(ZFt,"canBeUsed");i(QFt,"averageResponseTime");zlt={create:WFt,close:GFt,onMessage:YFt,postMessage:KFt,canBeUsed:ZFt,type:UFt,averageResponseTime:QFt,microSeconds:Alt}});function ife(r){var e=[].concat(r.methods,Olt).filter(Boolean);if(r.type){if(r.type==="simulate")return zlt;var t=e.find(function(s){return s.type===r.type});if(t)return t;throw new Error("method-type "+r.type+" not found")}r.webWorkerSupport||(e=e.filter(function(s){return s.type!=="idb"}));var a=e.find(function(s){return s.canBeUsed()});if(a)return a;throw new Error("No usable method found in "+JSON.stringify(Olt.map(function(s){return s.type})))}var Olt,Blt=h(()=>{klt();Mlt();Plt();Llt();Olt=[wlt,Tlt,Elt];i(ife,"chooseMethod")});function JFt(r){r=ng(r);var e=ife(r);return e.type==="node"?e.clearNodeFolder().then(function(){return!0}):blt}function eqt(r){ofe=r}function Nlt(r,e,t){var a=r.method.microSeconds(),s={time:a,type:e,data:t},o=r._prepP?r._prepP:zn;return o.then(function(){var n=r.method.postMessage(r._state,s);return r._uMP.add(n),n.catch().then(function(){return r._uMP.delete(n)}),n})}function tqt(r){var e=r.method.create(r.name,r.options);glt(e)?(r._prepP=e,e.then(function(t){r._state=t})):r._state=e}function Flt(r){return r._addEL.message.length>0||r._addEL.internal.length>0}function qlt(r,e,t){r._addEL[e].push(t),rqt(r)}function Hlt(r,e,t){r._addEL[e]=r._addEL[e].filter(function(a){return a!==t}),aqt(r)}function rqt(r){if(!r._iL&&Flt(r)){var e=i(function(s){r._addEL[s.type].forEach(function(o){s.time>=o.time&&o.fn(s.data)})},"listenerFn"),t=r.method.microSeconds();r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,e,t)}):(r._iL=!0,r.method.onMessage(r._state,e,t))}}function aqt(r){if(r._iL&&!Flt(r)){r._iL=!1;var e=r.method.microSeconds();r.method.onMessage(r._state,null,e)}}var nfe,XFt,lg,ofe,Vlt=h(()=>{Uh();Blt();Nee();nfe=new Set,XFt=0,lg=i(function(e,t){this.id=XFt++,nfe.add(this),this.name=e,ofe&&(t=ofe),this.options=ng(t),this.method=ife(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,tqt(this)},"BroadcastChannel");lg._pubkey=!0;i(JFt,"clearNodeFolder");i(eqt,"enforceOptions"),lg.prototype={postMessage:i(function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(e));return Nlt(this,"message",e)},"postMessage"),postInternal:i(function(e){return Nlt(this,"internal",e)},"postInternal"),set onmessage(r){var e=this.method.microSeconds(),t={time:e,fn:r};Hlt(this,"message",this._onML),r&&typeof r=="function"?(this._onML=t,qlt(this,"message",t)):this._onML=null},addEventListener:i(function(e,t){var a=this.method.microSeconds(),s={time:a,fn:t};qlt(this,e,s)},"addEventListener"),removeEventListener:i(function(e,t){var a=this._addEL[e].find(function(s){return s.fn===t});Hlt(this,e,a)},"removeEventListener"),close:i(function(){var e=this;if(!this.closed){nfe.delete(this),this.closed=!0;var t=this._prepP?this._prepP:zn;return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(Array.from(e._uMP))}).then(function(){return Promise.all(e._befC.map(function(a){return a()}))}).then(function(){return e.method.close(e._state)})}},"close"),get type(){return this.method.type},get isClosed(){return this.closed}};i(Nlt,"_post");i(tqt,"_prepareChannel");i(Flt,"_hasMessageListeners");i(qlt,"_addListenerObject");i(Hlt,"_removeListenerObject");i(rqt,"_startListening");i(aqt,"_stopListening")});function jlt(r){if(typeof WorkerGlobalScope=="function"&&self instanceof WorkerGlobalScope){var e=self.close.bind(self);self.close=function(){return r(),e()}}else{if(typeof window.addEventListener!="function")return;window.addEventListener("beforeunload",function(){r()},!0),window.addEventListener("unload",function(){r()},!0)}}var Ult=h(()=>{i(jlt,"addBrowser")});function Wlt(r){process.on("exit",function(){return r()}),process.on("beforeExit",function(){return r().then(function(){return process.exit()})}),process.on("SIGINT",function(){return r().then(function(){return process.exit()})}),process.on("uncaughtException",function(e){return r().then(function(){console.trace(e),process.exit(101)})})}var Glt=h(()=>{i(Wlt,"addNode")});function oqt(){Klt||(Klt=!0,iqt(nqt))}function Ylt(r){if(oqt(),typeof r!="function")throw new Error("Listener is no function");cg.add(r);var e={remove:i(function(){return cg.delete(r)},"remove"),run:i(function(){return cg.delete(r),r()},"run")};return e}function nqt(){var r=[];return cg.forEach(function(e){r.push(e()),cg.delete(e)}),Promise.all(r)}function RZr(){cg.clear()}function zZr(){return cg.size}var sqt,iqt,cg,Klt,Zlt=h(()=>{Ult();Glt();sqt=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",iqt=sqt?Wlt:jlt,cg=new Set,Klt=!1;i(oqt,"startListening");i(Ylt,"add");i(nqt,"runAll");i(RZr,"removeAll");i(zZr,"getSize")});function zu(r,e){var t={context:"leader",action:e,token:r.token};return r.broadcastChannel.postInternal(t)}function m4(r){r.isLeader=!0,r._hasLeader=!0;var e=Ylt(function(){return r.die()});r._unl.push(e);var t=i(function(s){s.context==="leader"&&s.action==="apply"&&zu(r,"tell"),s.context==="leader"&&s.action==="tell"&&!r._dpLC&&(r._dpLC=!0,r._dpL(),zu(r,"tell"))},"isLeaderListener");return r.broadcastChannel.addEventListener("internal",t),r._lstns.push(t),zu(r,"tell")}var qee=h(()=>{Zlt();i(zu,"sendLeaderMessage");i(m4,"beLeader")});var lfe,Qlt,Xlt=h(()=>{Uh();qee();lfe=i(function(e,t){var a=this;this.broadcastChannel=e,e._befC.push(function(){return a.die()}),this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Au(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+e.method.type+"||"+e.name},"LeaderElectionWebLock"),Qlt="LeaderElectionWebLock.die() called";lfe.prototype={hasLeader:i(function(){var e=this;return navigator.locks.query().then(function(t){var a=t.held?t.held.filter(function(s){return s.name===e.lN}):[];return!!(a&&a.length>0)})},"hasLeader"),awaitLeadership:i(function(){var e=this;if(!this._wLMP){this._wKMC.c=new AbortController;var t=new Promise(function(a,s){e._wKMC.res=a,e._wKMC.rej=s});this._wLMP=new Promise(function(a,s){navigator.locks.request(e.lN,{signal:e._wKMC.c.signal},function(){return e._wKMC.c=void 0,e.isDead||m4(e),a(),t}).catch(function(o){o.message&&o.message===Qlt||(e._wKMC.rej&&e._wKMC.rej(o),s(o))})})}return this._wLMP},"awaitLeadership"),set onduplicate(r){},die:i(function(){var e=this;return this.isDead?this._dP:(this._lstns.forEach(function(t){return e.broadcastChannel.removeEventListener("internal",t)}),this._lstns=[],this._unl.forEach(function(t){return t.remove()}),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort(new Error(Qlt)),this._dP=zu(this,"death"),this._dP)},"die")}});function lqt(r){return r.isLeader?zn:new Promise(function(e){var t=!1;function a(){t||(t=!0,r.broadcastChannel.removeEventListener("internal",o),e(!0))}i(a,"finish"),r.applyOnce().then(function(){r.isLeader&&a()});var s=i(function(){return kd(r._options.fallbackInterval).then(function(){if(!(r.isDead||t))if(r.isLeader)a();else return r.applyOnce(!0).then(function(){r.isLeader?a():s()})})},"tryOnFallBack");s();var o=i(function(l){l.context==="leader"&&l.action==="death"&&(r._hasLeader=!1,r.applyOnce().then(function(){r.isLeader&&a()}))},"whenDeathListener");r.broadcastChannel.addEventListener("internal",o),r._lstns.push(o)})}function cqt(r,e){return r||(r={}),r=JSON.parse(JSON.stringify(r)),r.fallbackInterval||(r.fallbackInterval=3e3),r.responseTime||(r.responseTime=e.method.averageResponseTime(e.options)),r}function dqt(r,e){if(r._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");e=cqt(e,r);var t=xlt()?new lfe(r,e):new Jlt(r,e);return r._befC.push(function(){return t.die()}),r._leaderElector=t,t}var Jlt,ect=h(()=>{Uh();qee();Xlt();Jlt=i(function(e,t){var a=this;this.broadcastChannel=e,this._options=t,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=Au(),this._aplQ=zn,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var s=i(function(n){n.context==="leader"&&(n.action==="death"&&(a._hasLeader=!1),n.action==="tell"&&(a._hasLeader=!0))},"hasLeaderListener");this.broadcastChannel.addEventListener("internal",s),this._lstns.push(s)},"LeaderElection");Jlt.prototype={hasLeader:i(function(){return Promise.resolve(this._hasLeader)},"hasLeader"),applyOnce:i(function(e){var t=this;if(this.isLeader)return kd(0,!0);if(this.isDead)return kd(0,!1);if(this._aplQC>1)return this._aplQ;var a=i(function(){if(t.isLeader)return vlt;var o=!1,n,l=new Promise(function(u){n=i(function(){o=!0,u()},"stopCriteriaPromiseResolve")}),c=i(function(p){p.context==="leader"&&p.token!=t.token&&(p.action==="apply"&&p.token>t.token&&n(),p.action==="tell"&&(n(),t._hasLeader=!0))},"handleMessage");t.broadcastChannel.addEventListener("internal",c);var d=e?t._options.responseTime*4:t._options.responseTime;return zu(t,"apply").then(function(){return Promise.race([kd(d),l.then(function(){return Promise.reject(new Error)})])}).then(function(){if(!t.isDead)return zu(t,"apply")}).then(function(){return Promise.race([kd(d),l.then(function(){return Promise.reject(new Error)})])}).catch(function(){}).then(function(){return t.broadcastChannel.removeEventListener("internal",c),!o&&!t.isDead?m4(t).then(function(){return!0}):!1})},"applyRun");return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then(function(){return a()}).then(function(){t._aplQC=t._aplQC-1}),this._aplQ.then(function(){return t.isLeader})},"applyOnce"),awaitLeadership:i(function(){return this._aLP||(this._aLP=lqt(this)),this._aLP},"awaitLeadership"),set onduplicate(r){this._dpL=r},die:i(function(){var e=this;return this.isDead?this._dP:(this._lstns.forEach(function(t){return e.broadcastChannel.removeEventListener("internal",t)}),this._lstns=[],this._unl.forEach(function(t){return t.remove()}),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,this._dP=zu(this,"death"),this._dP)},"die")};i(lqt,"_awaitLeadershipOnce");i(cqt,"fillOptionsWithDefaults");i(dqt,"createLeaderElection")});var tct=h(()=>{Vlt();ect();qee()});var rct=h(()=>{wh();l2();h4();tct()});var cfe,dfe,act=h(()=>{rct();cfe=globalThis.BroadcastChannel;cfe||(cfe=lg);dfe=class{static{i(this,"DeesComms")}constructor(){this.broadcastChannel=new cfe("dees-comms"),this.typedrouter=new ps.TypedRouter,this.typedtarget=new ps.TypedTarget({postMethodWithTypedRouter:i(async e=>{this.postMessage(e)},"postMethodWithTypedRouter"),typedRouterRef:this.typedrouter}),this.broadcastChannel.onmessage=async e=>{let t=e.method?e:e.data,a=await this.typedrouter.routeAndAddResponse(t,{skipHooks:!0});a&&!a.error&&this.postMessage(a)}}createTypedRequest(e){return new ps.TypedRequest(this.typedtarget,e)}async postMessage(e){this.broadcastChannel.postMessage(e)}async createTypedHandler(e,t){this.typedrouter.addTypedHandler(new ps.TypedHandler(e,t))}}});var g4={};St(g4,{DeesComms:()=>dfe});var sct=h(()=>{act()});function Or(r){if(r&&typeof r=="object")switch(r[ho]){case ul:case Sd:return!0}return!1}function kr(r){if(r&&typeof r=="object")switch(r[ho]){case b4:case ul:case dn:case Sd:return!0}return!1}var b4,v4,ul,Hee,dn,Sd,ho,un,pn,hn,fr,tr,fn,y4,Br=h(()=>{b4=Symbol.for("yaml.alias"),v4=Symbol.for("yaml.document"),ul=Symbol.for("yaml.map"),Hee=Symbol.for("yaml.pair"),dn=Symbol.for("yaml.scalar"),Sd=Symbol.for("yaml.seq"),ho=Symbol.for("yaml.node.type"),un=i(r=>!!r&&typeof r=="object"&&r[ho]===b4,"isAlias"),pn=i(r=>!!r&&typeof r=="object"&&r[ho]===v4,"isDocument"),hn=i(r=>!!r&&typeof r=="object"&&r[ho]===ul,"isMap"),fr=i(r=>!!r&&typeof r=="object"&&r[ho]===Hee,"isPair"),tr=i(r=>!!r&&typeof r=="object"&&r[ho]===dn,"isScalar"),fn=i(r=>!!r&&typeof r=="object"&&r[ho]===Sd,"isSeq");i(Or,"isCollection");i(kr,"isNode");y4=i(r=>(tr(r)||Or(r))&&!!r.anchor,"hasAnchor")});function Ln(r,e){let t=oct(e);pn(r)?J2(null,r.contents,t,Object.freeze([r]))===_d&&(r.contents=null):J2(null,r,t,Object.freeze([]))}function J2(r,e,t,a){let s=nct(r,e,t,a);if(kr(s)||fr(s))return lct(r,a,s),J2(r,s,t,a);if(typeof s!="symbol"){if(Or(e)){a=Object.freeze(a.concat(e));for(let o=0;o<e.items.length;++o){let n=J2(o,e.items[o],t,a);if(typeof n=="number")o=n-1;else{if(n===mn)return mn;n===_d&&(e.items.splice(o,1),o-=1)}}}else if(fr(e)){a=Object.freeze(a.concat(e));let o=J2("key",e.key,t,a);if(o===mn)return mn;o===_d&&(e.key=null);let n=J2("value",e.value,t,a);if(n===mn)return mn;n===_d&&(e.value=null)}}return s}async function dg(r,e){let t=oct(e);pn(r)?await ew(null,r.contents,t,Object.freeze([r]))===_d&&(r.contents=null):await ew(null,r,t,Object.freeze([]))}async function ew(r,e,t,a){let s=await nct(r,e,t,a);if(kr(s)||fr(s))return lct(r,a,s),ew(r,s,t,a);if(typeof s!="symbol"){if(Or(e)){a=Object.freeze(a.concat(e));for(let o=0;o<e.items.length;++o){let n=await ew(o,e.items[o],t,a);if(typeof n=="number")o=n-1;else{if(n===mn)return mn;n===_d&&(e.items.splice(o,1),o-=1)}}}else if(fr(e)){a=Object.freeze(a.concat(e));let o=await ew("key",e.key,t,a);if(o===mn)return mn;o===_d&&(e.key=null);let n=await ew("value",e.value,t,a);if(n===mn)return mn;n===_d&&(e.value=null)}}return s}function oct(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function nct(r,e,t,a){if(typeof t=="function")return t(r,e,a);if(hn(e))return t.Map?.(r,e,a);if(fn(e))return t.Seq?.(r,e,a);if(fr(e))return t.Pair?.(r,e,a);if(tr(e))return t.Scalar?.(r,e,a);if(un(e))return t.Alias?.(r,e,a)}function lct(r,e,t){let a=e[e.length-1];if(Or(a))a.items[r]=t;else if(fr(a))r==="key"?a.key=t:a.value=t;else if(pn(a))a.contents=t;else{let s=un(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}var mn,ict,_d,x4=h(()=>{Br();mn=Symbol("break visit"),ict=Symbol("skip children"),_d=Symbol("remove node");i(Ln,"visit"),Ln.BREAK=mn,Ln.SKIP=ict,Ln.REMOVE=_d;i(J2,"visit_");i(dg,"visitAsync"),dg.BREAK=mn,dg.SKIP=ict,dg.REMOVE=_d;i(ew,"visitAsync_");i(oct,"initVisitor");i(nct,"callVisitor");i(lct,"replaceNode")});var pqt,hqt,lc,ufe=h(()=>{Br();x4();pqt={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hqt=i(r=>r.replace(/[!,[\]{}]/g,e=>pqt[e]),"escapeTagName"),lc=class r{static{i(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let a=e.trim().split(/[ \t]+/),s=a.shift();switch(s){case"%TAG":{if(a.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),a.length<2))return!1;let[o,n]=a;return this.tags[o]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,a.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=a;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let n=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,n),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let n=e.slice(2,-1);return n==="!"||n==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),n)}let[,a,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let o=this.tags[a];if(o)try{return o+decodeURIComponent(s)}catch(n){return t(String(n)),null}return a==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,a]of Object.entries(this.tags))if(e.startsWith(a))return t+hqt(e.substring(a.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],a=Object.entries(this.tags),s;if(e&&a.length>0&&kr(e.contents)){let o={};Ln(e.contents,(n,l)=>{kr(l)&&l.tag&&(o[l.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,n]of a)o==="!!"&&n==="tag:yaml.org,2002:"||(!e||s.some(l=>l.startsWith(n)))&&t.push(`%TAG ${o} ${n}`);return t.join(`
|
|
14
|
+
`),"stringifyJsonL"),VNt=i((r,e,t={})=>{let a=new WeakSet,s=i(l=>{if(l===null||typeof l!="object")return l;let c=bee("",l);if(c&&c.type==="EncodedBuffer"&&typeof c.data=="string")return c;if(a.has(l))return"__cycle__";if(a.add(l),Array.isArray(l))return l.map(u=>s(u));let d={};for(let u of Object.keys(l))try{d[u]=s(l[u])}catch{d[u]="__unserializable__"}return d},"sanitize"),o=s(r),n={...t,cycles:!0};if(e&&!n.cmp){let l=new Map;e.forEach((c,d)=>l.set(c,d)),n.cmp=(c,d)=>{let u=l.has(c.key)?l.get(c.key):Number.POSITIVE_INFINITY,p=l.has(d.key)?l.get(d.key):Number.POSITIVE_INFINITY;return u!==p?u-p:c.key<d.key?-1:c.key>d.key?1:0}}return gee(o,n)},"stableOneWayStringify"),ag=i((r,e,t={})=>{let a=Mhe(r);r=JSON.parse(a);let s={...t};if(e&&!s.cmp){let n=new Map;e.forEach((l,c)=>n.set(l,c)),s.cmp=(l,c)=>{let d=n.has(l.key)?n.get(l.key):Number.POSITIVE_INFINITY,u=n.has(c.key)?n.get(c.key):Number.POSITIVE_INFINITY;return d!==u?d-u:l.key<c.key?-1:l.key>c.key?1:0}}return gee(r,s)},"stringify"),jNt=i(r=>{let e=ag(r),t=JSON.parse(e);return JSON.stringify(t,null,2)},"stringifyPretty"),UNt=i((...r)=>{let e=ag(...r);return uo.base64.encodeUri(e)},"stringifyBase64"),WNt=i(r=>{let e=uo.base64,a=(e.decodeUri||e.decode)(r);return vee(a)},"parseBase64"),Dhe=class r{static{i(this,"Smartjson")}static enfoldFromObject(e){let t=new this,a=t.saveableProperties||[];for(let s in e)a.indexOf(s)!==-1&&(t[s]=e[s]);return t}static enfoldFromJson(e){let t=vee(e);return this.enfoldFromObject(t)}saveableProperties=[];foldToObject(){let e=new Set;return e.add(this),this.foldToObjectInternal(e)}foldToObjectInternal(e){let t={},a=i(o=>{if(o instanceof r){if(e.has(o))throw new Error("cycle detected");return e.add(o),o.foldToObjectInternal(e)}return Array.isArray(o)?o.map(n=>a(n)):structuredClone(o)},"foldValue"),s=this.saveableProperties||[];for(let o of s){let n=this[o];t[o]=a(n)}return t}foldToJson(){let e=this.foldToObject();return ag(e)}},GNt=i(()=>(r,e)=>{let t=String(e.name);e.addInitializer(function(){this.saveableProperties||(this.saveableProperties=[]),this.saveableProperties.includes(t)||this.saveableProperties.push(t)})},"foldDec"),Nnt=i((r,e)=>{let t=ag(r),a=ag(e);return t===a},"deepEqualObjects"),KNt=i((r,e)=>{let t=$he(r),a=$he(e);return Nnt(t,a)},"deepEqualJsonLStrings")});var Fnt={};var qnt=h(()=>{});var Ehe=h(()=>{H_();e4();sg();Po();cd();qnt()});var yee,Vnt,YNt,ZNt,xee,jnt,Unt,QNt,a4,Phe=h(()=>{Ehe();yee=class{static{i(this,"WebStoreDb")}constructor(e){this.nativeDb=e}async get(e,t,a={}){return this.runObjectStoreRequest(e,"readonly",s=>s.get(t),a)}async getKey(e,t,a={}){return this.runObjectStoreRequest(e,"readonly",s=>s.getKey(t),a)}async put(e,t,a,s={}){return this.runObjectStoreRequest(e,"readwrite",o=>a===void 0?o.put(t):o.put(t,a),s)}async delete(e,t,a={}){await this.runObjectStoreRequest(e,"readwrite",s=>s.delete(t),a)}async clear(e,t={}){await this.runObjectStoreRequest(e,"readwrite",a=>a.clear(),t)}async getAllKeys(e,t={}){return this.runObjectStoreRequest(e,"readonly",a=>a.getAllKeys(),t)}close(){this.nativeDb.close()}async runObjectStoreRequest(e,t,a,s){s.signal?.throwIfAborted();let o=this.nativeDb.transaction(e,t),n=o.objectStore(e),l=a(n),c,d=new Promise((p,m)=>{c=m}),u=i(()=>{try{o.abort()}catch(p){if(!(p instanceof DOMException)||p.name!=="InvalidStateError"){c(p);return}}s.signal&&c(s.signal.reason)},"abortTransaction");s.signal?.addEventListener("abort",u,{once:!0});try{let[p]=await Promise.race([Promise.all([YNt(l),ZNt(o)]),d]);return p}catch(p){throw s.signal?.aborted?s.signal.reason:p}finally{s.signal?.removeEventListener("abort",u)}}},Vnt=i(async(r,e)=>{if(e?.throwIfAborted(),!e)return r;let t,a=new Promise((o,n)=>{t=n}),s=i(()=>{t(e.reason)},"abortListener");e.addEventListener("abort",s,{once:!0});try{return await Promise.race([r,a])}finally{e.removeEventListener("abort",s)}},"awaitWithSignal"),YNt=i(r=>new Promise((e,t)=>{r.onsuccess=()=>e(r.result),r.onerror=()=>t(xee("IndexedDB request failed",r.error))}),"indexedDbRequestToPromise"),ZNt=i(r=>new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(xee("IndexedDB transaction aborted",r.error)),r.onerror=()=>t(xee("IndexedDB transaction failed",r.error))}),"indexedDbTransactionToPromise"),xee=i((r,e)=>e?new Error(`${r}: ${e.message}`,{cause:e}):new Error(r),"createIndexedDbError"),jnt=i((r,e)=>{r.objectStoreNames.contains(e)||r.createObjectStore(e)},"ensureObjectStore"),Unt=i(async(r,e,t)=>{if(!globalThis.indexedDB)throw new Error("IndexedDB is not available in this runtime");return new Promise((a,s)=>{let o=!1,n=typeof e=="number"?globalThis.indexedDB.open(r,e):globalThis.indexedDB.open(r),l=i(c=>{o||(o=!0,s(c instanceof Error?c:new Error(String(c))))},"rejectOnce");n.onupgradeneeded=()=>{if(t)try{t(n.result)}catch(c){n.transaction?.abort(),l(c)}},n.onsuccess=()=>{if(o){n.result.close();return}o=!0;let c=n.result;c.onversionchange=()=>c.close(),a(c)},n.onerror=()=>l(xee(`Failed to open IndexedDB database "${r}"`,n.error)),n.onblocked=()=>l(new Error(`Opening IndexedDB database "${r}" was blocked by another connection`))})},"openNativeDb"),QNt=i(async(r,e)=>{let t=await Unt(r,void 0,s=>jnt(s,e));if(t.objectStoreNames.contains(e))return new yee(t);let a=t.version+1;if(t.close(),t=await Unt(r,a,s=>jnt(s,e)),!t.objectStoreNames.contains(e))throw t.close(),new Error(`Failed to create IndexedDB object store "${e}" in database "${r}"`);return new yee(t)},"openWebStoreDb"),a4=class{static{i(this,"WebStore")}constructor(e){this.lifecycleGeneration=0,this.closeCoveredGeneration=0,this.activeOperations=new Set,this.options=e}trackOperation(e){this.lifecycleGeneration+=1;let t;return t=(async()=>e())().finally(()=>{this.activeOperations.delete(t)}),this.activeOperations.add(t),t}init(e={}){return this.trackOperation(()=>this.initForOperation(e.signal))}async initForOperation(e){e?.throwIfAborted();let t=this.closePromise;return t&&(await Vnt(t,e),e?.throwIfAborted()),this.initPromise||(this.initPromise=this.runInit().catch(a=>{throw this.initPromise=void 0,a})),Vnt(this.initPromise,e)}async runInit(){let e=new ic.Smartenv;if(!e.isBrowser&&!globalThis.indexedDB&&(await e.getSafeNodeModule("fake-indexeddb/auto"),!globalThis.indexedDB)){let t=await e.getSafeNodeModule("fake-indexeddb");globalThis.indexedDB=new t.IDBFactory}this.db=await QNt(this.options.dbName,this.options.storeName)}runDataOperation(e,t){return this.trackOperation(async()=>(await this.initForOperation(t.signal),t.signal?.throwIfAborted(),e(this.db)))}close(){let e=this.lifecycleGeneration;if(this.closePromise&&e<=this.closeCoveredGeneration)return this.closePromise;let t=this.closePromise,a=[...this.activeOperations];if(!t&&!this.initPromise&&a.length===0)return Promise.resolve();let s;return s=(async()=>{try{if(t)try{await t}catch{}await Promise.allSettled(a);let o=this.initPromise;if(!o)return;try{await o}catch{return}finally{this.initPromise===o&&(this.initPromise=void 0)}this.db.close()}finally{this.closePromise===s&&(this.closePromise=void 0)}})(),this.closePromise=s,this.closeCoveredGeneration=e,s}async get(e,t={}){return this.runDataOperation(a=>a.get(this.options.storeName,e,t),t)}async check(e,t={}){return this.runDataOperation(async a=>await a.getKey(this.options.storeName,e,t)!==void 0,t)}async set(e,t,a={}){return this.runDataOperation(s=>s.put(this.options.storeName,t,e,a),a)}async delete(e,t={}){return this.runDataOperation(a=>a.delete(this.options.storeName,e,t),t)}async clear(e={}){return this.runDataOperation(t=>t.clear(this.options.storeName,e),e)}async keys(e={}){return this.runDataOperation(t=>t.getAllKeys(this.options.storeName,e),e)}}});var Ahe,Wnt=h(()=>{Phe();Ehe();Ahe=class{static{i(this,"TypedrequestCache")}constructor(e="default"){this.webstore=new a4({dbName:"trStore",storeName:`trStore-${e}`})}buildKey(e){return wa.stringify({method:e.method,request:e.request})}async setByRequest(e){if(!e.response)throw new Error("You cannot store requests without a response present");await this.webstore.set(this.buildKey(e),e)}async getByRequest(e){return await this.webstore.get(this.buildKey(e))}}});var oc={};St(oc,{TypedrequestCache:()=>Ahe,WebStore:()=>a4});var wee=h(()=>{Wnt();Phe()});var s4=h(()=>{wh();e4();sg();Po();wee()});var i4,F2,XNt,o4=h(()=>{s4();i4=256,F2=class{static{i(this,"CacheStore")}constructor(e="webrequest-v4",t="cache"){this.lifecycleController=new AbortController,this.closeReason=new Error("Webrequest cache store is closed"),this.disposed=!1,this.pruneGeneration=0,this.pruneWaiters=new Set,this.activeOwnedOperations=new Set,this.webstore=new oc.WebStore({dbName:e,storeName:t}),this.initPromise=this.init()}async init(){}generateCacheKey(e){let t=e.url,a=e.method;return a==="GET"?t:`${a}:${t}`}async set(e,t,a={}){await this.initPromise;let s=this.getOperationSignal(a.signal),o=a.maxEntries??i4;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError("webrequest cache maxEntries must be a positive safe integer");await this.webstore.set(e,t,{signal:s}),await this.schedulePrune(o,s)}async get(e,t={}){await this.initPromise;let a=this.getOperationSignal(t.signal);try{let s=await this.webstore.get(e,{signal:a});return s===void 0?null:this.isCacheEntry(s)?s:(await this.webstore.delete(e,{signal:a}),null)}catch{if(a.aborted)throw a.reason;return null}}async has(e,t={}){return await this.get(e,t)!==null}async delete(e,t={}){await this.initPromise;let a=this.getOperationSignal(t.signal);await this.webstore.delete(e,{signal:a})}async clear(e={}){await this.initPromise;let t=this.getOperationSignal(e.signal);await this.webstore.clear({signal:t})}responseFromCacheEntry(e){let t=new Headers(e.headers);return new Response(e.response,{status:e.status,statusText:e.statusText,headers:t})}cacheEntryFromResponse(e,t,a,s={}){return this.trackOwnedOperation(async()=>{let o=this.getOperationSignal(s.signal),n=s.preserveResponse!==!1,l=n?t.clone():t,c=await this.consumeArrayBuffer(l,o,n?t.body:void 0,s.responseSignal),d={};return l.headers.forEach((u,p)=>{d[p]=u}),{response:c,headers:d,timestamp:Date.now(),etag:a?.etag||l.headers.get("etag")||void 0,lastModified:a?.lastModified||l.headers.get("last-modified")||void 0,maxAge:a?.maxAge,url:e,status:l.status,statusText:l.statusText}})}async pruneExpired(e={}){await this.initPromise;let t=this.getOperationSignal(e.signal),a=await this.collectEntries(t),s=0;for(let o of a)t.throwIfAborted(),!(o.valid&&!this.isExpired(o))&&(await this.webstore.delete(o.key,{signal:t}),s+=1);return s}async schedulePrune(e,t){t?.throwIfAborted();let a=++this.pruneGeneration;this.pendingPruneMaxEntries=this.pendingPruneMaxEntries===void 0?e:Math.min(this.pendingPruneMaxEntries,e);let s,o,n=new Promise((c,d)=>{s=c,o=d}),l={generation:a,resolve:s,reject:o};this.pruneWaiters.add(l),this.ensurePruneLoop();try{await XNt(n,t)}finally{this.pruneWaiters.delete(l)}}ensurePruneLoop(){if(this.pruneLoopPromise)return this.pruneLoopPromise;let e;return e=this.runPruneLoop().catch(t=>{this.pendingPruneMaxEntries=void 0,this.settlePruneWaiters(this.pruneGeneration,t)}).finally(()=>{this.pruneLoopPromise===e&&(this.pruneLoopPromise=void 0,this.pendingPruneMaxEntries!==void 0&&!this.disposed&&this.ensurePruneLoop())}),this.pruneLoopPromise=e,e}async runPruneLoop(){for(;this.pendingPruneMaxEntries!==void 0;){let e=this.pendingPruneMaxEntries;this.pendingPruneMaxEntries=void 0;let t=this.pruneGeneration;await this.pruneToLimit(e,this.lifecycleController.signal),this.settlePruneWaiters(t)}}settlePruneWaiters(e,t){for(let a of this.pruneWaiters)a.generation>e||(this.pruneWaiters.delete(a),t===void 0?a.resolve():a.reject(t))}async pruneToLimit(e,t){let a=await this.collectEntries(t),s=a.filter(l=>!l.valid||this.isExpired(l));for(let l of s)t?.throwIfAborted(),await this.webstore.delete(l.key,{signal:t});let o=a.filter(l=>l.valid&&!this.isExpired(l)).sort((l,c)=>l.timestamp===c.timestamp?l.key.localeCompare(c.key):(l.timestamp??0)-(c.timestamp??0)),n=Math.max(0,o.length-e);for(let l of o.slice(0,n))t?.throwIfAborted(),await this.webstore.delete(l.key,{signal:t})}async collectEntries(e){e?.throwIfAborted();let t=await this.webstore.keys({signal:e}),a=[];for(let s of t)if(e?.throwIfAborted(),typeof s=="string")try{let o=await this.webstore.get(s,{signal:e});a.push(this.isCacheEntry(o)?{key:s,valid:!0,timestamp:o.timestamp,maxAge:o.maxAge}:{key:s,valid:!1,timestamp:0})}catch{if(e?.aborted)throw e.reason;continue}return a}isCacheEntry(e){if(!e||typeof e!="object")return!1;let t=Reflect.get(e,"response"),a=Reflect.get(e,"headers"),s=Reflect.get(e,"timestamp"),o=Reflect.get(e,"url"),n=Reflect.get(e,"status"),l=Reflect.get(e,"statusText");return t instanceof ArrayBuffer&&typeof a=="object"&&a!==null&&Number.isFinite(s)&&typeof o=="string"&&Number.isInteger(n)&&typeof l=="string"}isExpired(e){return e.maxAge!==void 0&&e.maxAge>0&&Date.now()-e.timestamp>=e.maxAge}getOperationSignal(e){if(this.disposed)throw this.closeReason;return e?.throwIfAborted(),e?AbortSignal.any([e,this.lifecycleController.signal]):this.lifecycleController.signal}trackOwnedOperation(e){let t;return t=e().finally(()=>{this.activeOwnedOperations.delete(t)}),this.activeOwnedOperations.add(t),t}close(){if(this.closePromise)return this.closePromise;this.disposed=!0,this.lifecycleController.abort(this.closeReason);let e=this.pruneLoopPromise,t=[...this.activeOwnedOperations];return this.closePromise=(async()=>{await Promise.allSettled([...t,...e?[e]:[]]),await this.webstore.close()})(),this.closePromise}async consumeArrayBuffer(e,t,a,s){if(t?.throwIfAborted(),!t)return e.arrayBuffer();let o=e.body?.getReader();if(!o)return new ArrayBuffer(0);let n=[],l=0,c,d=new Promise((v,f)=>{c=f}),u,p=i(()=>{c(t.reason),s?.aborted||(u=Promise.all([o.cancel(t.reason).catch(()=>{}),a?.cancel(t.reason).catch(()=>{})]).then(()=>{}))},"abortListener");t.addEventListener("abort",p,{once:!0});try{for(;;){let v=await Promise.race([o.read(),d]);if(v.done)break;n.push(v.value),l+=v.value.byteLength}}finally{t.removeEventListener("abort",p),u&&await u;try{o.releaseLock()}catch{}}let m=new Uint8Array(l),b=0;for(let v of n)m.set(v,b),b+=v.byteLength;return m.buffer}},XNt=i(async(r,e)=>{if(e?.throwIfAborted(),!e)return r;let t,a=new Promise((o,n)=>{t=n}),s=i(()=>{t(e.reason)},"abortListener");e.addEventListener("abort",s,{once:!0});try{return await Promise.race([r,a])}finally{e.removeEventListener("abort",s)}},"awaitWithSignal")});function JNt(r){let e={maxAge:0,immutable:!1,noCache:!1,noStore:!1,mustRevalidate:!1};if(!r)return e;let t=r.toLowerCase().split(",").map(a=>a.trim());for(let a of t)if(a==="no-cache")e.noCache=!0;else if(a==="no-store")e.noStore=!0;else if(a==="immutable")e.immutable=!0;else if(a==="must-revalidate")e.mustRevalidate=!0;else if(a.startsWith("max-age=")){let s=parseInt(a.split("=")[1],10);isNaN(s)||(e.maxAge=s*1e3)}return e}function eFt(r){if(r)try{return new Date(r).getTime()}catch{return}}function wd(r){let e=r.get("cache-control"),t=r.get("expires"),a=r.get("etag"),s=r.get("last-modified"),o=JNt(e);if(o.maxAge===0&&t){let n=eFt(t);n&&(o.maxAge=Math.max(0,n-Date.now()))}return{maxAge:o.maxAge||0,etag:a||void 0,lastModified:s||void 0,immutable:o.immutable||!1,noCache:o.noCache||!1,noStore:o.noStore||!1,mustRevalidate:o.mustRevalidate||!1}}function See(r,e){if(e.noStore)return!1;if(e.immutable)return!0;let t=Date.now()-r.timestamp,a=r.maxAge||e.maxAge||0;return a===0?!1:t<a}function q2(r){return r.noCache||r.mustRevalidate}function _ee(r){let e={};return r.etag&&(e["if-none-match"]=r.etag),r.lastModified&&(e["if-modified-since"]=r.lastModified),e}function Cee(r){let e={};return r.forEach((t,a)=>{e[a]=t}),e}function Gnt(r){let e=new Headers;return Object.entries(r).forEach(([t,a])=>{e.set(t,a)}),e}var Rhe=h(()=>{i(JNt,"parseCacheControl");i(eFt,"parseExpires");i(wd,"extractCacheMetadata");i(See,"isFresh");i(q2,"requiresRevalidation");i(_ee,"createConditionalHeaders");i(Cee,"headersToObject");i(Gnt,"objectToHeaders")});function tFt(r){let e=new AbortController,t=!1,a=!1,s=new sr.Timeout(r,null);return s.promise.then(()=>{t=!0,e.abort()}),{controller:e,cleanup:i(()=>{a||(a=!0,s.cancel())},"cleanup"),didTimeout:i(()=>t,"didTimeout")}}async function zhe(r,e,t){let a=r instanceof Request?r.url:String(r),{controller:s,cleanup:o,didTimeout:n}=tFt(t),l=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal;try{let c=await fetch(r,{...e,signal:l});return o(),c}catch(c){throw o(),n()?Hh(a,t):c}}async function Znt(r,e){if(e.signal?.aborted){let u=Ynt(e.signal);throw await r.body?.cancel(u).catch(()=>{}),u}if(e.bodyTimeoutMs!==void 0&&e.bodyTimeoutMs<=0){let u=Hh(e.url,e.reportedTimeoutMs??e.bodyTimeoutMs);throw await r.body?.cancel(u).catch(()=>{}),u}if(e.bodyTimeoutMs===void 0&&!e.signal)return await r.json();let t=r.body?.getReader();if(!t)return JSON.parse("");let a,s,o,n=new Promise((u,p)=>{o=p}),l=i(u=>{a||(a=u,t.cancel(u).catch(()=>{}),o(u))},"terminate"),c=i(()=>{e.signal&&l(Ynt(e.signal))},"abortListener");if(e.signal&&(e.signal.aborted?c():e.signal.addEventListener("abort",c,{once:!0})),e.bodyTimeoutMs!==void 0){let u=e.reportedTimeoutMs??e.bodyTimeoutMs;s=setTimeout(()=>{l(Hh(e.url,u))},e.bodyTimeoutMs)}let d=i(async()=>{let u=new TextDecoder,p="";for(;;){let m;try{m=await t.read()}catch(b){throw a||b}if(a)throw a;if(m.done)break;p+=u.decode(m.value,{stream:!0})}if(p+=u.decode(),a)throw a;return JSON.parse(p)},"readBody");try{return await Promise.race([d(),n])}finally{s!==void 0&&clearTimeout(s),e.signal?.removeEventListener("abort",c);try{t.releaseLock()}catch{}}}var Knt,Hh,n4,Ynt,l4=h(()=>{s4();i(tFt,"createTimeoutController");Knt=Symbol("webrequestTimeoutError"),Hh=i((r,e)=>{let t=new Error(`Request timeout after ${e}ms: ${r}`);return Object.defineProperty(t,Knt,{configurable:!1,enumerable:!1,value:!0,writable:!1}),t},"createTimeoutError"),n4=i(r=>r instanceof Error&&Reflect.get(r,Knt)===!0,"isWebrequestTimeoutError");i(zhe,"fetchWithTimeout");Ynt=i(r=>{if(r.reason instanceof Error)return r.reason;let e=new Error("The request was aborted");return e.name="AbortError",e},"normalizeAbortReason");i(Znt,"consumeJsonWithTimeout")});function Xnt(r){switch(r){case"network-first":return new Tee;case"cache-first":return new Lhe;case"stale-while-revalidate":return new Ohe;case"network-only":return new Bhe;case"cache-only":return new Nhe;default:return new Tee}}var Tee,Lhe,Ohe,Bhe,Nhe,c4,Qnt,H2,Jnt=h(()=>{o4();Rhe();l4();Tee=class{static{i(this,"NetworkFirstStrategy")}async execute(e){let t;try{return t=await e.fetchFn(e.request),t.ok&&await this.cacheResponse(e,t),{response:t,fromCache:!1,revalidated:!1}}catch(a){if(await H2(t,a,e.request.signal),e.signal?.aborted)throw e.signal.reason;if(n4(a))throw a;e.logging&&console.log("[webrequest] Network failed, trying cache:",a);let s=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(s)return{response:e.cacheStore.responseFromCacheEntry(s),fromCache:!0,revalidated:!1};throw a}}async cacheResponse(e,t){let a=wd(t.headers);if(a.maxAge=c4(a.maxAge,e.cacheMaxAge),a.noStore)return;let s=await e.cacheStore.cacheEntryFromResponse(e.request.url,t,a,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,s,{signal:e.signal,maxEntries:e.cacheMaxEntries})}},Lhe=class{static{i(this,"CacheFirstStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(t){let o=wd(new Headers(t.headers));if(Qnt(e,t,o)&&!q2(o))return e.logging&&console.log("[webrequest] Cache hit (fresh):",e.request.url),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1};if(q2(o)&&(t.etag||t.lastModified))return await this.revalidate(e,t)}e.logging&&console.log("[webrequest] Cache miss, fetching:",e.request.url);let a=await e.fetchFn(e.request),s=wd(a.headers);if(s.maxAge=c4(s.maxAge,e.cacheMaxAge),!s.noStore)try{let o=await e.cacheStore.cacheEntryFromResponse(e.request.url,a,s,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,o,{signal:e.signal,maxEntries:e.cacheMaxEntries})}catch(o){throw await H2(a,o,e.request.signal),o}return{response:a,fromCache:!1,revalidated:!1}}async revalidate(e,t){let a=_ee(t),s=new Request(e.request.url,{method:e.request.method,headers:{...Cee(e.request.headers),...a},signal:e.signal}),o;try{if(o=await e.fetchFn(s),o.status===304)return e.logging&&console.log("[webrequest] Cache revalidated (304):",e.request.url),t.timestamp=Date.now(),await e.cacheStore.set(e.cacheKey,t,{signal:e.signal,maxEntries:e.cacheMaxEntries}),await H2(o,"304 response replaced by cached response",s.signal),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!0};if(o.ok){let n=wd(o.headers);if(n.maxAge=c4(n.maxAge,e.cacheMaxAge),!n.noStore){let l=await e.cacheStore.cacheEntryFromResponse(e.request.url,o,n,{signal:e.signal,responseSignal:s.signal});await e.cacheStore.set(e.cacheKey,l,{signal:e.signal,maxEntries:e.cacheMaxEntries})}}return{response:o,fromCache:!1,revalidated:!0}}catch(n){if(await H2(o,n,s.signal),e.signal?.aborted)throw e.signal.reason;if(n4(n))throw n;return e.logging&&console.log("[webrequest] Revalidation failed, using cache:",n),{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1}}}},Ohe=class{static{i(this,"StaleWhileRevalidateStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(t){let o=e.cacheStore.responseFromCacheEntry(t);return e.scheduleBackgroundRevalidation(async n=>{let l={...e,request:new Request(e.request,{signal:n}),signal:n};await this.revalidateInBackground(l,t)}),{response:o,fromCache:!0,revalidated:!1}}let a=await e.fetchFn(e.request),s=wd(a.headers);if(s.maxAge=c4(s.maxAge,e.cacheMaxAge),!s.noStore&&a.ok)try{let o=await e.cacheStore.cacheEntryFromResponse(e.request.url,a,s,{signal:e.signal,responseSignal:e.request.signal});await e.cacheStore.set(e.cacheKey,o,{signal:e.signal,maxEntries:e.cacheMaxEntries})}catch(o){throw await H2(a,o,e.request.signal),o}return{response:a,fromCache:!1,revalidated:!1}}async revalidateInBackground(e,t){let a=wd(new Headers(t.headers));if(Qnt(e,t,a)&&!q2(a))return;let s;try{if(e.signal?.throwIfAborted(),s=await e.fetchFn(e.request),s.ok){let o=wd(s.headers);if(o.maxAge=c4(o.maxAge,e.cacheMaxAge),!o.noStore){let n=await e.cacheStore.cacheEntryFromResponse(e.request.url,s,o,{signal:e.signal,responseSignal:e.request.signal,preserveResponse:!1});await e.cacheStore.set(e.cacheKey,n,{signal:e.signal,maxEntries:e.cacheMaxEntries}),e.logging&&console.log("[webrequest] Background revalidation complete:",e.request.url)}}}catch(o){if(e.signal?.aborted)return;e.logging&&console.warn("[webrequest] Background revalidation failed:",o)}finally{await H2(s,"background revalidation response discarded",e.request.signal)}}},Bhe=class{static{i(this,"NetworkOnlyStrategy")}async execute(e){return{response:await e.fetchFn(e.request),fromCache:!1,revalidated:!1}}},Nhe=class{static{i(this,"CacheOnlyStrategy")}async execute(e){let t=await e.cacheStore.get(e.cacheKey,{signal:e.signal});if(!t)throw new Error(`Cache miss for ${e.request.url} (cache-only mode)`);return{response:e.cacheStore.responseFromCacheEntry(t),fromCache:!0,revalidated:!1}}},c4=i((r,e)=>e===void 0?r:Math.min(r,e),"resolveEffectiveMaxAge"),Qnt=i((r,e,t)=>See(e,t)?r.cacheMaxAge===void 0?!0:Date.now()-e.timestamp<r.cacheMaxAge:!1,"isFreshForContext"),H2=i(async(r,e,t)=>{!r?.body||r.bodyUsed||t?.aborted||await r.body.cancel(e).catch(()=>{})},"cancelDiscardedResponse");i(Xnt,"getStrategyHandler")});var V2,Fhe=h(()=>{o4();Jnt();o4();l4();V2=class{static{i(this,"CacheManager")}constructor(e,t,a){this.lifecycleController=new AbortController,this.closeReason=new Error("Webrequest cache manager is closed"),this.disposed=!1,this.backgroundRevalidations=new Map,this.cacheStore=a??new F2(e,t)}async execute(e,t,a){if(this.disposed)throw this.closeReason;e.signal.throwIfAborted();let s=this.determineStrategy(e,t);if(s==="network-only")return{response:await a(e),fromCache:!1,revalidated:!1};let o=t.cacheMaxEntries??i4;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError("webrequest cacheMaxEntries must be a positive safe integer");if(t.cacheMaxAge!==void 0&&(!Number.isSafeInteger(t.cacheMaxAge)||t.cacheMaxAge<0))throw new RangeError("webrequest cacheMaxAge must be a non-negative safe integer");let n=t.timeout??6e4,l=new AbortController,c=setTimeout(()=>{l.abort(Hh(e.url,n))},Math.max(0,n)),d=AbortSignal.any([e.signal,this.lifecycleController.signal,l.signal]);try{let u=this.generateCacheKey(e,t),p=Xnt(s),m={request:e,cacheKey:u,cacheStore:this.cacheStore,fetchFn:a,logging:t.logging,signal:d,cacheMaxAge:t.cacheMaxAge,cacheMaxEntries:o,scheduleBackgroundRevalidation:i(b=>{this.scheduleBackgroundRevalidation(u,e.url,n,b)},"scheduleBackgroundRevalidation")};return await p.execute(m)}finally{clearTimeout(c)}}determineStrategy(e,t){return t.cacheStrategy?t.cacheStrategy:t.cache?this.mapCacheModeToStrategy(t.cache):e.cache?this.mapCacheModeToStrategy(e.cache):"network-first"}mapCacheModeToStrategy(e){switch(e){case"default":return"network-first";case"no-store":case"reload":return"network-only";case"no-cache":return"network-first";case"force-cache":return"cache-first";case"only-if-cached":return"cache-only";default:return"network-first"}}generateCacheKey(e,t){return t.cacheKey?typeof t.cacheKey=="function"?t.cacheKey(e):t.cacheKey:this.cacheStore.generateCacheKey(e)}async clear(){await this.cacheStore.clear()}async delete(e){await this.cacheStore.delete(e)}async has(e){return await this.cacheStore.has(e)}getStore(){return this.cacheStore}scheduleBackgroundRevalidation(e,t,a,s){if(this.disposed||this.backgroundRevalidations.has(e))return;let o=new AbortController,n=AbortSignal.any([this.lifecycleController.signal,o.signal]),l=setTimeout(()=>{o.abort(Hh(t,a))},Math.max(0,a)),c;c=s(n).catch(()=>{}).finally(()=>{clearTimeout(l),this.backgroundRevalidations.get(e)===c&&this.backgroundRevalidations.delete(e)}),this.backgroundRevalidations.set(e,c)}close(){if(this.closePromise)return this.closePromise;this.disposed=!0,this.lifecycleController.abort(this.closeReason);let e=[...this.backgroundRevalidations.values()];return this.closePromise=(async()=>{await Promise.allSettled(e),await this.cacheStore.close()})(),this.closePromise}}});function elt(r){switch(r){case"exponential":return new Mee;case"linear":return new qhe;case"constant":return new Hhe;default:return new Mee}}function tlt(r,e=.1){let t=r*e*Math.random();return r+t}var Mee,qhe,Hhe,rlt=h(()=>{Mee=class{static{i(this,"ExponentialBackoff")}calculate(e,t,a){let s=t*Math.pow(2,e-1);return Math.min(s,a)}},qhe=class{static{i(this,"LinearBackoff")}calculate(e,t,a){let s=t*e;return Math.min(s,a)}},Hhe=class{static{i(this,"ConstantBackoff")}calculate(e,t,a){return Math.min(t,a)}};i(elt,"getBackoffCalculator");i(tlt,"addJitter")});var j2,Vhe=h(()=>{s4();rlt();j2=class{static{i(this,"RetryManager")}constructor(e={},t){this.signal=t,this.options={maxAttempts:e.maxAttempts??3,backoff:e.backoff??"exponential",initialDelay:e.initialDelay??1e3,maxDelay:e.maxDelay??3e4,retryOn:e.retryOn??[408,429,500,502,503,504],onRetry:e.onRetry??(()=>{})}}async execute(e,t){let a;for(let s=1;s<=this.options.maxAttempts;s++){this.throwIfAborted();try{let o=await e();if(o instanceof Response&&this.shouldRetryResponse(o)){if(s===this.options.maxAttempts)return o;await this.cancelResponseBody(o,`Retrying after HTTP ${o.status}`);let n=this.calculateDelay(s);this.options.onRetry(s,new Error(`HTTP ${o.status}`),n),await this.delay(n);continue}return o}catch(o){if(this.signal?.aborted)throw this.getAbortError();a=o instanceof Error?o:new Error(String(o));let n=t?t(o,s):this.shouldRetryError(o);if(s===this.options.maxAttempts||!n)throw a;let l=this.calculateDelay(s);this.options.onRetry(s,a,l),await this.delay(l)}}throw a||new Error("Max retry attempts reached")}async executeWithFallbacks(e,t,a){if(e.length===0)throw new Error("No URLs provided for fallback execution");let s,o=[];for(let n of e){this.throwIfAborted();try{let l=await this.execute(async()=>await a(n,t));if(l.status<400||l.status>=400&&l.status<500&&l.status!==408)return l;await this.cancelResponseBody(l,`Trying fallback after HTTP ${l.status}`),o.push(n),s=new Error(`Request failed with status ${l.status}`)}catch(l){if(this.signal?.aborted)throw this.getAbortError();o.push(n),s=l instanceof Error?l:new Error(String(l))}}throw new Error(`All URLs failed: ${o.join(", ")}. Last error: ${s?.message||"Unknown error"}`)}shouldRetryResponse(e){let t=this.options.retryOn;return typeof t=="function"?t(e):Array.isArray(t)?t.includes(e.status):!1}shouldRetryError(e){if(e instanceof TypeError&&e.message.includes("fetch")||e.name==="AbortError"||e.message.includes("timeout"))return!0;let t=this.options.retryOn;return typeof t=="function"?t(void 0,e):!1}calculateDelay(e){let a=elt(this.options.backoff).calculate(e,this.options.initialDelay,this.options.maxDelay);return tlt(a)}async delay(e){if(!this.signal){await sr.delayFor(e);return}if(this.signal.aborted)throw this.getAbortError();let t=new sr.Timeout(e,null),a,s=new Promise((n,l)=>{a=l}),o=i(()=>{t.cancel(),a(this.getAbortError())},"abortListener");try{this.signal.addEventListener("abort",o,{once:!0}),this.signal.aborted&&o(),await Promise.race([t.promise,s])}finally{t.cancel(),this.signal.removeEventListener("abort",o)}}async cancelResponseBody(e,t){await e.body?.cancel(t).catch(()=>{})}throwIfAborted(){if(this.signal?.aborted)throw this.getAbortError()}getAbortError(){if(this.signal?.reason instanceof Error)return this.signal.reason;let e=new Error("The request was aborted");return e.name="AbortError",e}}});var U2,jhe=h(()=>{s4();U2=class{static{i(this,"RequestDeduplicator")}constructor(){this.inFlightRequests=new Map}generateKey(e){let t=e.url,a=e.method;return a==="GET"||a==="HEAD"?`${a}:${t}`:`${a}:${t}:${Date.now()}`}async execute(e,t){let a=this.inFlightRequests.get(e);if(a){let o=await a.promise;return{response:this.cloneValue(o),wasDeduplicated:!0}}let s=kt.defer();this.inFlightRequests.set(e,s);try{let o=await t();return s.resolve(o),this.inFlightRequests.delete(e),{response:o,wasDeduplicated:!1}}catch(o){throw s.reject(o),this.inFlightRequests.delete(e),o}}isInFlight(e){return this.inFlightRequests.has(e)}getInFlightCount(){return this.inFlightRequests.size}clear(){this.inFlightRequests.clear()}cloneValue(e){return e instanceof Response?e.clone():{...e,response:e.response.clone()}}}});var ig,rFt,Uhe=h(()=>{vhe();Fhe();Vhe();jhe();l4();ig=class{static{i(this,"WebrequestClient")}constructor(e={}){this.closeReason=new Error("Webrequest client is closed"),this.disposed=!1,this.defaultOptions=e,this.interceptorManager=new O2,this.cacheManager=new V2,this.deduplicator=new U2}addRequestInterceptor(e){this.interceptorManager.addRequestInterceptor(e)}addResponseInterceptor(e){this.interceptorManager.addResponseInterceptor(e)}addErrorInterceptor(e){this.interceptorManager.addErrorInterceptor(e)}removeRequestInterceptor(e){this.interceptorManager.removeRequestInterceptor(e)}removeResponseInterceptor(e){this.interceptorManager.removeResponseInterceptor(e)}removeErrorInterceptor(e){this.interceptorManager.removeErrorInterceptor(e)}clearInterceptors(){this.interceptorManager.clearAll()}async clearCache(){await this.cacheManager.clear()}async deleteCache(e){await this.cacheManager.delete(e)}async request(e,t={}){return(await this.requestWithMetadata(e,t)).response}async requestWithMetadata(e,t={}){if(this.disposed)throw this.closeReason;let a={...this.defaultOptions,...t},s;if(typeof e=="string"?s=new Request(e,a):s=e,s=await this.interceptorManager.processRequest(s),a.interceptors?.request)for(let n of a.interceptors.request)s=await n(s);if(a.deduplicate??!1){let n=this.deduplicator.generateKey(s);return(await this.deduplicator.execute(n,async()=>await this.executeRequest(s,a))).response}return await this.executeRequest(s,a)}async executeRequest(e,t){try{let a=typeof t.retry=="object"?t.retry:t.retry?{}:void 0,s=i(async c=>{let d=t.timeout??6e4,u={...t};return delete u.body,delete u.headers,delete u.method,delete u.signal,await zhe(c,{...u,signal:c.signal},d)},"fetchFnForRequest"),o=i(async(c,d)=>{let u=t.timeout??6e4;return await zhe(c,d,u)},"fetchFnForFallbacks"),n;if(a){let c=new j2(a,t.signal);if(t.fallbackUrls&&t.fallbackUrls.length>0){let d=[e.url,...t.fallbackUrls];n={response:await c.executeWithFallbacks(d,{method:e.method,headers:e.headers,body:e.body,...t},o),fromCache:!1,revalidated:!1}}else{let d,u=await c.execute(async()=>{let p=await this.cacheManager.execute(e,t,s);return d=p,p.response});n=d?.response===u?d:{response:u,fromCache:!1,revalidated:!1}}}else n=await this.cacheManager.execute(e,t,s);let l=await this.interceptorManager.processResponse(n.response);if(t.interceptors?.response)for(let c of t.interceptors.response)l=await c(l);return rFt(l,n)}catch(a){throw await this.interceptorManager.processError(a instanceof Error?a:new Error(String(a)))}}async close(){return this.closePromise?this.closePromise:(this.disposed=!0,this.closePromise=this.cacheManager.close(),this.closePromise)}async requestJsonWithMetadata(e,t){let a={...this.defaultOptions,...t},s=a.timeout??6e4,o=a.retry?void 0:performance.now()+s,n=o===void 0?void 0:new AbortController,l=n?a.signal?AbortSignal.any([a.signal,n.signal]):n.signal:a.signal,c=n===void 0?void 0:setTimeout(()=>{n.abort(Hh(e,s))},Math.max(0,s));try{let d=await this.requestWithMetadata(e,{...t,signal:l}),u=d.response;if(l?.aborted)throw await u.body?.cancel(l.reason).catch(()=>{}),l.reason instanceof Error?l.reason:new Error("The request was aborted");if(!u.ok)throw await u.body?.cancel(`HTTP ${u.status}`).catch(()=>{}),new Error(`HTTP ${u.status}: ${u.statusText}`);let p=o===void 0?s:o-performance.now(),m=await Znt(u,{bodyTimeoutMs:p,reportedTimeoutMs:s,signal:l,url:e});return Object.freeze({data:m,response:u,metadata:d.metadata})}catch(d){throw l?.aborted&&l.reason instanceof Error?l.reason:d}finally{c!==void 0&&clearTimeout(c)}}async getJson(e,t={}){return(await this.getJsonWithMetadata(e,t)).data}async getJsonWithMetadata(e,t={}){return await this.requestJsonWithMetadata(e,{...t,method:"GET",headers:{Accept:"application/json",...t.headers||{}}})}async postJson(e,t,a={}){return(await this.postJsonWithMetadata(e,t,a)).data}async postJsonWithMetadata(e,t,a={}){return await this.requestJsonWithMetadata(e,{...a,method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers||{}},body:JSON.stringify(t)})}async putJson(e,t,a={}){return(await this.putJsonWithMetadata(e,t,a)).data}async putJsonWithMetadata(e,t,a={}){return await this.requestJsonWithMetadata(e,{...a,method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json",...a.headers||{}},body:JSON.stringify(t)})}async deleteJson(e,t={}){return(await this.deleteJsonWithMetadata(e,t)).data}async deleteJsonWithMetadata(e,t={}){return await this.requestJsonWithMetadata(e,{...t,method:"DELETE",headers:{Accept:"application/json",...t.headers||{}}})}},rFt=i((r,e)=>{let t=Object.freeze({fromCache:e.fromCache,revalidated:e.revalidated});return Object.freeze({response:r,metadata:t})},"createResponseResult")});async function _i(r,e){let t=r instanceof Request?r.url:String(r),a=r instanceof Request?r:new Request(t,e);return await po.request(a,e)}var po,alt=h(()=>{Uhe();po=new ig;i(_i,"webrequest"),_i.requestWithMetadata=async function(r,e){let t=r instanceof Request?r.url:String(r),a=r instanceof Request?r:new Request(t,e);return await po.requestWithMetadata(a,e)},_i.getJson=async function(r,e){return await po.getJson(r,e)},_i.getJsonWithMetadata=async function(r,e){return await po.getJsonWithMetadata(r,e)},_i.postJson=async function(r,e,t){return await po.postJson(r,e,t)},_i.postJsonWithMetadata=async function(r,e,t){return await po.postJsonWithMetadata(r,e,t)},_i.putJson=async function(r,e,t){return await po.putJson(r,e,t)},_i.putJsonWithMetadata=async function(r,e,t){return await po.putJsonWithMetadata(r,e,t)},_i.deleteJson=async function(r,e){return await po.deleteJson(r,e)},_i.deleteJsonWithMetadata=async function(r,e){return await po.deleteJsonWithMetadata(r,e)},_i.addRequestInterceptor=function(r){po.addRequestInterceptor(r)},_i.addResponseInterceptor=function(r){po.addResponseInterceptor(r)},_i.addErrorInterceptor=function(r){po.addErrorInterceptor(r)},_i.clearInterceptors=function(){po.clearInterceptors()},_i.clearCache=async function(){await po.clearCache()},_i.createClient=function(r){return new ig(r)},_i.getDefaultClient=function(){return po}});var Vh={};St(Vh,{CacheManager:()=>V2,CacheStore:()=>F2,InterceptorManager:()=>O2,RequestDeduplicator:()=>U2,RetryManager:()=>j2,WebrequestClient:()=>ig,createConditionalHeaders:()=>_ee,defaultCacheMaxEntries:()=>i4,extractCacheMetadata:()=>wd,headersToObject:()=>Cee,isFresh:()=>See,isWebrequestTimeoutError:()=>n4,objectToHeaders:()=>Gnt,requiresRevalidation:()=>q2,webrequest:()=>_i});var Whe=h(()=>{alt();Uhe();Fhe();o4();Vhe();vhe();jhe();l4();Rhe()});var Pu,og=h(()=>{l2();Pu=rl(sQ(),1);H_();bnt();wh();vnt();Po();Whe()});var dl,W2=h(()=>{dl=class extends Error{static{i(this,"TypedResponseError")}constructor(e,t){super(e),this.name="TypedResponseError",this.errorText=e,this.errorData=t??{}}}});var $ee,slt=h(()=>{W2();og();$ee=class{static{i(this,"TypedTools")}constructor(){this.localData={}}async passGuards(e,t){let a=new J_.GuardSet(e);if(!await a.allGuardsPass(t)){let o=await a.getFailedHint(t);throw new dl(`guard failed: ${o}`,{failedHint:o})}}}});var Ghe,Khe=h(()=>{og();W2();slt();Ghe=class r{static{i(this,"TypedHandler")}static{this.internalErrorMessage="Internal server error"}constructor(e,t){this.method=e,this.handlerFunction=t}async addResponse(e){if(e.method!==this.method)throw new Error("this handler has been given a wrong method to answer to. Please use a TypedRouter to filter requests");let t,a=new $ee;e.localData&&(a.localData=e.localData);let s=await this.handlerFunction(e.request,a).catch(o=>{o instanceof dl?t=o:(console.error(`TypedRequest handler '${this.method}' failed`),t=new dl(r.internalErrorMessage))});return t&&(e.error={text:t.errorText,data:t.errorData}),s&&(e.response=s),e?.correlation?.phase&&(e.correlation.phase="response"),e}}});var G2,Yhe=h(()=>{G2=Object.freeze({redacted:!0})});var ilt,olt,nlt,Eee,aFt,Pee,Aee,K2,clt,dlt,ult,plt,hlt,Dee,Zhe,sFt,llt,Y2,iFt,oFt,nFt,lFt,cFt,Z2,Qhe=h(()=>{Yhe();ilt=Object.freeze(["onOutgoingRequest","onIncomingResponse","onIncomingRequest","onOutgoingResponse"]),olt=Symbol.for("@api.global/typedrequest:global-hooks:3.8"),nlt=i(r=>({payloadProjector:r?.payloadProjector,errorProjector:r?.errorProjector}),"copyProjectionOptions"),Eee=i((r={})=>({hooks:r,projectedRegistrationsByPhase:{}}),"createTypedRouterHookRegistrationState"),aFt=i(r=>ilt.filter(e=>Object.hasOwn(r,e)).map(e=>[e,r[e]]),"getSuppliedHookEntries"),Pee=i((r,e,t)=>{let a=aFt(e);r.hooks={...r.hooks,...e};for(let[s]of a){let o=r.hooks[s];if(typeof o!="function"){delete r.projectedRegistrationsByPhase[s];continue}r.projectedRegistrationsByPhase[s]={callback:o,projectionOptions:nlt(t)}}},"mergeTypedRouterHookRegistrations"),Aee=i((r,e)=>{r.hooks=e;for(let t of ilt)delete r.projectedRegistrationsByPhase[t]},"replaceTypedRouterHookRegistrations"),K2=i(()=>{let r=globalThis[olt];if(r?.version==="3.8"&&r.stateShape==="callback-bound-projections-v1"&&r.subscribers instanceof Map)return r;let e={version:"3.8",stateShape:"callback-bound-projections-v1",legacy:Eee(),subscribers:new Map};return globalThis[olt]=e,e},"getRealmGlobalHookState"),clt=i(()=>K2().legacy.hooks,"getLegacyGlobalHooks"),dlt=i(r=>{Aee(K2().legacy,r)},"replaceLegacyGlobalHooks"),ult=i((r,e)=>{Pee(K2().legacy,r,e)},"mergeLegacyGlobalHooks"),plt=i((r,e)=>{let t=K2(),a=Symbol("typedrequest-hook-subscriber"),s=Eee();Pee(s,r,e),t.subscribers.set(a,s);let o=!1;return()=>{o||(o=!0,t.subscribers.delete(a))}},"addGlobalHookSubscriber"),hlt=i(()=>{let r=K2();Aee(r.legacy,{}),r.subscribers.clear()},"clearGlobalHookRegistrations"),Dee=i(r=>{try{console.error(`TypedRequest hook projection failed (${r})`)}catch{}},"logProjectionFailure"),Zhe=i(r=>{try{console.error(`TypedRequest hook callback failed (${r})`)}catch{}},"logCallbackFailure"),sFt=i((r,e)=>{let t={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0};try{return Object.freeze(t)}catch{Dee(e);return}},"createMetadata"),llt=i(r=>typeof SharedArrayBuffer>"u"?!1:r instanceof SharedArrayBuffer||Object.prototype.toString.call(r)==="[object SharedArrayBuffer]","isSharedArrayBuffer"),Y2=i((r,e=new Set)=>{if(!(r===null||typeof r!="object"&&typeof r!="function")){if(llt(r))throw new TypeError("TypedRequest hook projections cannot contain SharedArrayBuffer");if(ArrayBuffer.isView(r)){if(llt(r.buffer))throw new TypeError("TypedRequest hook projections cannot contain SharedArrayBuffer-backed views");return}if(!e.has(r)){if(e.add(r),r instanceof Map){for(let[t,a]of r)Y2(t,e),Y2(a,e);return}if(r instanceof Set){for(let t of r)Y2(t,e);return}for(let t of Reflect.ownKeys(r)){let a=Reflect.getOwnPropertyDescriptor(r,t);if(a){if(!Object.hasOwn(a,"value"))throw new TypeError("TypedRequest hook projections cannot contain accessor properties");Y2(a.value,e)}}}}},"assertNoSharedArrayBuffer"),iFt=i((r,e,t,a)=>{if(!e||!t.payloadProjector)return{payload:G2,payloadRedacted:!0};try{let s=t.payloadProjector(r,e);Y2(s);let o=structuredClone(s);return Y2(o),o!==null&&(typeof o=="object"||typeof o=="function")&&Object.freeze(o),{payload:o,payloadRedacted:!1}}catch{return Dee(a),{payload:G2,payloadRedacted:!0}}},"snapshotPayload"),oFt=i((r,e,t,a)=>{if(!(!e||r.errorText===void 0||!t.errorProjector))try{let s=t.errorProjector(r.errorText,e);if(s===void 0)return;let o=structuredClone(s);if(typeof o!="string")throw new TypeError("TypedRequest error projector must return a string or undefined");return o}catch{Dee(a);return}},"snapshotError"),nFt=i((r,e,t)=>{let a=sFt(r,t),s=iFt(r.payload,a,e,t),o=oFt(r,a,e,t),n={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0,...s,...o===void 0?{}:{error:o}};try{return Object.freeze(n)}catch{Dee(t);let l={correlationId:r.correlationId,method:r.method,direction:r.direction,phase:r.phase,timestamp:r.timestamp,...r.durationMs===void 0?{}:{durationMs:r.durationMs},hasError:r.errorText!==void 0,payload:G2,payloadRedacted:!0};try{return Object.freeze(l)}catch{return l}}},"projectLogEntry"),lFt=i((r,e)=>{try{let t=r.hooks[e];if(typeof t!="function")return;let a=r.projectedRegistrationsByPhase[e];return{callback:t,projectionOptions:a?.callback===t?nlt(a.projectionOptions):{}}}catch{Zhe(e);return}},"snapshotDispatchRecipient"),cFt=i((r,e,t)=>{let a=nFt(t,r.projectionOptions,e);try{let s=r.callback(a);s&&typeof s.then=="function"&&Promise.resolve(s).catch(()=>{Zhe(e)})}catch{Zhe(e)}},"dispatchToRecipient"),Z2=i((r,e,t)=>{let a=K2(),o=[a.legacy,...Array.from(a.subscribers.values()),...t?[t]:[]].map(n=>lFt(n,r)).filter(n=>!!n);for(let n of o)cFt(n,r,e)},"dispatchTypedRequestHook")});var d4,Ree=h(()=>{og();zee();Khe();Xhe();W2();Qhe();Yhe();d4=class r{static{i(this,"TypedRouter")}constructor(){this.hookRegistrationState=Eee(),this.routerMap=new Fs.ObjectMap,this.fallbackRouterMap=new Fs.ObjectMap,this.fallbackParentRouters=new Set,this.handlerMap=new Fs.ObjectMap,this.registeredVirtualStreams=new Fs.ObjectMap,this.middlewares=[],this.fireEventInterestMap=new Fs.InterestMap(e=>e)}static{this.internalErrorMessage="Internal server error"}static get globalHooks(){return clt()}static set globalHooks(e){dlt(e)}static setGlobalHooks(e,t){ult(e,t)}static addGlobalHooks(e,t){return plt(e,t)}static clearGlobalHooks(){hlt()}get hooks(){return this.hookRegistrationState.hooks}set hooks(e){Aee(this.hookRegistrationState,e)}setHooks(e,t){Pee(this.hookRegistrationState,e,t)}callHook(e,t){Z2(e,t,this.hookRegistrationState)}setErrorFromCaughtError(e,t,a){if(t instanceof dl){e.error={text:t.errorText,data:t.errorData??{}};return}console.error(`TypedRequest ${a} failed`),e.error={text:r.internalErrorMessage,data:{}}}getRegisteredVirtualStreamById(e){return this.registeredVirtualStreams.findSync(t=>t.streamId===e)}registerVirtualStream(e){let t=this.getRegisteredVirtualStreamById(e.streamId);return t||(this.registeredVirtualStreams.add(e),e)}unregisterVirtualStream(e){this.registeredVirtualStreams.remove(e)}addMiddleware(e){this.middlewares.push(e)}addTypedHandler(e){if(this.getTypedHandlerForMethod(e.method))throw new Error(`a TypedHandler for ${e.method} alredy exists! Can't add another one.`);this.handlerMap.add(e);try{this.validateAffectedCompositionRoots()}catch(a){throw this.handlerMap.remove(e),a}}addTypedRouter(e){if(e===this)throw new Error("A TypedRouter cannot be composed with itself.");if(!this.routerMap.findSync(a=>a===e)){let a=this.canReachRouter(e),s=e.canReachRouter(this);if(a!==s)throw new Error("Cannot add a bidirectional TypedRouter edge across an existing composition boundary.");this.routerMap.add(e),e.routerMap.add(this);try{this.validateAffectedCompositionRoots()}catch(o){throw this.routerMap.remove(e),e.routerMap.remove(this),o}}}addFallbackRouter(e){if(e===this)throw new Error("A TypedRouter cannot use itself as a fallback.");if(this.fallbackRouterMap.findSync(a=>a===e))return()=>{};if(e.canReachRouter(this))throw new Error("Adding this fallback would create a TypedRouter composition cycle.");this.fallbackRouterMap.add(e),e.fallbackParentRouters.add(this);try{this.validateAffectedCompositionRoots()}catch(a){throw this.fallbackRouterMap.remove(e),e.fallbackParentRouters.delete(this),a}let t=!1;return()=>{t||(t=!0,this.fallbackRouterMap.remove(e),e.fallbackParentRouters.delete(this))}}getMethodNames(){return[...this.collectReachableHandlers().keys()].sort()}canReachRouter(e,t=new Set){if(this===e)return!0;if(t.has(this))return!1;t.add(this);for(let a of[...this.routerMap.getArray(),...this.fallbackRouterMap.getArray()])if(a.canReachRouter(e,t))return!0;return!1}collectReachableHandlers(e=new Set,t=new Map){if(e.has(this))return t;e.add(this);for(let a of this.handlerMap.getArray()){let s=t.get(a.method);s||(s=new Set,t.set(a.method,s)),s.add(this)}for(let a of[...this.routerMap.getArray(),...this.fallbackRouterMap.getArray()])a.collectReachableHandlers(e,t);return t}getAffectedCompositionRoots(){let e=new Set,t=[this];for(;t.length>0;){let a=t.pop();e.has(a)||(e.add(a),t.push(...a.routerMap.getArray(),...a.fallbackParentRouters))}return e}validateAffectedCompositionRoots(){for(let e of this.getAffectedCompositionRoots())for(let[t,a]of e.collectReachableHandlers())if(a.size>1)throw new Error(`TypedRouter composition exposes more than one handler for method "${t}".`)}checkForTypedHandler(e){return!!this.getTypedHandlerForMethod(e)}getTypedHandlerForMethod(e,t=[]){t.push(this);let a;return a=this.handlerMap.findSync(s=>s.method===e),a||this.routerMap.getArray().forEach(s=>{!a&&!t.includes(s)&&(a=s.getTypedHandlerForMethod(e,t))}),a||this.fallbackRouterMap.getArray().forEach(s=>{!a&&!t.includes(s)&&(a=s.getTypedHandlerForMethod(e,t))}),a}getTypedHandlerAndRouter(e,t=[]){t.push(this);let a=this.handlerMap.findSync(s=>s.method===e);if(a)return{handler:a,router:this};for(let s of this.routerMap.getArray())if(!t.includes(s)){let o=s.getTypedHandlerAndRouter(e,t);if(o)return o}for(let s of this.fallbackRouterMap.getArray())if(!t.includes(s)){let o=s.getTypedHandlerAndRouter(e,t);if(o)return o}return null}static{this.defaultRouteOptions={localRequest:!1,skipHooks:!1}}async routeAndAddResponse(e,t={}){let a={...r.defaultRouteOptions,...t};if(e=Rn.decodePayloadFromNetwork(e,{typedrouter:this}),e.localData=a.trustedLocalData?{...a.trustedLocalData}:e.localData||{},e.localData.firstTypedrouter=this,e.method==="##VirtualStream##"){let s=await this.handleStreamTypedRequest(e);return s.localData=null,s}if(e?.correlation?.phase==="request"||a.localRequest){let s=Date.now();a.skipHooks||this.callHook("onIncomingRequest",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"incoming",phase:"request",timestamp:s,payload:e.request});let o=this.getTypedHandlerAndRouter(e.method);if(!o)return console.log(`Cannot find handler for methodname ${e.method}`),e.error={text:"There is no available method for this call on the server side",data:{}},e.correlation.phase="response",e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e;let{handler:n,router:l}=o;if(l.middlewares.length>0)try{for(let c of l.middlewares)await c(e)}catch(c){return this.setErrorFromCaughtError(e,c,`middleware for method '${e.method}'`),e.correlation.phase="response",e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e}return e=await n.addResponse(e),e.localData=void 0,e=Rn.encodePayloadForNetwork(e,{typedrouter:this}),a.skipHooks||this.callHook("onOutgoingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"outgoing",phase:"response",timestamp:Date.now(),durationMs:Date.now()-s,payload:e.response,errorText:e.error?.text}),e}else return e?.correlation?.phase==="response"?(a.skipHooks||this.callHook("onIncomingResponse",{correlationId:e.correlation?.id||"unknown",method:e.method,direction:"incoming",phase:"response",timestamp:Date.now(),payload:e.response,errorText:e.error?.text}),this.fireEventInterestMap.findInterest(e.correlation.id)?.fullfillInterest(e),null):(console.log("TypedRouter received a malformed request DTO"),null)}async handleStreamTypedRequest(e){let t=this.getRegisteredVirtualStreamById(e.request.streamId);return t?t.handleStreamTr(e):(e.response={streamId:e.request.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:"end",keepAlive:!1,next:!1,backpressure:!1},e)}}});var Q2,jh,u4,Rn,zee=h(()=>{og();Ree();Q2="#############CLOSING BIT#############",jh=class extends Error{static{i(this,"VirtualStreamClosedError")}constructor(e="VirtualStream is closed",t){super(e,t),this.name="VirtualStreamClosedError"}},u4=class{static{i(this,"VirtualStreamActivationScope")}constructor(){this.trackedStreams=new Set,this.settled=!1}track(e){this.settled||this.trackedStreams.add(e)}commit(){let e=[...this.trackedStreams];this.settled=!0,this.trackedStreams.clear();for(let t of e)t.commitActivation()}async rollback(e){if(this.settled)return;this.settled=!0;let t=[...this.trackedStreams];this.trackedStreams.clear(),await Promise.all(t.map(a=>a.abort(e)))}},Rn=class r{static{i(this,"VirtualStream")}constructor(){this.streamId=Pu.uni(),this.lifecycleStateInternal="idle",this.keepAlive=!0,this.sendAdmissionTail=Promise.resolve(),this.frameAdmissionTail=Promise.resolve(),this.closeStarted=!1,this.activationCommitted=!1,this.activationResolvers=new Set,this.respondingDrainResolvers=new Set,this.sendBackpressuredArray=new Fs.BackpressuredArray(16),this.receiveBackpressuredArray=new Fs.BackpressuredArray(16)}static{this.respondingRegistrationIdleTimeoutMs=15e3}static{this.gracefulCloseTimeoutMs=1e4}static encodePayloadForNetwork(e,t,a,s=[]){return!e||rg.isBufferLike(e)?e:e instanceof r?(e.activate(t),!a?.response||s.includes("response")?{_isVirtualStream:!0,streamId:e.streamId}:{_OBMITTED_VIRTUAL_STREAM:!0,reason:"path is under .request: omitted for deduplication reasons in response cycle."}):Array.isArray(e)?e.map((o,n)=>r.encodePayloadForNetwork(o,t,a||e,s.concat(String(n)))):e!==null&&typeof e=="object"?e instanceof Set||e instanceof Map||e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof Promise||typeof e.then=="function"?e:Object.entries(e).reduce((o,[n,l])=>(o[n]=r.encodePayloadForNetwork(l,t,a||e,s.concat(n)),o),{}):e}static decodePayloadFromNetwork(e,t){return r.decodePayloadFromNetworkInternal(e,t,new Map)}static containsNetworkDescriptor(e){return!e||rg.isBufferLike(e)||typeof e!="object"?!1:e._isVirtualStream===!0?!0:Array.isArray(e)?e.some(t=>r.containsNetworkDescriptor(t)):Object.values(e).some(t=>r.containsNetworkDescriptor(t))}static decodePayloadFromNetworkInternal(e,t,a){if(rg.isBufferLike(e)||e instanceof d4||e===null||typeof e!="object"||e instanceof Set||e instanceof Map||e instanceof Date||e instanceof RegExp||e instanceof Error||e instanceof Promise||typeof e.then=="function")return e;if(e._isVirtualStream===!0){if(typeof e.streamId!="string"||e.streamId.length===0)throw new TypeError("VirtualStream network descriptor requires a non-empty streamId");let s=a.get(e.streamId);if(s)return s;let o=t.typedrouter?.getRegisteredVirtualStreamById(e.streamId);if(o)return o.refreshRespondingRegistration(),a.set(e.streamId,o),o;let n=new r;return n.streamId=e.streamId,n.activate(t),a.set(e.streamId,n),n}return Array.isArray(e)?e.map(s=>r.decodePayloadFromNetworkInternal(s,t,a)):Object.keys(e).reduce((s,o)=>(s[o]=r.decodePayloadFromNetworkInternal(e[o],t,a),s),{})}get lifecycleState(){return this.lifecycleStateInternal}activate(e){if(this.lifecycleStateInternal==="closed")throw this.getCloseError();let t=e.sendMethod?"requesting":e.typedrouter?"responding":void 0;if(!t)throw new Error("VirtualStream requires a send method or TypedRouter");if(this.lifecycleStateInternal==="active"&&this.side!==t)throw new Error(`VirtualStream ${this.streamId} is already active on the ${this.side} side`);let a=this.lifecycleStateInternal==="idle";if(this.lifecycleStateInternal="active",this.keepAlive=!0,this.side=t,t==="requesting")this.sendMethod=e.sendMethod;else{if(this.typedrouter=e.typedrouter,this.typedrouter.registerVirtualStream(this)!==this)throw this.lifecycleStateInternal="idle",this.typedrouter=void 0,new Error(`VirtualStream ${this.streamId} is already registered on this router`);this.refreshRespondingRegistration()}a&&(e.activationScope?e.activationScope.track(this):this.commitActivation())}commitActivation(){if(this.lifecycleStateInternal==="active"&&this.side==="requesting"){this.activationCommitted=!0;let e=[...this.activationResolvers];this.activationResolvers.clear();for(let t of e)t();this.startKeepAliveLoop(),this.ensureQueueWork()}}getCloseError(e){return this.closeError||(this.closeError=new jh("VirtualStream is closed",e===void 0?void 0:{cause:e})),this.closeError}assertNotClosed(){if(this.lifecycleStateInternal==="closed")throw this.getCloseError()}assertCanSend(){if(this.assertNotClosed(),this.closeStarted)throw new jh("VirtualStream is closing")}async acquireSendAdmission(){let e=this.sendAdmissionTail,t;return this.sendAdmissionTail=new Promise(a=>{t=a}),await e,t}async acquireFrameAdmission(){let e=this.frameAdmissionTail,t;return this.frameAdmissionTail=new Promise(a=>{t=a}),await e,t}async waitForOutboundDrain(){for(;this.sendBackpressuredArray.data.length>0||this.queueWorkPromise;){this.assertNotClosed(),this.ensureQueueWork();let e=this.queueWorkPromise;e?await e:this.activationCommitted||await new Promise(t=>{this.activationResolvers.add(t)})}this.assertNotClosed()}async waitWithinGracefulCloseDeadline(e){let t,a=new Promise((s,o)=>{t=setTimeout(()=>{o(new jh("VirtualStream graceful close timed out"))},r.gracefulCloseTimeoutMs),t.unref?.()});try{await Promise.race([e,a])}finally{t&&clearTimeout(t)}}async waitForRespondingDrain(){this.sendBackpressuredArray.data.length!==0&&await new Promise(e=>{this.respondingDrainResolvers.add(e)})}resolveRespondingDrain(){if(this.sendBackpressuredArray.data.length>0)return;let e=[...this.respondingDrainResolvers];this.respondingDrainResolvers.clear();for(let t of e)t()}static reconstituteBinaryData(e){if(e==null||e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer(e))return e;if(typeof e=="object"){if(e.type==="EncodedBuffer"&&typeof e.data=="string"&&e.data.startsWith("base64:")){let a=e.data.slice(7);if(typeof Buffer<"u"){let s=Buffer.from(a,"base64");return new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}return new Uint8Array(Array.from(atob(a)).map(s=>s.charCodeAt(0)))}if(e.type==="Buffer"&&Array.isArray(e.data))return new Uint8Array(e.data);let t=Object.keys(e);if(t.length>0&&t.every(a=>/^\d+$/.test(a))){let a=new Array(t.length);for(let s of t)a[Number(s)]=e[s];if(a.every(s=>typeof s=="number"))return new Uint8Array(a)}}return e}ensureQueueWork(){this.lifecycleStateInternal==="closed"||this.side!=="requesting"||!this.activationCommitted||this.queueWorkPromise||(this.queueWorkPromise=this.workOnQueue().catch(async e=>{await this.abort(e)}).finally(()=>{this.queueWorkPromise=void 0,this.lifecycleStateInternal==="active"&&this.side==="requesting"&&this.sendBackpressuredArray.data.length>0&&this.ensureQueueWork()}))}async workOnQueue(){this.assertNotClosed();let e=!this.receiveBackpressuredArray.checkSpaceAvailable(),t=!1,a=!1,s=i(async()=>{let o=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"feedback",next:this.sendBackpressuredArray.data.length>0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable()});this.acceptRemoteResponse(o)&&(a=!!o.response?.backpressure,t=!!o.response?.next)},"getFeedback");for(await s();this.sendBackpressuredArray.data.length>0||t;){for(this.assertNotClosed(),t&&this.sendBackpressuredArray.data.length===0&&!this.receiveBackpressuredArray.checkSpaceAvailable()&&(await this.receiveBackpressuredArray.waitForSpace(),this.assertNotClosed(),e=!this.receiveBackpressuredArray.checkSpaceAvailable());a;)await sr.delayFor(50),this.assertNotClosed(),await s();let o=this.sendBackpressuredArray.data.length>0?this.sendBackpressuredArray.shift():void 0,n=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:o===void 0?"read":"chunk",backpressure:e,next:this.sendBackpressuredArray.data.length>0,...o===void 0?{}:{chunkData:o}});if(!this.acceptRemoteResponse(n))return;a=!!n.response?.backpressure,e=!this.receiveBackpressuredArray.checkSpaceAvailable(),t=!!n.response?.next}}async sendStreamRequest(e){let t=await this.acquireFrameAdmission();try{if(this.assertNotClosed(),!this.sendMethod)throw new Error("VirtualStream is missing a send method");return await this.sendMethod({method:"##VirtualStream##",request:e,response:null})}finally{t()}}acceptRemoteResponse(e){if(this.lifecycleStateInternal==="closed")return!1;let t=e.response?.chunkData;return t!==void 0&&this.receiveBackpressuredArray.push(r.reconstituteBinaryData(t)),e.response?.keepAlive===!1||e.response?.mainPurpose==="end"?(this.terminate(new jh("Remote VirtualStream is closed"),t===Q2),!1):!0}async handleStreamTr(e){if(this.lifecycleStateInternal==="closed")return e.response=this.createClosedResponse(e),e;if(this.refreshRespondingRegistration(),e.request.keepAlive===!1||e.request.mainPurpose==="end")return e.response=this.createClosedResponse(e),await this.abort(),e;let t=e.request.chunkData===Q2;e.request.chunkData!==void 0&&this.receiveBackpressuredArray.push(r.reconstituteBinaryData(e.request.chunkData));let a=!!e.request.backpressure,s=!t&&!a&&this.sendBackpressuredArray.data.length>0?this.sendBackpressuredArray.shift():void 0;this.resolveRespondingDrain();let o=s===Q2;return e.response={streamId:this.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:o?"end":s!==void 0?"chunk":e.request.mainPurpose==="keepAlive"?"keepAlive":"feedback",keepAlive:!o,next:this.sendBackpressuredArray.data.length>0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable(),...s===void 0?{}:{chunkData:s}},(t||o)&&(e.response.mainPurpose="end",e.response.keepAlive=!1,this.terminate(void 0,t)),e}createClosedResponse(e){return{streamId:e.request.streamId,cycleId:e.request.cycleId,cycle:"response",mainPurpose:"end",keepAlive:!1,next:!1,backpressure:!1}}refreshRespondingRegistration(){this.side!=="responding"||this.lifecycleStateInternal!=="active"||(this.respondingExpiryTimer&&clearTimeout(this.respondingExpiryTimer),this.respondingExpiryTimer=setTimeout(()=>{this.abort(new jh("Responding VirtualStream registration expired"))},r.respondingRegistrationIdleTimeoutMs),this.respondingExpiryTimer.unref?.())}async cleanup(){await this.abort()}cleanupRegistration(){if(this.respondingExpiryTimer&&(clearTimeout(this.respondingExpiryTimer),this.respondingExpiryTimer=void 0),this.typedrouter){let e=this.typedrouter;this.typedrouter=void 0,e.unregisterVirtualStream(this)}}startKeepAliveLoop(){this.side!=="requesting"||this.lifecycleStateInternal==="closed"||this.keepAliveLoopPromise||(this.keepAliveLoopPromise=this.runKeepAliveLoop().catch(async e=>{await this.abort(e)}).finally(()=>{this.keepAliveLoopPromise=void 0}))}async runKeepAliveLoop(){for(await sr.delayFor(0);this.keepAlive&&this.lifecycleStateInternal==="active";)await this.triggerKeepAlive(),this.keepAlive&&this.lifecycleStateInternal==="active"&&await sr.delayFor(1e3)}async triggerKeepAlive(){let e=await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"keepAlive",keepAlive:!0,backpressure:!this.receiveBackpressuredArray.checkSpaceAvailable()});this.acceptRemoteResponse(e)&&e.response?.next&&this.ensureQueueWork()}async sendData(e){let t=await this.acquireSendAdmission();try{this.assertCanSend(),await this.sendBackpressuredArray.waitForSpace(),this.assertCanSend(),this.sendBackpressuredArray.push(e),this.ensureQueueWork(),await this.sendBackpressuredArray.waitForSpace(),this.assertCanSend()}finally{t()}}async fetchData(){if(this.receiveBackpressuredArray.checkHasItems())return this.receiveBackpressuredArray.shift();if(this.assertNotClosed(),await this.receiveBackpressuredArray.waitForItems(),!this.receiveBackpressuredArray.checkHasItems())throw this.getCloseError();return this.receiveBackpressuredArray.shift()}async readFromWebstream(e,t=!0){let a=e.getReader();try{let s=!1;for(;!s;){let{value:o,done:n}=await a.read();o!==void 0&&await this.sendData(o),s=n}t&&await this.close(!0)}finally{a.releaseLock()}}async writeToWebstream(e){let t=e.getWriter();try{for(;this.lifecycleStateInternal!=="closed"||this.receiveBackpressuredArray.checkHasItems();){let a=await this.fetchData();if(a===Q2)break;await t.write(a)}await t.close()}finally{t.releaseLock()}}async close(e=!1){if(this.lifecycleStateInternal!=="closed"){if(this.closeStarted=!0,e){if(this.side==="requesting"&&this.sendMethod)try{await this.waitWithinGracefulCloseDeadline(this.waitForOutboundDrain()),await this.sendStreamRequest({streamId:this.streamId,cycleId:Pu.uni(),cycle:"request",mainPurpose:"chunk",chunkData:Q2,next:!1,backpressure:!1})}catch{}else if(this.side==="responding"){this.sendBackpressuredArray.push(Q2);try{await this.waitWithinGracefulCloseDeadline(this.waitForRespondingDrain())}catch{}}}await this.abort()}}async abort(e){this.terminate(e)}terminate(e,t=!1){if(this.lifecycleStateInternal==="closed")return;this.getCloseError(e),this.lifecycleStateInternal="closed",this.keepAlive=!1,this.activationCommitted=!1,this.sendMethod=void 0,this.sendBackpressuredArray.data.length=0,t||(this.receiveBackpressuredArray.data.length=0),this.sendBackpressuredArray.destroy(),this.receiveBackpressuredArray.destroy();let a=[...this.activationResolvers];this.activationResolvers.clear();for(let o of a)o();let s=[...this.respondingDrainResolvers];this.respondingDrainResolvers.clear();for(let o of s)o();this.cleanupRegistration()}}});var Jhe,efe=h(()=>{Ree();og();Jhe=class{static{i(this,"TypedTarget")}constructor(e){if(this.isAsync=!1,e.postMethodWithTypedRouter&&!e.typedRouterRef)throw new Error("you have to specify a typedrouter when using postmethod with typedrouter");let t=e.responseTimeoutMs??3e4;if(!Number.isSafeInteger(t)||t<=0||t>2147483647)throw new RangeError("TypedTarget responseTimeoutMs must be a positive safe integer no greater than 2147483647");this.options=e,this.responseTimeoutMs=t}async post(e,t={}){if(t.signal&&this.options.supportsAbortSignal!==!0)throw new Error("TypedTarget does not declare AbortSignal transport support");let a=this.options.postMethod||this.options.postMethodWithTypedRouter;if(!a)throw new Error("TypedTarget requires a post method");let s;this.options.typedRouterRef&&(s=await this.options.typedRouterRef.fireEventInterestMap.addInterest(e.correlation.id,e));let o=t.signal;if(o?.aborted)throw s?.destroy(),o.reason??new DOMException("The operation was aborted","AbortError");let n,l=o?new Promise((u,p)=>{n=i(()=>{s?.destroy(),p(o.reason??new DOMException("The operation was aborted","AbortError"))},"abortListener"),o.addEventListener("abort",n,{once:!0})}):void 0,c,d=s?new Promise((u,p)=>{c=setTimeout(()=>{p(new Error(`TypedTarget response timed out after ${this.responseTimeoutMs}ms`))},this.responseTimeoutMs),c.unref?.()}):void 0;try{let u=Promise.resolve(a(e,t)),p=await Promise.race([u,...d?[d]:[],...l?[l]:[]]);return s?await Promise.race([s.interestFullfilled,d,...l?[l]:[]]):p||e}finally{c&&clearTimeout(c),o&&n&&o.removeEventListener("abort",n),s?.destroy()}}}});var flt,Lee,mlt,Oee,Bee,p4,Xhe=h(()=>{og();zee();W2();Qhe();efe();flt=new Vh.WebrequestClient,Lee=2147483647,mlt=1e4,Oee=class extends Error{static{i(this,"TypedRequestTimeoutError")}constructor(e,t){super(`Typed request "${e}" timed out after ${t}ms`),this.name="TypedRequestTimeoutError",this.method=e,this.timeoutMs=t}},Bee=class extends Error{static{i(this,"TypedRequestRetryLimitError")}constructor(e,t){super(`Typed request "${e}" exceeded its ${t} server-directed retries`),this.name="TypedRequestRetryLimitError",this.method=e,this.maxRetries=t}},p4=class{static{i(this,"TypedRequest")}constructor(e,t){this.skipHooks=!1,typeof e=="string"?this.urlEndPoint=e:this.typedTarget=e,this.method=t}async fire(e,t=!1){let a=Date.now(),s=this.resolveFireOptions(t),o=new u4,n={method:this.method,request:e,response:null,correlation:{id:Pu.uni(),phase:"request"}};try{n=Rn.encodePayloadForNetwork(n,{sendMethod:i(p=>this.postStreamTrObject(p),"sendMethod"),activationScope:o});let l=Rn.containsNetworkDescriptor(n);if(l&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("VirtualStreams require TypedTarget AbortSignal transport support");if(s.useCache&&l)throw new Error("TypedRequest response caching is not supported for requests containing VirtualStreams");this.assertDeadline(s),s.useCache&&(s.cacheKey=await this.createCacheKey(n),this.assertDeadline(s)),this.skipHooks||Z2("onOutgoingRequest",{correlationId:n.correlation.id,method:this.method,direction:"outgoing",phase:"request",timestamp:a,payload:e});let c=await this.postTrObject(n,s),d=c.error;if(this.assertDeadline(s),d)throw this.skipHooks||Z2("onIncomingResponse",{correlationId:n.correlation.id,method:this.method,direction:"incoming",phase:"response",timestamp:Date.now(),durationMs:Date.now()-a,payload:c.response,errorText:d.text}),this.assertDeadline(s),new dl(d.text,d.data);let u=Rn.containsNetworkDescriptor(c);if(u&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("VirtualStreams require TypedTarget AbortSignal transport support");return s.useCache&&s.cacheKey&&u&&(await flt.deleteCache(s.cacheKey),this.assertDeadline(s)),c=Rn.decodePayloadFromNetwork(c,{sendMethod:i(p=>this.postStreamTrObject(p),"sendMethod"),activationScope:o}),this.assertDeadline(s),this.skipHooks||Z2("onIncomingResponse",{correlationId:n.correlation.id,method:this.method,direction:"incoming",phase:"response",timestamp:Date.now(),durationMs:Date.now()-a,payload:c?.response}),this.assertDeadline(s),o.commit(),c.response}catch(l){throw await o.rollback(l),l}}async postTrObject(e,t={useCache:!1,maxRetries:3}){let a=0;for(;;){this.assertDeadline(t);let s;if(this.urlEndPoint)try{s=await flt.postJson(this.urlEndPoint,e,{cacheKey:t.cacheKey,cacheStrategy:t.useCache?"cache-first":"network-only",timeout:this.getRemainingTimeout(t)})}catch(o){throw t.timeoutMs!==void 0&&(this.hasDeadlineExpired(t)||Vh.isWebrequestTimeoutError(o))?this.createTimeoutError(t):o}else s=await this.postTypedTarget(e,t);if(this.assertDeadline(t),s.error&&!s.retry||!s.retry)return s;if(console.log(`Server requested a retry for TypedRequest method '${this.method}'`),a>=t.maxRetries)throw new Bee(this.method,t.maxRetries);a+=1,await this.waitForRetry(s.retry.waitForMs,t)}}async postStreamTrObject(e){let t={useCache:!1,maxRetries:3,timeoutMs:mlt,deadlineAt:performance.now()+mlt};return this.postTrObject(e,t)}async postTypedTarget(e,t){let a=this.getRemainingTimeout(t);if(a===void 0)return this.typedTarget.post(e);let s=new AbortController,o=setTimeout(()=>{s.abort(this.createTimeoutError(t))},a);o.unref?.();try{return await this.typedTarget.post(e,{signal:s.signal})}catch(n){throw s.signal.aborted?this.createTimeoutError(t):n}finally{clearTimeout(o)}}resolveFireOptions(e){let t=typeof e=="boolean"?{useCache:e}:e;if(!t||typeof t!="object")throw new TypeError("TypedRequest fire options must be a boolean or an options object");if(t.useCache!==void 0&&typeof t.useCache!="boolean")throw new TypeError("TypedRequest useCache must be a boolean");if(t.timeoutMs!==void 0&&(!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<=0||t.timeoutMs>Lee))throw new RangeError(`TypedRequest timeoutMs must be a positive safe integer no greater than ${Lee}`);if(t.maxRetries!==void 0&&(!Number.isSafeInteger(t.maxRetries)||t.maxRetries<0||t.maxRetries>1e3))throw new RangeError("TypedRequest maxRetries must be a safe integer between 0 and 1000");if(t.timeoutMs!==void 0&&!this.urlEndPoint&&this.typedTarget.options.supportsAbortSignal!==!0)throw new Error("TypedRequest timeoutMs requires an HTTP URL or a TypedTarget with AbortSignal support");return{useCache:t.useCache??!1,timeoutMs:t.timeoutMs,maxRetries:t.maxRetries??3,deadlineAt:t.timeoutMs===void 0?void 0:performance.now()+t.timeoutMs}}getRemainingTimeout(e){if(e.deadlineAt===void 0||e.timeoutMs===void 0)return;let t=Math.ceil(e.deadlineAt-performance.now());if(t<=0)throw this.createTimeoutError(e);return t}assertDeadline(e){this.getRemainingTimeout(e)}hasDeadlineExpired(e){return e.deadlineAt!==void 0&&performance.now()>=e.deadlineAt}createTimeoutError(e){return new Oee(this.method,e.timeoutMs)}async waitForRetry(e,t){if(!Number.isSafeInteger(e)||e<=0||e>Lee)throw new RangeError(`TypedRequest retry waitForMs must be a positive safe integer no greater than ${Lee}`);let a=this.getRemainingTimeout(t);if(a===void 0){await sr.delayFor(e);return}if(e>=a)throw await sr.delayFor(a),this.createTimeoutError(t);await sr.delayFor(e),this.assertDeadline(t)}async createCacheKey(e){let t=JSON.stringify({endpoint:this.urlEndPoint,method:e.method,request:e.request}),a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return`typedrequest:v1:${Array.from(new Uint8Array(a),o=>o.toString(16).padStart(2,"0")).join("")}`}}});var ps={};St(ps,{TYPED_REQUEST_REDACTED_PAYLOAD:()=>G2,TypedHandler:()=>Ghe,TypedRequest:()=>p4,TypedRequestRetryLimitError:()=>Bee,TypedRequestTimeoutError:()=>Oee,TypedResponseError:()=>dl,TypedRouter:()=>d4,TypedTarget:()=>Jhe,VirtualStream:()=>Rn,VirtualStreamActivationScope:()=>u4,VirtualStreamClosedError:()=>jh});var h4=h(()=>{Xhe();Khe();Ree();W2();efe();zee()});function glt(r){return r&&typeof r.then=="function"}function kd(r,e){return r||(r=0),new Promise(function(t){return setTimeout(function(){return t(e)},r)})}function ylt(r,e){return Math.floor(Math.random()*(e-r+1)+r)}function Au(){return Math.random().toString(36).substring(2)}function Ru(){var r=Date.now()*1e3;return r<=tfe&&(r=tfe+1),tfe=r,r}function xlt(){return typeof navigator<"u"&&typeof navigator.locks<"u"&&typeof navigator.locks.request=="function"}var blt,vlt,zn,tfe,Uh=h(()=>{i(glt,"isPromise");blt=Promise.resolve(!1),vlt=Promise.resolve(!0),zn=Promise.resolve();i(kd,"sleep");i(ylt,"randomInt");i(Au,"randomToken");tfe=0;i(Ru,"microSeconds");i(xlt,"supportsWebLockAPI")});function pFt(r){var e={time:Ru(),messagesCallback:null,bc:new BroadcastChannel(r),subFns:[]};return e.bc.onmessage=function(t){e.messagesCallback&&e.messagesCallback(t.data)},e}function hFt(r){r.bc.close(),r.subFns=[]}function fFt(r,e){try{return r.bc.postMessage(e,!1),zn}catch(t){return Promise.reject(t)}}function mFt(r,e){r.messagesCallback=e}function gFt(){if(typeof globalThis<"u"&&globalThis.Deno&&globalThis.Deno.args)return!0;if((typeof window<"u"||typeof self<"u")&&typeof BroadcastChannel=="function"){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}else return!1}function bFt(){return 150}var dFt,uFt,wlt,klt=h(()=>{Uh();dFt=Ru,uFt="native";i(pFt,"create");i(hFt,"close");i(fFt,"postMessage");i(mFt,"onMessage");i(gFt,"canBeUsed");i(bFt,"averageResponseTime");wlt={create:pFt,close:hFt,onMessage:mFt,postMessage:fFt,canBeUsed:gFt,type:uFt,averageResponseTime:bFt,microSeconds:dFt}});function vFt(r){let e=rfe()-r.ttl,t=r.map[Symbol.iterator]();for(;;){let a=t.next().value;if(!a)break;let s=a[0];if(a[1]<e)r.map.delete(s);else break}}function rfe(){return Date.now()}var X2,afe=h(()=>{X2=class{static{i(this,"ObliviousSet")}ttl;map=new Map;_to=!1;constructor(e){this.ttl=e}has(e){let t=this.map.get(e);return typeof t>"u"?!1:t<rfe()-this.ttl?(this.map.delete(e),!1):!0}add(e){this.map.delete(e),this.map.set(e,rfe()),this._to||(this._to=!0,setTimeout(()=>{this._to=!1,vFt(this)},0))}clear(){this.map.clear()}};i(vFt,"removeTooOldValues");i(rfe,"now")});function ng(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=JSON.parse(JSON.stringify(r));return typeof e.webWorkerSupport>"u"&&(e.webWorkerSupport=!0),e.idb||(e.idb={}),e.idb.ttl||(e.idb.ttl=1e3*45),e.idb.fallbackInterval||(e.idb.fallbackInterval=150),r.idb&&typeof r.idb.onclose=="function"&&(e.idb.onclose=r.idb.onclose),e.localstorage||(e.localstorage={}),e.localstorage.removeTimeout||(e.localstorage.removeTimeout=1e3*60),r.methods&&(e.methods=r.methods),e.node||(e.node={}),e.node.ttl||(e.node.ttl=1e3*60*2),e.node.maxParallelWrites||(e.node.maxParallelWrites=2048),typeof e.node.useFastPath>"u"&&(e.node.useFastPath=!0),e}var Nee=h(()=>{i(ng,"fillOptionsWithDefaults")});function Slt(){if(typeof indexedDB<"u")return indexedDB;if(typeof window<"u"){if(typeof window.mozIndexedDB<"u")return window.mozIndexedDB;if(typeof window.webkitIndexedDB<"u")return window.webkitIndexedDB;if(typeof window.msIndexedDB<"u")return window.msIndexedDB}return!1}function Fee(r){r.commit&&r.commit()}function kFt(r){var e=Slt(),t=xFt+r,a=e.open(t);return a.onupgradeneeded=function(s){var o=s.target.result;o.createObjectStore(nc,{keyPath:"id",autoIncrement:!0})},new Promise(function(s,o){a.onerror=function(n){return o(n)},a.onsuccess=function(){s(a.result)}})}function SFt(r,e,t){var a=Date.now(),s={uuid:e,time:a,data:t},o=r.transaction([nc],"readwrite",f4);return new Promise(function(n,l){o.oncomplete=function(){return n()},o.onerror=function(d){return l(d)};var c=o.objectStore(nc);c.add(s),Fee(o)})}function oZr(r){var e=r.transaction(nc,"readonly",f4),t=e.objectStore(nc),a=[];return new Promise(function(s){t.openCursor().onsuccess=function(o){var n=o.target.result;n?(a.push(n.value),n.continue()):(Fee(e),s(a))}})}function _Ft(r,e){var t=r.transaction(nc,"readonly",f4),a=t.objectStore(nc),s=[],o=IDBKeyRange.bound(e+1,1/0);if(a.getAll){var n=a.getAll(o);return new Promise(function(c,d){n.onerror=function(u){return d(u)},n.onsuccess=function(u){c(u.target.result)}})}function l(){try{return o=IDBKeyRange.bound(e+1,1/0),a.openCursor(o)}catch{return a.openCursor()}}return i(l,"openCursor"),new Promise(function(c,d){var u=l();u.onerror=function(p){return d(p)},u.onsuccess=function(p){var m=p.target.result;m?m.value.id<e+1?m.continue(e+1):(s.push(m.value),m.continue()):(Fee(t),c(s))}})}function CFt(r,e){if(r.closed)return Promise.resolve([]);var t=r.db.transaction(nc,"readwrite",f4),a=t.objectStore(nc);return Promise.all(e.map(function(s){var o=a.delete(s);return new Promise(function(n){o.onsuccess=function(){return n()}})}))}function TFt(r,e){var t=Date.now()-e,a=r.transaction(nc,"readonly",f4),s=a.objectStore(nc),o=[];return new Promise(function(n){s.openCursor().onsuccess=function(l){var c=l.target.result;if(c){var d=c.value;d.time<t?(o.push(d),c.continue()):(Fee(a),n(o))}else n(o)}})}function MFt(r){return TFt(r.db,r.options.idb.ttl).then(function(e){return CFt(r,e.map(function(t){return t.id}))})}function IFt(r,e){return e=ng(e),kFt(r).then(function(t){var a={closed:!1,lastCursorId:0,channelName:r,options:e,uuid:Au(),eMIs:new X2(e.idb.ttl*2),writeBlockPromise:zn,messagesCallback:null,readQueuePromises:[],db:t};return t.onclose=function(){a.closed=!0,e.idb.onclose&&e.idb.onclose()},_lt(a),a})}function _lt(r){r.closed||Clt(r).then(function(){return kd(r.options.idb.fallbackInterval)}).then(function(){return _lt(r)})}function $Ft(r,e){return!(r.uuid===e.uuid||e.eMIs.has(r.id)||r.data.time<e.messagesCallbackTime)}function Clt(r){return r.closed?zn:r.messagesCallback?_Ft(r.db,r.lastCursorId).then(function(e){var t=e.filter(function(a){return!!a}).map(function(a){return a.id>r.lastCursorId&&(r.lastCursorId=a.id),a}).filter(function(a){return $Ft(a,r)}).sort(function(a,s){return a.time-s.time});return t.forEach(function(a){r.messagesCallback&&(r.eMIs.add(a.id),r.messagesCallback(a.data))}),zn}):zn}function DFt(r){r.closed=!0,r.db.close()}function EFt(r,e){return r.writeBlockPromise=r.writeBlockPromise.then(function(){return SFt(r.db,r.uuid,e)}).then(function(){ylt(0,10)===0&&MFt(r)}),r.writeBlockPromise}function PFt(r,e,t){r.messagesCallbackTime=t,r.messagesCallback=e,Clt(r)}function AFt(){return!!Slt()}function RFt(r){return r.idb.fallbackInterval*2}var yFt,xFt,nc,f4,wFt,Tlt,Mlt=h(()=>{Uh();afe();Nee();yFt=Ru,xFt="pubkey.broadcast-channel-0-",nc="messages",f4={durability:"relaxed"},wFt="idb";i(Slt,"getIdb");i(Fee,"commitIndexedDBTransaction");i(kFt,"createDatabase");i(SFt,"writeMessage");i(oZr,"getAllMessages");i(_Ft,"getMessagesHigherThan");i(CFt,"removeMessagesById");i(TFt,"getOldMessages");i(MFt,"cleanOldMessages");i(IFt,"create");i(_lt,"_readLoop");i($Ft,"_filterMessage");i(Clt,"readNewMessages");i(DFt,"close");i(EFt,"postMessage");i(PFt,"onMessage");i(AFt,"canBeUsed");i(RFt,"averageResponseTime");Tlt={create:IFt,close:DFt,onMessage:PFt,postMessage:EFt,canBeUsed:AFt,type:wFt,averageResponseTime:RFt,microSeconds:yFt}});function Ilt(){var r;if(typeof window>"u")return null;try{r=window.localStorage,r=window["ie8-eventlistener/storage"]||window.localStorage}catch{}return r}function $lt(r){return LFt+r}function BFt(r,e){return new Promise(function(t){kd().then(function(){var a=$lt(r.channelName),s={token:Au(),time:Date.now(),data:e,uuid:r.uuid},o=JSON.stringify(s);Ilt().setItem(a,o);var n=document.createEvent("Event");n.initEvent("storage",!0,!0),n.key=a,n.newValue=o,window.dispatchEvent(n),t()})})}function NFt(r,e){var t=$lt(r),a=i(function(o){o.key===t&&e(JSON.parse(o.newValue))},"listener");return window.addEventListener("storage",a),a}function FFt(r){window.removeEventListener("storage",r)}function qFt(r,e){if(e=ng(e),!Dlt())throw new Error("BroadcastChannel: localstorage cannot be used");var t=Au(),a=new X2(e.localstorage.removeTimeout),s={channelName:r,uuid:t,eMIs:a};return s.listener=NFt(r,function(o){s.messagesCallback&&o.uuid!==t&&(!o.token||a.has(o.token)||o.data.time&&o.data.time<s.messagesCallbackTime||(a.add(o.token),s.messagesCallback(o.data)))}),s}function HFt(r){FFt(r.listener)}function VFt(r,e,t){r.messagesCallbackTime=t,r.messagesCallback=e}function Dlt(){var r=Ilt();if(!r)return!1;try{var e="__broadcastchannel_check";r.setItem(e,"works"),r.removeItem(e)}catch{return!1}return!0}function jFt(){var r=120,e=navigator.userAgent.toLowerCase();return e.includes("safari")&&!e.includes("chrome")?r*2:r}var zFt,LFt,OFt,Elt,Plt=h(()=>{afe();Nee();Uh();zFt=Ru,LFt="pubkey.broadcastChannel-",OFt="localstorage";i(Ilt,"getLocalStorage");i($lt,"storageKey");i(BFt,"postMessage");i(NFt,"addStorageEventListener");i(FFt,"removeStorageEventListener");i(qFt,"create");i(HFt,"close");i(VFt,"onMessage");i(Dlt,"canBeUsed");i(jFt,"averageResponseTime");Elt={create:qFt,close:HFt,onMessage:VFt,postMessage:BFt,canBeUsed:Dlt,type:OFt,averageResponseTime:jFt,microSeconds:zFt}});function WFt(r){var e={time:Alt(),name:r,messagesCallback:null};return sfe.add(e),e}function GFt(r){sfe.delete(r)}function KFt(r,e){return new Promise(function(t){return setTimeout(function(){var a=Array.from(sfe);a.forEach(function(s){s.name===r.name&&s!==r&&s.messagesCallback&&s.time<e.time&&s.messagesCallback(e)}),t()},Rlt)})}function YFt(r,e){r.messagesCallback=e}function ZFt(){return!0}function QFt(){return Rlt}var Alt,UFt,sfe,Rlt,zlt,Llt=h(()=>{Uh();Alt=Ru,UFt="simulate",sfe=new Set;i(WFt,"create");i(GFt,"close");Rlt=5;i(KFt,"postMessage");i(YFt,"onMessage");i(ZFt,"canBeUsed");i(QFt,"averageResponseTime");zlt={create:WFt,close:GFt,onMessage:YFt,postMessage:KFt,canBeUsed:ZFt,type:UFt,averageResponseTime:QFt,microSeconds:Alt}});function ife(r){var e=[].concat(r.methods,Olt).filter(Boolean);if(r.type){if(r.type==="simulate")return zlt;var t=e.find(function(s){return s.type===r.type});if(t)return t;throw new Error("method-type "+r.type+" not found")}r.webWorkerSupport||(e=e.filter(function(s){return s.type!=="idb"}));var a=e.find(function(s){return s.canBeUsed()});if(a)return a;throw new Error("No usable method found in "+JSON.stringify(Olt.map(function(s){return s.type})))}var Olt,Blt=h(()=>{klt();Mlt();Plt();Llt();Olt=[wlt,Tlt,Elt];i(ife,"chooseMethod")});function JFt(r){r=ng(r);var e=ife(r);return e.type==="node"?e.clearNodeFolder().then(function(){return!0}):blt}function eqt(r){ofe=r}function Nlt(r,e,t){var a=r.method.microSeconds(),s={time:a,type:e,data:t},o=r._prepP?r._prepP:zn;return o.then(function(){var n=r.method.postMessage(r._state,s);return r._uMP.add(n),n.catch().then(function(){return r._uMP.delete(n)}),n})}function tqt(r){var e=r.method.create(r.name,r.options);glt(e)?(r._prepP=e,e.then(function(t){r._state=t})):r._state=e}function Flt(r){return r._addEL.message.length>0||r._addEL.internal.length>0}function qlt(r,e,t){r._addEL[e].push(t),rqt(r)}function Hlt(r,e,t){r._addEL[e]=r._addEL[e].filter(function(a){return a!==t}),aqt(r)}function rqt(r){if(!r._iL&&Flt(r)){var e=i(function(s){r._addEL[s.type].forEach(function(o){s.time>=o.time&&o.fn(s.data)})},"listenerFn"),t=r.method.microSeconds();r._prepP?r._prepP.then(function(){r._iL=!0,r.method.onMessage(r._state,e,t)}):(r._iL=!0,r.method.onMessage(r._state,e,t))}}function aqt(r){if(r._iL&&!Flt(r)){r._iL=!1;var e=r.method.microSeconds();r.method.onMessage(r._state,null,e)}}var nfe,XFt,lg,ofe,Vlt=h(()=>{Uh();Blt();Nee();nfe=new Set,XFt=0,lg=i(function(e,t){this.id=XFt++,nfe.add(this),this.name=e,ofe&&(t=ofe),this.options=ng(t),this.method=ife(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,tqt(this)},"BroadcastChannel");lg._pubkey=!0;i(JFt,"clearNodeFolder");i(eqt,"enforceOptions"),lg.prototype={postMessage:i(function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(e));return Nlt(this,"message",e)},"postMessage"),postInternal:i(function(e){return Nlt(this,"internal",e)},"postInternal"),set onmessage(r){var e=this.method.microSeconds(),t={time:e,fn:r};Hlt(this,"message",this._onML),r&&typeof r=="function"?(this._onML=t,qlt(this,"message",t)):this._onML=null},addEventListener:i(function(e,t){var a=this.method.microSeconds(),s={time:a,fn:t};qlt(this,e,s)},"addEventListener"),removeEventListener:i(function(e,t){var a=this._addEL[e].find(function(s){return s.fn===t});Hlt(this,e,a)},"removeEventListener"),close:i(function(){var e=this;if(!this.closed){nfe.delete(this),this.closed=!0;var t=this._prepP?this._prepP:zn;return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(Array.from(e._uMP))}).then(function(){return Promise.all(e._befC.map(function(a){return a()}))}).then(function(){return e.method.close(e._state)})}},"close"),get type(){return this.method.type},get isClosed(){return this.closed}};i(Nlt,"_post");i(tqt,"_prepareChannel");i(Flt,"_hasMessageListeners");i(qlt,"_addListenerObject");i(Hlt,"_removeListenerObject");i(rqt,"_startListening");i(aqt,"_stopListening")});function jlt(r){if(typeof WorkerGlobalScope=="function"&&self instanceof WorkerGlobalScope){var e=self.close.bind(self);self.close=function(){return r(),e()}}else{if(typeof window.addEventListener!="function")return;window.addEventListener("beforeunload",function(){r()},!0),window.addEventListener("unload",function(){r()},!0)}}var Ult=h(()=>{i(jlt,"addBrowser")});function Wlt(r){process.on("exit",function(){return r()}),process.on("beforeExit",function(){return r().then(function(){return process.exit()})}),process.on("SIGINT",function(){return r().then(function(){return process.exit()})}),process.on("uncaughtException",function(e){return r().then(function(){console.trace(e),process.exit(101)})})}var Glt=h(()=>{i(Wlt,"addNode")});function oqt(){Klt||(Klt=!0,iqt(nqt))}function Ylt(r){if(oqt(),typeof r!="function")throw new Error("Listener is no function");cg.add(r);var e={remove:i(function(){return cg.delete(r)},"remove"),run:i(function(){return cg.delete(r),r()},"run")};return e}function nqt(){var r=[];return cg.forEach(function(e){r.push(e()),cg.delete(e)}),Promise.all(r)}function RZr(){cg.clear()}function zZr(){return cg.size}var sqt,iqt,cg,Klt,Zlt=h(()=>{Ult();Glt();sqt=Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",iqt=sqt?Wlt:jlt,cg=new Set,Klt=!1;i(oqt,"startListening");i(Ylt,"add");i(nqt,"runAll");i(RZr,"removeAll");i(zZr,"getSize")});function zu(r,e){var t={context:"leader",action:e,token:r.token};return r.broadcastChannel.postInternal(t)}function m4(r){r.isLeader=!0,r._hasLeader=!0;var e=Ylt(function(){return r.die()});r._unl.push(e);var t=i(function(s){s.context==="leader"&&s.action==="apply"&&zu(r,"tell"),s.context==="leader"&&s.action==="tell"&&!r._dpLC&&(r._dpLC=!0,r._dpL(),zu(r,"tell"))},"isLeaderListener");return r.broadcastChannel.addEventListener("internal",t),r._lstns.push(t),zu(r,"tell")}var qee=h(()=>{Zlt();i(zu,"sendLeaderMessage");i(m4,"beLeader")});var lfe,Qlt,Xlt=h(()=>{Uh();qee();lfe=i(function(e,t){var a=this;this.broadcastChannel=e,e._befC.push(function(){return a.die()}),this._options=t,this.isLeader=!1,this.isDead=!1,this.token=Au(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=!1,this._wKMC={},this.lN="pubkey-bc||"+e.method.type+"||"+e.name},"LeaderElectionWebLock"),Qlt="LeaderElectionWebLock.die() called";lfe.prototype={hasLeader:i(function(){var e=this;return navigator.locks.query().then(function(t){var a=t.held?t.held.filter(function(s){return s.name===e.lN}):[];return!!(a&&a.length>0)})},"hasLeader"),awaitLeadership:i(function(){var e=this;if(!this._wLMP){this._wKMC.c=new AbortController;var t=new Promise(function(a,s){e._wKMC.res=a,e._wKMC.rej=s});this._wLMP=new Promise(function(a,s){navigator.locks.request(e.lN,{signal:e._wKMC.c.signal},function(){return e._wKMC.c=void 0,e.isDead||m4(e),a(),t}).catch(function(o){o.message&&o.message===Qlt||(e._wKMC.rej&&e._wKMC.rej(o),s(o))})})}return this._wLMP},"awaitLeadership"),set onduplicate(r){},die:i(function(){var e=this;return this.isDead?this._dP:(this._lstns.forEach(function(t){return e.broadcastChannel.removeEventListener("internal",t)}),this._lstns=[],this._unl.forEach(function(t){return t.remove()}),this._unl=[],this.isLeader&&(this.isLeader=!1),this.isDead=!0,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort(new Error(Qlt)),this._dP=zu(this,"death"),this._dP)},"die")}});function lqt(r){return r.isLeader?zn:new Promise(function(e){var t=!1;function a(){t||(t=!0,r.broadcastChannel.removeEventListener("internal",o),e(!0))}i(a,"finish"),r.applyOnce().then(function(){r.isLeader&&a()});var s=i(function(){return kd(r._options.fallbackInterval).then(function(){if(!(r.isDead||t))if(r.isLeader)a();else return r.applyOnce(!0).then(function(){r.isLeader?a():s()})})},"tryOnFallBack");s();var o=i(function(l){l.context==="leader"&&l.action==="death"&&(r._hasLeader=!1,r.applyOnce().then(function(){r.isLeader&&a()}))},"whenDeathListener");r.broadcastChannel.addEventListener("internal",o),r._lstns.push(o)})}function cqt(r,e){return r||(r={}),r=JSON.parse(JSON.stringify(r)),r.fallbackInterval||(r.fallbackInterval=3e3),r.responseTime||(r.responseTime=e.method.averageResponseTime(e.options)),r}function dqt(r,e){if(r._leaderElector)throw new Error("BroadcastChannel already has a leader-elector");e=cqt(e,r);var t=xlt()?new lfe(r,e):new Jlt(r,e);return r._befC.push(function(){return t.die()}),r._leaderElector=t,t}var Jlt,ect=h(()=>{Uh();qee();Xlt();Jlt=i(function(e,t){var a=this;this.broadcastChannel=e,this._options=t,this.isLeader=!1,this._hasLeader=!1,this.isDead=!1,this.token=Au(),this._aplQ=zn,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=!1;var s=i(function(n){n.context==="leader"&&(n.action==="death"&&(a._hasLeader=!1),n.action==="tell"&&(a._hasLeader=!0))},"hasLeaderListener");this.broadcastChannel.addEventListener("internal",s),this._lstns.push(s)},"LeaderElection");Jlt.prototype={hasLeader:i(function(){return Promise.resolve(this._hasLeader)},"hasLeader"),applyOnce:i(function(e){var t=this;if(this.isLeader)return kd(0,!0);if(this.isDead)return kd(0,!1);if(this._aplQC>1)return this._aplQ;var a=i(function(){if(t.isLeader)return vlt;var o=!1,n,l=new Promise(function(u){n=i(function(){o=!0,u()},"stopCriteriaPromiseResolve")}),c=i(function(p){p.context==="leader"&&p.token!=t.token&&(p.action==="apply"&&p.token>t.token&&n(),p.action==="tell"&&(n(),t._hasLeader=!0))},"handleMessage");t.broadcastChannel.addEventListener("internal",c);var d=e?t._options.responseTime*4:t._options.responseTime;return zu(t,"apply").then(function(){return Promise.race([kd(d),l.then(function(){return Promise.reject(new Error)})])}).then(function(){if(!t.isDead)return zu(t,"apply")}).then(function(){return Promise.race([kd(d),l.then(function(){return Promise.reject(new Error)})])}).catch(function(){}).then(function(){return t.broadcastChannel.removeEventListener("internal",c),!o&&!t.isDead?m4(t).then(function(){return!0}):!1})},"applyRun");return this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then(function(){return a()}).then(function(){t._aplQC=t._aplQC-1}),this._aplQ.then(function(){return t.isLeader})},"applyOnce"),awaitLeadership:i(function(){return this._aLP||(this._aLP=lqt(this)),this._aLP},"awaitLeadership"),set onduplicate(r){this._dpL=r},die:i(function(){var e=this;return this.isDead?this._dP:(this._lstns.forEach(function(t){return e.broadcastChannel.removeEventListener("internal",t)}),this._lstns=[],this._unl.forEach(function(t){return t.remove()}),this._unl=[],this.isLeader&&(this._hasLeader=!1,this.isLeader=!1),this.isDead=!0,this._dP=zu(this,"death"),this._dP)},"die")};i(lqt,"_awaitLeadershipOnce");i(cqt,"fillOptionsWithDefaults");i(dqt,"createLeaderElection")});var tct=h(()=>{Vlt();ect();qee()});var rct=h(()=>{wh();l2();h4();tct()});var cfe,dfe,act=h(()=>{rct();cfe=globalThis.BroadcastChannel;cfe||(cfe=lg);dfe=class{static{i(this,"DeesComms")}constructor(){this.broadcastChannel=new cfe("dees-comms"),this.typedrouter=new ps.TypedRouter,this.typedtarget=new ps.TypedTarget({postMethodWithTypedRouter:i(async e=>{this.postMessage(e)},"postMethodWithTypedRouter"),typedRouterRef:this.typedrouter}),this.broadcastChannel.onmessage=async e=>{let t=e.method?e:e.data,a=await this.typedrouter.routeAndAddResponse(t,{skipHooks:!0});a&&!a.error&&this.postMessage(a)}}createTypedRequest(e){return new ps.TypedRequest(this.typedtarget,e)}async postMessage(e){this.broadcastChannel.postMessage(e)}async createTypedHandler(e,t){this.typedrouter.addTypedHandler(new ps.TypedHandler(e,t))}}});var g4={};St(g4,{DeesComms:()=>dfe});var sct=h(()=>{act()});function Or(r){if(r&&typeof r=="object")switch(r[ho]){case ul:case Sd:return!0}return!1}function kr(r){if(r&&typeof r=="object")switch(r[ho]){case b4:case ul:case dn:case Sd:return!0}return!1}var b4,v4,ul,Hee,dn,Sd,ho,un,pn,hn,fr,tr,fn,y4,Br=h(()=>{b4=Symbol.for("yaml.alias"),v4=Symbol.for("yaml.document"),ul=Symbol.for("yaml.map"),Hee=Symbol.for("yaml.pair"),dn=Symbol.for("yaml.scalar"),Sd=Symbol.for("yaml.seq"),ho=Symbol.for("yaml.node.type"),un=i(r=>!!r&&typeof r=="object"&&r[ho]===b4,"isAlias"),pn=i(r=>!!r&&typeof r=="object"&&r[ho]===v4,"isDocument"),hn=i(r=>!!r&&typeof r=="object"&&r[ho]===ul,"isMap"),fr=i(r=>!!r&&typeof r=="object"&&r[ho]===Hee,"isPair"),tr=i(r=>!!r&&typeof r=="object"&&r[ho]===dn,"isScalar"),fn=i(r=>!!r&&typeof r=="object"&&r[ho]===Sd,"isSeq");i(Or,"isCollection");i(kr,"isNode");y4=i(r=>(tr(r)||Or(r))&&!!r.anchor,"hasAnchor")});function Ln(r,e){let t=oct(e);pn(r)?J2(null,r.contents,t,Object.freeze([r]))===_d&&(r.contents=null):J2(null,r,t,Object.freeze([]))}function J2(r,e,t,a){let s=nct(r,e,t,a);if(kr(s)||fr(s))return lct(r,a,s),J2(r,s,t,a);if(typeof s!="symbol"){if(Or(e)){a=Object.freeze(a.concat(e));for(let o=0;o<e.items.length;++o){let n=J2(o,e.items[o],t,a);if(typeof n=="number")o=n-1;else{if(n===mn)return mn;n===_d&&(e.items.splice(o,1),o-=1)}}}else if(fr(e)){a=Object.freeze(a.concat(e));let o=J2("key",e.key,t,a);if(o===mn)return mn;o===_d&&(e.key=null);let n=J2("value",e.value,t,a);if(n===mn)return mn;n===_d&&(e.value=null)}}return s}async function dg(r,e){let t=oct(e);pn(r)?await ew(null,r.contents,t,Object.freeze([r]))===_d&&(r.contents=null):await ew(null,r,t,Object.freeze([]))}async function ew(r,e,t,a){let s=await nct(r,e,t,a);if(kr(s)||fr(s))return lct(r,a,s),ew(r,s,t,a);if(typeof s!="symbol"){if(Or(e)){a=Object.freeze(a.concat(e));for(let o=0;o<e.items.length;++o){let n=await ew(o,e.items[o],t,a);if(typeof n=="number")o=n-1;else{if(n===mn)return mn;n===_d&&(e.items.splice(o,1),o-=1)}}}else if(fr(e)){a=Object.freeze(a.concat(e));let o=await ew("key",e.key,t,a);if(o===mn)return mn;o===_d&&(e.key=null);let n=await ew("value",e.value,t,a);if(n===mn)return mn;n===_d&&(e.value=null)}}return s}function oct(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function nct(r,e,t,a){if(typeof t=="function")return t(r,e,a);if(hn(e))return t.Map?.(r,e,a);if(fn(e))return t.Seq?.(r,e,a);if(fr(e))return t.Pair?.(r,e,a);if(tr(e))return t.Scalar?.(r,e,a);if(un(e))return t.Alias?.(r,e,a)}function lct(r,e,t){let a=e[e.length-1];if(Or(a))a.items[r]=t;else if(fr(a))r==="key"?a.key=t:a.value=t;else if(pn(a))a.contents=t;else{let s=un(a)?"alias":"scalar";throw new Error(`Cannot replace node with ${s} parent`)}}var mn,ict,_d,x4=h(()=>{Br();mn=Symbol("break visit"),ict=Symbol("skip children"),_d=Symbol("remove node");i(Ln,"visit"),Ln.BREAK=mn,Ln.SKIP=ict,Ln.REMOVE=_d;i(J2,"visit_");i(dg,"visitAsync"),dg.BREAK=mn,dg.SKIP=ict,dg.REMOVE=_d;i(ew,"visitAsync_");i(oct,"initVisitor");i(nct,"callVisitor");i(lct,"replaceNode")});var pqt,hqt,lc,ufe=h(()=>{Br();x4();pqt={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},hqt=i(r=>r.replace(/[!,[\]{}]/g,e=>pqt[e]),"escapeTagName"),lc=class r{static{i(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let a=e.trim().split(/[ \t]+/),s=a.shift();switch(s){case"%TAG":{if(a.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),a.length<2))return!1;let[o,n]=a;return this.tags[o]=n,!0}case"%YAML":{if(this.yaml.explicit=!0,a.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=a;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let n=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,n),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let n=e.slice(2,-1);return n==="!"||n==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),n)}let[,a,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let o=this.tags[a];if(o)try{return o+decodeURIComponent(s)}catch(n){return t(String(n)),null}return a==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,a]of Object.entries(this.tags))if(e.startsWith(a))return t+hqt(e.substring(a.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],a=Object.entries(this.tags),s;if(e&&a.length>0&&kr(e.contents)){let o={};Ln(e.contents,(n,l)=>{kr(l)&&l.tag&&(o[l.tag]=!0)}),s=Object.keys(o)}else s=[];for(let[o,n]of a)o==="!!"&&n==="tag:yaml.org,2002:"||(!e||s.some(l=>l.startsWith(n)))&&t.push(`%TAG ${o} ${n}`);return t.join(`
|
|
15
15
|
`)}};lc.defaultYaml={explicit:!1,version:"1.2"},lc.defaultTags={"!!":"tag:yaml.org,2002:"}});function w4(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function Vee(r){let e=new Set;return Ln(r,{Value(t,a){a.anchor&&e.add(a.anchor)}}),e}function jee(r,e){for(let t=1;;++t){let a=`${r}${t}`;if(!e.has(a))return a}}function pfe(r,e){let t=[],a=new Map,s=null;return{onAnchor:i(o=>{t.push(o),s??(s=Vee(r));let n=jee(e,s);return s.add(n),n},"onAnchor"),setAnchors:i(()=>{for(let o of t){let n=a.get(o);if(typeof n=="object"&&n.anchor&&(tr(n.node)||Or(n.node)))n.node.anchor=n.anchor;else{let l=new Error("Failed to resolve repeated object (this should not happen)");throw l.source=o,l}}},"setAnchors"),sourceObjects:a}}var Uee=h(()=>{Br();x4();i(w4,"anchorIsValid");i(Vee,"anchorNames");i(jee,"findNewAnchor");i(pfe,"createNodeAnchors")});function Lu(r,e,t,a){if(a&&typeof a=="object")if(Array.isArray(a))for(let s=0,o=a.length;s<o;++s){let n=a[s],l=Lu(r,a,String(s),n);l===void 0?delete a[s]:l!==n&&(a[s]=l)}else if(a instanceof Map)for(let s of Array.from(a.keys())){let o=a.get(s),n=Lu(r,a,s,o);n===void 0?a.delete(s):n!==o&&a.set(s,n)}else if(a instanceof Set)for(let s of Array.from(a)){let o=Lu(r,a,s,s);o===void 0?a.delete(s):o!==s&&(a.delete(s),a.add(o))}else for(let[s,o]of Object.entries(a)){let n=Lu(r,a,s,o);n===void 0?delete a[s]:n!==o&&(a[s]=n)}return r.call(e,t,a)}var hfe=h(()=>{i(Lu,"applyReviver")});function qs(r,e,t){if(Array.isArray(r))return r.map((a,s)=>qs(a,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!y4(r))return r.toJSON(e,t);let a={aliasCount:0,count:1,res:void 0};t.anchors.set(r,a),t.onCreate=o=>{a.res=o,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!t?.keep?Number(r):r}var Wh=h(()=>{Br();i(qs,"toJS")});var Ou,Wee=h(()=>{hfe();Br();Wh();Ou=class{static{i(this,"NodeBase")}constructor(e){Object.defineProperty(this,ho,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:a,onAnchor:s,reviver:o}={}){if(!pn(e))throw new TypeError("A document argument is required");let n={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof a=="number"?a:100},l=qs(this,"",n);if(typeof s=="function")for(let{count:c,res:d}of n.anchors.values())s(d,c);return typeof o=="function"?Lu(o,{"":l},"",l):l}}});function Gee(r,e,t){if(un(e)){let a=e.resolve(r),s=t&&a&&t.get(a);return s?s.count*s.aliasCount:0}else if(Or(e)){let a=0;for(let s of e.items){let o=Gee(r,s,t);o>a&&(a=o)}return a}else if(fr(e)){let a=Gee(r,e.key,t),s=Gee(r,e.value,t);return Math.max(a,s)}return 1}var pl,k4=h(()=>{Uee();x4();Br();Wee();Wh();pl=class extends Ou{static{i(this,"Alias")}constructor(e){super(b4),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let a;t?.aliasResolveCache?a=t.aliasResolveCache:(a=[],Ln(e,{Node:i((o,n)=>{(un(n)||y4(n))&&a.push(n)},"Node")}),t&&(t.aliasResolveCache=a));let s;for(let o of a){if(o===this)break;o.anchor===this.source&&(s=o)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:a,doc:s,maxAliasCount:o}=t,n=this.resolve(s,t);if(!n){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let l=a.get(n);if(l||(qs(n,null,t),l=a.get(n)),l?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(o>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=Gee(s,n,a)),l.count*l.aliasCount>o)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return l.res}toString(e,t,a){let s=`*${this.source}`;if(e){if(w4(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${s} `}return s}};i(Gee,"getAliasCount")});var S4,Ct,Hs=h(()=>{Br();Wee();Wh();S4=i(r=>!r||typeof r!="function"&&typeof r!="object","isScalarValue"),Ct=class extends Ou{static{i(this,"Scalar")}constructor(e){super(dn),this.value=e}toJSON(e,t){return t?.keep?this.value:qs(this.value,e,t)}toString(){return String(this.value)}};Ct.BLOCK_FOLDED="BLOCK_FOLDED",Ct.BLOCK_LITERAL="BLOCK_LITERAL",Ct.PLAIN="PLAIN",Ct.QUOTE_DOUBLE="QUOTE_DOUBLE",Ct.QUOTE_SINGLE="QUOTE_SINGLE"});function mqt(r,e,t){if(e){let a=t.filter(o=>o.tag===e),s=a.find(o=>!o.format)??a[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(a=>a.identify?.(r)&&!a.format)}function Cd(r,e,t){if(pn(r)&&(r=r.contents),kr(r))return r;if(fr(r)){let p=t.schema[ul].createNode?.(t.schema,null,t);return p.items.push(r),p}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:a,onAnchor:s,onTagObj:o,schema:n,sourceObjects:l}=t,c;if(a&&r&&typeof r=="object"){if(c=l.get(r),c)return c.anchor??(c.anchor=s(r)),new pl(c.anchor);c={anchor:null,node:null},l.set(r,c)}e?.startsWith("!!")&&(e=fqt+e.slice(2));let d=mqt(r,e,n.tags);if(!d){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let p=new Ct(r);return c&&(c.node=p),p}d=r instanceof Map?n[ul]:Symbol.iterator in Object(r)?n[Sd]:n[ul]}o&&(o(d),delete t.onTagObj);let u=d?.createNode?d.createNode(t.schema,r,t):typeof d?.nodeClass?.from=="function"?d.nodeClass.from(t.schema,r,t):new Ct(r);return e?u.tag=e:d.default||(u.tag=d.tag),c&&(c.node=u),u}var fqt,_4=h(()=>{k4();Br();Hs();fqt="tag:yaml.org,2002:";i(mqt,"findTagObject");i(Cd,"createNode")});function tw(r,e,t){let a=t;for(let s=e.length-1;s>=0;--s){let o=e[s];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let n=[];n[o]=a,a=n}else a=new Map([[o,a]])}return Cd(a,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:i(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:r,sourceObjects:new Map})}var pg,ug,Kee=h(()=>{_4();Br();Wee();i(tw,"collectionFromPath");pg=i(r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,"isEmptyPath"),ug=class extends Ou{static{i(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(a=>kr(a)||fr(a)?a.clone(e):a),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(pg(e))this.add(t);else{let[a,...s]=e,o=this.get(a,!0);if(Or(o))o.addIn(s,t);else if(o===void 0&&this.schema)this.set(a,tw(this.schema,s,t));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${s}`)}}deleteIn(e){let[t,...a]=e;if(a.length===0)return this.delete(t);let s=this.get(t,!0);if(Or(s))return s.deleteIn(a);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${a}`)}getIn(e,t){let[a,...s]=e,o=this.get(a,!0);return s.length===0?!t&&tr(o)?o.value:o:Or(o)?o.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!fr(t))return!1;let a=t.value;return a==null||e&&tr(a)&&a.value==null&&!a.commentBefore&&!a.comment&&!a.tag})}hasIn(e){let[t,...a]=e;if(a.length===0)return this.has(t);let s=this.get(t,!0);return Or(s)?s.hasIn(a):!1}setIn(e,t){let[a,...s]=e;if(s.length===0)this.set(a,t);else{let o=this.get(a,!0);if(Or(o))o.setIn(s,t);else if(o===void 0&&this.schema)this.set(a,tw(this.schema,s,t));else throw new Error(`Expected YAML collection at ${a}. Remaining path: ${s}`)}}}});function On(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var ffe,cc,C4=h(()=>{ffe=i(r=>r.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");i(On,"indentComment");cc=i((r,e,t)=>r.endsWith(`
|
|
16
16
|
`)?On(t,e):t.includes(`
|
|
17
17
|
`)?`
|