@graffiti-garden/implementation-decentralized 0.0.2 → 0.0.4

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.
Files changed (48) hide show
  1. package/dist/1-services/4-inboxes-tests.d.ts.map +1 -1
  2. package/dist/1-services/4-inboxes.d.ts +3 -3
  3. package/dist/1-services/4-inboxes.d.ts.map +1 -1
  4. package/dist/3-protocol/3-object-encoding.d.ts.map +1 -1
  5. package/dist/3-protocol/4-graffiti.d.ts +2 -1
  6. package/dist/3-protocol/4-graffiti.d.ts.map +1 -1
  7. package/dist/3-protocol/login-dialog.html.d.ts +1 -1
  8. package/dist/3-protocol/login-dialog.html.d.ts.map +1 -1
  9. package/dist/browser/index.js +7 -7
  10. package/dist/browser/index.js.map +3 -3
  11. package/dist/browser/login-dialog.html-VTDKJZBG.js +44 -0
  12. package/dist/browser/login-dialog.html-VTDKJZBG.js.map +7 -0
  13. package/dist/browser/{style-YUTCEBZV-RWYJV575.js → style-RMTPI5KV-Y5KAOOZR.js} +19 -36
  14. package/dist/browser/style-RMTPI5KV-Y5KAOOZR.js.map +7 -0
  15. package/dist/cjs/1-services/4-inboxes-tests.js +2 -0
  16. package/dist/cjs/1-services/4-inboxes-tests.js.map +2 -2
  17. package/dist/cjs/1-services/4-inboxes.js +17 -8
  18. package/dist/cjs/1-services/4-inboxes.js.map +2 -2
  19. package/dist/cjs/3-protocol/1-sessions.js +1 -1
  20. package/dist/cjs/3-protocol/1-sessions.js.map +2 -2
  21. package/dist/cjs/3-protocol/3-object-encoding.js +3 -2
  22. package/dist/cjs/3-protocol/3-object-encoding.js.map +2 -2
  23. package/dist/cjs/3-protocol/4-graffiti.js +193 -135
  24. package/dist/cjs/3-protocol/4-graffiti.js.map +3 -3
  25. package/dist/cjs/3-protocol/login-dialog.html.js +9 -9
  26. package/dist/cjs/3-protocol/login-dialog.html.js.map +1 -1
  27. package/dist/esm/1-services/4-inboxes-tests.js +2 -0
  28. package/dist/esm/1-services/4-inboxes-tests.js.map +2 -2
  29. package/dist/esm/1-services/4-inboxes.js +19 -9
  30. package/dist/esm/1-services/4-inboxes.js.map +2 -2
  31. package/dist/esm/3-protocol/1-sessions.js +1 -1
  32. package/dist/esm/3-protocol/1-sessions.js.map +2 -2
  33. package/dist/esm/3-protocol/3-object-encoding.js +3 -2
  34. package/dist/esm/3-protocol/3-object-encoding.js.map +2 -2
  35. package/dist/esm/3-protocol/4-graffiti.js +194 -135
  36. package/dist/esm/3-protocol/4-graffiti.js.map +3 -3
  37. package/dist/esm/3-protocol/login-dialog.html.js +9 -9
  38. package/dist/esm/3-protocol/login-dialog.html.js.map +1 -1
  39. package/package.json +7 -7
  40. package/src/1-services/4-inboxes-tests.ts +2 -0
  41. package/src/1-services/4-inboxes.ts +25 -15
  42. package/src/3-protocol/1-sessions.ts +1 -1
  43. package/src/3-protocol/3-object-encoding.ts +4 -2
  44. package/src/3-protocol/4-graffiti.ts +260 -170
  45. package/src/3-protocol/login-dialog.html.ts +9 -9
  46. package/dist/browser/login-dialog.html-XUWYDNNI.js +0 -44
  47. package/dist/browser/login-dialog.html-XUWYDNNI.js.map +0 -7
  48. package/dist/browser/style-YUTCEBZV-RWYJV575.js.map +0 -7
@@ -1,10 +1,10 @@
1
- import{a as nf,b as rf,c as of}from"./chunk-RFBBAUMM.js";var Dl=nf((lt,Ul)=>{var uo=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,lo=(function(){function e(){this.fetch=!1,this.DOMException=uo.DOMException}return e.prototype=uo,new e})();(function(e){var t=(function(n){var r=typeof e<"u"&&e||typeof self<"u"&&self||typeof global<"u"&&global||{},o={searchParams:"URLSearchParams"in r,iterable:"Symbol"in r&&"iterator"in Symbol,blob:"FileReader"in r&&"Blob"in r&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in r,arrayBuffer:"ArrayBuffer"in r};function i(h){return h&&DataView.prototype.isPrototypeOf(h)}if(o.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(h){return h&&a.indexOf(Object.prototype.toString.call(h))>-1};function u(h){if(typeof h!="string"&&(h=String(h)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(h)||h==="")throw new TypeError('Invalid character in header field name: "'+h+'"');return h.toLowerCase()}function c(h){return typeof h!="string"&&(h=String(h)),h}function l(h){var w={next:function(){var z=h.shift();return{done:z===void 0,value:z}}};return o.iterable&&(w[Symbol.iterator]=function(){return w}),w}function d(h){this.map={},h instanceof d?h.forEach(function(w,z){this.append(z,w)},this):Array.isArray(h)?h.forEach(function(w){if(w.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+w.length);this.append(w[0],w[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(w){this.append(w,h[w])},this)}d.prototype.append=function(h,w){h=u(h),w=c(w);var z=this.map[h];this.map[h]=z?z+", "+w:w},d.prototype.delete=function(h){delete this.map[u(h)]},d.prototype.get=function(h){return h=u(h),this.has(h)?this.map[h]:null},d.prototype.has=function(h){return this.map.hasOwnProperty(u(h))},d.prototype.set=function(h,w){this.map[u(h)]=c(w)},d.prototype.forEach=function(h,w){for(var z in this.map)this.map.hasOwnProperty(z)&&h.call(w,this.map[z],z,this)},d.prototype.keys=function(){var h=[];return this.forEach(function(w,z){h.push(z)}),l(h)},d.prototype.values=function(){var h=[];return this.forEach(function(w){h.push(w)}),l(h)},d.prototype.entries=function(){var h=[];return this.forEach(function(w,z){h.push([z,w])}),l(h)},o.iterable&&(d.prototype[Symbol.iterator]=d.prototype.entries);function p(h){if(!h._noBody){if(h.bodyUsed)return Promise.reject(new TypeError("Already read"));h.bodyUsed=!0}}function v(h){return new Promise(function(w,z){h.onload=function(){w(h.result)},h.onerror=function(){z(h.error)}})}function f(h){var w=new FileReader,z=v(w);return w.readAsArrayBuffer(h),z}function y(h){var w=new FileReader,z=v(w),B=/charset=([A-Za-z0-9_-]+)/.exec(h.type),q=B?B[1]:"utf-8";return w.readAsText(h,q),z}function b(h){for(var w=new Uint8Array(h),z=new Array(w.length),B=0;B<w.length;B++)z[B]=String.fromCharCode(w[B]);return z.join("")}function S(h){if(h.slice)return h.slice(0);var w=new Uint8Array(h.byteLength);return w.set(new Uint8Array(h)),w.buffer}function I(){return this.bodyUsed=!1,this._initBody=function(h){this.bodyUsed=this.bodyUsed,this._bodyInit=h,h?typeof h=="string"?this._bodyText=h:o.blob&&Blob.prototype.isPrototypeOf(h)?this._bodyBlob=h:o.formData&&FormData.prototype.isPrototypeOf(h)?this._bodyFormData=h:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)?this._bodyText=h.toString():o.arrayBuffer&&o.blob&&i(h)?(this._bodyArrayBuffer=S(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||s(h))?this._bodyArrayBuffer=S(h):this._bodyText=h=Object.prototype.toString.call(h):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof h=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var h=p(this);return h||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(o.blob)return this.blob().then(f);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return y(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(b(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(C)}),this.json=function(){return this.text().then(JSON.parse)},this}var _=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function E(h){var w=h.toUpperCase();return _.indexOf(w)>-1?w:h}function x(h,w){if(!(this instanceof x))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');w=w||{};var z=w.body;if(h instanceof x){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,w.headers||(this.headers=new d(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!z&&h._bodyInit!=null&&(z=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);if(this.credentials=w.credentials||this.credentials||"same-origin",(w.headers||!this.headers)&&(this.headers=new d(w.headers)),this.method=E(w.method||this.method||"GET"),this.mode=w.mode||this.mode||null,this.signal=w.signal||this.signal||(function(){if("AbortController"in r){var L=new AbortController;return L.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&z)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(z),(this.method==="GET"||this.method==="HEAD")&&(w.cache==="no-store"||w.cache==="no-cache")){var B=/([?&])_=[^&]*/;if(B.test(this.url))this.url=this.url.replace(B,"$1_="+new Date().getTime());else{var q=/\?/;this.url+=(q.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function C(h){var w=new FormData;return h.trim().split("&").forEach(function(z){if(z){var B=z.split("="),q=B.shift().replace(/\+/g," "),L=B.join("=").replace(/\+/g," ");w.append(decodeURIComponent(q),decodeURIComponent(L))}}),w}function U(h){var w=new d,z=h.replace(/\r?\n[\t ]+/g," ");return z.split("\r").map(function(B){return B.indexOf(`
2
- `)===0?B.substr(1,B.length):B}).forEach(function(B){var q=B.split(":"),L=q.shift().trim();if(L){var mt=q.join(":").trim();try{w.append(L,mt)}catch(Ae){console.warn("Response "+Ae.message)}}}),w}I.call(x.prototype);function Z(h,w){if(!(this instanceof Z))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(w||(w={}),this.type="default",this.status=w.status===void 0?200:w.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=w.statusText===void 0?"":""+w.statusText,this.headers=new d(w.headers),this.url=w.url||"",this._initBody(h)}I.call(Z.prototype),Z.prototype.clone=function(){return new Z(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},Z.error=function(){var h=new Z(null,{status:200,statusText:""});return h.ok=!1,h.status=0,h.type="error",h};var Q=[301,302,303,307,308];Z.redirect=function(h,w){if(Q.indexOf(w)===-1)throw new RangeError("Invalid status code");return new Z(null,{status:w,headers:{location:h}})},n.DOMException=r.DOMException;try{new n.DOMException}catch{n.DOMException=function(w,z){this.message=w,this.name=z;var B=Error(w);this.stack=B.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function Ie(h,w){return new Promise(function(z,B){var q=new x(h,w);if(q.signal&&q.signal.aborted)return B(new n.DOMException("Aborted","AbortError"));var L=new XMLHttpRequest;function mt(){L.abort()}L.onload=function(){var ne={statusText:L.statusText,headers:U(L.getAllResponseHeaders()||"")};q.url.indexOf("file://")===0&&(L.status<200||L.status>599)?ne.status=200:ne.status=L.status,ne.url="responseURL"in L?L.responseURL:ne.headers.get("X-Request-URL");var ce="response"in L?L.response:L.responseText;setTimeout(function(){z(new Z(ce,ne))},0)},L.onerror=function(){setTimeout(function(){B(new TypeError("Network request failed"))},0)},L.ontimeout=function(){setTimeout(function(){B(new TypeError("Network request timed out"))},0)},L.onabort=function(){setTimeout(function(){B(new n.DOMException("Aborted","AbortError"))},0)};function Ae(ne){try{return ne===""&&r.location.href?r.location.href:ne}catch{return ne}}if(L.open(q.method,Ae(q.url),!0),q.credentials==="include"?L.withCredentials=!0:q.credentials==="omit"&&(L.withCredentials=!1),"responseType"in L&&(o.blob?L.responseType="blob":o.arrayBuffer&&(L.responseType="arraybuffer")),w&&typeof w.headers=="object"&&!(w.headers instanceof d||r.Headers&&w.headers instanceof r.Headers)){var hn=[];Object.getOwnPropertyNames(w.headers).forEach(function(ne){hn.push(u(ne)),L.setRequestHeader(ne,c(w.headers[ne]))}),q.headers.forEach(function(ne,ce){hn.indexOf(ce)===-1&&L.setRequestHeader(ce,ne)})}else q.headers.forEach(function(ne,ce){L.setRequestHeader(ce,ne)});q.signal&&(q.signal.addEventListener("abort",mt),L.onreadystatechange=function(){L.readyState===4&&q.signal.removeEventListener("abort",mt)}),L.send(typeof q._bodyInit>"u"?null:q._bodyInit)})}return Ie.polyfill=!0,r.fetch||(r.fetch=Ie,r.Headers=d,r.Request=x,r.Response=Z),n.Headers=d,n.Request=x,n.Response=Z,n.fetch=Ie,n})({})})(lo);lo.fetch.ponyfill=!0;delete lo.fetch.polyfill;var tn=uo.fetch?uo:lo;lt=tn.fetch;lt.default=tn.fetch;lt.fetch=tn.fetch;lt.Headers=tn.Headers;lt.Request=tn.Request;lt.Response=tn.Response;Ul.exports=lt});var af={type:"object",properties:{value:{type:"object"},channels:{type:"array",items:{type:"string"}},allowed:{type:"array",items:{type:"string"},nullable:!0},url:{type:"string"},actor:{type:"string"}},additionalProperties:!1,required:["value","channels","actor","url"]},Cy={...af,required:["value","channels"]};var it=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorForbidden",Object.setPrototypeOf(this,e.prototype)}},ae=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotFound",Object.setPrototypeOf(this,e.prototype)}},zt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorInvalidSchema",Object.setPrototypeOf(this,e.prototype)}},pr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorSchemaMismatch",Object.setPrototypeOf(this,e.prototype)}},Ot=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorTooLarge",Object.setPrototypeOf(this,e.prototype)}},mr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotAcceptable",Object.setPrototypeOf(this,e.prototype)}},Ue=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorCursorExpired",Object.setPrototypeOf(this,e.prototype)}};function ri(e){return typeof e=="string"?e:e.url}function oi(e,t,n){if(n===e.actor)return e;let r=e.allowed&&n?[n]:void 0,o=e.channels.filter(i=>t.includes(i));return{...e,...r?{allowed:r}:{},channels:o}}function vs(e,t){let[n,r]=e.toLowerCase().split(";")[0].split("/");return!n||!r?!1:t.some(o=>{let[i,a]=o.toLowerCase().split(";")[0].split("/");return!i||!a?!1:(i===n||i==="*")&&(a===r||a==="*")})}var ni;async function hr(e){if(!ni){let{default:t}=await import("./ajv-QBSREQSI.js");ni=new t({strict:!1})}try{return ni.compile(e)}catch(t){throw new zt(t instanceof Error?t.message:String(t))}}var sf=Object.freeze({status:"aborted"});function P(e,t,n){function r(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);let c=a.prototype,l=Object.keys(c);for(let d=0;d<l.length;d++){let p=l[d];p in s||(s[p]=c[p].bind(s))}}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function a(s){var u;let c=n?.Parent?new i:this;r(c,s),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var Xe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};var ii={};function Ye(e){return e&&Object.assign(ii,e),ii}function si(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function _s(e,t){return typeof t=="bigint"?t.toString():t}function ci(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function vr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var bs=Symbol("evaluating");function fe(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==bs)return r===void 0&&(r=bs,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function cf(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function uf(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}var ui="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var lf=ci(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function gn(e){if(yr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(yr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}var ws=new Set(["string","number","symbol"]);function br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function re(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function xs(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var $s={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Ss(e,t){if(!gn(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=uf(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return cf(this,"shape",i),i}});return yn(e,o)}function ht(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Qe(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function gr(e){return typeof e=="string"?e:e?.message}function at(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let o=gr(e.inst?._zod.def?.error?.(e))??gr(t?.error?.(e))??gr(n.customError?.(e))??gr(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function li(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}var Es=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,_s,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},ks=P("$ZodError",Es),vn=P("$ZodError",Es,{Parent:Error});var ff=e=>(t,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Xe;if(a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>at(u,i,Ye())));throw ui(s,o?.callee),s}return a.value},_r=ff(vn),pf=e=>async(t,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>at(u,i,Ye())));throw ui(s,o?.callee),s}return a.value},wr=pf(vn),mf=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Xe;return i.issues.length?{success:!1,error:new(e??ks)(i.issues.map(a=>at(a,o,Ye())))}:{success:!0,data:i.value}},bn=mf(vn),hf=e=>async(t,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>at(a,o,Ye())))}:{success:!0,data:i.value}},_n=hf(vn);var gf="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",yf=new RegExp(`^${gf}$`);var Is=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var As=/^-?\d+$/,di=/^-?\d+(?:\.\d+)?$/,Ts=/^(?:true|false)$/i;var Ps=/^undefined$/i;var gt=P("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),vf={number:"number",bigint:"bigint",object:"date"};var zs=P("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);let n=vf[typeof t.value];e._zod.onattach.push(r=>{let o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var Os=P("$ZodCheckNumberFormat",(e,t)=>{gt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=$s[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=o,s.maximum=i,n&&(s.pattern=As)}),e._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Us=P("$ZodCheckStringFormat",(e,t)=>{var n,r;gt.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})});var Rs={major:4,minor:3,patch:5};var ee=P("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Rs;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let o of r)for(let i of o._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,s,u)=>{let c=ht(a),l;for(let d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(c)continue;let p=a.issues.length,v=d._zod.check(a);if(v instanceof Promise&&u?.async===!1)throw new Xe;if(l||v instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await v,a.issues.length!==p&&(c||(c=ht(a,p)))});else{if(a.issues.length===p)continue;c||(c=ht(a,p))}}return l?l.then(()=>a):a},i=(a,s,u)=>{if(ht(a))return a.aborted=!0,a;let c=o(s,r,u);if(c instanceof Promise){if(u.async===!1)throw new Xe;return c.then(l=>e._zod.parse(l,u))}return e._zod.parse(c,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let c=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return c instanceof Promise?c.then(l=>i(l,a,s)):i(c,a,s)}let u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new Xe;return u.then(c=>o(c,r,s))}return o(u,r,s)}}fe(e,"~standard",()=>({validate:o=>{try{let i=bn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return _n(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Sr=P("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Is(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),pi=P("$ZodStringFormat",(e,t)=>{Us.init(e,t),Sr.init(e,t)});var Zs=P("$ZodURL",(e,t)=>{pi.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}});var mi=P("$ZodNumber",(e,t)=>{ee.init(e,t),e._zod.pattern=e._zod.bag.pattern??di,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Bs=P("$ZodNumberFormat",(e,t)=>{Os.init(e,t),mi.init(e,t)}),hi=P("$ZodBoolean",(e,t)=>{ee.init(e,t),e._zod.pattern=Ts,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var Fs=P("$ZodUndefined",(e,t)=>{ee.init(e,t),e._zod.pattern=Ps,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}});var Hs=P("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=n=>n}),Js=P("$ZodNever",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function js(e,t,n){e.issues.length&&t.issues.push(...Qe(n,e.issues)),t.value[n]=e.value}var Gs=P("$ZodArray",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let s=o[a],u=t.element._zod.run({value:s,issues:[]},r);u instanceof Promise?i.push(u.then(c=>js(c,n,a))):js(u,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function $r(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...Qe(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function bf(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=xs(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function _f(e,t,n,r,o,i){let a=[],s=o.keySet,u=o.catchall._zod,c=u.def.type,l=u.optout==="optional";for(let d in t){if(s.has(d))continue;if(c==="never"){a.push(d);continue}let p=u.run({value:t[d],issues:[]},r);p instanceof Promise?e.push(p.then(v=>$r(v,n,d,t,l))):$r(p,n,d,t,l)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var Vs=P("$ZodObject",(e,t)=>{if(ee.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}let r=ci(()=>bf(t));fe(e._zod,"propValues",()=>{let s=t.shape,u={};for(let c in s){let l=s[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(let d of l.values)u[c].add(d)}}return u});let o=yr,i=t.catchall,a;e._zod.parse=(s,u)=>{a??(a=r.value);let c=s.value;if(!o(c))return s.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),s;s.value={};let l=[],d=a.shape;for(let p of a.keys){let v=d[p],f=v._zod.optout==="optional",y=v._zod.run({value:c[p],issues:[]},u);y instanceof Promise?l.push(y.then(b=>$r(b,s,p,c,f))):$r(y,s,p,c,f)}return i?_f(l,c,s,u,r.value,e):l.length?Promise.all(l).then(()=>s):s}});function Ns(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!ht(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>at(a,r,Ye())))}),t)}var qs=P("$ZodUnion",(e,t)=>{ee.init(e,t),fe(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),fe(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),fe(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),fe(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>vr(i.source)).join("|")})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1,s=[];for(let u of t.options){let c=u._zod.run({value:o.value,issues:[]},i);if(c instanceof Promise)s.push(c),a=!0;else{if(c.issues.length===0)return c;s.push(c)}}return a?Promise.all(s).then(u=>Ns(u,o,e,i)):Ns(s,o,e,i)}});var Ks=P("$ZodIntersection",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,c])=>Cs(n,u,c)):Cs(n,i,a)}});function fi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(gn(e)&&gn(t)){let n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(let i of r){let a=fi(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],a=fi(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Cs(e,t,n){let r=new Map,o;for(let s of t.issues)if(s.code==="unrecognized_keys"){o??(o=s);for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else e.issues.push(s);for(let s of n.issues)if(s.code==="unrecognized_keys")for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else e.issues.push(s);let i=[...r].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&o&&e.issues.push({...o,keys:i}),ht(e))return e;let a=fi(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ws=P("$ZodTuple",(e,t)=>{ee.init(e,t);let n=t.items;e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];let a=[],s=[...n].reverse().findIndex(l=>l._zod.optin!=="optional"),u=s===-1?0:n.length-s;if(!t.rest){let l=i.length>n.length,d=i.length<u-1;if(l||d)return r.issues.push({...l?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:i,inst:e,origin:"array"}),r}let c=-1;for(let l of n){if(c++,c>=i.length&&c>=u)continue;let d=l._zod.run({value:i[c],issues:[]},o);d instanceof Promise?a.push(d.then(p=>xr(p,r,c))):xr(d,r,c)}if(t.rest){let l=i.slice(n.length);for(let d of l){c++;let p=t.rest._zod.run({value:d,issues:[]},o);p instanceof Promise?a.push(p.then(v=>xr(v,r,c))):xr(p,r,c)}}return a.length?Promise.all(a).then(()=>r):r}});function xr(e,t,n){e.issues.length&&t.issues.push(...Qe(n,e.issues)),t.value[n]=e.value}var Xs=P("$ZodRecord",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!gn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a){n.value={};let s=new Set;for(let c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){s.add(typeof c=="number"?c.toString():c);let l=t.valueType._zod.run({value:o[c],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...Qe(c,d.issues)),n.value[c]=d.value})):(l.issues.length&&n.issues.push(...Qe(c,l.issues)),n.value[c]=l.value)}let u;for(let c in o)s.has(c)||(u=u??[],u.push(c));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let u=t.keyType._zod.run({value:s,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&di.test(s)&&u.issues.length&&u.issues.some(d=>d.code==="invalid_type"&&d.expected==="number")){let d=t.keyType._zod.run({value:Number(s),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(u=d)}if(u.issues.length){t.mode==="loose"?n.value[s]=o[s]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(d=>at(d,r,Ye())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:o[s],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...Qe(s,d.issues)),n.value[u.value]=d.value})):(l.issues.length&&n.issues.push(...Qe(s,l.issues)),n.value[u.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}});var Ys=P("$ZodEnum",(e,t)=>{ee.init(e,t);let n=si(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>ws.has(typeof o)).map(o=>typeof o=="string"?br(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return r.has(a)||o.issues.push({code:"invalid_value",values:n,input:a,inst:e}),o}});function Ls(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var Qs=P("$ZodOptional",(e,t)=>{ee.init(e,t),e._zod.optin="optional",e._zod.optout="optional",fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),fe(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${vr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Ls(i,n.value)):Ls(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var ec=P("$ZodNullable",(e,t)=>{ee.init(e,t),fe(e._zod,"optin",()=>t.innerType._zod.optin),fe(e._zod,"optout",()=>t.innerType._zod.optout),fe(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${vr(n.source)}|null)$`):void 0}),fe(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)});var tc=P("$ZodCustom",(e,t)=>{gt.init(e,t),ee.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Ms(i,n,r,e));Ms(o,n,r,e)}});function Ms(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(li(o))}}var rc;var gi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function oc(){return new gi}(rc=globalThis).__zod_globalRegistry??(rc.__zod_globalRegistry=oc());var yi=globalThis.__zod_globalRegistry;function ic(e,t){return new e({type:"string",...re(t)})}function ac(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function sc(e,t){return new e({type:"number",checks:[],...re(t)})}function cc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function uc(e,t){return new e({type:"boolean",...re(t)})}function lc(e,t){return new e({type:"undefined",...re(t)})}function dc(e){return new e({type:"unknown"})}function fc(e,t){return new e({type:"never",...re(t)})}function vi(e,t){return new zs({check:"greater_than",...re(t),value:e,inclusive:!0})}function yt(e){return vi(0,e)}function pc(e,t,n){let r=re(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}var ue=P("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>_r(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>bn(e,n,r),e.parseAsync=async(n,r)=>wr(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>_n(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0}),e.with=e.check,e.clone=(n,r)=>yn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),bi=P("ZodMiniString",(e,t)=>{Sr.init(e,t),ue.init(e,t)});function H(e){return ic(bi,e)}var mc=P("ZodMiniStringFormat",(e,t)=>{pi.init(e,t),bi.init(e,t)});var Uf=P("ZodMiniURL",(e,t)=>{Zs.init(e,t),mc.init(e,t)});function J(e){return ac(Uf,e)}var _i=P("ZodMiniNumber",(e,t)=>{mi.init(e,t),ue.init(e,t)});function hc(e){return sc(_i,e)}var Df=P("ZodMiniNumberFormat",(e,t)=>{Bs.init(e,t),_i.init(e,t)});function Ut(e){return cc(Df,e)}var gc=P("ZodMiniBoolean",(e,t)=>{hi.init(e,t),ue.init(e,t)});function wi(e){return uc(gc,e)}var Rf=P("ZodMiniUndefined",(e,t)=>{Fs.init(e,t),ue.init(e,t)});function yc(e){return lc(Rf,e)}var jf=P("ZodMiniUnknown",(e,t)=>{Hs.init(e,t),ue.init(e,t)});function Nf(){return dc(jf)}var Cf=P("ZodMiniNever",(e,t)=>{Js.init(e,t),ue.init(e,t)});function Lf(e){return fc(Cf,e)}var Mf=P("ZodMiniArray",(e,t)=>{Gs.init(e,t),ue.init(e,t)});function V(e,t){return new Mf({type:"array",element:e,...re(t)})}var xi=P("ZodMiniObject",(e,t)=>{Vs.init(e,t),ue.init(e,t),fe(e,"shape",()=>t.shape)});function ve(e,t){let n={type:"object",shape:e??{},...re(t)};return new xi(n)}function be(e,t){return new xi({type:"object",shape:e,catchall:Lf(),...re(t)})}function me(e,t){return new xi({type:"object",shape:e,catchall:Nf(),...re(t)})}function et(e,t){return Ss(e,t)}var Zf=P("ZodMiniUnion",(e,t)=>{qs.init(e,t),ue.init(e,t)});function st(e,t){return new Zf({type:"union",options:e,...re(t)})}var Bf=P("ZodMiniIntersection",(e,t)=>{Ks.init(e,t),ue.init(e,t)});function vc(e,t){return new Bf({type:"intersection",left:e,right:t})}var Ff=P("ZodMiniTuple",(e,t)=>{Ws.init(e,t),ue.init(e,t)});function le(e,t,n){let r=t instanceof ee,o=r?n:t,i=r?t:null;return new Ff({type:"tuple",items:e,rest:i,...re(o)})}var Hf=P("ZodMiniRecord",(e,t)=>{Xs.init(e,t),ue.init(e,t)});function bc(e,t,n){return new Hf({type:"record",keyType:e,valueType:t,...re(n)})}var Jf=P("ZodMiniEnum",(e,t)=>{Ys.init(e,t),ue.init(e,t),e.options=Object.values(t.entries)});function _c(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Jf({type:"enum",entries:n,...re(t)})}var Gf=P("ZodMiniOptional",(e,t)=>{Qs.init(e,t),ue.init(e,t)});function X(e){return new Gf({type:"optional",innerType:e})}var Vf=P("ZodMiniNullable",(e,t)=>{ec.init(e,t),ue.init(e,t)});function Le(e){return new Vf({type:"nullable",innerType:e})}var qf=P("ZodMiniCustom",(e,t)=>{tc.init(e,t),ue.init(e,t)});function vt(e,t){return pc(qf,e??(()=>!0),t)}function Dt(e,t={}){let n=vt(r=>r instanceof e,t);return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Sc=me({value:me({}),channels:V(H()),allowed:X(Le(V(J())))}),dE=et(Sc,{url:J(),actor:J()}),xc=st([me({url:J()}),J()]),Rt=me({actor:J()}),xn=X(Le(Rt)),Ec=me({data:Dt(Blob),allowed:X(Le(V(J())))}),fE=et(Ec,{actor:J()}),Qf=me({types:X(V(H())),maxBytes:X(Ut().check(yt()))});async function*$c(e){for(;;){let t=await e.next();if(t.done){let{cursor:n,continue:r}=t.value;return{cursor:n,continue:(...o)=>{let i=le([xn]).parse(o);return r(...i)}}}else yield t.value}}var kr=class{constructor(t){this.graffiti=t,this.sessionEvents=this.graffiti.sessionEvents}sessionEvents;login=(...t)=>{let n=le([X(J())]).parse(t);return this.graffiti.login(...n)};logout=(...t)=>{let n=le([Rt]).parse(t);return this.graffiti.logout(...n)};handleToActor=(...t)=>{let n=le([H()]).parse(t);return this.graffiti.handleToActor(...n)};actorToHandle=(...t)=>{let n=le([J()]).parse(t);return this.graffiti.actorToHandle(...n)};post=(...t)=>{let n=le([Sc,Rt]).parse(t);return this.graffiti.post(...n)};get=(...t)=>{let n=le([xc,me({}),xn]).parse(t);return this.graffiti.get(n[0],n[1],n[2])};delete=(...t)=>{let n=le([xc,Rt]).parse(t);return this.graffiti.delete(...n)};postMedia=(...t)=>{let n=le([Ec,Rt]).parse(t);return this.graffiti.postMedia(...n)};getMedia=(...t)=>{let n=le([J(),Qf,xn]).parse(t);return this.graffiti.getMedia(...n)};deleteMedia=(...t)=>{let n=le([J(),Rt]).parse(t);return this.graffiti.deleteMedia(...n)};discover=(...t)=>{let n=le([V(H()),me({}),xn]).parse(t),r=this.graffiti.discover(n[0],n[1],n[2]);return $c(r)};continueDiscover=(...t)=>{let n=le([H(),xn]).parse(t),r=this.graffiti.continueDiscover(...n);return $c(r)}};function ep(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function $i(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >= 0, got ${e}`)}}function Ir(e,t,n=""){let r=ep(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;throw new Error(a+"expected Uint8Array"+s+", got "+u)}return e}function kc(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");$i(e.outputLen),$i(e.blockLen)}function bt(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var tp=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Si(e){if(e===null)return"null";if(e===void 0)return"undefined";if(e===!0||e===!1)return"boolean";let t=typeof e;if(t==="string"||t==="number"||t==="bigint"||t==="symbol")return t;if(t==="function")return"Function";if(Array.isArray(e))return"Array";if(e instanceof Uint8Array)return"Uint8Array";if(e.constructor===Object)return"Object";let n=np(e);return n||"Object"}function np(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(tp.includes(t))return t}var g=class{constructor(t,n,r){this.major=t,this.majorEncoded=t<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,n){return t===n||t.major===n.major&&t.name===n.name}};g.uint=new g(0,"uint",!0);g.negint=new g(1,"negint",!0);g.bytes=new g(2,"bytes",!0);g.string=new g(3,"string",!0);g.array=new g(4,"array",!1);g.map=new g(5,"map",!1);g.tag=new g(6,"tag",!1);g.float=new g(7,"float",!0);g.false=new g(7,"false",!0);g.true=new g(7,"true",!0);g.null=new g(7,"null",!0);g.undefined=new g(7,"undefined",!0);g.break=new g(7,"break",!0);var k=class{constructor(t,n,r){this.type=t,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var $n=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",rp=new TextEncoder;function Ar(e){return $n&&globalThis.Buffer.isBuffer(e)}function Ei(e){return e instanceof Uint8Array?Ar(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var Tr=$n?e=>e.length>64?globalThis.Buffer.from(e):Ic(e):e=>e.length>64?rp.encode(e):Ic(e),Me=e=>Uint8Array.from(e),jt=$n?(e,t,n)=>Ar(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),Ac=$n?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Ei(globalThis.Buffer.concat(e,t))):(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)r+o.length>n.length&&(o=o.subarray(0,n.length-r)),n.set(o,r),r+=o.length;return n},Tc=$n?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function Pr(e,t){if(Ar(e)&&Ar(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function Ic(e){let t=[],n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(o=65536+((o&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128)}return t}var op=256,Sn=class{constructor(t=op){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let n=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=n.length-(this.maxCursor-this.cursor)-1;n.set(t,o)}else{if(n){let o=n.length-(this.maxCursor-this.cursor)-1;o<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(n=Tc(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=jt(r,0,this.cursor)}else n=Ac(this.chunks,this.cursor);return t&&this.reset(),n}},zr=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let n=this.dest.subarray(0,this.cursor);return t&&this.reset(),n}};var M="CBOR decode error:",Or="CBOR encode error:",En=[];En[23]=1;En[24]=2;En[25]=3;En[26]=5;En[27]=9;function tt(e,t,n){if(e.length-t<n)throw new Error(`${M} not enough data for type`)}var ie=[24,256,65536,4294967296,BigInt("18446744073709551616")];function _e(e,t,n){tt(e,t,1);let r=e[t];if(n.strict===!0&&r<ie[0])throw new Error(`${M} integer encoded in more bytes than necessary (strict decode)`);return r}function we(e,t,n){tt(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<ie[1])throw new Error(`${M} integer encoded in more bytes than necessary (strict decode)`);return r}function xe(e,t,n){tt(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<ie[2])throw new Error(`${M} integer encoded in more bytes than necessary (strict decode)`);return r}function $e(e,t,n){tt(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],o=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],i=(BigInt(r)<<BigInt(32))+BigInt(o);if(n.strict===!0&&i<ie[3])throw new Error(`${M} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(n.allowBigInt===!0)return i;throw new Error(`${M} integers outside of the safe integer range are not supported`)}function Pc(e,t,n,r){return new k(g.uint,_e(e,t+1,r),2)}function zc(e,t,n,r){return new k(g.uint,we(e,t+1,r),3)}function Oc(e,t,n,r){return new k(g.uint,xe(e,t+1,r),5)}function Uc(e,t,n,r){return new k(g.uint,$e(e,t+1,r),9)}function Te(e,t){return W(e,0,t.value)}function W(e,t,n){if(n<ie[0]){let r=Number(n);e.push([t|r])}else if(n<ie[1]){let r=Number(n);e.push([t|24,r])}else if(n<ie[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<ie[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<ie[4]){let o=[t|27,0,0,0,0,0,0,0],i=Number(r&BigInt(4294967295)),a=Number(r>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=a&255,a=a>>8,o[3]=a&255,a=a>>8,o[2]=a&255,a=a>>8,o[1]=a&255,e.push(o)}else throw new Error(`${M} encountered BigInt larger than allowable range`)}}Te.encodedSize=function(t){return W.encodedSize(t.value)};W.encodedSize=function(t){return t<ie[0]?1:t<ie[1]?2:t<ie[2]?3:t<ie[3]?5:9};Te.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function Dc(e,t,n,r){return new k(g.negint,-1-_e(e,t+1,r),2)}function Rc(e,t,n,r){return new k(g.negint,-1-we(e,t+1,r),3)}function jc(e,t,n,r){return new k(g.negint,-1-xe(e,t+1,r),5)}var ki=BigInt(-1),Nc=BigInt(1);function Cc(e,t,n,r){let o=$e(e,t+1,r);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new k(g.negint,i,9)}if(r.allowBigInt!==!0)throw new Error(`${M} integers outside of the safe integer range are not supported`);return new k(g.negint,ki-BigInt(o),9)}function Ur(e,t){let n=t.value,r=typeof n=="bigint"?n*ki-Nc:n*-1-1;W(e,t.type.majorEncoded,r)}Ur.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*ki-Nc:n*-1-1;return r<ie[0]?1:r<ie[1]?2:r<ie[2]?3:r<ie[3]?5:9};Ur.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function kn(e,t,n,r){tt(e,t,n+r);let o=jt(e,t+n,t+n+r);return new k(g.bytes,o,n+r)}function Lc(e,t,n,r){return kn(e,t,1,n)}function Mc(e,t,n,r){return kn(e,t,2,_e(e,t+1,r))}function Zc(e,t,n,r){return kn(e,t,3,we(e,t+1,r))}function Bc(e,t,n,r){return kn(e,t,5,xe(e,t+1,r))}function Fc(e,t,n,r){let o=$e(e,t+1,r);if(typeof o=="bigint")throw new Error(`${M} 64-bit integer bytes lengths not supported`);return kn(e,t,9,o)}function Dr(e){return e.encodedBytes===void 0&&(e.encodedBytes=g.equals(e.type,g.string)?Tr(e.value):e.value),e.encodedBytes}function Nt(e,t){let n=Dr(t);W(e,t.type.majorEncoded,n.length),e.push(n)}Nt.encodedSize=function(t){let n=Dr(t);return W.encodedSize(n.length)+n.length};Nt.compareTokens=function(t,n){return ap(Dr(t),Dr(n))};function ap(e,t){return e.length<t.length?-1:e.length>t.length?1:Pr(e,t)}var Hc=new TextDecoder,cp=32;function up(e,t,n){if(n-t<cp){let o="";for(let i=t;i<n;i++){let a=e[i];if(a&128)return Hc.decode(e.subarray(t,n));o+=String.fromCharCode(a)}return o}return Hc.decode(e.subarray(t,n))}function In(e,t,n,r,o){let i=n+r;tt(e,t,i);let a=new k(g.string,up(e,t+n,t+i),i);return o.retainStringBytes===!0&&(a.byteValue=jt(e,t+n,t+i)),a}function Jc(e,t,n,r){return In(e,t,1,n,r)}function Gc(e,t,n,r){return In(e,t,2,_e(e,t+1,r),r)}function Vc(e,t,n,r){return In(e,t,3,we(e,t+1,r),r)}function qc(e,t,n,r){return In(e,t,5,xe(e,t+1,r),r)}function Kc(e,t,n,r){let o=$e(e,t+1,r);if(typeof o=="bigint")throw new Error(`${M} 64-bit integer string lengths not supported`);return In(e,t,9,o,r)}var Wc=Nt;function Ct(e,t,n,r){return new k(g.array,r,n)}function Xc(e,t,n,r){return Ct(e,t,1,n)}function Yc(e,t,n,r){return Ct(e,t,2,_e(e,t+1,r))}function Qc(e,t,n,r){return Ct(e,t,3,we(e,t+1,r))}function eu(e,t,n,r){return Ct(e,t,5,xe(e,t+1,r))}function tu(e,t,n,r){let o=$e(e,t+1,r);if(typeof o=="bigint")throw new Error(`${M} 64-bit integer array lengths not supported`);return Ct(e,t,9,o)}function nu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${M} indefinite length items not allowed`);return Ct(e,t,1,1/0)}function Rr(e,t){W(e,g.array.majorEncoded,t.value)}Rr.compareTokens=Te.compareTokens;Rr.encodedSize=function(t){return W.encodedSize(t.value)};function Lt(e,t,n,r){return new k(g.map,r,n)}function ru(e,t,n,r){return Lt(e,t,1,n)}function ou(e,t,n,r){return Lt(e,t,2,_e(e,t+1,r))}function iu(e,t,n,r){return Lt(e,t,3,we(e,t+1,r))}function au(e,t,n,r){return Lt(e,t,5,xe(e,t+1,r))}function su(e,t,n,r){let o=$e(e,t+1,r);if(typeof o=="bigint")throw new Error(`${M} 64-bit integer map lengths not supported`);return Lt(e,t,9,o)}function cu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${M} indefinite length items not allowed`);return Lt(e,t,1,1/0)}function jr(e,t){W(e,g.map.majorEncoded,t.value)}jr.compareTokens=Te.compareTokens;jr.encodedSize=function(t){return W.encodedSize(t.value)};function uu(e,t,n,r){return new k(g.tag,n,1)}function lu(e,t,n,r){return new k(g.tag,_e(e,t+1,r),2)}function du(e,t,n,r){return new k(g.tag,we(e,t+1,r),3)}function fu(e,t,n,r){return new k(g.tag,xe(e,t+1,r),5)}function pu(e,t,n,r){return new k(g.tag,$e(e,t+1,r),9)}function Nr(e,t){W(e,g.tag.majorEncoded,t.value)}Nr.compareTokens=Te.compareTokens;Nr.encodedSize=function(t){return W.encodedSize(t.value)};var Ii=20,Ai=21,Ti=22,Pi=23;function mu(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${M} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new k(g.null,null,1):new k(g.undefined,void 0,1)}function hu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${M} indefinite length items not allowed`);return new k(g.break,void 0,1)}function zi(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${M} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${M} Infinity values are not supported`)}return new k(g.float,e,t)}function gu(e,t,n,r){return zi(Oi(e,t+1),3,r)}function yu(e,t,n,r){return zi(Ui(e,t+1),5,r)}function vu(e,t,n,r){return zi(xu(e,t+1),9,r)}function An(e,t,n){let r=t.value;if(r===!1)e.push([g.float.majorEncoded|Ii]);else if(r===!0)e.push([g.float.majorEncoded|Ai]);else if(r===null)e.push([g.float.majorEncoded|Ti]);else if(r===void 0)e.push([g.float.majorEncoded|Pi]);else{let o,i=!1;(!n||n.float64!==!0)&&(_u(r),o=Oi(De,1),r===o||Number.isNaN(r)?(De[0]=249,e.push(De.slice(0,3)),i=!0):(wu(r),o=Ui(De,1),r===o&&(De[0]=250,e.push(De.slice(0,5)),i=!0))),i||(mp(r),o=xu(De,1),De[0]=251,e.push(De.slice(0,9)))}}An.encodedSize=function(t,n){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){_u(r);let o=Oi(De,1);if(r===o||Number.isNaN(r))return 3;if(wu(r),o=Ui(De,1),r===o)return 5}return 9};var bu=new ArrayBuffer(9),Pe=new DataView(bu,1),De=new Uint8Array(bu,0);function _u(e){if(e===1/0)Pe.setUint16(0,31744,!1);else if(e===-1/0)Pe.setUint16(0,64512,!1);else if(Number.isNaN(e))Pe.setUint16(0,32256,!1);else{Pe.setFloat32(0,e);let t=Pe.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)Pe.setUint16(0,31744,!1);else if(n===0)Pe.setUint16(0,(e&2147483648)>>16|r>>13,!1);else{let o=n-127;o<-24?Pe.setUint16(0,0):o<-14?Pe.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):Pe.setUint16(0,(t&2147483648)>>16|o+15<<10|r>>13,!1)}}}function Oi(e,t){if(e.length-t<2)throw new Error(`${M} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,o=n&1023,i;return r===0?i=o*2**-24:r!==31?i=(o+1024)*2**(r-25):i=o===0?1/0:NaN,n&32768?-i:i}function wu(e){Pe.setFloat32(0,e,!1)}function Ui(e,t){if(e.length-t<4)throw new Error(`${M} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function mp(e){Pe.setFloat64(0,e,!1)}function xu(e,t){if(e.length-t<8)throw new Error(`${M} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}An.compareTokens=Te.compareTokens;function F(e,t,n){throw new Error(`${M} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Cr(e){return()=>{throw new Error(`${M} ${e}`)}}var $=[];for(let e=0;e<=23;e++)$[e]=F;$[24]=Pc;$[25]=zc;$[26]=Oc;$[27]=Uc;$[28]=F;$[29]=F;$[30]=F;$[31]=F;for(let e=32;e<=55;e++)$[e]=F;$[56]=Dc;$[57]=Rc;$[58]=jc;$[59]=Cc;$[60]=F;$[61]=F;$[62]=F;$[63]=F;for(let e=64;e<=87;e++)$[e]=Lc;$[88]=Mc;$[89]=Zc;$[90]=Bc;$[91]=Fc;$[92]=F;$[93]=F;$[94]=F;$[95]=Cr("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)$[e]=Jc;$[120]=Gc;$[121]=Vc;$[122]=qc;$[123]=Kc;$[124]=F;$[125]=F;$[126]=F;$[127]=Cr("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)$[e]=Xc;$[152]=Yc;$[153]=Qc;$[154]=eu;$[155]=tu;$[156]=F;$[157]=F;$[158]=F;$[159]=nu;for(let e=160;e<=183;e++)$[e]=ru;$[184]=ou;$[185]=iu;$[186]=au;$[187]=su;$[188]=F;$[189]=F;$[190]=F;$[191]=cu;for(let e=192;e<=215;e++)$[e]=uu;$[216]=lu;$[217]=du;$[218]=fu;$[219]=pu;$[220]=F;$[221]=F;$[222]=F;$[223]=F;for(let e=224;e<=243;e++)$[e]=Cr("simple values are not supported");$[244]=F;$[245]=F;$[246]=F;$[247]=mu;$[248]=Cr("simple values are not supported");$[249]=gu;$[250]=yu;$[251]=vu;$[252]=F;$[253]=F;$[254]=F;$[255]=hu;var Re=[];for(let e=0;e<24;e++)Re[e]=new k(g.uint,e,1);for(let e=-1;e>=-24;e--)Re[31-e]=new k(g.negint,e,1);Re[64]=new k(g.bytes,new Uint8Array(0),1);Re[96]=new k(g.string,"",1);Re[128]=new k(g.array,0,1);Re[160]=new k(g.map,0,1);Re[244]=new k(g.false,!1,1);Re[245]=new k(g.true,!0,1);Re[246]=new k(g.null,null,1);function Di(e){switch(e.type){case g.false:return Me([244]);case g.true:return Me([245]);case g.null:return Me([246]);case g.bytes:return e.value.length?void 0:Me([64]);case g.string:return e.value===""?Me([96]):void 0;case g.array:return e.value===0?Me([128]):void 0;case g.map:return e.value===0?Me([160]):void 0;case g.uint:return e.value<24?Me([Number(e.value)]):void 0;case g.negint:if(e.value>=-24)return Me([31-Number(e.value)])}}var gp={float64:!1,mapSorter:bp,quickEncodeToken:Di},Iu=Object.freeze({float64:!0,mapSorter:_p,quickEncodeToken:Di});function yp(){let e=[];return e[g.uint.major]=Te,e[g.negint.major]=Ur,e[g.bytes.major]=Nt,e[g.string.major]=Wc,e[g.array.major]=Rr,e[g.map.major]=jr,e[g.tag.major]=Nr,e[g.float.major]=An,e}var Mt=yp(),Lr=new Sn,Pn=class e{constructor(t,n){this.obj=t,this.parent=n}includes(t){let n=this;do if(n.obj===t)return!0;while(n=n.parent);return!1}static createCheck(t,n){if(t&&t.includes(n))throw new Error(`${Or} object contains circular references`);return new e(n,t)}},ct={null:new k(g.null,null),undefined:new k(g.undefined,void 0),true:new k(g.true,!0),false:new k(g.false,!1),emptyArray:new k(g.array,0),emptyMap:new k(g.map,0)},Ze={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new k(g.float,e):e>=0?new k(g.uint,e):new k(g.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new k(g.uint,e):new k(g.negint,e)},Uint8Array(e,t,n,r){return new k(g.bytes,e)},string(e,t,n,r){return new k(g.string,e)},boolean(e,t,n,r){return e?ct.true:ct.false},null(e,t,n,r){return ct.null},undefined(e,t,n,r){return ct.undefined},ArrayBuffer(e,t,n,r){return new k(g.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new k(g.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[ct.emptyArray,new k(g.break)]:ct.emptyArray;r=Pn.createCheck(r,e);let o=[],i=0;for(let a of e)o[i++]=Mr(a,n,r);return n.addBreakTokens?[new k(g.array,e.length),o,new k(g.break)]:[new k(g.array,e.length),o]},Object(e,t,n,r){let o=t!=="Object",i=o?e.keys():Object.keys(e),a=o?e.size:i.length,s;if(a){s=new Array(a),r=Pn.createCheck(r,e);let u=!o&&n.ignoreUndefinedProperties,c=0;for(let l of i){let d=o?e.get(l):e[l];u&&d===void 0||(s[c++]=[Mr(l,n,r),Mr(d,n,r)])}c<a&&(s.length=c)}return s?.length?(vp(s,n),n.addBreakTokens?[new k(g.map,s.length),s,new k(g.break)]:[new k(g.map,s.length),s]):n.addBreakTokens===!0?[ct.emptyMap,new k(g.break)]:ct.emptyMap}};Ze.Map=Ze.Object;Ze.Buffer=Ze.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Ze[`${e}Array`]=Ze.DataView;function Mr(e,t={},n){let r=Si(e),o=t&&t.typeEncoders&&t.typeEncoders[r]||Ze[r];if(typeof o=="function"){let a=o(e,r,t,n);if(a!=null)return a}let i=Ze[r];if(!i)throw new Error(`${Or} unsupported type: ${r}`);return i(e,r,t,n)}function vp(e,t){t.mapSorter&&e.sort(t.mapSorter)}function bp(e,t){let n=Array.isArray(e[0])?e[0][0]:e[0],r=Array.isArray(t[0])?t[0][0]:t[0];if(n.type!==r.type)return n.type.compare(r.type);let o=n.type.major,i=Mt[o].compareTokens(n,r);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function _p(e,t){if(e[0]instanceof k&&t[0]instanceof k){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=$u(n.value)),r._keyBytes||(r._keyBytes=$u(r.value)),Pr(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function $u(e){return Tu(e,Mt,Iu)}function Tn(e,t,n,r){if(Array.isArray(t))for(let o of t)Tn(e,o,n,r);else n[t.type.major](e,t,r)}var Su=g.uint.majorEncoded,Eu=g.negint.majorEncoded,wp=g.bytes.majorEncoded,xp=g.string.majorEncoded,ku=g.array.majorEncoded,$p=g.float.majorEncoded|Ii,Sp=g.float.majorEncoded|Ai,Ep=g.float.majorEncoded|Ti,kp=g.float.majorEncoded|Pi,Ip=BigInt(-1),Ap=BigInt(1);function Tp(e){return e.addBreakTokens!==!0}function Au(e,t,n,r){let o=Si(t),i=n.typeEncoders&&n.typeEncoders[o];if(i){let a=i(t,o,n,r);if(a!=null){Tn(e,a,Mt,n);return}}switch(o){case"null":e.push([Ep]);return;case"undefined":e.push([kp]);return;case"boolean":e.push([t?Sp:$p]);return;case"number":!Number.isInteger(t)||!Number.isSafeInteger(t)?An(e,new k(g.float,t),n):t>=0?W(e,Su,t):W(e,Eu,t*-1-1);return;case"bigint":t>=BigInt(0)?W(e,Su,t):W(e,Eu,t*Ip-Ap);return;case"string":{let a=Tr(t);W(e,xp,a.length),e.push(a);return}case"Uint8Array":W(e,wp,t.length),e.push(t);return;case"Array":if(!t.length){e.push([ku]);return}r=Pn.createCheck(r,t),W(e,ku,t.length);for(let a of t)Au(e,a,n,r);return;case"Object":case"Map":{let a=Ze.Object(t,o,n,r);Tn(e,a,Mt,n)}return;default:{let a=Ze[o];if(!a)throw new Error(`${Or} unsupported type: ${o}`);let s=a(t,o,n,r);Tn(e,s,Mt,n)}}}function Tu(e,t,n,r){let o=r instanceof Uint8Array,i=o?new zr(r):Lr,a=Mr(e,n);if(!Array.isArray(a)&&n.quickEncodeToken){let s=n.quickEncodeToken(a);if(s)return o?(i.push(s),i.toBytes()):s;let u=t[a.type.major];if(u.encodedSize){let c=u.encodedSize(a,n);if(o||(i=new Sn(c)),u(i,a,n),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${a} was wrong`);return o?i.toBytes():Ei(i.chunks[0])}}return i.reset(),Tn(i,a,t,n),i.toBytes(!0)}function Ri(e,t){return t=Object.assign({},gp,t),Tp(t)?(Lr.reset(),Au(Lr,e,t,void 0),Lr.toBytes(!0)):Tu(e,Mt,t)}var Pp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Zr=class{constructor(t,n={}){this._pos=0,this.data=t,this.options=n}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let t=this.data[this._pos],n=Re[t];if(n===void 0){let r=$[t];if(!r)throw new Error(`${M} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;n=r(this.data,this._pos,o,this.options)}return this._pos+=n.encodedLength,n}},zn=Symbol.for("DONE"),Br=Symbol.for("BREAK");function zp(e,t,n){let r=[];for(let o=0;o<e.value;o++){let i=Zt(t,n);if(i===Br){if(e.value===1/0)break;throw new Error(`${M} got unexpected break to lengthed array`)}if(i===zn)throw new Error(`${M} found array but not enough entries (got ${o}, expected ${e.value})`);r[o]=i}return r}function Op(e,t,n){let r=n.useMaps===!0,o=n.rejectDuplicateMapKeys===!0,i=r?void 0:{},a=r?new Map:void 0;for(let s=0;s<e.value;s++){let u=Zt(t,n);if(u===Br){if(e.value===1/0)break;throw new Error(`${M} got unexpected break to lengthed map`)}if(u===zn)throw new Error(`${M} found map but not enough entries (got ${s} [no key], expected ${e.value})`);if(!r&&typeof u!="string")throw new Error(`${M} non-string keys not supported (got ${typeof u})`);if(o&&(r&&a.has(u)||!r&&Object.hasOwn(i,u)))throw new Error(`${M} found repeat map key "${u}"`);let c=Zt(t,n);if(c===zn)throw new Error(`${M} found map but not enough entries (got ${s} [no value], expected ${e.value})`);r?a.set(u,c):i[u]=c}return r?a:i}function Zt(e,t){if(e.done())return zn;let n=e.next();if(g.equals(n.type,g.break))return Br;if(n.type.terminal)return n.value;if(g.equals(n.type,g.array))return zp(n,e,t);if(g.equals(n.type,g.map))return Op(n,e,t);if(g.equals(n.type,g.tag)){if(t.tags&&typeof t.tags[n.value]=="function"){let r=Zt(e,t);return t.tags[n.value](r)}throw new Error(`${M} tag not supported (${n.value})`)}throw new Error("unsupported")}function Pu(e,t){if(!(e instanceof Uint8Array))throw new Error(`${M} data to decode must be a Uint8Array`);t=Object.assign({},Pp,t);let n=t.tokenizer||new Zr(e,t),r=Zt(n,t);if(r===zn)throw new Error(`${M} did not find any content to decode`);if(r===Br)throw new Error(`${M} got unexpected break`);return[r,e.subarray(n.pos())]}function ji(e,t){let[n,r]=Pu(e,t);if(r.length>0)throw new Error(`${M} too many terminals, data makes no sense`);return n}var bk=new Uint8Array(0);function zu(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function Bt(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Dp(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<e.length;o++){var i=e.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");n[a]=o}var s=e.length,u=e.charAt(0),c=Math.log(s)/Math.log(256),l=Math.log(256)/Math.log(s);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,b=0,S=0,I=f.length;S!==I&&f[S]===0;)S++,y++;for(var _=(I-S)*l+1>>>0,E=new Uint8Array(_);S!==I;){for(var x=f[S],C=0,U=_-1;(x!==0||C<b)&&U!==-1;U--,C++)x+=256*E[U]>>>0,E[U]=x%s>>>0,x=x/s>>>0;if(x!==0)throw new Error("Non-zero carry");b=C,S++}for(var Z=_-b;Z!==_&&E[Z]===0;)Z++;for(var Q=u.repeat(y);Z<_;++Z)Q+=e.charAt(E[Z]);return Q}function p(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var b=0,S=0;f[y]===u;)b++,y++;for(var I=(f.length-y)*c+1>>>0,_=new Uint8Array(I);f[y];){var E=n[f.charCodeAt(y)];if(E===255)return;for(var x=0,C=I-1;(E!==0||x<S)&&C!==-1;C--,x++)E+=s*_[C]>>>0,_[C]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");S=x,y++}if(f[y]!==" "){for(var U=I-S;U!==I&&_[U]===0;)U++;for(var Z=new Uint8Array(b+(I-U)),Q=b;U!==I;)Z[Q++]=_[U++];return Z}}}function v(f){var y=p(f);if(y)return y;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:p,decode:v}}var Rp=Dp,jp=Rp,Ou=jp;var Ni=class{name;prefix;baseEncode;constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Ci=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,n,r){this.name=t,this.prefix=n;let o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Uu(this,t)}},Li=class{decoders;constructor(t){this.decoders=t}or(t){return Uu(this,t)}decode(t){let n=t[0],r=this.decoders[n];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Uu(e,t){return new Li({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Mi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,n,r,o){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new Ni(t,n,r),this.decoder=new Ci(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function Du({name:e,prefix:t,encode:n,decode:r}){return new Mi(e,t,n,r)}function Ft({name:e,prefix:t,alphabet:n}){let{encode:r,decode:o}=Ou(n,e);return Du({prefix:t,name:e,encode:r,decode:i=>Bt(o(i))})}function Np(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;let i=new Uint8Array(o*n/8|0),a=0,s=0,u=0;for(let c=0;c<o;++c){let l=t[e[c]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);s=s<<n|l,a+=n,a>=8&&(a-=8,i[u++]=255&s>>a)}if(a>=n||(255&s<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function Cp(e,t,n){let r=t[t.length-1]==="=",o=(1<<n)-1,i="",a=0,s=0;for(let u=0;u<e.length;++u)for(s=s<<8|e[u],a+=8;a>n;)a-=n,i+=t[o&s>>a];if(a!==0&&(i+=t[o&s<<n-a]),r)for(;(i.length*n&7)!==0;)i+="=";return i}function Lp(e){let t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function Be({name:e,prefix:t,bitsPerChar:n,alphabet:r}){let o=Lp(r);return Du({prefix:t,name:e,encode(i){return Cp(i,r,n)},decode(i){return Np(i,o,n,e)}})}var On=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kk=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ik=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ak=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Tk=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pk=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),zk=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ok=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uk=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Fr=Ft({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),jk=Ft({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nt=Ft({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Lk=Ft({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mp=Nu,Ru=128,Zp=127,Bp=~Zp,Fp=Math.pow(2,31);function Nu(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Fp;)t[n++]=e&255|Ru,e/=128;for(;e&Bp;)t[n++]=e&255|Ru,e>>>=7;return t[n]=e|0,Nu.bytes=n-r+1,t}var Hp=Zi,Jp=128,ju=127;function Zi(e,r){var n=0,r=r||0,o=0,i=r,a,s=e.length;do{if(i>=s)throw Zi.bytes=0,new RangeError("Could not decode varint");a=e[i++],n+=o<28?(a&ju)<<o:(a&ju)*Math.pow(2,o),o+=7}while(a>=Jp);return Zi.bytes=i-r,n}var Gp=Math.pow(2,7),Vp=Math.pow(2,14),qp=Math.pow(2,21),Kp=Math.pow(2,28),Wp=Math.pow(2,35),Xp=Math.pow(2,42),Yp=Math.pow(2,49),Qp=Math.pow(2,56),em=Math.pow(2,63),tm=function(e){return e<Gp?1:e<Vp?2:e<qp?3:e<Kp?4:e<Wp?5:e<Xp?6:e<Yp?7:e<Qp?8:e<em?9:10},nm={encode:Mp,decode:Hp,encodingLength:tm},rm=nm,Un=rm;function Dn(e,t=0){return[Un.decode(e,t),Un.decode.bytes]}function Ht(e,t,n=0){return Un.encode(e,t,n),t}function Jt(e){return Un.encodingLength(e)}function Lu(e,t){let n=t.byteLength,r=Jt(e),o=r+Jt(n),i=new Uint8Array(o+n);return Ht(e,i,0),Ht(n,i,r),i.set(t,o),new Gt(e,n,t,i)}function Mu(e){let t=Bt(e),[n,r]=Dn(t),[o,i]=Dn(t.subarray(r)),a=t.subarray(r+i);if(a.byteLength!==o)throw new Error("Incorrect length");return new Gt(n,o,a,t)}function Zu(e,t){if(e===t)return!0;{let n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&zu(e.bytes,n.bytes)}}var Gt=class{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}};function Bu(e,t){let{bytes:n,version:r}=e;return r===0?am(n,Bi(e),t??nt.encoder):sm(n,Bi(e),t??On.encoder)}var Fu=new WeakMap;function Bi(e){let t=Fu.get(e);if(t==null){let n=new Map;return Fu.set(e,n),n}return t}var jn=class e{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:n}=this;if(t!==Rn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==cm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:n}=this.multihash,r=Lu(t,n);return e.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,n){let r=n;return r!=null&&t.code===r.code&&t.version===r.version&&Zu(t.multihash,r.multihash)}toString(t){return Bu(this,t)}toJSON(){return{"/":Bu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let n=t;if(n instanceof e)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){let{version:r,code:o,multihash:i,bytes:a}=n;return new e(r,o,i,a??Hu(r,o,i.bytes))}else if(n[um]===!0){let{version:r,multihash:o,code:i}=n,a=Mu(o);return e.create(r,i,a)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==Rn)throw new Error(`Version 0 CID must use dag-pb (code: ${Rn}) block encoding`);return new e(t,n,r,r.bytes)}case 1:{let o=Hu(t,n,r.bytes);return new e(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,Rn,t)}static createV1(t,n){return e.create(1,t,n)}static decode(t){let[n,r]=e.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(t){let n=e.inspectBytes(t),r=n.size-n.multihashSize,o=Bt(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");let i=o.subarray(n.multihashSize-n.digestSize),a=new Gt(n.multihashCode,n.digestSize,i,o);return[n.version===0?e.createV0(a):e.createV1(n.codec,a),t.subarray(n.size)]}static inspectBytes(t){let n=0,r=()=>{let[d,p]=Dn(t.subarray(n));return n+=p,d},o=r(),i=Rn;if(o===18?(o=0,n=0):i=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let a=n,s=r(),u=r(),c=n+u,l=c-a;return{version:o,codec:i,multihashCode:s,digestSize:u,multihashSize:l,size:c}}static parse(t,n){let[r,o]=im(t,n),i=e.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Bi(i).set(r,t),i}};function im(e,t){switch(e[0]){case"Q":{let n=t??nt;return[nt.prefix,n.decode(`${nt.prefix}${e}`)]}case nt.prefix:{let n=t??nt;return[nt.prefix,n.decode(e)]}case On.prefix:{let n=t??On;return[On.prefix,n.decode(e)]}case Fr.prefix:{let n=t??Fr;return[Fr.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function am(e,t,n){let{prefix:r}=n;if(r!==nt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);let o=t.get(r);if(o==null){let i=n.encode(e).slice(1);return t.set(r,i),i}else return o}function sm(e,t,n){let{prefix:r}=n,o=t.get(r);if(o==null){let i=n.encode(e);return t.set(r,i),i}else return o}var Rn=112,cm=18;function Hu(e,t,n){let r=Jt(e),o=r+Jt(t),i=new Uint8Array(o+n.byteLength);return Ht(e,i,0),Ht(t,i,r),i.set(n,o),i}var um=Symbol.for("@ipld/js-cid/CID");var Ju=42;function lm(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function dm(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=jn.asCID(e);if(!t)return null;let n=new Uint8Array(t.bytes.byteLength+1);return n.set(t.bytes,1),[new k(g.tag,Ju),new k(g.bytes,n)]}function fm(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function pm(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function mm(e){for(let t of e.keys())if(typeof t!="string"||t.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Fi={float64:!0,typeEncoders:{Map:mm,Object:dm,undefined:fm,number:pm}},Xk={...Fi,typeEncoders:{...Fi.typeEncoders}};function hm(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return jn.decode(e.subarray(1))}var Hr={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Hr.tags[Ju]=hm;var Yk={...Hr,tags:Hr.tags.slice()};var Se=e=>Ri(e,Fi),Fe=e=>ji(lm(e),Hr);function gm(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function ym(){let e=new Map;return function(t,n){try{let o=function(a){if(r)return a;let s=e.get(t.didUrl);return s!==void 0?s:Promise.resolve(n()).then(function(u){var c;return((c=u.didResolutionMetadata)==null?void 0:c.error)!=="notFound"&&e.set(t.didUrl,u),u})},r,i=(function(){if(t.params&&t.params["no-cache"]==="true")return Promise.resolve(n()).then(function(a){return r=1,a})})();return Promise.resolve(i&&i.then?i.then(o):o(i))}catch(r){return Promise.reject(r)}}}function vm(e,t){return t()}var bm="(?:%[0-9a-fA-F]{2})",Gu=`(?:[a-zA-Z0-9._-]|${bm})`,_m="([a-z0-9]+)",wm=`((?:${Gu}*:)*(${Gu}+))`,Vu="[a-zA-Z0-9_.:%-]",xm=`;${Vu}+=${Vu}*`,$m=`((${xm})*)`,Sm="(/[^#?]*)?",Em="([?][^#]*)?",km="(#.*)?",Im=new RegExp(`^did:${_m}:${wm}${$m}${Sm}${Em}${km}$`);function Am(e){if(e===""||!e)return null;let t=e.match(Im);if(t){let n={did:`did:${t[1]}:${t[2]}`,method:t[1],id:t[2],didUrl:e};if(t[4]){let r=t[4].slice(1).split(";");n.params={};for(let o of r){let i=o.split("=");n.params[i[0]]=i[1]}}return t[6]&&(n.path=t[6]),t[7]&&(n.query=t[7].slice(1)),t[8]&&(n.fragment=t[8].slice(1)),n}return null}var Jr={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function Tm(e){return function(t,n,r){try{return Promise.resolve(gm(function(){return Promise.resolve(e(t,n,r)).then(function(o){return{...Jr,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:o}})},function(o){return{...Jr,didResolutionMetadata:{error:"notFound",message:o.toString()}}}))}catch(o){return Promise.reject(o)}}}var Gr=class{constructor(t={},n={}){this.registry=void 0,this.cache=void 0,this.registry=t,this.cache=n.cache===!0?ym():n.cache||vm,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=Tm(n.legacyResolvers[r]))})}resolve(t,n={}){try{let r=this,o=Am(t);if(o===null)return Promise.resolve({...Jr,didResolutionMetadata:{error:"invalidDid"}});let i=r.registry[o.method];return i?Promise.resolve(r.cache(o,()=>i(o.did,o,r,n))):Promise.resolve({...Jr,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(r){return Promise.reject(r)}}};function Nn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Pm}=Object.prototype,{getPrototypeOf:Ji}=Object,{iterator:qr,toStringTag:Ku}=Symbol,Kr=(e=>t=>{let n=Pm.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),je=e=>(e=e.toLowerCase(),t=>Kr(t)===e),Wr=e=>t=>typeof t===e,{isArray:qt}=Array,Vt=Wr("undefined");function Cn(e){return e!==null&&!Vt(e)&&e.constructor!==null&&!Vt(e.constructor)&&he(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Wu=je("ArrayBuffer");function zm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Wu(e.buffer),t}var Om=Wr("string"),he=Wr("function"),Xu=Wr("number"),Ln=e=>e!==null&&typeof e=="object",Um=e=>e===!0||e===!1,Vr=e=>{if(Kr(e)!=="object")return!1;let t=Ji(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Ku in e)&&!(qr in e)},Dm=e=>{if(!Ln(e)||Cn(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Rm=je("Date"),jm=je("File"),Nm=je("Blob"),Cm=je("FileList"),Lm=e=>Ln(e)&&he(e.pipe),Mm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||he(e.append)&&((t=Kr(e))==="formdata"||t==="object"&&he(e.toString)&&e.toString()==="[object FormData]"))},Zm=je("URLSearchParams"),[Bm,Fm,Hm,Jm]=["ReadableStream","Request","Response","Headers"].map(je),Gm=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Mn(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),qt(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Cn(e))return;let i=n?Object.getOwnPropertyNames(e):Object.keys(e),a=i.length,s;for(r=0;r<a;r++)s=i[r],t.call(null,e[s],s,e)}}function Yu(e,t){if(Cn(e))return null;t=t.toLowerCase();let n=Object.keys(e),r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}var wt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Qu=e=>!Vt(e)&&e!==wt;function Hi(){let{caseless:e,skipUndefined:t}=Qu(this)&&this||{},n={},r=(o,i)=>{let a=e&&Yu(n,i)||i;Vr(n[a])&&Vr(o)?n[a]=Hi(n[a],o):Vr(o)?n[a]=Hi({},o):qt(o)?n[a]=o.slice():(!t||!Vt(o))&&(n[a]=o)};for(let o=0,i=arguments.length;o<i;o++)arguments[o]&&Mn(arguments[o],r);return n}var Vm=(e,t,n,{allOwnKeys:r}={})=>(Mn(t,(o,i)=>{n&&he(o)?e[i]=Nn(o,n):e[i]=o},{allOwnKeys:r}),e),qm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Km=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Wm=(e,t,n,r)=>{let o,i,a,s={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],(!r||r(a,e,t))&&!s[a]&&(t[a]=e[a],s[a]=!0);e=n!==!1&&Ji(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Xm=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;let r=e.indexOf(t,n);return r!==-1&&r===n},Ym=e=>{if(!e)return null;if(qt(e))return e;let t=e.length;if(!Xu(t))return null;let n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Qm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Ji(Uint8Array)),eh=(e,t)=>{let r=(e&&e[qr]).call(e),o;for(;(o=r.next())&&!o.done;){let i=o.value;t.call(e,i[0],i[1])}},th=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},nh=je("HTMLFormElement"),rh=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),qu=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),oh=je("RegExp"),el=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};Mn(n,(o,i)=>{let a;(a=t(o,i,e))!==!1&&(r[i]=a||o)}),Object.defineProperties(e,r)},ih=e=>{el(e,(t,n)=>{if(he(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;let r=e[n];if(he(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},ah=(e,t)=>{let n={},r=o=>{o.forEach(i=>{n[i]=!0})};return qt(e)?r(e):r(String(e).split(t)),n},sh=()=>{},ch=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function uh(e){return!!(e&&he(e.append)&&e[Ku]==="FormData"&&e[qr])}var lh=e=>{let t=new Array(10),n=(r,o)=>{if(Ln(r)){if(t.indexOf(r)>=0)return;if(Cn(r))return r;if(!("toJSON"in r)){t[o]=r;let i=qt(r)?[]:{};return Mn(r,(a,s)=>{let u=n(a,o+1);!Vt(u)&&(i[s]=u)}),t[o]=void 0,i}}return r};return n(e,0)},dh=je("AsyncFunction"),fh=e=>e&&(Ln(e)||he(e))&&he(e.then)&&he(e.catch),tl=((e,t)=>e?setImmediate:t?((n,r)=>(wt.addEventListener("message",({source:o,data:i})=>{o===wt&&i===n&&r.length&&r.shift()()},!1),o=>{r.push(o),wt.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",he(wt.postMessage)),ph=typeof queueMicrotask<"u"?queueMicrotask.bind(wt):typeof process<"u"&&process.nextTick||tl,mh=e=>e!=null&&he(e[qr]),m={isArray:qt,isArrayBuffer:Wu,isBuffer:Cn,isFormData:Mm,isArrayBufferView:zm,isString:Om,isNumber:Xu,isBoolean:Um,isObject:Ln,isPlainObject:Vr,isEmptyObject:Dm,isReadableStream:Bm,isRequest:Fm,isResponse:Hm,isHeaders:Jm,isUndefined:Vt,isDate:Rm,isFile:jm,isBlob:Nm,isRegExp:oh,isFunction:he,isStream:Lm,isURLSearchParams:Zm,isTypedArray:Qm,isFileList:Cm,forEach:Mn,merge:Hi,extend:Vm,trim:Gm,stripBOM:qm,inherits:Km,toFlatObject:Wm,kindOf:Kr,kindOfTest:je,endsWith:Xm,toArray:Ym,forEachEntry:eh,matchAll:th,isHTMLForm:nh,hasOwnProperty:qu,hasOwnProp:qu,reduceDescriptors:el,freezeMethods:ih,toObjectSet:ah,toCamelCase:rh,noop:sh,toFiniteNumber:ch,findKey:Yu,global:wt,isContextDefined:Qu,isSpecCompliantForm:uh,toJSONObject:lh,isAsyncFn:dh,isThenable:fh,setImmediate:tl,asap:ph,isIterable:mh};function Kt(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o,this.status=o.status?o.status:null)}m.inherits(Kt,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:m.toJSONObject(this.config),code:this.code,status:this.status}}});var nl=Kt.prototype,rl={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{rl[e]={value:e}});Object.defineProperties(Kt,rl);Object.defineProperty(nl,"isAxiosError",{value:!0});Kt.from=(e,t,n,r,o,i)=>{let a=Object.create(nl);m.toFlatObject(e,a,function(l){return l!==Error.prototype},c=>c!=="isAxiosError");let s=e&&e.message?e.message:"Error",u=t==null&&e?e.code:t;return Kt.call(a,s,u,n,r,o),e&&a.cause==null&&Object.defineProperty(a,"cause",{value:e,configurable:!0}),a.name=e&&e.name||"Error",i&&Object.assign(a,i),a};var O=Kt;var Xr=null;function Gi(e){return m.isPlainObject(e)||m.isArray(e)}function il(e){return m.endsWith(e,"[]")?e.slice(0,-2):e}function ol(e,t,n){return e?e.concat(t).map(function(o,i){return o=il(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function hh(e){return m.isArray(e)&&!e.some(Gi)}var gh=m.toFlatObject(m,{},null,function(t){return/^is[A-Z]/.test(t)});function yh(e,t,n){if(!m.isObject(e))throw new TypeError("target must be an object");t=t||new(Xr||FormData),n=m.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,b){return!m.isUndefined(b[y])});let r=n.metaTokens,o=n.visitor||l,i=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&m.isSpecCompliantForm(t);if(!m.isFunction(o))throw new TypeError("visitor must be a function");function c(f){if(f===null)return"";if(m.isDate(f))return f.toISOString();if(m.isBoolean(f))return f.toString();if(!u&&m.isBlob(f))throw new O("Blob is not supported. Use a Buffer instead.");return m.isArrayBuffer(f)||m.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,y,b){let S=f;if(f&&!b&&typeof f=="object"){if(m.endsWith(y,"{}"))y=r?y:y.slice(0,-2),f=JSON.stringify(f);else if(m.isArray(f)&&hh(f)||(m.isFileList(f)||m.endsWith(y,"[]"))&&(S=m.toArray(f)))return y=il(y),S.forEach(function(_,E){!(m.isUndefined(_)||_===null)&&t.append(a===!0?ol([y],E,i):a===null?y:y+"[]",c(_))}),!1}return Gi(f)?!0:(t.append(ol(b,y,i),c(f)),!1)}let d=[],p=Object.assign(gh,{defaultVisitor:l,convertValue:c,isVisitable:Gi});function v(f,y){if(!m.isUndefined(f)){if(d.indexOf(f)!==-1)throw Error("Circular reference detected in "+y.join("."));d.push(f),m.forEach(f,function(S,I){(!(m.isUndefined(S)||S===null)&&o.call(t,S,m.isString(I)?I.trim():I,y,p))===!0&&v(S,y?y.concat(I):[I])}),d.pop()}}if(!m.isObject(e))throw new TypeError("data must be an object");return v(e),t}var ut=yh;function al(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function sl(e,t){this._pairs=[],e&&ut(e,this,t)}var cl=sl.prototype;cl.append=function(t,n){this._pairs.push([t,n])};cl.toString=function(t){let n=t?function(r){return t.call(this,r,al)}:al;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};var Yr=sl;function vh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Zn(e,t,n){if(!t)return e;let r=n&&n.encode||vh;m.isFunction(n)&&(n={serialize:n});let o=n&&n.serialize,i;if(o?i=o(t,n):i=m.isURLSearchParams(t)?t.toString():new Yr(t,n).toString(r),i){let a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}var Vi=class{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){m.forEach(this.handlers,function(r){r!==null&&t(r)})}},qi=Vi;var Qr={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var ul=typeof URLSearchParams<"u"?URLSearchParams:Yr;var ll=typeof FormData<"u"?FormData:null;var dl=typeof Blob<"u"?Blob:null;var fl={isBrowser:!0,classes:{URLSearchParams:ul,FormData:ll,Blob:dl},protocols:["http","https","file","blob","url","data"]};var Xi={};rf(Xi,{hasBrowserEnv:()=>Wi,hasStandardBrowserEnv:()=>bh,hasStandardBrowserWebWorkerEnv:()=>_h,navigator:()=>Ki,origin:()=>wh});var Wi=typeof window<"u"&&typeof document<"u",Ki=typeof navigator=="object"&&navigator||void 0,bh=Wi&&(!Ki||["ReactNative","NativeScript","NS"].indexOf(Ki.product)<0),_h=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",wh=Wi&&window.location.href||"http://localhost";var Y={...Xi,...fl};function Yi(e,t){return ut(e,new Y.classes.URLSearchParams,{visitor:function(n,r,o,i){return Y.isNode&&m.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function xh(e){return m.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $h(e){let t={},n=Object.keys(e),r,o=n.length,i;for(r=0;r<o;r++)i=n[r],t[i]=e[i];return t}function Sh(e){function t(n,r,o,i){let a=n[i++];if(a==="__proto__")return!0;let s=Number.isFinite(+a),u=i>=n.length;return a=!a&&m.isArray(o)?o.length:a,u?(m.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!s):((!o[a]||!m.isObject(o[a]))&&(o[a]=[]),t(n,r,o[a],i)&&m.isArray(o[a])&&(o[a]=$h(o[a])),!s)}if(m.isFormData(e)&&m.isFunction(e.entries)){let n={};return m.forEachEntry(e,(r,o)=>{t(xh(r),o,n,0)}),n}return null}var eo=Sh;function Eh(e,t,n){if(m.isString(e))try{return(t||JSON.parse)(e),m.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}var Qi={transitional:Qr,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){let r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=m.isObject(t);if(i&&m.isHTMLForm(t)&&(t=new FormData(t)),m.isFormData(t))return o?JSON.stringify(eo(t)):t;if(m.isArrayBuffer(t)||m.isBuffer(t)||m.isStream(t)||m.isFile(t)||m.isBlob(t)||m.isReadableStream(t))return t;if(m.isArrayBufferView(t))return t.buffer;if(m.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Yi(t,this.formSerializer).toString();if((s=m.isFileList(t))||r.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return ut(s?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),Eh(t)):t}],transformResponse:[function(t){let n=this.transitional||Qi.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(m.isResponse(t)||m.isReadableStream(t))return t;if(t&&m.isString(t)&&(r&&!this.responseType||o)){let a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(s){if(a)throw s.name==="SyntaxError"?O.from(s,O.ERR_BAD_RESPONSE,this,null,this.response):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Y.classes.FormData,Blob:Y.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};m.forEach(["delete","get","head","post","put","patch"],e=>{Qi.headers[e]={}});var Wt=Qi;var kh=m.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),pl=e=>{let t={},n,r,o;return e&&e.split(`
3
- `).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||t[n]&&kh[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};var ml=Symbol("internals");function Bn(e){return e&&String(e).trim().toLowerCase()}function to(e){return e===!1||e==null?e:m.isArray(e)?e.map(to):String(e)}function Ih(e){let t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}var Ah=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ea(e,t,n,r,o){if(m.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!m.isString(t)){if(m.isString(r))return t.indexOf(r)!==-1;if(m.isRegExp(r))return r.test(t)}}function Th(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Ph(e,t){let n=m.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,a){return this[r].call(this,t,o,i,a)},configurable:!0})})}var Xt=class{constructor(t){t&&this.set(t)}set(t,n,r){let o=this;function i(s,u,c){let l=Bn(u);if(!l)throw new Error("header name must be a non-empty string");let d=m.findKey(o,l);(!d||o[d]===void 0||c===!0||c===void 0&&o[d]!==!1)&&(o[d||u]=to(s))}let a=(s,u)=>m.forEach(s,(c,l)=>i(c,l,u));if(m.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if(m.isString(t)&&(t=t.trim())&&!Ah(t))a(pl(t),n);else if(m.isObject(t)&&m.isIterable(t)){let s={},u,c;for(let l of t){if(!m.isArray(l))throw TypeError("Object iterator must return a key-value pair");s[c=l[0]]=(u=s[c])?m.isArray(u)?[...u,l[1]]:[u,l[1]]:l[1]}a(s,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=Bn(t),t){let r=m.findKey(this,t);if(r){let o=this[r];if(!n)return o;if(n===!0)return Ih(o);if(m.isFunction(n))return n.call(this,o,r);if(m.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Bn(t),t){let r=m.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||ea(this,this[r],r,n)))}return!1}delete(t,n){let r=this,o=!1;function i(a){if(a=Bn(a),a){let s=m.findKey(r,a);s&&(!n||ea(r,r[s],s,n))&&(delete r[s],o=!0)}}return m.isArray(t)?t.forEach(i):i(t),o}clear(t){let n=Object.keys(this),r=n.length,o=!1;for(;r--;){let i=n[r];(!t||ea(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){let n=this,r={};return m.forEach(this,(o,i)=>{let a=m.findKey(r,i);if(a){n[a]=to(o),delete n[i];return}let s=t?Th(i):String(i).trim();s!==i&&delete n[i],n[s]=to(o),r[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let n=Object.create(null);return m.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&m.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
4
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){let r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){let r=(this[ml]=this[ml]={accessors:{}}).accessors,o=this.prototype;function i(a){let s=Bn(a);r[s]||(Ph(o,a),r[s]=!0)}return m.isArray(t)?t.forEach(i):i(t),this}};Xt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);m.reduceDescriptors(Xt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});m.freezeMethods(Xt);var oe=Xt;function Fn(e,t){let n=this||Wt,r=t||n,o=oe.from(r.headers),i=r.data;return m.forEach(e,function(s){i=s.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function Hn(e){return!!(e&&e.__CANCEL__)}function hl(e,t,n){O.call(this,e??"canceled",O.ERR_CANCELED,t,n),this.name="CanceledError"}m.inherits(hl,O,{__CANCEL__:!0});var He=hl;function Jn(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new O("Request failed with status code "+n.status,[O.ERR_BAD_REQUEST,O.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function ta(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function zh(e,t){e=e||10;let n=new Array(e),r=new Array(e),o=0,i=0,a;return t=t!==void 0?t:1e3,function(u){let c=Date.now(),l=r[i];a||(a=c),n[o]=u,r[o]=c;let d=i,p=0;for(;d!==o;)p+=n[d++],d=d%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),c-a<t)return;let v=l&&c-l;return v?Math.round(p*1e3/v):void 0}}var gl=zh;function Oh(e,t){let n=0,r=1e3/t,o,i,a=(c,l=Date.now())=>{n=l,o=null,i&&(clearTimeout(i),i=null),e(...c)};return[(...c)=>{let l=Date.now(),d=l-n;d>=r?a(c,l):(o=c,i||(i=setTimeout(()=>{i=null,a(o)},r-d)))},()=>o&&a(o)]}var yl=Oh;var Yt=(e,t,n=3)=>{let r=0,o=gl(50,250);return yl(i=>{let a=i.loaded,s=i.lengthComputable?i.total:void 0,u=a-r,c=o(u),l=a<=s;r=a;let d={loaded:a,total:s,progress:s?a/s:void 0,bytes:u,rate:c||void 0,estimated:c&&s&&l?(s-a)/c:void 0,event:i,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(d)},n)},na=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ra=e=>(...t)=>m.asap(()=>e(...t));var vl=Y.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Y.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Y.origin),Y.navigator&&/(msie|trident)/i.test(Y.navigator.userAgent)):()=>!0;var bl=Y.hasStandardBrowserEnv?{write(e,t,n,r,o,i,a){if(typeof document>"u")return;let s=[`${e}=${encodeURIComponent(t)}`];m.isNumber(n)&&s.push(`expires=${new Date(n).toUTCString()}`),m.isString(r)&&s.push(`path=${r}`),m.isString(o)&&s.push(`domain=${o}`),i===!0&&s.push("secure"),m.isString(a)&&s.push(`SameSite=${a}`),document.cookie=s.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function oa(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ia(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Gn(e,t,n){let r=!oa(t);return e&&(r||n==!1)?ia(e,t):t}var _l=e=>e instanceof oe?{...e}:e;function Ne(e,t){t=t||{};let n={};function r(c,l,d,p){return m.isPlainObject(c)&&m.isPlainObject(l)?m.merge.call({caseless:p},c,l):m.isPlainObject(l)?m.merge({},l):m.isArray(l)?l.slice():l}function o(c,l,d,p){if(m.isUndefined(l)){if(!m.isUndefined(c))return r(void 0,c,d,p)}else return r(c,l,d,p)}function i(c,l){if(!m.isUndefined(l))return r(void 0,l)}function a(c,l){if(m.isUndefined(l)){if(!m.isUndefined(c))return r(void 0,c)}else return r(void 0,l)}function s(c,l,d){if(d in t)return r(c,l);if(d in e)return r(void 0,c)}let u={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(c,l,d)=>o(_l(c),_l(l),d,!0)};return m.forEach(Object.keys({...e,...t}),function(l){let d=u[l]||o,p=d(e[l],t[l],l);m.isUndefined(p)&&d!==s||(n[l]=p)}),n}var no=e=>{let t=Ne({},e),{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:i,headers:a,auth:s}=t;if(t.headers=a=oe.from(a),t.url=Zn(Gn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&a.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):""))),m.isFormData(n)){if(Y.hasStandardBrowserEnv||Y.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(m.isFunction(n.getHeaders)){let u=n.getHeaders(),c=["content-type","content-length"];Object.entries(u).forEach(([l,d])=>{c.includes(l.toLowerCase())&&a.set(l,d)})}}if(Y.hasStandardBrowserEnv&&(r&&m.isFunction(r)&&(r=r(t)),r||r!==!1&&vl(t.url))){let u=o&&i&&bl.read(i);u&&a.set(o,u)}return t};var Uh=typeof XMLHttpRequest<"u",wl=Uh&&function(e){return new Promise(function(n,r){let o=no(e),i=o.data,a=oe.from(o.headers).normalize(),{responseType:s,onUploadProgress:u,onDownloadProgress:c}=o,l,d,p,v,f;function y(){v&&v(),f&&f(),o.cancelToken&&o.cancelToken.unsubscribe(l),o.signal&&o.signal.removeEventListener("abort",l)}let b=new XMLHttpRequest;b.open(o.method.toUpperCase(),o.url,!0),b.timeout=o.timeout;function S(){if(!b)return;let _=oe.from("getAllResponseHeaders"in b&&b.getAllResponseHeaders()),x={data:!s||s==="text"||s==="json"?b.responseText:b.response,status:b.status,statusText:b.statusText,headers:_,config:e,request:b};Jn(function(U){n(U),y()},function(U){r(U),y()},x),b=null}"onloadend"in b?b.onloadend=S:b.onreadystatechange=function(){!b||b.readyState!==4||b.status===0&&!(b.responseURL&&b.responseURL.indexOf("file:")===0)||setTimeout(S)},b.onabort=function(){b&&(r(new O("Request aborted",O.ECONNABORTED,e,b)),b=null)},b.onerror=function(E){let x=E&&E.message?E.message:"Network Error",C=new O(x,O.ERR_NETWORK,e,b);C.event=E||null,r(C),b=null},b.ontimeout=function(){let E=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",x=o.transitional||Qr;o.timeoutErrorMessage&&(E=o.timeoutErrorMessage),r(new O(E,x.clarifyTimeoutError?O.ETIMEDOUT:O.ECONNABORTED,e,b)),b=null},i===void 0&&a.setContentType(null),"setRequestHeader"in b&&m.forEach(a.toJSON(),function(E,x){b.setRequestHeader(x,E)}),m.isUndefined(o.withCredentials)||(b.withCredentials=!!o.withCredentials),s&&s!=="json"&&(b.responseType=o.responseType),c&&([p,f]=Yt(c,!0),b.addEventListener("progress",p)),u&&b.upload&&([d,v]=Yt(u),b.upload.addEventListener("progress",d),b.upload.addEventListener("loadend",v)),(o.cancelToken||o.signal)&&(l=_=>{b&&(r(!_||_.type?new He(null,e,b):_),b.abort(),b=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));let I=ta(o.url);if(I&&Y.protocols.indexOf(I)===-1){r(new O("Unsupported protocol "+I+":",O.ERR_BAD_REQUEST,e));return}b.send(i||null)})};var Dh=(e,t)=>{let{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o,i=function(c){if(!o){o=!0,s();let l=c instanceof Error?c:this.reason;r.abort(l instanceof O?l:new He(l instanceof Error?l.message:l))}},a=t&&setTimeout(()=>{a=null,i(new O(`timeout ${t} of ms exceeded`,O.ETIMEDOUT))},t),s=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(i):c.removeEventListener("abort",i)}),e=null)};e.forEach(c=>c.addEventListener("abort",i));let{signal:u}=r;return u.unsubscribe=()=>m.asap(s),u}},xl=Dh;var Rh=function*(e,t){let n=e.byteLength;if(!t||n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},jh=async function*(e,t){for await(let n of Nh(e))yield*Rh(n,t)},Nh=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},aa=(e,t,n,r)=>{let o=jh(e,t),i=0,a,s=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{let{done:c,value:l}=await o.next();if(c){s(),u.close();return}let d=l.byteLength;if(n){let p=i+=d;n(p)}u.enqueue(new Uint8Array(l))}catch(c){throw s(c),c}},cancel(u){return s(u),o.return()}},{highWaterMark:2})};var $l=64*1024,{isFunction:ro}=m,Ch=(({Request:e,Response:t})=>({Request:e,Response:t}))(m.global),{ReadableStream:Sl,TextEncoder:El}=m.global,kl=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Lh=e=>{e=m.merge.call({skipUndefined:!0},Ch,e);let{fetch:t,Request:n,Response:r}=e,o=t?ro(t):typeof fetch=="function",i=ro(n),a=ro(r);if(!o)return!1;let s=o&&ro(Sl),u=o&&(typeof El=="function"?(f=>y=>f.encode(y))(new El):async f=>new Uint8Array(await new n(f).arrayBuffer())),c=i&&s&&kl(()=>{let f=!1,y=new n(Y.origin,{body:new Sl,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!y}),l=a&&s&&kl(()=>m.isReadableStream(new r("").body)),d={stream:l&&(f=>f.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!d[f]&&(d[f]=(y,b)=>{let S=y&&y[f];if(S)return S.call(y);throw new O(`Response type '${f}' is not supported`,O.ERR_NOT_SUPPORT,b)})});let p=async f=>{if(f==null)return 0;if(m.isBlob(f))return f.size;if(m.isSpecCompliantForm(f))return(await new n(Y.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(m.isArrayBufferView(f)||m.isArrayBuffer(f))return f.byteLength;if(m.isURLSearchParams(f)&&(f=f+""),m.isString(f))return(await u(f)).byteLength},v=async(f,y)=>{let b=m.toFiniteNumber(f.getContentLength());return b??p(y)};return async f=>{let{url:y,method:b,data:S,signal:I,cancelToken:_,timeout:E,onDownloadProgress:x,onUploadProgress:C,responseType:U,headers:Z,withCredentials:Q="same-origin",fetchOptions:Ie}=no(f),h=t||fetch;U=U?(U+"").toLowerCase():"text";let w=xl([I,_&&_.toAbortSignal()],E),z=null,B=w&&w.unsubscribe&&(()=>{w.unsubscribe()}),q;try{if(C&&c&&b!=="get"&&b!=="head"&&(q=await v(Z,S))!==0){let ce=new n(y,{method:"POST",body:S,duplex:"half"}),Pt;if(m.isFormData(S)&&(Pt=ce.headers.get("content-type"))&&Z.setContentType(Pt),ce.body){let[ti,fr]=na(q,Yt(ra(C)));S=aa(ce.body,$l,ti,fr)}}m.isString(Q)||(Q=Q?"include":"omit");let L=i&&"credentials"in n.prototype,mt={...Ie,signal:w,method:b.toUpperCase(),headers:Z.normalize().toJSON(),body:S,duplex:"half",credentials:L?Q:void 0};z=i&&new n(y,mt);let Ae=await(i?h(z,Ie):h(y,mt)),hn=l&&(U==="stream"||U==="response");if(l&&(x||hn&&B)){let ce={};["status","statusText","headers"].forEach(ys=>{ce[ys]=Ae[ys]});let Pt=m.toFiniteNumber(Ae.headers.get("content-length")),[ti,fr]=x&&na(Pt,Yt(ra(x),!0))||[];Ae=new r(aa(Ae.body,$l,ti,()=>{fr&&fr(),B&&B()}),ce)}U=U||"text";let ne=await d[m.findKey(d,U)||"text"](Ae,f);return!hn&&B&&B(),await new Promise((ce,Pt)=>{Jn(ce,Pt,{data:ne,headers:oe.from(Ae.headers),status:Ae.status,statusText:Ae.statusText,config:f,request:z})})}catch(L){throw B&&B(),L&&L.name==="TypeError"&&/Load failed|fetch/i.test(L.message)?Object.assign(new O("Network Error",O.ERR_NETWORK,f,z),{cause:L.cause||L}):O.from(L,L&&L.code,f,z)}}},Mh=new Map,sa=e=>{let t=e&&e.env||{},{fetch:n,Request:r,Response:o}=t,i=[r,o,n],a=i.length,s=a,u,c,l=Mh;for(;s--;)u=i[s],c=l.get(u),c===void 0&&l.set(u,c=s?new Map:Lh(t)),l=c;return c},oT=sa();var ca={http:Xr,xhr:wl,fetch:{get:sa}};m.forEach(ca,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Il=e=>`- ${e}`,Bh=e=>m.isFunction(e)||e===null||e===!1;function Fh(e,t){e=m.isArray(e)?e:[e];let{length:n}=e,r,o,i={};for(let a=0;a<n;a++){r=e[a];let s;if(o=r,!Bh(r)&&(o=ca[(s=String(r)).toLowerCase()],o===void 0))throw new O(`Unknown adapter '${s}'`);if(o&&(m.isFunction(o)||(o=o.get(t))))break;i[s||"#"+a]=o}if(!o){let a=Object.entries(i).map(([u,c])=>`adapter ${u} `+(c===!1?"is not supported by the environment":"is not available in the build")),s=n?a.length>1?`since :
5
- `+a.map(Il).join(`
6
- `):" "+Il(a[0]):"as no adapter specified";throw new O("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return o}var oo={getAdapter:Fh,adapters:ca};function ua(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new He(null,e)}function io(e){return ua(e),e.headers=oe.from(e.headers),e.data=Fn.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),oo.getAdapter(e.adapter||Wt.adapter,e)(e).then(function(r){return ua(e),r.data=Fn.call(e,e.transformResponse,r),r.headers=oe.from(r.headers),r},function(r){return Hn(r)||(ua(e),r&&r.response&&(r.response.data=Fn.call(e,e.transformResponse,r.response),r.response.headers=oe.from(r.response.headers))),Promise.reject(r)})}var ao="1.13.2";var so={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{so[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});var Al={};so.transitional=function(t,n,r){function o(i,a){return"[Axios v"+ao+"] Transitional option '"+i+"'"+a+(r?". "+r:"")}return(i,a,s)=>{if(t===!1)throw new O(o(a," has been removed"+(n?" in "+n:"")),O.ERR_DEPRECATED);return n&&!Al[a]&&(Al[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,a,s):!0}};so.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Hh(e,t,n){if(typeof e!="object")throw new O("options must be an object",O.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),o=r.length;for(;o-- >0;){let i=r[o],a=t[i];if(a){let s=e[i],u=s===void 0||a(s,i,e);if(u!==!0)throw new O("option "+i+" must be "+u,O.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new O("Unknown option "+i,O.ERR_BAD_OPTION)}}var Vn={assertOptions:Hh,validators:so};var Je=Vn.validators,Qt=class{constructor(t){this.defaults=t||{},this.interceptors={request:new qi,response:new qi}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;let i=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=`
7
- `+i):r.stack=i}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Ne(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Vn.assertOptions(r,{silentJSONParsing:Je.transitional(Je.boolean),forcedJSONParsing:Je.transitional(Je.boolean),clarifyTimeoutError:Je.transitional(Je.boolean)},!1),o!=null&&(m.isFunction(o)?n.paramsSerializer={serialize:o}:Vn.assertOptions(o,{encode:Je.function,serialize:Je.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Vn.assertOptions(n,{baseUrl:Je.spelling("baseURL"),withXsrfToken:Je.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=i&&m.merge(i.common,i[n.method]);i&&m.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),n.headers=oe.concat(a,i);let s=[],u=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(n)===!1||(u=u&&y.synchronous,s.unshift(y.fulfilled,y.rejected))});let c=[];this.interceptors.response.forEach(function(y){c.push(y.fulfilled,y.rejected)});let l,d=0,p;if(!u){let f=[io.bind(this),void 0];for(f.unshift(...s),f.push(...c),p=f.length,l=Promise.resolve(n);d<p;)l=l.then(f[d++],f[d++]);return l}p=s.length;let v=n;for(;d<p;){let f=s[d++],y=s[d++];try{v=f(v)}catch(b){y.call(this,b);break}}try{l=io.call(this,v)}catch(f){return Promise.reject(f)}for(d=0,p=c.length;d<p;)l=l.then(c[d++],c[d++]);return l}getUri(t){t=Ne(this.defaults,t);let n=Gn(t.baseURL,t.url,t.allowAbsoluteUrls);return Zn(n,t.params,t.paramsSerializer)}};m.forEach(["delete","get","head","options"],function(t){Qt.prototype[t]=function(n,r){return this.request(Ne(r||{},{method:t,url:n,data:(r||{}).data}))}});m.forEach(["post","put","patch"],function(t){function n(r){return function(i,a,s){return this.request(Ne(s||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:a}))}}Qt.prototype[t]=n(),Qt.prototype[t+"Form"]=n(!0)});var qn=Qt;var la=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});let r=this;this.promise.then(o=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i,a=new Promise(s=>{r.subscribe(s),i=s}).then(o);return a.cancel=function(){r.unsubscribe(i)},a},t(function(i,a,s){r.reason||(r.reason=new He(i,a,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},Tl=la;function da(e){return function(n){return e.apply(null,n)}}function fa(e){return m.isObject(e)&&e.isAxiosError===!0}var pa={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(pa).forEach(([e,t])=>{pa[t]=e});var Pl=pa;function zl(e){let t=new qn(e),n=Nn(qn.prototype.request,t);return m.extend(n,qn.prototype,t,{allOwnKeys:!0}),m.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return zl(Ne(e,o))},n}var te=zl(Wt);te.Axios=qn;te.CanceledError=He;te.CancelToken=Tl;te.isCancel=Hn;te.VERSION=ao;te.toFormData=ut;te.AxiosError=O;te.Cancel=te.CanceledError;te.all=function(t){return Promise.all(t)};te.spread=da;te.isAxiosError=fa;te.mergeConfig=Ne;te.AxiosHeaders=oe;te.formToJSON=e=>eo(m.isHTMLForm(e)?new FormData(e):e);te.getAdapter=oo.getAdapter;te.HttpStatusCode=Pl;te.default=te;var co=te;var{Axios:t0,AxiosError:n0,CanceledError:r0,isCancel:o0,CancelToken:i0,VERSION:a0,all:s0,Cancel:c0,isAxiosError:u0,spread:l0,toFormData:d0,AxiosHeaders:f0,HttpStatusCode:p0,formToJSON:m0,getAdapter:h0,mergeConfig:g0}=co;function Jh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function Ee(e,t,n){if(!e.s){if(n instanceof ma)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Ee.bind(null,e,t);return}if(n&&n.then){n.then(Ee.bind(null,e,t),Ee.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var ma=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Ee(r,1,i(this.v))}catch(a){Ee(r,2,a)}return r}else return this}return this.o=function(i){try{let a=i.v;i.s&1?Ee(r,1,t?t(a):a):n?Ee(r,1,n(a)):Ee(r,2,a)}catch(a){Ee(r,2,a)}},r},e})();function en(e){return e instanceof ma&&e.s&1}function Gh(e,t){var n;do{var r=e();if(r&&r.then)if(en(r))r=r.v;else{n=!0;break}var o=t();if(en(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ma,a=Ee.bind(null,i,2);return(n?r.then(s):o.then(u)).then(void 0,a),i;function s(c){for(r=c;o=t(),en(o)&&(o=o.v),!!o;){if(o.then){o.then(u).then(void 0,a);return}if(r=e(),r&&r.then)if(en(r))r=r.v;else{r.then(s).then(void 0,a);return}}Ee(i,1,r)}function u(c){if(c){do{if(r=e(),r&&r.then)if(en(r))r=r.v;else{r.then(s).then(void 0,a);return}if(c=t(),en(c)&&(c=c.v),!c){Ee(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else Ee(i,1,r)}}function Ol(){return{plc:function(t,n){try{let o=function(){let l=typeof u?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{contentType:l}}},r,i=null,a=`https://plc.directory/${encodeURIComponent(t)}`,s={},u=null,c=Gh(function(){function l(){r||u?.id===t||(i="resolver_error: DID document id does not match requested did")}let d=Jh(function(){return Promise.resolve(co.get(a)).then(function(p){u=p.data})},function(p){i=`resolver_error: '"https://plc.directory/" + DID' must resolve to a valid https URL containing a JSON document: ${p}`,r=1});return d&&d.then?d.then(l):l(d)},function(){return!r&&!1});return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(r){return Promise.reject(r)}}}}var Rl=of(Dl(),1);function Vh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var qh=function(e){try{return Promise.resolve((0,Rl.default)(e,{mode:"cors"})).then(function(t){if(t.status>=400)throw new Error(`Bad response ${t.statusText}`);return t.json()})}catch(t){return Promise.reject(t)}};function ke(e,t,n){if(!e.s){if(n instanceof ha)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=ke.bind(null,e,t);return}if(n&&n.then){n.then(ke.bind(null,e,t),ke.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Kh="/.well-known/did.json",ha=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{ke(r,1,i(this.v))}catch(a){ke(r,2,a)}return r}else return this}return this.o=function(i){try{let a=i.v;i.s&1?ke(r,1,t?t(a):a):n?ke(r,1,n(a)):ke(r,2,a)}catch(a){ke(r,2,a)}},r},e})();function nn(e){return e instanceof ha&&e.s&1}function Wh(e,t){var n;do{var r=e();if(r&&r.then)if(nn(r))r=r.v;else{n=!0;break}var o=t();if(nn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ha,a=ke.bind(null,i,2);return(n?r.then(s):o.then(u)).then(void 0,a),i;function s(c){for(r=c;o=t(),nn(o)&&(o=o.v),!!o;){if(o.then){o.then(u).then(void 0,a);return}if(r=e(),r&&r.then)if(nn(r))r=r.v;else{r.then(s).then(void 0,a);return}}ke(i,1,r)}function u(c){if(c){do{if(r=e(),r&&r.then)if(nn(r))r=r.v;else{r.then(s).then(void 0,a);return}if(c=t(),nn(c)&&(c=c.v),!c){ke(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else ke(i,1,r)}}function jl(){return{web:function(t,n){try{let o=function(){let p=typeof l?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{contentType:p}}},r,i=null,a=decodeURIComponent(n.id)+Kh,s=n.id.split(":");s.length>1&&(a=s.map(decodeURIComponent).join("/")+"/did.json");let u=`https://${a}`,c={},l=null,d=Wh(function(){function p(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let v=Vh(function(){return Promise.resolve(qh(u)).then(function(f){l=f})},function(f){i=`resolver_error: DID must resolve to a valid https URL containing a JSON document: ${f}`,r=1});return v&&v.then?v.then(p):p(v)},function(){return!r&&!1});return Promise.resolve(d&&d.then?d.then(o):o(d))}catch(r){return Promise.reject(r)}}}}var fo=class{methods={...Ol(),...jl()};resolver=new Gr(this.methods,{cache:!0});async resolve(t){if(!Object.keys(this.methods).some(r=>t.startsWith(`did:${r}:`)))throw new Error(`Unrecognized DID method: ${t}`);let{didDocument:n}=await this.resolver.resolve(t);if(!n)throw new ae(`DID not found: ${t}`);return n}};var va;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(va="oauth4webapi/v3.8.3");function Qn(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var ye="ERR_INVALID_ARG_VALUE",ze="ERR_INVALID_ARG_TYPE";function K(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var $t=Symbol(),yo=Symbol(),vo=Symbol(),St=Symbol();var po=Symbol();var Xh=new TextEncoder,Yh=new TextDecoder;function Nl(e){return typeof e=="string"?Xh.encode(e):Yh.decode(e)}var ba;Uint8Array.prototype.toBase64?ba=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):ba=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var _a;Uint8Array.fromBase64?_a=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw K("The input to be decoded is not correctly encoded.",ye,t)}}:_a=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw K("The input to be decoded is not correctly encoded.",ye,t)}};function wa(e){return typeof e=="string"?_a(e):ba(e)}var dt=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=So,Error.captureStackTrace?.(this,this.constructor)}},Wn=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor)}};function N(e,t,n){return new Wn(e,{code:t,cause:n})}function mo(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function xa(e){Qn(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(va&&!t.has("user-agent")&&t.set("user-agent",va),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',ye);return t}function Ll(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw K('"options.signal" must return or be an instance of AbortSignal',ze);return t}}function Ml(e){return e.includes("//")?e.replace("//","/"):e}function Qh(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=Ml(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function eg(e,t){return e.pathname=Ml(`${e.pathname}/${t}`),e}async function tg(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,ze);wo(e,r?.[$t]!==!0);let o=n(new URL(e.href)),i=xa(r?.headers);return i.set("accept","application/json"),(r?.[St]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Ll(o,r?.signal)})}async function Zl(e,t){return tg(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":eg(n,".well-known/openid-configuration");break;case"oauth2":Qh(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',ye)}return n},t)}function Kn(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw K(`${n} must be a number`,ze,o);if(e>0)return;if(t){if(e!==0)throw K(`${n} must be a non-negative number`,ye,o);return}throw K(`${n} must be a positive number`,ye,o)}catch(i){throw r?N(i.message,r,o):i}}function ge(e,t,n,r){try{if(typeof e!="string")throw K(`${t} must be a string`,ze,r);if(e.length===0)throw K(`${t} must not be empty`,ye,r)}catch(o){throw n?N(o.message,n,r):o}}async function Bl(e,t){let n=e;if(!(n instanceof URL)&&n!==go)throw K('"expectedIssuerIdentifier" must be an instance of URL',ze);if(!Qn(t,Response))throw K('"response" must be an instance of Response',ze);if(t.status!==200)throw N('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Eo,t);Ua(t);let r=await od(t);if(ge(r.issuer,'"response" body "issuer" property',G,{body:r}),n!==go&&new URL(r.issuer).href!==n.href)throw N('"response" body "issuer" property does not match the expected value',ko,{expected:n.href,body:r,attribute:"issuer"});return r}function Fl(e){rg(e,"application/json")}function ng(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return N(n,Pa,e)}function rg(e,t){if(Ia(e)!==t)throw ng(e,t)}function og(){return wa(crypto.getRandomValues(new Uint8Array(32)))}function Hl(){return og()}function $a(e){let t=e?.[yo];return typeof t=="number"&&Number.isFinite(t)?t:0}function Sa(e){let t=e?.[vo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ea(){return Math.floor(Date.now()/1e3)}function bo(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',ze);ge(e.issuer,'"as.issuer"')}function _o(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',ze);ge(e.client_id,'"client.client_id"')}function ka(e){return ge(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function Jl(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var ig=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function wo(e,t){if(t&&e.protocol!=="https:")throw N("only requests to HTTPS are allowed",za,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw N("only HTTP and HTTPS requests are allowed",Oa,e)}function Cl(e,t,n,r){let o;if(typeof e!="string"||!(o=ig(e)))throw N(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Pg:zg,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return wo(o,r),o}function xo(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Cl(e.mtls_endpoint_aliases[t],t,n,r):Cl(e[t],t,n,r)}function Gl(e){if(e instanceof on){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof rn?e.error==="use_dpop_nonce":!1}var rn=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ag,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:n.response}),Error.captureStackTrace?.(this,this.constructor)}},Xn=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Tg,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},on=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ig,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},ho="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ag="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",sg='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',cg="("+ho+")\\s*=\\s*"+sg,ug="("+ho+")\\s*=\\s*("+ho+")",lg=new RegExp("^[,\\s]*("+ho+")"),dg=new RegExp("^[,\\s]*"+cg+"[,\\s]*(.*)"),fg=new RegExp("^[,\\s]*"+ug+"[,\\s]*(.*)"),pg=new RegExp("^("+ag+")(?:$|[,\\s])(.*)");function mg(e){if(!Qn(e,Response))throw K('"response" must be an instance of Response',ze);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(lg),i=o?.[1].toLowerCase();if(!i)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let s=a.match(/^\s+(.*)$/),u=!!s;r=s?s[1]:void 0;let c={},l;if(u)for(;r;){let p,v;if(o=r.match(dg)){if([,p,v,r]=o,v.includes("\\"))try{v=JSON.parse(`"${v}"`)}catch{}c[p.toLowerCase()]=v;continue}if(o=r.match(fg)){[,p,v,r]=o,c[p.toLowerCase()]=v;continue}if(o=r.match(pg)){if(Object.keys(c).length)break;[,l,r]=o;break}return}else r=a||void 0;let d={scheme:i,parameters:c};l&&(d.token68=l),n.push(d)}if(n.length)return n}async function hg(e){if(e.status>399&&e.status<500){Ua(e),Fl(e);try{let t=await e.clone().json();if(mo(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function Vl(e,t,n){if(e.status!==t){bg(e);let r;throw(r=await hg(e))?(await e.body?.cancel(),new rn("server responded with an error in the response body",{cause:r,response:e})):N(`"response" is not a conform ${n} response (unexpected HTTP status code)`,Eo,e)}}function gg(e){if(!Aa.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',ye)}function Ia(e){return e.headers.get("content-type")?.split(";")[0]}async function ql(e,t,n,r,o,i,a){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[St]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Ll(r,a?.signal)})}async function yg(e,t,n,r,o,i){let a=xo(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[$t]!==!0);o.set("grant_type",r);let s=xa(i?.headers);s.set("accept","application/json"),i?.DPoP!==void 0&&(gg(i.DPoP),await i.DPoP.addProof(a,s,"POST"));let u=await ql(e,t,n,a,o,s,i);return i?.DPoP?.cacheNonce(u,a),u}var Kl=new WeakMap,vg=new WeakMap;function $o(e){if(!e.id_token)return;let t=Kl.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',ye);return t}async function Wl(e,t,n,r,o,i){if(bo(e),_o(t),!Qn(n,Response))throw K('"response" must be an instance of Response',ze);await Vl(n,200,"Token Endpoint"),Ua(n);let a=await od(n);if(ge(a.access_token,'"response" body "access_token" property',G,{body:a}),ge(a.token_type,'"response" body "token_type" property',G,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let s=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Kn(s,!0,'"response" body "expires_in" property',G,{body:a}),a.expires_in=s}if(a.refresh_token!==void 0&&ge(a.refresh_token,'"response" body "refresh_token" property',G,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw N('"response" body "scope" property must be a string',G,{body:a});if(a.id_token!==void 0){ge(a.id_token,'"response" body "id_token" property',G,{body:a});let s=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&s.push("auth_time"),t.default_max_age!==void 0&&(Kn(t.default_max_age,!0,'"client.default_max_age"'),s.push("auth_time")),r?.length&&s.push(...r);let{claims:u,jwt:c}=await Og(a.id_token,Dg.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),$a(t),Sa(t),o).then(Sg.bind(void 0,s)).then(wg.bind(void 0,e)).then(_g.bind(void 0,t.client_id));if(Array.isArray(u.aud)&&u.aud.length!==1){if(u.azp===void 0)throw N('ID Token "aud" (audience) claim includes additional untrusted audiences',Ge,{claims:u,claim:"aud"});if(u.azp!==t.client_id)throw N('unexpected ID Token "azp" (authorized party) claim value',Ge,{expected:t.client_id,claims:u,claim:"azp"})}u.auth_time!==void 0&&Kn(u.auth_time,!0,'ID Token "auth_time" (authentication time)',G,{claims:u}),vg.set(n,c),Kl.set(a,u)}if(i?.[a.token_type]!==void 0)i[a.token_type](n,a);else if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new dt("unsupported `token_type` value",{cause:{body:a}});return a}function bg(e){let t;if(t=mg(e))throw new on("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function _g(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw N('unexpected JWT "aud" (audience) claim value',Ge,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw N('unexpected JWT "aud" (audience) claim value',Ge,{expected:e,claims:t.claims,claim:"aud"});return t}function wg(e,t){let n=e[Da]?.(t)??e.issuer;if(t.claims.iss!==n)throw N('unexpected JWT "iss" (issuer) claim value',Ge,{expected:n,claims:t.claims,claim:"iss"});return t}var Aa=new WeakSet;function xg(e){return Aa.add(e),e}var Ta=Symbol();async function Xl(e,t,n,r,o,i,a){if(bo(e),_o(t),!Aa.has(r))throw K('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ye);ge(o,'"redirectUri"');let s=xt(r,"code");if(!s)throw N('no authorization code in "callbackParameters"',G);let u=new URLSearchParams(a?.additionalParameters);return u.set("redirect_uri",o),u.set("code",s),i!==Ta&&(ge(i,'"codeVerifier"'),u.set("code_verifier",i)),yg(e,t,n,"authorization_code",u,a)}var $g={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Sg(e,t){for(let n of e)if(t.claims[n]===void 0)throw N(`JWT "${n}" (${$g[n]}) claim missing`,G,{claims:t.claims});return t}var ga=Symbol(),ya=Symbol();async function Yl(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Eg(e,t,n,r.expectedNonce,r.maxAge,r[po],r.recognizedTokenTypes):kg(e,t,n,r?.[po],r?.recognizedTokenTypes)}async function Eg(e,t,n,r,o,i,a){let s=[];switch(r){case void 0:r=ga;break;case ga:break;default:ge(r,'"expectedNonce" argument'),s.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=ya;break;case ya:break;default:Kn(o,!0,'"maxAge" argument'),s.push("auth_time")}let u=await Wl(e,t,n,s,i,a);ge(u.id_token,'"response" body "id_token" property',G,{body:u});let c=$o(u);if(o!==ya){let l=Ea()+$a(t),d=Sa(t);if(c.auth_time+o<l-d)throw N("too much time has elapsed since the last End-User authentication",an,{claims:c,now:l,tolerance:d,claim:"auth_time"})}if(r===ga){if(c.nonce!==void 0)throw N('unexpected ID Token "nonce" claim value',Ge,{expected:void 0,claims:c,claim:"nonce"})}else if(c.nonce!==r)throw N('unexpected ID Token "nonce" claim value',Ge,{expected:r,claims:c,claim:"nonce"});return u}async function kg(e,t,n,r,o){let i=await Wl(e,t,n,void 0,r,o),a=$o(i);if(a){if(t.default_max_age!==void 0){Kn(t.default_max_age,!0,'"client.default_max_age"');let s=Ea()+$a(t),u=Sa(t);if(a.auth_time+t.default_max_age<s-u)throw N("too much time has elapsed since the last End-User authentication",an,{claims:a,now:s,tolerance:u,claim:"auth_time"})}if(a.nonce!==void 0)throw N('unexpected ID Token "nonce" claim value',Ge,{expected:void 0,claims:a,claim:"nonce"})}return i}var Ig="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ag="OAUTH_RESPONSE_BODY_ERROR",So="OAUTH_UNSUPPORTED_OPERATION",Tg="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Yn="OAUTH_PARSE_ERROR",G="OAUTH_INVALID_RESPONSE";var Pa="OAUTH_RESPONSE_IS_NOT_JSON",Eo="OAUTH_RESPONSE_IS_NOT_CONFORM",za="OAUTH_HTTP_REQUEST_FORBIDDEN",Oa="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",an="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Ge="OAUTH_JWT_CLAIM_COMPARISON_FAILED",ko="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Pg="OAUTH_MISSING_SERVER_METADATA",zg="OAUTH_INVALID_SERVER_METADATA";async function Ql(e,t,n,r,o){bo(e),_o(t),ge(r,'"token"');let i=xo(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[$t]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let s=xa(o?.headers);return s.delete("accept"),ql(e,t,n,i,a,s,o)}async function ed(e){if(!Qn(e,Response))throw K('"response" must be an instance of Response',ze);await Vl(e,200,"Revocation Endpoint")}function Ua(e){if(e.bodyUsed)throw K('"response" body has been used already',ye)}async function Og(e,t,n,r,o){let{0:i,1:a,length:s}=e.split(".");if(s===5)if(o!==void 0)e=await o(e),{0:i,1:a,length:s}=e.split(".");else throw new dt("JWE decryption is not configured",{cause:e});if(s!==3)throw N("Invalid JWT",G,e);let u;try{u=JSON.parse(Nl(wa(i)))}catch(d){throw N("failed to parse JWT Header body as base64url encoded JSON",Yn,d)}if(!mo(u))throw N("JWT Header must be a top level object",G,e);if(t(u),u.crit!==void 0)throw new dt('no JWT "crit" header parameter extensions are supported',{cause:{header:u}});let c;try{c=JSON.parse(Nl(wa(a)))}catch(d){throw N("failed to parse JWT Payload body as base64url encoded JSON",Yn,d)}if(!mo(c))throw N("JWT Payload must be a top level object",G,e);let l=Ea()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw N('unexpected JWT "exp" (expiration time) claim type',G,{claims:c});if(c.exp<=l-r)throw N('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',an,{claims:c,now:l,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw N('unexpected JWT "iat" (issued at) claim type',G,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw N('unexpected JWT "iss" (issuer) claim type',G,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw N('unexpected JWT "nbf" (not before) claim type',G,{claims:c});if(c.nbf>l+r)throw N('unexpected JWT "nbf" (not before) claim value',an,{claims:c,now:l,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw N('unexpected JWT "aud" (audience) claim type',G,{claims:c});return{header:u,claims:c,jwt:e}}async function Ug(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",ye,{cause:e});return e.text()}async function td(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",ye,{cause:e});if(Ia(e)!=="application/x-www-form-urlencoded")throw K("form_post responses are expected to use the application/x-www-form-urlencoded content-type",ye,{cause:e});return Ug(e)}function Dg(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:n,reason:"default value"});return}throw N('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function xt(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw N(`"${t}" parameter must be provided only once`,G);return n}var nd=Symbol(),Rg=Symbol();function rd(e,t,n,r){if(bo(e),_o(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw K('"parameters" must be an instance of URLSearchParams, or URL',ze);if(xt(n,"response"))throw N('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',G,{parameters:n});let o=xt(n,"iss"),i=xt(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw N('response parameter "iss" (issuer) missing',G,{parameters:n});if(o&&o!==e.issuer)throw N('unexpected "iss" (issuer) response parameter value',G,{expected:e.issuer,parameters:n});switch(r){case void 0:case Rg:if(i!==void 0)throw N('unexpected "state" response parameter encountered',G,{expected:void 0,parameters:n});break;case nd:break;default:if(ge(r,'"expectedState" argument'),i!==r)throw N(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',G,{expected:r,parameters:n})}if(xt(n,"error"))throw new Xn("authorization response from the server is an error",{cause:n});let s=xt(n,"id_token"),u=xt(n,"token");if(s!==void 0||u!==void 0)throw new dt("implicit and hybrid flows are not supported");return xg(new URLSearchParams(n))}async function od(e,t=Fl){let n;try{n=await e.json()}catch(r){throw t(e),N('failed to parse "response" body as JSON',Yn,r)}if(!mo(n))throw N('"response" body must be a top level object',G,{body:n});return n}var go=Symbol(),Da=Symbol();var tr,id;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(id="openid-client/v6.8.1",tr={"user-agent":id});var Ce=e=>ja.get(e),ja,Ra;function Ng(e){return e!==void 0?ka(e):(Ra||=new WeakMap,(t,n,r,o)=>{let i;return(i=Ra.get(n))||(Cg(n.client_secret,'"metadata.client_secret"'),i=ka(n.client_secret),Ra.set(n,i)),i(t,n,r,o)})}function Cg(e,t){if(typeof e!="string")throw Ve(`${t} must be a string`,rr);if(e.length===0)throw Ve(`${t} must not be empty`,nr)}function Lg(){return Jl()}var sn=St;var nr="ERR_INVALID_ARG_VALUE",rr="ERR_INVALID_ARG_TYPE";function Ve(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function sd(){return Hl()}var cn=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},fP=new TextDecoder;function pe(e,t,n){return new cn(e,{cause:t,code:n})}function er(e){if(e instanceof TypeError||e instanceof cn||e instanceof rn||e instanceof Xn||e instanceof on)throw e;if(e instanceof Wn)switch(e.code){case za:throw pe("only requests to HTTPS are allowed",e,e.code);case Oa:throw pe("only requests to HTTP or HTTPS are allowed",e,e.code);case Eo:throw pe("unexpected HTTP response status code",e.cause,e.code);case Pa:throw pe("unexpected response content-type",e.cause,e.code);case Yn:throw pe("parsing error occured",e,e.code);case G:throw pe("invalid response encountered",e,e.code);case Ge:throw pe("unexpected JWT claim value encountered",e,e.code);case ko:throw pe("unexpected JSON attribute value encountered",e,e.code);case an:throw pe("JWT timestamp claim value failed validation",e,e.code);default:throw pe(e.message,e,e.code)}if(e instanceof dt)throw pe("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw pe("runtime operation error",e,So);case"NotSupportedError":throw pe("runtime unsupported operation",e,So);case"TimeoutError":throw pe("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw pe("operation aborted",e,"OAUTH_ABORT")}throw new cn("something went wrong",{cause:e})}function Mg(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[ud]=!0,!0):!1}function Zg(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function cd(e,t,n,r,o){let i=await Bg(e,o),a=new un(i,t,n,r),s=Ce(a);if(o?.[sn]&&(s.fetch=o[sn]),o?.timeout&&(s.timeout=o.timeout),o?.execute)for(let u of o.execute)u(a);return a}async function Bg(e,t){if(!(e instanceof URL))throw Ve('"server" must be an instance of URL',rr);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?Zl(e,{algorithm:t?.algorithm,[St]:t?.[sn],[$t]:t?.execute?.includes(ad),signal:o,headers:new Headers(tr)}):(t?.[sn]||fetch)((wo(e,!t?.execute?.includes(ad)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...tr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Bl(go,a)).catch(er);return n&&new URL(i.issuer).href!==e.href&&(Mg(e,i,t)||Zg(e,t)||(()=>{throw new cn("discovered metadata issuer does not match the expected issuer",{code:ko,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Fg(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Hg(e){Object.defineProperties(e,Fg(e))}var ud=Symbol(),un=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw Ve('"clientId" must be a non-empty string',rr);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw Ve('"clientId" and "metadata.client_id" must be the same',nr);let i={...structuredClone(r),client_id:n};i[yo]=r?.[yo]??0,i[vo]=r?.[vo]??30;let a;o?a=o:typeof i.client_secret=="string"&&i.client_secret.length?a=Ng(i.client_secret):a=Lg();let s=Object.freeze(i),u=structuredClone(t);ud in t&&(u[Da]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let c=Object.freeze(u);ja||=new WeakMap,ja.set(this,{__proto__:null,as:c,c:s,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(Ce(this).as);return Hg(t),t}clientMetadata(){return structuredClone(Ce(this).c)}get timeout(){return Ce(this).timeout}set timeout(t){Ce(this).timeout=t}get[sn](){return Ce(this).fetch}set[sn](t){Ce(this).fetch=t}};Object.freeze(un.prototype);function Jg(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){try{return $o(this)}catch{return}}}}}function Gg(e){Object.defineProperties(e,Jg(e))}function ad(e){Ce(e).tlsOnly=!1}function Vg(e){return e=new URL(e),e.search="",e.hash="",e.href}function qg(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Na(e,t,n,r,o){if(Ca(e),o?.flag!==Io&&!(t instanceof URL)&&!qg(t,"Request"))throw Ve('"currentUrl" must be an instance of URL, or Request',rr);let i,a,{as:s,c:u,auth:c,fetch:l,tlsOnly:d,jarm:p,hybrid:v,nonRepudiation:f,timeout:y,decrypt:b,implicit:S}=Ce(e);if(o?.flag===Io)i=o.authResponse,a=o.redirectUri;else{if(!(t instanceof URL)){let x=t;switch(t=new URL(t.url),x.method){case"GET":break;case"POST":let C=new URLSearchParams(await td(x));if(v)t.hash=C.toString();else for(let[U,Z]of C.entries())t.searchParams.append(U,Z);break;default:throw Ve("unexpected Request HTTP method",nr)}}switch(a=Vg(t),!0){case!!p:i=await p(t,n?.expectedState);break;case!!v:i=await v(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!S:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=rd(s,u,t.searchParams,n?.expectedState)}catch(x){er(x)}}}let I=await Xl(s,u,c,i,a,n?.pkceCodeVerifier||Ta,{additionalParameters:r,[St]:l,[$t]:!d,DPoP:o?.DPoP,headers:new Headers(tr),signal:dd(y)}).catch(er);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let _=Yl(s,u,I,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[po]:b}),E;try{E=await _}catch(x){if(Kg(x,o))return Na(e,void 0,n,r,{...o,flag:Io,authResponse:i,redirectUri:a});er(x)}return E.id_token&&await f?.(I),Gg(E),E}function ld(e,t){Ca(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:a,implicit:s}=Ce(e),u=xo(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw Ve("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",nr);a&&t.set("response_mode","jwt")}for(let[c,l]of t.entries())u.searchParams.append(c,l);return u}function Ca(e){if(!(e instanceof un))throw Ve('"config" must be an instance of Configuration',rr);if(Object.getPrototypeOf(e)!==un.prototype)throw Ve("subclassing Configuration is not allowed",nr)}function dd(e){return e?AbortSignal.timeout(e*1e3):void 0}function Kg(e,t){return t?.DPoP&&t.flag!==Io?Gl(e):!1}var Io=Symbol();async function fd(e,t,n){Ca(e);let{as:r,c:o,auth:i,fetch:a,tlsOnly:s,timeout:u}=Ce(e);return Ql(r,o,i,t,{[St]:a,[$t]:!s,additionalParameters:new URLSearchParams(n),headers:new Headers(tr),signal:dd(u)}).then(ed).catch(er)}var pd="oauth2:",or="graffiti-auth-oauth2-data",Ao=class{eventTarget=new EventTarget;constructor(){let t=this.completeOauth();(async()=>{await new Promise(r=>setTimeout(r,0)),await t;let n=new CustomEvent("initialized");this.eventTarget.dispatchEvent(n)})()}async login(...t){try{await this.login_(...t)}catch(n){let r=n instanceof Error?n:new Error("Unknown error"),o={loginId:t[1],error:r};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:o}))}}async login_(t,n,r){let o=await this.getAuthorizationConfiguration(t),i=r.map(encodeURIComponent).join(" "),a=sd(),s,u;if(typeof window<"u"){s=window.location.href;let d={loginId:n,redirectUri:s,authorizationEndpoint:t,state:a,serviceEndpoints:r};window.localStorage.setItem(or,JSON.stringify(d))}else{let p=(await import("node:http").catch(f=>{throw new Error("Unrecognized environment: cannot find window or node:http")})).createServer();try{await new Promise((f,y)=>{p.once("error",y),p.listen(0,"::1",f)})}catch{try{p.close()}catch{}throw new Error("Failed to start local oauth callback server.")}let v=p.address();if(!v){try{p.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}s=typeof v=="string"?`http://${v}`:`http://${v.family==="IPv6"?`[${v.address}]`:v.address}:${v.port}`,u=new Promise((f,y)=>{let b=setTimeout(()=>{try{p.close()}catch{}y("Oauth callback timed out.")},3e5),S=new Set;p.on("connection",_=>{S.add(_),_.on("close",()=>{S.delete(_)})});let I=async(_,E)=>{try{let x=new URL(_.url??"/",s);await this.onCallbackUrl({loginId:n,callbackUrl:x,configuration:o,expectedState:a,serviceEndpoints:r}),E.statusCode=200,E.setHeader("Content-Type","text/plain"),E.end("You may now close this window.")}catch(x){throw E.statusCode=500,E.setHeader("Content-Type","text/plain"),E.end("Error processing OAuth callback."),x}finally{clearTimeout(b),p.off("request",I);for(let x of S)x.destroy();p.close(()=>f())}};p.on("request",I)})}let c=new URL(s);c.hash="",c.search="";let l=ld(o,{scope:i,redirect_uri:c.toString(),state:a});typeof window<"u"?window.location.href=l.toString():(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await u)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(or);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(or);return}let r=Wg.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(or);return}let{loginId:o,redirectUri:i,authorizationEndpoint:a,state:s,serviceEndpoints:u}=r.data;try{let c=new URL(i),l=new URL(window.location.href);if(c.pathname!==l.pathname)return;let d=l.searchParams;return!d.has("code")&&!d.has("error")?void 0:(window.history.replaceState({},document.title,c.toString()),window.localStorage.removeItem(or),new Promise(p=>setTimeout(p,0)).then(()=>this.getAuthorizationConfiguration(a)).then(p=>this.onCallbackUrl({loginId:o,callbackUrl:l,configuration:p,expectedState:s,serviceEndpoints:u})).catch(p=>{let v=p instanceof Error?p:new Error("Unknown error"),f={loginId:o,error:v};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:f}))}))}catch(c){console.error(c)}}async onCallbackUrl(t){let{loginId:n,callbackUrl:r,configuration:o,expectedState:i,serviceEndpoints:a}=t,s=await Na(o,r,{expectedState:i}),u=s.access_token,l=s.scope?.split(" ").map(decodeURIComponent)||a;if(!a.every(p=>l.includes(p)))throw new Error("Not all requested service endpoints were granted.");let d=new CustomEvent("login",{detail:{loginId:n,token:u}});this.eventTarget.dispatchEvent(d)}async logout(t,n,r){try{await this.logout_(t,n,r)}catch(o){let i=o instanceof Error?o:new Error("Unknown error"),a={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:a}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await fd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(pd))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(pd.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await cd(r,"graffiti-client")}},md=vc(ve({loginId:H()}),st([ve({token:H(),error:X(yc())}),ve({error:Dt(Error)})])),hd=ve({logoutId:H(),error:X(Dt(Error))}),gd=X(Le(ve({error:X(Dt(Error))}))),Wg=ve({loginId:H(),redirectUri:J(),authorizationEndpoint:J(),state:H(),serviceEndpoints:V(J())});var Xg="https://";function Oe(e){if(!e.startsWith(Xg))throw new Error("Unrecognized storage bucket endpoint type")}async function To(e){Oe(e);let t=`${e}/auth`,n=await fetch(t);if(!n.ok)throw new Error("Failed to get storage bucket authorization endpoint");return await n.text()}var La=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function qe(...e){let t=await fetch(...e);if(!t.ok){let n;try{n=await t.text()}catch{n=t.statusText}throw t.status===401?new La(n):t.status===403?new it(n):t.status===404?new ae(n):t.status===410?new Ue(n):t.status===413?new Ot(n):new Error(n)}return t}var Po=class{getAuthorizationEndpoint=To;async put(t,n,r,o){Oe(t);let i=`${t}/value/${encodeURIComponent(n)}`;await qe(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){Oe(t);let o=`${t}/value/${encodeURIComponent(n)}`;await qe(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){Oe(t);let o=`${t}/value/${encodeURIComponent(n)}`,i=await qe(o),a=i.body?.getReader();if(!a)throw new Error("Failed to read value from storage bucket");let s=i.headers.get("Content-Length"),u=s?Number(s):void 0;if(!!u&&!!Number.isFinite(u)&&u>=0){let f=u;if(r!==void 0&&f>r)throw new Error("Value exceeds maximum byte limit");let y=new Uint8Array(f),b=0,S=!1;try{for(;b<=y.length;){let{done:I,value:_}=await a.read();if(I){S=!0;break}if(!_||_.length===0)continue;let E=b+_.length;if(E>y.length)throw new Error("Received more data than expected");y.set(_,b),b=E}}finally{a.releaseLock()}if(!S)throw new Error("Failed to read complete value from storage bucket");return b===f?y:y.slice(0,b)}let l=[],d=0;try{for(;;){let{done:f,value:y}=await a.read();if(f)break;if(!(!y||y.length===0)){if(d+=y.length,r!==void 0&&d>r)throw new Error("Value exceeds maximum byte limit");l.push(y.slice())}}}finally{a.releaseLock()}let p=new Uint8Array(d),v=0;for(let f of l)p.set(f,v),v+=f.length;return p}async*export(t,n){Oe(t);let r=`${t}/export`,o;for(;;){let a=await(await qe(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),s=Fe(await a.arrayBuffer()),u=Yg.parse(s);for(let c of u.keys)yield{key:c};if(u.cursor)o=u.cursor;else break}}},Yg=ve({keys:V(H()),cursor:X(Le(H()))});var Oo=class{getAuthorizationEndpoint=To;cache_=null;get cache(){return this.cache_||(this.cache_=ay()),this.cache_}async send(t,n){Oe(t);let r=`${t}/send`,i=await(await qe(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(Se({m:n}))})).blob(),a=Fe(await i.arrayBuffer());return ry.parse(a).id}async get(t,n,r){let o=zo(t,n),i=await this.cache,a=await i.messages.get(o);if(a)return a;let s=`${t}/message/${n}`,c=await(await qe(s,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})).blob(),l=Fe(await c.arrayBuffer()),d=wd.parse(l);return await i.messages.set(o,d),d}async label(t,n,r,o){if(Oe(t),o){let u=`${t}/label/${n}`;await qe(u,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(Se({l:r}))})}let i=await this.cache,a=zo(t,n),s=await i.messages.get(a);s&&await i.messages.set(a,{...s,l:r})}async fetchMessageBatch(t,n,r,o,i){let a=await qe(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r}),s=a.headers.get("Retry-After"),u=s?parseInt(s):void 0,c=u&&Number.isFinite(u)?Date.now()+u*1e3:void 0;return{response:a,waitTil:c}}async*yieldFromCache(t,n,r,o,i=0){let a=o.messageIds.slice(i);yield*await Promise.all(a.map(async u=>{let c=await t.messages.get(zo(n,u));if(!c){try{await t.messageIds.del(r)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return c}))}async*lockedMessageStreamer(...t){if(typeof window>"u"||!await xd()){let f=this.messageStreamer(...t);for(;;){let y=await f.next();if(y.done)return y.value;yield y.value}}let n=await t[0],r=`graffiti:inbox:${n}`,o=()=>{},i=!1;if(await new Promise(f=>{window.navigator.locks.request(r,{mode:"exclusive",ifAvailable:!0},async y=>{i=!!y,f(),await new Promise(b=>o=b)})}),i)try{let f=this.messageStreamer(...t);for(;;){let y=await f.next();if(y.done)return y.value;yield y.value}}finally{o()}o(),await window.navigator.locks.request(r,()=>{});let a=t[1],s=t[5]??{},u=t[6],c=t[7],l=await this.cache,d=await l.messageIds.get(n);if(!d)throw new Error("Cache not found");if(u!==void 0&&u!==d.version)throw new Ue("Cursor is stale");let p=this.yieldFromCache(l,a,n,d,c);for await(let f of p)yield f;let v={numSeen:d.messageIds.length,version:d.version,messageIdsCacheKey:n,objectSchema:s};return JSON.stringify(v)}async*messageStreamer(t,n,r,o,i,a={},s,u=0){let c=await hr(a),l=await t,d=await this.cache,p=await d.messageIds.get(l);if(s!==void 0&&s!==p?.version)throw new Ue("Cursor is stale");let v=p?.waitTil;await bd(v);let f=p?.cursor,y;try{let x=await this.fetchMessageBatch(n,r,o,i,f);y=x.response,v=x.waitTil}catch(x){if(!(x instanceof Ue&&f))throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(C=>setTimeout(C,5e3)),x;if(await d.messageIds.del(l),s===void 0)p=void 0;else throw x}if(y!==void 0&&p){let x=this.yieldFromCache(d,n,l,p,u);for await(let C of x)yield C}if(y===void 0){let x=await this.fetchMessageBatch(n,r,o,i);y=x.response,v=x.waitTil}let b=y,S,I=p?.version??crypto.randomUUID(),_=p?.messageIds??[];for(;;){let x=await b.blob(),C=Fe(await x.arrayBuffer()),{results:U,hasMore:Z,cursor:Q}=oy.parse(C);S=Q;let Ie=U.map(w=>{let z=w[ln][ft];if(!c(z))throw new Error("Server returned data that does not match schema");return{...w,[ln]:{...w[ln],[ft]:z}}});await Promise.all(Ie.map(w=>d.messages.set(zo(n,w[Ma]),w))),_=[..._,...Ie.map(w=>w[Ma])],await d.messageIds.set(l,{cursor:S,version:I,messageIds:_,waitTil:v}),u+=Ie.length;for(let w of Ie)yield w;if(!Z)break;await bd(v);let h=await this.fetchMessageBatch(n,r,void 0,i,S);b=h.response,v=h.waitTil}return JSON.stringify({numSeen:u,version:I,messageIdsCacheKey:l,objectSchema:a})}query(t,n,r,o){Oe(t);let i=Se({tags:n,schema:r}),a=yd(t,"query",i);return this.lockedMessageStreamer(a,t,"query",new Uint8Array(i),o,r)}continueQuery(t,n,r){Oe(t);let o=JSON.parse(n),{messageIdsCacheKey:i,numSeen:a,objectSchema:s,version:u}=iy.parse(o);return this.lockedMessageStreamer(Promise.resolve(i),t,"query",void 0,r,s,u,a)}export(t,n){Oe(t);let r=yd(t,"export");return this.lockedMessageStreamer(r,t,"export",void 0,n)}},Qg=be({value:me({}),channels:V(H()),allowed:X(Le(V(J()))),url:J(),actor:J()}),_d=vt(e=>e instanceof Uint8Array),ey=V(_d),ir="t",ft="o",ar="m",ty=be({[ir]:ey,[ft]:Qg,[ar]:_d}),Ma="id",ln="m",ny="l",wd=be({[Ma]:H(),[ln]:ty,[ny]:hc()}),ry=be({id:H()}),oy=be({results:V(wd),hasMore:wi(),cursor:H()}),iy=be({messageIdsCacheKey:H(),version:H(),numSeen:Ut().check(yt()),objectSchema:st([me({}),wi()])});async function xd(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function zo(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function yd(e,t,n){let r=Se({inboxUrl:e,type:t,body:n??null});return crypto.subtle.digest("SHA-256",new Uint8Array(r)).then(o=>Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join(""))}async function vd(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function ay(){if(await xd()){let{openDB:n}=await import("./build-BXWPS7VK.js"),r=await n("graffiti-inbox-cache",1,{upgrade(o){o.objectStoreNames.contains("m")||o.createObjectStore("m"),o.objectStoreNames.contains("q")||o.createObjectStore("q")}});return{messages:{get:async o=>{try{return r.get("m",o)}catch(i){console.error("Error getting message from cache:",i),console.error("resetting cache..."),await vd();return}},set:async(o,i)=>{await r.put("m",i,o)},del:o=>r.delete("m",o)},messageIds:{get:async o=>{try{return await r.get("q",o)}catch(i){console.error("Error getting message IDs from cache:",i),console.error("resetting cache..."),await vd();return}},set:async(o,i)=>{await r.put("q",i,o)},del:o=>r.delete("q",o)}}}let e=new Map,t=new Map;return{messages:{get:async n=>e.get(n),set:async(n,r)=>{e.set(n,r)},del:async n=>{e.delete(n)}},messageIds:{get:async n=>t.get(n),set:async(n,r)=>{t.set(n,r)},del:async n=>{t.delete(n)}}}}async function bd(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var dn="base64url";var Uo=class{async encode(t,n){if(t!==dn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function $d(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function Sd(e,t,n){let r=async o=>{Ir(o);let i=$d();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},r}function sy(e){if(kc(e),typeof e.webCryptoName!="string")throw new Error("non-web hash")}var Et=Sd("SHA-256",64,32);var Ed=Sd("SHA-512",128,64),Za=(()=>{let e=async(t,n,r)=>{let o=$d();Ir(n,void 0,"key"),Ir(r,void 0,"message"),sy(t);let i=await o.importKey("raw",n,{name:"HMAC",hash:t.webCryptoName},!1,["sign"]);return new Uint8Array(await o.sign("HMAC",i,r))};return e.create=(t,n)=>{throw new Error("not implemented")},e})();var Do="sha2-256",sr=18,fn=32,Ro=class{async register(t,n){if(t!==Do)throw new Error(`Unsupported content address method: ${t}`);let r=await Et(n),o=new Uint8Array(2+r.length);return o[0]=sr,o[1]=fn,o.set(r,2),o}async getMethod(t){if(t[0]===sr&&t[1]===fn&&t.length===2+fn)return Do;throw new Error("Unrecognized content address format.")}};var Od={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:de,n:jo,Gx:kd,Gy:Id,a:Ba,d:Fa,h:cy}=Od,It=32,cr=64,uy=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{let t=new Error(e);throw uy(t,se),t},ly=e=>typeof e=="bigint",dy=e=>typeof e=="string",fy=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",We=(e,t,n="")=>{let r=fy(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;se(a+"expected Uint8Array"+s+", got "+u)}return e},Va=e=>new Uint8Array(e),Ud=e=>Uint8Array.from(e),Dd=(e,t)=>e.toString(16).padStart(t,"0"),Rd=e=>Array.from(We(e)).map(t=>Dd(t,2)).join(""),rt={_0:48,_9:57,A:65,F:70,a:97,f:102},Ad=e=>{if(e>=rt._0&&e<=rt._9)return e-rt._0;if(e>=rt.A&&e<=rt.F)return e-(rt.A-10);if(e>=rt.a&&e<=rt.f)return e-(rt.a-10)},jd=e=>{let t="hex invalid";if(!dy(e))return se(t);let n=e.length,r=n/2;if(n%2)return se(t);let o=Va(r);for(let i=0,a=0;i<r;i++,a+=2){let s=Ad(e.charCodeAt(a)),u=Ad(e.charCodeAt(a+1));if(s===void 0||u===void 0)return se(t);o[i]=s*16+u}return o},py=()=>globalThis?.crypto,my=()=>py()?.subtle??se("crypto.subtle must be defined, consider polyfill"),ur=(...e)=>{let t=Va(e.reduce((r,o)=>r+We(o).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t};var No=BigInt,kt=(e,t,n,r="bad number: out of range")=>ly(e)&&t<=e&&e<n?e:se(r),A=(e,t=de)=>{let n=e%t;return n>=0n?n:t+n},Nd=e=>A(e,jo),hy=(e,t)=>{(e===0n||t<=0n)&&se("no inverse n="+e+" mod="+t);let n=A(e,t),r=t,o=0n,i=1n,a=1n,s=0n;for(;n!==0n;){let u=r/n,c=r%n,l=o-a*u,d=i-s*u;r=n,n=c,o=a,i=s,a=l,s=d}return r===1n?A(o,t):se("no inverse")};var Ha=e=>e instanceof ot?e:se("Point expected"),Ja=2n**256n,ot=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=Ja;this.X=kt(t,0n,i),this.Y=kt(n,0n,i),this.Z=kt(r,1n,i),this.T=kt(o,0n,i),Object.freeze(this)}static CURVE(){return Od}static fromAffine(t){return new e(t.x,t.y,1n,A(t.x*t.y))}static fromBytes(t,n=!1){let r=Fa,o=Ud(We(t,It)),i=t[31];o[31]=i&-129;let a=qa(o);kt(a,0n,n?Ja:de);let u=A(a*a),c=A(u-1n),l=A(r*u+1n),{isValid:d,value:p}=yy(c,l);d||se("bad point: y not sqrt");let v=(p&1n)===1n,f=(i&128)!==0;return!n&&p===0n&&f&&se("bad point: x==0, isLastByteOdd"),f!==v&&(p=A(-p)),new e(p,a,1n,A(p*a))}static fromHex(t,n){return e.fromBytes(jd(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ba,n=Fa,r=this;if(r.is0())return se("bad point: ZERO");let{X:o,Y:i,Z:a,T:s}=r,u=A(o*o),c=A(i*i),l=A(a*a),d=A(l*l),p=A(u*t),v=A(l*A(p+c)),f=A(d+A(n*A(u*c)));if(v!==f)return se("bad point: equation left != right (1)");let y=A(o*i),b=A(a*s);return y!==b?se("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:o}=this,{X:i,Y:a,Z:s}=Ha(t),u=A(n*s),c=A(i*o),l=A(r*s),d=A(a*o);return u===c&&l===d}is0(){return this.equals(pn)}negate(){return new e(A(-this.X),this.Y,this.Z,A(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=Ba,i=A(t*t),a=A(n*n),s=A(2n*A(r*r)),u=A(o*i),c=t+n,l=A(A(c*c)-i-a),d=u+a,p=d-s,v=u-a,f=A(l*p),y=A(d*v),b=A(l*v),S=A(p*d);return new e(f,y,S,b)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:a,Y:s,Z:u,T:c}=Ha(t),l=Ba,d=Fa,p=A(n*a),v=A(r*s),f=A(i*d*c),y=A(o*u),b=A((n+r)*(a+s)-p-v),S=A(y-f),I=A(y+f),_=A(v-l*p),E=A(b*S),x=A(I*_),C=A(b*_),U=A(S*I);return new e(E,x,U,C)}subtract(t){return this.add(Ha(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return pn;if(kt(t,1n,jo),t===1n)return this;if(this.equals(pt))return $y(t).p;let r=pn,o=pt;for(let i=this;t>0n;i=i.double(),t>>=1n)t&1n?r=r.add(i):n&&(o=o.add(i));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(pn))return{x:0n,y:1n};let o=hy(r,de);A(r*o)!==1n&&se("invalid inverse");let i=A(t*o),a=A(n*o);return{x:i,y:a}}toBytes(){let{x:t,y:n}=this.assertValidity().toAffine(),r=Cd(n);return r[31]|=t&1n?128:0,r}toHex(){return Rd(this.toBytes())}clearCofactor(){return this.multiply(No(cy),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(jo/2n,!1).double();return jo%2n&&(t=t.add(this)),t.is0()}},pt=new ot(kd,Id,1n,A(kd*Id)),pn=new ot(0n,1n,1n,0n);ot.BASE=pt;ot.ZERO=pn;var Cd=e=>jd(Dd(kt(e,0n,Ja),cr)).reverse(),qa=e=>No("0x"+Rd(Ud(We(e)).reverse())),Ke=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=de;return n},gy=e=>{let n=e*e%de*e%de,r=Ke(n,2n)*n%de,o=Ke(r,1n)*e%de,i=Ke(o,5n)*o%de,a=Ke(i,10n)*i%de,s=Ke(a,20n)*a%de,u=Ke(s,40n)*s%de,c=Ke(u,80n)*u%de,l=Ke(c,80n)*u%de,d=Ke(l,10n)*i%de;return{pow_p_5_8:Ke(d,2n)*e%de,b2:n}},Td=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,yy=(e,t)=>{let n=A(t*t*t),r=A(n*n*t),o=gy(e*r).pow_p_5_8,i=A(e*n*o),a=A(t*i*i),s=i,u=A(i*Td),c=a===e,l=a===A(-e),d=a===A(-e*Td);return c&&(i=s),(l||d)&&(i=u),(A(i)&1n)===1n&&(i=A(-i)),{isValid:c||l,value:i}},Co=e=>Nd(qa(e)),Ka=(...e)=>Wa.sha512Async(ur(...e));var vy=e=>{let t=e.slice(0,It);t[0]&=248,t[31]&=127,t[31]|=64;let n=e.slice(It,cr),r=Co(t),o=pt.multiply(r),i=o.toBytes();return{head:t,prefix:n,scalar:r,point:o,pointBytes:i}},Ld=e=>Ka(We(e,It)).then(vy);var Md=e=>Ld(e).then(t=>t.pointBytes);var Zd=e=>Ka(e.hashable).then(e.finish);var by=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=Co(t),a=pt.multiply(i).toBytes();return{hashable:ur(a,r,n),finish:c=>{let l=Nd(i+Co(c)*o);return We(ur(a,Cd(l)),cr)}}},Bd=async(e,t)=>{let n=We(e),r=await Ld(t),o=await Ka(r.prefix,n);return Zd(by(r,o,n))};var Fd={zip215:!0},_y=(e,t,n,r=Fd)=>{e=We(e,cr),t=We(t),n=We(n,It);let{zip215:o}=r,i,a,s,u,c=Uint8Array.of();try{i=ot.fromBytes(n,o),a=ot.fromBytes(e.slice(0,It),o),s=qa(e.slice(It,cr)),u=pt.multiply(s,!1),c=ur(a.toBytes(),i.toBytes(),t)}catch{}return{hashable:c,finish:d=>{if(u==null||!o&&i.isSmallOrder())return!1;let p=Co(d);return a.add(i.multiply(p,!1)).add(u.negate()).clearCofactor().is0()}}},Hd=async(e,t,n,r=Fd)=>Zd(_y(e,t,n,r));var Wa={sha512Async:async e=>{let t=my(),n=ur(e);return Va(await t.digest("SHA-512",n.buffer))},sha512:void 0};var Lo=8,wy=256,Jd=Math.ceil(wy/Lo)+1,Ga=2**(Lo-1),xy=()=>{let e=[],t=pt,n=t;for(let r=0;r<Jd;r++){n=t,e.push(n);for(let o=1;o<Ga;o++)n=n.add(t),e.push(n);t=n.double()}return e},Pd,zd=(e,t)=>{let n=t.negate();return e?n:t},$y=e=>{let t=Pd||(Pd=xy()),n=pn,r=pt,o=2**Lo,i=o,a=No(o-1),s=No(Lo);for(let u=0;u<Jd;u++){let c=Number(e&a);e>>=s,c>Ga&&(c-=i,e+=1n);let l=u*Ga,d=l,p=l+Math.abs(c)-1,v=u%2!==0,f=c<0;c===0?r=r.add(zd(v,t[d])):n=n.add(zd(f,t[p]))}return e!==0n&&se("invalid wnaf"),{p:n,f:r}};Wa.sha512Async=Ed;var At="pk:sha2-256+ed25519",Xa=0,Mo=class{async register(t,n){if(t!==At)throw new Error(`Unsupported channel attestation method: ${t}`);let r=await this.channelToPrivateKey(n);return await this.channelPublicIdFromPrivateKey(r)}async getMethod(t){if(t[0]===Xa)return At;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await Et(n)}async channelPublicIdFromPrivateKey(t){let n=await Md(t),r=new Uint8Array(n.length+1);return r[0]=Xa,r.set(n,1),r}async attest(t,n,r){if(t!==At)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),a=new TextEncoder().encode(n);return{attestation:await Bd(a,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Xa)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await Hd(t,new TextEncoder().encode(n),r.slice(1))}};var Ya="hmac:sha2-256",Gd=0,Zo=class{async attest(t,n){if(t!==Ya)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=bt(),o=await Za(Et,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=Gd,i[1]=sr,i[2]=fn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],a=r[2];if(o!==Gd||i!==sr||a!==fn)throw new Error("Unrecognized allowed ticket format");let s=await Za(Et,r.slice(3),new TextEncoder().encode(n));return t.length!==s.length?!1:s.every((u,c)=>t[c]===u)}};var Qa="did:web:",Bo=class{constructor(t){this.services=t}actorToHandle=async t=>{let r=(await this.services.dids.resolve(t)).alsoKnownAs?.at(0);if(!r)throw new ae(`Handle for actor DID ${t} not found`);if(!r.startsWith(Qa))throw new Error(`Handle DID ${r} is not a valid handle`);let o=r.slice(Qa.length),i=await this.services.dids.resolve(r);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(t))throw new Error(`Handle ${o} does not match actor ${t}`);return o};handleToActor=async t=>{let n=`${Qa}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new ae(`Actor for handle DID ${n} not found`);let i=await this.services.dids.resolve(o);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(n))throw new Error(`Actor ${o} does not match handle ${t}`);return o}};var Go="GraffitiInbox",qo="GraffitiStorageBucket",rs="#graffitiPersonalInbox",Ko="#graffitiStorageBucket",Sy="#graffitiSharedInbox_",Vo=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let a=gd.safeParse(i.detail);if(!a.success)return;let s=a.data?.error;s&&console.log(s),o()})});this.services.authorization.eventTarget.addEventListener("login",this.onLogin.bind(this)),this.services.authorization.eventTarget.addEventListener("logout",this.onLogout.bind(this));let r;if(typeof window<"u"){let o=new URLSearchParams(window.location.search).get("actor");if(o)try{let i=decodeURIComponent(o),a=new URL(window.location.toString());a.searchParams.delete("actor"),window.history.replaceState({},"",a.toString()),r=this.login(i)}catch(i){console.error("Error decoding actor:",i)}}(async()=>{await new Promise(i=>setTimeout(i,0)),await r;for(let i of this.loggedInSessions){let a=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(a)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}sessionEvents=new EventTarget;inProgressLogin=void 0;inProgressLogout=void 0;async login(t){try{await this.login_(t)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n)),session:{actor:t}}});this.sessionEvents.dispatchEvent(r)}}async login_(t){if(this.loggedInSessions.find(_=>_.actor===t)){this.sessionEvents.dispatchEvent(new CustomEvent("login",{detail:{session:{actor:t}}}));return}let o=(await this.services.dids.resolve(t)).service;if(!o)throw new Error(`No services found in actor document for ${t}`);let i=o.find(_=>_.id===Ko&&_.type===qo),a=o.find(_=>_.id===rs&&_.type===Go),s=o.filter(_=>_.id.match(new RegExp(`^${Sy}\\d+$`))&&_.type===Go);if(!a||!i||s.length===0)throw new Error(`Required services not found in actor document for ${t}`);let u=ts(i),c=ts(a),l=s.map(ts),d=[{endpoint:u,type:"bucket"},{endpoint:c,type:"personal-inbox"},...l.map(_=>({endpoint:_,type:"shared-inbox"}))],p=await Promise.all(d.map(async({endpoint:_,type:E})=>{let x=await(E==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(_):this.services.inboxes.getAuthorizationEndpoint(_));return{endpoint:_,authorizationEndpoint:x,type:E}})),v=new Map;p.forEach(({authorizationEndpoint:_,endpoint:E,type:x})=>{v.has(_)||v.set(_,[]),v.get(_).push({endpoint:E,type:x})});let f=[...v.entries()],b={...{actor:t},tokens:[],servicesByAuthorization:f};typeof window<"u"?window.localStorage.setItem(Fo,JSON.stringify(b)):this.inProgressLogin=b;let[S,I]=f[0];await this.services.authorization.login(S,t,I.map(_=>_.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=md.safeParse(t.detail);if(!n.success)return;let r=n.data.loginId;try{await this.onLogin_(n.data)}catch(o){let i=new CustomEvent("login",{detail:{error:o instanceof Error?o:new Error(String(o)),session:{actor:r}}});this.sessionEvents.dispatchEvent(i)}}async onLogin_(t){if(t.error)throw t.error;let n=t.token,r=t.loginId,o;if(typeof window<"u"){let i=window.localStorage.getItem(Fo);if(!i)throw new Error("No in-progress login found");let a=JSON.parse(i);o=ns.parse(a)}else{if(!this.inProgressLogin)throw new Error("No in-progress login found");o=this.inProgressLogin}if(o.actor!==r)throw new Error("Actor mismatch in login response - concurrent logins?");if(o.tokens.push(n),o.tokens.length===o.servicesByAuthorization.length){typeof window>"u"?this.inProgressLogin=void 0:window.localStorage.removeItem(Fo);let i=o.servicesByAuthorization.flatMap(([c,l],d)=>l.map(p=>({token:o.tokens[d],serviceEndpoint:p.endpoint,authorizationEndpoint:c,type:p.type}))),a={...o,storageBucket:i.find(c=>c.type==="bucket"),personalInbox:i.find(c=>c.type==="personal-inbox"),sharedInboxes:i.filter(c=>c.type==="shared-inbox")},s=this.loggedInSessions;s.push(a),this.loggedInSessions=s;let u=new CustomEvent("login",{detail:{session:{actor:r}}});this.sessionEvents.dispatchEvent(u)}else{typeof window<"u"?window.localStorage.setItem(Fo,JSON.stringify(o)):this.inProgressLogin=o;let[i,a]=o.servicesByAuthorization[o.tokens.length];await this.services.authorization.login(i,r,a.map(s=>s.endpoint))}}async logout(t){try{await this.logout_(t)}catch(n){let r=new CustomEvent("logout",{detail:{error:n instanceof Error?n:new Error(String(n)),actor:t}});this.sessionEvents.dispatchEvent(r)}}async logout_(t){let n=this.loggedInSessions.find(a=>a.actor===t);if(!n)throw new Error(`No session found for actor ${t}`);this.loggedInSessions=this.loggedInSessions.filter(a=>a.actor!==t);let r=n.tokens.pop();if(!r)throw new Error("No tokens found in session");typeof window<"u"?window.localStorage.setItem(Ho,JSON.stringify(n)):this.inProgressLogout=n;let[o,i]=n.servicesByAuthorization[n.tokens.length];await this.services.authorization.logout(o,t,r)}async onLogout(t){if(!(t instanceof CustomEvent))return;let n=hd.safeParse(t.detail);if(!n.success)return;let r=n.data.logoutId;try{await this.onLogout_(n.data)}catch(o){let i=new CustomEvent("logout",{detail:{error:o instanceof Error?o:new Error(String(o)),actor:r}});this.sessionEvents.dispatchEvent(i)}}async onLogout_(t){if(t.error)throw t.error;let n=t.logoutId,r;if(typeof window<"u"){let i=window.localStorage.getItem(Ho);if(!i)throw new Error("No in-progress logout found");let a=JSON.parse(i);r=ns.parse(a)}else{if(!this.inProgressLogout)throw new Error("No in-progress logout found");r=this.inProgressLogout}if(r.actor!==n)throw new Error("Actor mismatch in logout response - concurrent logouts?");let o=r.tokens.pop();if(o){typeof window<"u"?window.localStorage.setItem(Ho,JSON.stringify(r)):this.inProgressLogout=r;let[i,a]=r.servicesByAuthorization[r.tokens.length];await this.services.authorization.logout(i,n,o)}else{typeof window>"u"?this.inProgressLogout=void 0:window.localStorage.removeItem(Ho);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return Vd;let t=window.localStorage.getItem(Jo);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),window.localStorage.removeItem(Jo),[]}let r=V(Iy).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),window.localStorage.removeItem(Jo),[])}set loggedInSessions(t){if(typeof window>"u"){Vd=t;return}window.localStorage.setItem(Jo,JSON.stringify(t))}resolveSession(t){let n=this.loggedInSessions.find(r=>r.actor===t.actor);if(!n){let r=new CustomEvent("logout",{detail:{actor:t.actor}});throw this.sessionEvents.dispatchEvent(r),new Error("Not logged in")}return n}},Vd=[],Fo="graffiti-login-in-progress",Ho="graffiti-logout-in-progress",Jo="graffiti-sessions-logged-in",Ey=ve({actor:J()}),es=ve({token:H(),serviceEndpoint:J(),authorizationEndpoint:J()}),ky=V(le([J(),V(ve({endpoint:J(),type:_c(["bucket","personal-inbox","shared-inbox"])}))])),ns=et(Ey,{tokens:V(H()),servicesByAuthorization:ky}),Iy=et(ns,{storageBucket:es,personalInbox:es,sharedInboxes:V(es)});function ts(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var Wo=32*1024,Xo=class{constructor(t){this.primitives=t}async encode(t,n){t=us(t);let r=await Promise.all(t.channels.map(f=>this.primitives.channelAttestations.attest(At,n,f))),o=r.map(f=>f.attestation),i=r.map(f=>f.channelPublicId),a={[is]:t.value,[as]:o,[Wd]:bt(32)},s;if(Array.isArray(t.allowed)){let f=await Promise.all(t.allowed.map(async y=>this.primitives.allowedAttestations.attest(Ya,y)));a[ss]=f.map(y=>y.attestation),s=f.map(y=>y.ticket)}let u=Se(a);if(u.byteLength>Wo)throw new Error("The object is too large");let c=await this.primitives.contentAddresses.register(Do,u),l=await this.primitives.stringEncoder.encode(dn,c),d=Ty(n,l),p=[new TextEncoder().encode(d),...i];return{object:{value:t.value,channels:t.channels,url:d,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:p,objectBytes:u,allowedTickets:s}}async validate(t,n,r,o){if(r.byteLength>Wo)throw new Error("Object is too big");let{actor:i,contentAddress:a}=ls(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let s=n.at(0);if(!s)throw new Error("No object URL tag");if(new TextDecoder().decode(s)!==t.url)throw new Error("Object URL tag does not match object URL");let u=n.slice(1),c=await this.primitives.stringEncoder.decode(a),l=await this.primitives.contentAddresses.getMethod(c),d=await this.primitives.contentAddresses.register(l,r);if(d.length!==c.length||!d.every((_,E)=>_===c[E]))throw new Error("Content address is invalid");let p=Fe(r),v=Ay.parse(p),f=v[is],y=v[as],b=v[ss],S=Se(f),I=Se(t.value);if(S.length!==I.length||!S.every((_,E)=>_===I[E]))throw new Error("Object value does not match storage value");if(y.length!==u.length)throw new Error("Not as many channel attestations and public ids");for(let[_,E]of y.entries()){let x=u[_];if(!await this.primitives.channelAttestations.validate(E,i,x))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==u.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let _=await this.primitives.channelAttestations.getMethod(u[0]),E=await Promise.all(t.channels.map(x=>this.primitives.channelAttestations.register(_,x)));for(let[x,C]of E.entries()){let U=u[x];if(C.length!==U.length||!C.every((Z,Q)=>Z===U[Q]))throw new Error("Channel public id does not match expected")}}if(o){if(!b)throw new Error("Object is public but thought to be private");let _,E,x;if("recipient"in o?(_=[o.recipient],E=[o.allowedTicket],x=b.filter((C,U)=>U===o.allowedIndex)):(_=[...t.allowed??[]],E=o.allowedTickets,x=b),_.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!_.every(C=>t.allowed?.includes(C)))throw new Error("Recipient not in object allowed list");for(let[C,U]of _.entries()){let Z=E.at(C),Q=x.at(C);if(!Z)throw new Error("Missing allowed ticket for recipient");if(!Q)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(Q,U,Z))throw new Error("Invalid allowed attestation for recipient")}}else if(b)throw new Error("Object is private but no recipient info provided")}},is="v",as="c",ss="a",Wd="n",os=vt(e=>e instanceof Uint8Array),Ay=be({[is]:me({}),[as]:V(os),[ss]:X(V(os)),[Wd]:os}),cs="graffiti:";function qd(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function Kd(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function Ty(e,t){return`${cs}${qd(e)}:${qd(t)}`}function ls(e){if(!e.startsWith(cs))throw new Error("Invalid object URL");let n=e.slice(cs.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:Kd(r),contentAddress:Kd(o)}}function us(e){return e===void 0?null:Array.isArray(e)?e.map(us):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,us(n)])):e}var Xd=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;constructor(e){this.useTemplateHTML=e.useTemplateHTML,this.onManualClose=e.onManualClose,this.dialog.className="graffiti-modal",this.dialog.addEventListener("click",n=>{if("pointerType"in n&&!n.pointerType)return;let r=this.dialog.getBoundingClientRect();(r.top>n.clientY||r.left>n.clientX||n.clientY>r.top+r.height||n.clientX>r.left+r.width)&&(this.close(),this.onManualClose?.())});let t=document.createElement("div");this.shadow=t.attachShadow({mode:"closed"}),this.shadow.appendChild(this.dialog),document.body.append(t)}get templates(){return this.templates_||(this.main_,this.templates_=new Promise(async e=>e(await this.useTemplateHTML())).then(e=>{let t=new DOMParser().parseFromString(e,"text/html"),n=new Map;return t.querySelectorAll("template").forEach(r=>{let o=r.id;o&&n.set(o,r)}),n})),this.templates_}get main(){return this.main_||(this.templates_,this.main_=Promise.all([import("./style-YUTCEBZV-RWYJV575.js"),import("./graffiti-KV3G3O72-URO7SJIJ.js"),import("./rock-salt-LI7DAH66-KPFEBIBO.js")]).then(async([{default:e},{default:t},{default:n}])=>{let r=document.createElement("header"),o=document.createElement("button");o.className="secondary",o.textContent="Close",o?.addEventListener("click",()=>{this.close(),this.onManualClose?.()}),r.appendChild(o);let i=document.createElement("main");this.dialog.appendChild(r),this.dialog.appendChild(i);let a=new FontFace("Rock Salt",`url(${n})`,{style:"normal",weight:"400"});document.fonts.add(a),await a.load(),e=e.replace("url(graffiti.jpg)",`url(${t})`);let s=new CSSStyleSheet;return s.replace(e).then(()=>{this.shadow.adoptedStyleSheets=[s]}),i})),this.main_}async open(){await this.main,this.dialog.showModal(),this.dialog.focus()}close(){this.dialog.close()}async displayTemplate(e){let t=await this.main;t.innerHTML="";let n=(await this.templates).get(e);if(!n)throw new Error(`Template not found: ${e}`);let r=n.content.cloneNode(!0);return t.appendChild(r),t}};var ef=vt(e=>e instanceof Uint8Array),ps="k",mn="t",gs=be({[ps]:H(),[mn]:X(H())}),Tt="id",ms="e",lr="a",Py=V(be({[Tt]:H(),[ms]:X(J()),[lr]:X(J())})),Yo="s",Qo="n",zy=et(gs,{[Yo]:X(V(ef)),[Qo]:Py}),dr="a",hs="i",Oy=et(gs,{[dr]:ef,[hs]:Ut().check(yt())}),Uy=st([gs,zy,Oy]),Dy=0,ds=1,Yd=2,fs=3,ei=class{dids=new fo;authorization=new Ao;storageBuckets=new Po;inboxes=new Oo;stringEncoder=new Uo;contentAddresses=new Ro;channelAttestations=new Mo;allowedAttestations=new Zo;sessions=new Vo({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new Bo({dids:this.dids});objectEncoding=new Xo({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new Xd({useTemplateHTML:()=>import("./login-dialog.html-XUWYDNNI.js").then(({template:t})=>t),onManualClose:()=>{let t=new CustomEvent("login",{detail:{error:new Error("User cancelled login"),manual:!0}});this.sessionEvents.dispatchEvent(t)}});defaultInboxEndpoints;identityCreatorEndpoint;constructor(t){this.defaultInboxEndpoints=t?.defaultInboxEndpoints??["https://graffiti.actor/i/shared"],this.identityCreatorEndpoint=t?.identityCreatorEndpoint??"https://graffiti.actor/create",this.sessionEvents.addEventListener("login",async n=>{if(!(n instanceof CustomEvent))return;let r=n.detail;if(r.error!==void 0&&!("manual"in r&&r.manual)){alert("Login failed: "+r.error.message);let o=r.session?.actor,i;if(o)try{i=await this.actorToHandle(o)}catch(a){console.error("Failed to handle actor:",a)}this.login_(i)}})}actorToHandle=this.handles.actorToHandle.bind(this.handles);handleToActor=this.handles.handleToActor.bind(this.handles);sessionEvents=this.sessions.sessionEvents;login=async t=>{try{let n;try{n=t?await this.actorToHandle(t):void 0}catch(r){console.error("Error fetching handle for actor:",r)}await this.login_(n)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n))}});this.sessionEvents.dispatchEvent(r)}};async login_(t){if(typeof window<"u"){let n;if(t!==void 0){n=await this.modal?.displayTemplate("graffiti-login-handle");let o=n?.querySelector("#username");o?.setAttribute("value",t),o?.addEventListener("focus",()=>o?.select()),new Promise(i=>{setTimeout(()=>i(),0)}).then(()=>{o?.focus()}),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async i=>{i.preventDefault(),o?.setAttribute("disabled","true");let a=n?.querySelector("#graffiti-login-handle-submit");if(a?.setAttribute("disabled","true"),a&&(a.innerHTML="Logging in..."),!o?.value){alert("No handle provided"),this.login_("");return}let s=o.value;if(!s.includes(".")&&!s.startsWith("localhost")){let c=new URL(this.identityCreatorEndpoint).host;s=`${s}.${c}`}let u;try{u=await this.handleToActor(s)}catch{alert("Could not find an identity associated with that handle."),this.login_(s);return}try{await this.sessions.login(u)}catch(c){alert("Error logging in."),console.error(c),this.login_(s)}})}else n=await this.modal?.displayTemplate("graffiti-login-welcome"),n?.querySelector("#graffiti-login-existing")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),new Promise(o=>{setTimeout(()=>o(),0)}).then(()=>{n?.querySelector("#graffiti-login-new")?.focus()});let r=new URL(this.identityCreatorEndpoint);r.searchParams.set("redirect_uri",encodeURIComponent(window.location.toString())),n?.querySelector("#graffiti-login-new")?.setAttribute("href",r.toString()),await this.modal?.open()}else{let n=await import("readline").catch(a=>{throw new Error("Unrecognized environment: neither window nor readline")});console.log("If you do not already have a Graffiti handle, you can create one here:"),console.log(this.identityCreatorEndpoint);let r=n.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(a=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,s=>{r.close(),a(s||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:a,objectBytes:s,allowedTickets:u}=await this.objectEncoding.encode(n,r.actor),c=bt(),l=await this.stringEncoder.encode(dn,c);return await this.storageBuckets.put(o.storageBucket.serviceEndpoint,l,s,o.storageBucket.token),await this.announceObject(i,a,u,l,r),i};get=async(...t)=>{let[n,r,o]=t,i,a=await hr(r);if(o){let c=this.sessions.resolveSession(o);i=[c.personalInbox,...c.sharedInboxes]}else i=this.defaultInboxEndpoints.map(c=>({serviceEndpoint:c}));let s=ri(n),u=[new TextEncoder().encode(s)];for(let c of i){let l,d=this.querySingleEndpoint(c.serviceEndpoint,{tags:u,objectSchema:{}},c.token,o?.actor);for await(let p of d)p.object.url===s&&(p.tombstone?l=void 0:l=p.object);if(l){if(!a(l))throw new pr("Object exists but does not match the supplied schema");return l}}throw new ae("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ri(t),{actor:i}=ls(o);if(i!==n.actor)throw new it("Cannot delete someone else's actor");let a=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),s;for await(let f of a)f.object.url===o&&(f.tombstone?s=void 0:s=f);if(!s)throw new ae(`Object ${o} not found`);let{object:u,storageBucketKey:c,tags:l,allowedTickets:d,announcements:p,messageId:v}=s;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,c,r.storageBucket.token),await this.announceObject(u,l,d,c,n,[...p??[],{[lr]:n.actor,[Tt]:v}]),u};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),a=bt(),s=await this.stringEncoder.encode(dn,a);await this.storageBuckets.put(i.storageBucket.serviceEndpoint,s,new Uint8Array(await n.data.arrayBuffer()),i.storageBucket.token);let{url:u}=await this.post({value:{key:s,type:o,size:n.data.size},channels:[],allowed:n.allowed},r);return u};getMedia=async(...t)=>{let[n,r,o]=t,i=await this.get(n,Ry,o),{key:a,type:s,size:u}=i.value;if(r?.maxBytes&&u>r.maxBytes)throw new Ot("File size exceeds limit");if(r?.types&&!vs(s,r.types))throw new mr(`Unacceptable media type, ${s}`);let l=(await this.dids.resolve(i.actor))?.service?.find(f=>f.id===Ko&&f.type===qo);if(!l)throw new ae(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new ae(`Actor ${i.actor} does not have a valid storage bucket endpoint`);let d=l.serviceEndpoint,p=await this.storageBuckets.get(d,a,u);return{data:new Blob([p.slice()],{type:s}),actor:i.actor,allowed:i.allowed}};deleteMedia=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),i=await this.delete(n,r);if(!("key"in i.value&&typeof i.value.key=="string"))throw new Error("Deleted object was not media: "+JSON.stringify(i,null,2));await this.storageBuckets.delete(o.storageBucket.serviceEndpoint,i.value.key,o.storageBucket.token)};async*discoverMeta(t,n,r,o){let i=new Map,a;if(o){let d=this.sessions.resolveSession(o);a=[d.personalInbox,...d.sharedInboxes]}else a=this.defaultInboxEndpoints.map(d=>({serviceEndpoint:d}));for(let d in r)if(!a.some(p=>p.serviceEndpoint===d))throw new it("Cursor does not match actor's inboxes");let s=await Promise.all(t.map(d=>this.channelAttestations.register(At,d))),u=a.map(d=>{let p=r[d.serviceEndpoint];return this.querySingleEndpoint(d.serviceEndpoint,p?{cursor:p}:{tags:s,objectSchema:n},d.token,o?.actor)}),c=u.map(async(d,p)=>Qd(d,p)),l=c.length;for(;l>0;){let d=await Promise.race(c);if(d.error!==void 0)c[d.index]=new Promise(()=>{}),l--,yield{error:d.error,origin:a[d.index].serviceEndpoint};else if(d.result.done){let p=a[d.index];r[p.serviceEndpoint]=d.result.value,c[d.index]=new Promise(()=>{}),l--}else{c[d.index]=Qd(u[d.index],d.index);let{object:p,tombstone:v,tags:f}=d.result.value;if(v){if(i.get(p.url)===!0)continue;i.set(p.url,!0),yield{tombstone:v,object:{url:p.url}}}else{if(i.get(p.url)===!1)continue;let b=s.reduce((S,I,_)=>{for(let E of f)if(I.length===E.length&&I.every((x,C)=>E[C]===x)){S.push(_);break}return S},[]).map(S=>t[S]);b.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:a[d.index].serviceEndpoint}),i.set(p.url,!1),yield{object:{...p,channels:b}}}}}return{cursor:JSON.stringify({channels:t,cursors:r}),continue:d=>this.discoverMeta(t,n,r,d)}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let a=JSON.parse(n),s=jy.parse(a);o=s.channels,i=s.cursors}catch{return(async function*(){throw new Ue("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async announceObject(t,n,r,o,i,a){let s=this.sessions.resolveSession(i),u={[ps]:o},c=[],l=t.allowed;if(Array.isArray(l)){if(!r||r.length!==l.length)throw new Error("If allowed actors are specified, there must be a corresponding ticket for each allowed actor");let v=await Promise.allSettled(l.map(async(f,y)=>{let b=JSON.parse(JSON.stringify(t)),S=oi(b,[],f),_=(await this.dids.resolve(f)).service?.find(U=>U.type===Go&&U.id===rs);if(!_)throw new Error(`Recipient ${f} does not have a personal inbox`);if(typeof _.serviceEndpoint!="string")throw new Error(`Recipient ${f} does not have a valid personal inbox endpoint`);let E=a?a.find(U=>U[lr]===f)?.[Tt]:void 0,x={...u,...E?{[mn]:E}:{},[dr]:r[y],[hs]:y},C=await this.inboxes.send(_.serviceEndpoint,{[ir]:n,[ft]:S,[ar]:Se(x)});c.push({[Tt]:C,[lr]:f})}));for(let[f,y]of v.entries())if(y.status==="rejected"){let b=l[f];console.error("Error sending to recipient:",b),console.error(y.reason)}}else{let v=JSON.parse(JSON.stringify(t)),f=oi(v,[]),y=s.sharedInboxes,b=await Promise.allSettled(y.map(async S=>{let I=a?a.find(x=>x[ms]===S.serviceEndpoint)?.[Tt]:void 0,_={...u,...I?{[mn]:I}:{}},E=await this.inboxes.send(S.serviceEndpoint,{...I?{[mn]:I}:{},[ir]:n,[ft]:f,[ar]:Se(_)});c.push({[Tt]:E,[ms]:S.serviceEndpoint})}));for(let[S,I]of b.entries())if(I.status==="rejected"){let _=y[S];console.error("Error sending to inbox:",_),console.error(I.reason)}}let d=a?a.find(v=>v[lr]===i.actor)?.[Tt]:void 0,p={...u,...r?{[Yo]:r}:{},...d?{[mn]:d}:{},[Qo]:c};await this.inboxes.send(s.personalInbox.serviceEndpoint,{[ir]:n,[ft]:t,[ar]:Se(p)})}async*querySingleEndpoint(t,n,r,o){let i="tags"in n?this.inboxes.query(t,n.tags,n.objectSchema,r):this.inboxes.continueQuery(t,n.cursor,r);for(;;){let a=await i.next();if(a.done)return a.value;let s=a.value,u=s.l;if(u!==ds&&u!==Dy)continue;let c=s.id,{o:l,m:d,t:p}=s.m,v;try{let _=Fe(d);v=Uy.parse(_)}catch{this.inboxes.label(t,c,fs,r);continue}let{[ps]:f,[mn]:y}=v,b=Yo in v?v[Yo]:void 0,S=Qo in v?v[Qo]:void 0;if(u===ds){yield{messageId:c,object:l,storageBucketKey:f,allowedTickets:b,tags:p,announcements:S};continue}let I;try{let _=l.actor,x=(await this.dids.resolve(_))?.service?.find(Q=>Q.id===Ko&&Q.type===qo);if(!x)throw new ae(`Actor ${_} has no storage bucket service`);if(typeof x.serviceEndpoint!="string")throw new ae(`Actor ${_} does not have a valid storage bucket endpoint`);let C=x.serviceEndpoint,U=await this.storageBuckets.get(C,f,Wo);if(dr in v&&!o)throw new it("Recipient is required when allowed ticket is present");let Z=b?{allowedTickets:b}:dr in v?{recipient:o??"null",allowedTicket:v[dr],allowedIndex:v[hs]}:void 0;await this.objectEncoding.validate(l,p,U,Z)}catch(_){I=_}y?I instanceof ae?(this.inboxes.get(t,y,r).then(_=>{_&&_[ln][ft].url===l.url&&this.inboxes.label(t,y,Yd,r),this.inboxes.label(t,c,Yd,r)}),yield{messageId:c,tombstone:!0,object:l,storageBucketKey:f,allowedTickets:b,tags:p,announcements:S}):(console.error("Recieved an incorrect object"),console.error(I),this.inboxes.label(t,c,fs,r)):I===void 0?(this.inboxes.label(t,c,ds,r),yield{messageId:c,object:l,storageBucketKey:f,tags:p,allowedTickets:b,announcements:S}):(console.error("Recieved an incorrect object"),console.error(I),this.inboxes.label(t,c,fs,r))}}},Ry={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},jy=be({cursors:bc(J(),H()),channels:V(H())});async function Qd(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Ue||n instanceof zt)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var tf=class extends kr{constructor(t){let n=new ei(t);super(n)}};export{tf as GraffitiDecentralized};
1
+ import{a as ef,b as tf,c as nf}from"./chunk-RFBBAUMM.js";var Ul=ef((ft,Ol)=>{var lo=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,fo=(function(){function e(){this.fetch=!1,this.DOMException=lo.DOMException}return e.prototype=lo,new e})();(function(e){var t=(function(n){var r=typeof e<"u"&&e||typeof self<"u"&&self||typeof global<"u"&&global||{},o={searchParams:"URLSearchParams"in r,iterable:"Symbol"in r&&"iterator"in Symbol,blob:"FileReader"in r&&"Blob"in r&&(function(){try{return new Blob,!0}catch{return!1}})(),formData:"FormData"in r,arrayBuffer:"ArrayBuffer"in r};function i(h){return h&&DataView.prototype.isPrototypeOf(h)}if(o.arrayBuffer)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],s=ArrayBuffer.isView||function(h){return h&&a.indexOf(Object.prototype.toString.call(h))>-1};function u(h){if(typeof h!="string"&&(h=String(h)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(h)||h==="")throw new TypeError('Invalid character in header field name: "'+h+'"');return h.toLowerCase()}function c(h){return typeof h!="string"&&(h=String(h)),h}function l(h){var _={next:function(){var z=h.shift();return{done:z===void 0,value:z}}};return o.iterable&&(_[Symbol.iterator]=function(){return _}),_}function d(h){this.map={},h instanceof d?h.forEach(function(_,z){this.append(z,_)},this):Array.isArray(h)?h.forEach(function(_){if(_.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+_.length);this.append(_[0],_[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(_){this.append(_,h[_])},this)}d.prototype.append=function(h,_){h=u(h),_=c(_);var z=this.map[h];this.map[h]=z?z+", "+_:_},d.prototype.delete=function(h){delete this.map[u(h)]},d.prototype.get=function(h){return h=u(h),this.has(h)?this.map[h]:null},d.prototype.has=function(h){return this.map.hasOwnProperty(u(h))},d.prototype.set=function(h,_){this.map[u(h)]=c(_)},d.prototype.forEach=function(h,_){for(var z in this.map)this.map.hasOwnProperty(z)&&h.call(_,this.map[z],z,this)},d.prototype.keys=function(){var h=[];return this.forEach(function(_,z){h.push(z)}),l(h)},d.prototype.values=function(){var h=[];return this.forEach(function(_){h.push(_)}),l(h)},d.prototype.entries=function(){var h=[];return this.forEach(function(_,z){h.push([z,_])}),l(h)},o.iterable&&(d.prototype[Symbol.iterator]=d.prototype.entries);function p(h){if(!h._noBody){if(h.bodyUsed)return Promise.reject(new TypeError("Already read"));h.bodyUsed=!0}}function b(h){return new Promise(function(_,z){h.onload=function(){_(h.result)},h.onerror=function(){z(h.error)}})}function f(h){var _=new FileReader,z=b(_);return _.readAsArrayBuffer(h),z}function g(h){var _=new FileReader,z=b(_),Z=/charset=([A-Za-z0-9_-]+)/.exec(h.type),q=Z?Z[1]:"utf-8";return _.readAsText(h,q),z}function v(h){for(var _=new Uint8Array(h),z=new Array(_.length),Z=0;Z<_.length;Z++)z[Z]=String.fromCharCode(_[Z]);return z.join("")}function k(h){if(h.slice)return h.slice(0);var _=new Uint8Array(h.byteLength);return _.set(new Uint8Array(h)),_.buffer}function A(){return this.bodyUsed=!1,this._initBody=function(h){this.bodyUsed=this.bodyUsed,this._bodyInit=h,h?typeof h=="string"?this._bodyText=h:o.blob&&Blob.prototype.isPrototypeOf(h)?this._bodyBlob=h:o.formData&&FormData.prototype.isPrototypeOf(h)?this._bodyFormData=h:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)?this._bodyText=h.toString():o.arrayBuffer&&o.blob&&i(h)?(this._bodyArrayBuffer=k(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||s(h))?this._bodyArrayBuffer=k(h):this._bodyText=h=Object.prototype.toString.call(h):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof h=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var h=p(this);return h||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(o.blob)return this.blob().then(f);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return g(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(v(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(O)}),this.json=function(){return this.text().then(JSON.parse)},this}var w=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function S(h){var _=h.toUpperCase();return w.indexOf(_)>-1?_:h}function x(h,_){if(!(this instanceof x))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');_=_||{};var z=_.body;if(h instanceof x){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,_.headers||(this.headers=new d(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!z&&h._bodyInit!=null&&(z=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);if(this.credentials=_.credentials||this.credentials||"same-origin",(_.headers||!this.headers)&&(this.headers=new d(_.headers)),this.method=S(_.method||this.method||"GET"),this.mode=_.mode||this.mode||null,this.signal=_.signal||this.signal||(function(){if("AbortController"in r){var C=new AbortController;return C.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&z)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(z),(this.method==="GET"||this.method==="HEAD")&&(_.cache==="no-store"||_.cache==="no-cache")){var Z=/([?&])_=[^&]*/;if(Z.test(this.url))this.url=this.url.replace(Z,"$1_="+new Date().getTime());else{var q=/\?/;this.url+=(q.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function O(h){var _=new FormData;return h.trim().split("&").forEach(function(z){if(z){var Z=z.split("="),q=Z.shift().replace(/\+/g," "),C=Z.join("=").replace(/\+/g," ");_.append(decodeURIComponent(q),decodeURIComponent(C))}}),_}function M(h){var _=new d,z=h.replace(/\r?\n[\t ]+/g," ");return z.split("\r").map(function(Z){return Z.indexOf(`
2
+ `)===0?Z.substr(1,Z.length):Z}).forEach(function(Z){var q=Z.split(":"),C=q.shift().trim();if(C){var gt=q.join(":").trim();try{_.append(C,gt)}catch(Te){console.warn("Response "+Te.message)}}}),_}A.call(x.prototype);function B(h,_){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(_||(_={}),this.type="default",this.status=_.status===void 0?200:_.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=_.statusText===void 0?"":""+_.statusText,this.headers=new d(_.headers),this.url=_.url||"",this._initBody(h)}A.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},B.error=function(){var h=new B(null,{status:200,statusText:""});return h.ok=!1,h.status=0,h.type="error",h};var ie=[301,302,303,307,308];B.redirect=function(h,_){if(ie.indexOf(_)===-1)throw new RangeError("Invalid status code");return new B(null,{status:_,headers:{location:h}})},n.DOMException=r.DOMException;try{new n.DOMException}catch{n.DOMException=function(_,z){this.message=_,this.name=z;var Z=Error(_);this.stack=Z.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function Ae(h,_){return new Promise(function(z,Z){var q=new x(h,_);if(q.signal&&q.signal.aborted)return Z(new n.DOMException("Aborted","AbortError"));var C=new XMLHttpRequest;function gt(){C.abort()}C.onload=function(){var ne={statusText:C.statusText,headers:M(C.getAllResponseHeaders()||"")};q.url.indexOf("file://")===0&&(C.status<200||C.status>599)?ne.status=200:ne.status=C.status,ne.url="responseURL"in C?C.responseURL:ne.headers.get("X-Request-URL");var ce="response"in C?C.response:C.responseText;setTimeout(function(){z(new B(ce,ne))},0)},C.onerror=function(){setTimeout(function(){Z(new TypeError("Network request failed"))},0)},C.ontimeout=function(){setTimeout(function(){Z(new TypeError("Network request timed out"))},0)},C.onabort=function(){setTimeout(function(){Z(new n.DOMException("Aborted","AbortError"))},0)};function Te(ne){try{return ne===""&&r.location.href?r.location.href:ne}catch{return ne}}if(C.open(q.method,Te(q.url),!0),q.credentials==="include"?C.withCredentials=!0:q.credentials==="omit"&&(C.withCredentials=!1),"responseType"in C&&(o.blob?C.responseType="blob":o.arrayBuffer&&(C.responseType="arraybuffer")),_&&typeof _.headers=="object"&&!(_.headers instanceof d||r.Headers&&_.headers instanceof r.Headers)){var hn=[];Object.getOwnPropertyNames(_.headers).forEach(function(ne){hn.push(u(ne)),C.setRequestHeader(ne,c(_.headers[ne]))}),q.headers.forEach(function(ne,ce){hn.indexOf(ce)===-1&&C.setRequestHeader(ce,ne)})}else q.headers.forEach(function(ne,ce){C.setRequestHeader(ce,ne)});q.signal&&(q.signal.addEventListener("abort",gt),C.onreadystatechange=function(){C.readyState===4&&q.signal.removeEventListener("abort",gt)}),C.send(typeof q._bodyInit>"u"?null:q._bodyInit)})}return Ae.polyfill=!0,r.fetch||(r.fetch=Ae,r.Headers=d,r.Request=x,r.Response=B),n.Headers=d,n.Request=x,n.Response=B,n.fetch=Ae,n})({})})(fo);fo.fetch.ponyfill=!0;delete fo.fetch.polyfill;var nn=lo.fetch?lo:fo;ft=nn.fetch;ft.default=nn.fetch;ft.fetch=nn.fetch;ft.Headers=nn.Headers;ft.Request=nn.Request;ft.Response=nn.Response;Ol.exports=ft});var rf={type:"object",properties:{value:{type:"object"},channels:{type:"array",items:{type:"string"}},allowed:{type:"array",items:{type:"string"},nullable:!0},url:{type:"string"},actor:{type:"string"}},additionalProperties:!1,required:["value","channels","actor","url"]},Cy={...rf,required:["value","channels"]};var st=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorForbidden",Object.setPrototypeOf(this,e.prototype)}},Q=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotFound",Object.setPrototypeOf(this,e.prototype)}},Dt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorInvalidSchema",Object.setPrototypeOf(this,e.prototype)}},pr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorSchemaMismatch",Object.setPrototypeOf(this,e.prototype)}},Rt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorTooLarge",Object.setPrototypeOf(this,e.prototype)}},mr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotAcceptable",Object.setPrototypeOf(this,e.prototype)}},De=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorCursorExpired",Object.setPrototypeOf(this,e.prototype)}};function ii(e){return typeof e=="string"?e:e.url}function ai(e,t,n){if(n===e.actor)return e;let r=e.allowed&&n?[n]:void 0,o=e.channels.filter(i=>t.includes(i));return{...e,...r?{allowed:r}:{},channels:o}}function _s(e,t){let[n,r]=e.toLowerCase().split(";")[0].split("/");return!n||!r?!1:t.some(o=>{let[i,a]=o.toLowerCase().split(";")[0].split("/");return!i||!a?!1:(i===n||i==="*")&&(a===r||a==="*")})}var oi;async function hr(e){if(!oi){let{default:t}=await import("./ajv-QBSREQSI.js");oi=new t({strict:!1})}try{return oi.compile(e)}catch(t){throw new Dt(t instanceof Error?t.message:String(t))}}var of=Object.freeze({status:"aborted"});function P(e,t,n){function r(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);let c=a.prototype,l=Object.keys(c);for(let d=0;d<l.length;d++){let p=l[d];p in s||(s[p]=c[p].bind(s))}}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function a(s){var u;let c=n?.Parent?new i:this;r(c,s),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var Ye=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};var si={};function Qe(e){return e&&Object.assign(si,e),si}function ui(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function xs(e,t){return typeof t=="bigint"?t.toString():t}function li(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function vr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var ws=Symbol("evaluating");function de(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ws)return r===void 0&&(r=ws,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function af(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function sf(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}var di="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var cf=li(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function gn(e){if(yr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(yr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}var $s=new Set(["string","number","symbol"]);function br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function re(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ss(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Es={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ks(e,t){if(!gn(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=sf(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return af(this,"shape",i),i}});return yn(e,o)}function yt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function et(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function gr(e){return typeof e=="string"?e:e?.message}function ct(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let o=gr(e.inst?._zod.def?.error?.(e))??gr(t?.error?.(e))??gr(n.customError?.(e))??gr(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function fi(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}var Is=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,xs,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},As=P("$ZodError",Is),vn=P("$ZodError",Is,{Parent:Error});var lf=e=>(t,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ye;if(a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>ct(u,i,Qe())));throw di(s,o?.callee),s}return a.value},_r=lf(vn),df=e=>async(t,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>ct(u,i,Qe())));throw di(s,o?.callee),s}return a.value},wr=df(vn),ff=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ye;return i.issues.length?{success:!1,error:new(e??As)(i.issues.map(a=>ct(a,o,Qe())))}:{success:!0,data:i.value}},bn=ff(vn),pf=e=>async(t,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>ct(a,o,Qe())))}:{success:!0,data:i.value}},_n=pf(vn);var mf="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",hf=new RegExp(`^${mf}$`);var Ts=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ps=/^-?\d+$/,pi=/^-?\d+(?:\.\d+)?$/,zs=/^(?:true|false)$/i;var Os=/^undefined$/i;var vt=P("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gf={number:"number",bigint:"bigint",object:"date"};var Us=P("$ZodCheckGreaterThan",(e,t)=>{vt.init(e,t);let n=gf[typeof t.value];e._zod.onattach.push(r=>{let o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var Ds=P("$ZodCheckNumberFormat",(e,t)=>{vt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Es[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=o,s.maximum=i,n&&(s.pattern=Ps)}),e._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Rs=P("$ZodCheckStringFormat",(e,t)=>{var n,r;vt.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})});var Ns={major:4,minor:3,patch:6};var ee=P("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ns;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let o of r)for(let i of o._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,s,u)=>{let c=yt(a),l;for(let d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(c)continue;let p=a.issues.length,b=d._zod.check(a);if(b instanceof Promise&&u?.async===!1)throw new Ye;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,a.issues.length!==p&&(c||(c=yt(a,p)))});else{if(a.issues.length===p)continue;c||(c=yt(a,p))}}return l?l.then(()=>a):a},i=(a,s,u)=>{if(yt(a))return a.aborted=!0,a;let c=o(s,r,u);if(c instanceof Promise){if(u.async===!1)throw new Ye;return c.then(l=>e._zod.parse(l,u))}return e._zod.parse(c,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let c=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return c instanceof Promise?c.then(l=>i(l,a,s)):i(c,a,s)}let u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new Ye;return u.then(c=>o(c,r,s))}return o(u,r,s)}}de(e,"~standard",()=>({validate:o=>{try{let i=bn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return _n(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),Sr=P("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ts(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),hi=P("$ZodStringFormat",(e,t)=>{Rs.init(e,t),Sr.init(e,t)});var Fs=P("$ZodURL",(e,t)=>{hi.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),o=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=o.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}});var gi=P("$ZodNumber",(e,t)=>{ee.init(e,t),e._zod.pattern=e._zod.bag.pattern??pi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Hs=P("$ZodNumberFormat",(e,t)=>{Ds.init(e,t),gi.init(e,t)}),yi=P("$ZodBoolean",(e,t)=>{ee.init(e,t),e._zod.pattern=zs,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var Js=P("$ZodUndefined",(e,t)=>{ee.init(e,t),e._zod.pattern=Os,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}});var Gs=P("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=n=>n}),Vs=P("$ZodNever",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Cs(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}var qs=P("$ZodArray",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let s=o[a],u=t.element._zod.run({value:s,issues:[]},r);u instanceof Promise?i.push(u.then(c=>Cs(c,n,a))):Cs(u,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function $r(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...et(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function yf(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=Ss(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function vf(e,t,n,r,o,i){let a=[],s=o.keySet,u=o.catchall._zod,c=u.def.type,l=u.optout==="optional";for(let d in t){if(s.has(d))continue;if(c==="never"){a.push(d);continue}let p=u.run({value:t[d],issues:[]},r);p instanceof Promise?e.push(p.then(b=>$r(b,n,d,t,l))):$r(p,n,d,t,l)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var Ks=P("$ZodObject",(e,t)=>{if(ee.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}let r=li(()=>yf(t));de(e._zod,"propValues",()=>{let s=t.shape,u={};for(let c in s){let l=s[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(let d of l.values)u[c].add(d)}}return u});let o=yr,i=t.catchall,a;e._zod.parse=(s,u)=>{a??(a=r.value);let c=s.value;if(!o(c))return s.issues.push({expected:"object",code:"invalid_type",input:c,inst:e}),s;s.value={};let l=[],d=a.shape;for(let p of a.keys){let b=d[p],f=b._zod.optout==="optional",g=b._zod.run({value:c[p],issues:[]},u);g instanceof Promise?l.push(g.then(v=>$r(v,s,p,c,f))):$r(g,s,p,c,f)}return i?vf(l,c,s,u,r.value,e):l.length?Promise.all(l).then(()=>s):s}});function Ls(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!yt(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>ct(a,r,Qe())))}),t)}var Ws=P("$ZodUnion",(e,t)=>{ee.init(e,t),de(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),de(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),de(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),de(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>vr(i.source)).join("|")})$`)}});let n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(o,i)=>{if(n)return r(o,i);let a=!1,s=[];for(let u of t.options){let c=u._zod.run({value:o.value,issues:[]},i);if(c instanceof Promise)s.push(c),a=!0;else{if(c.issues.length===0)return c;s.push(c)}}return a?Promise.all(s).then(u=>Ls(u,o,e,i)):Ls(s,o,e,i)}});var Xs=P("$ZodIntersection",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,c])=>Ms(n,u,c)):Ms(n,i,a)}});function mi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(gn(e)&&gn(t)){let n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),o={...e,...t};for(let i of r){let a=mi(e[i],t[i]);if(!a.valid)return{valid:!1,mergeErrorPath:[i,...a.mergeErrorPath]};o[i]=a.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],a=mi(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ms(e,t,n){let r=new Map,o;for(let s of t.issues)if(s.code==="unrecognized_keys"){o??(o=s);for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else e.issues.push(s);for(let s of n.issues)if(s.code==="unrecognized_keys")for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else e.issues.push(s);let i=[...r].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&o&&e.issues.push({...o,keys:i}),yt(e))return e;let a=mi(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ys=P("$ZodTuple",(e,t)=>{ee.init(e,t);let n=t.items;e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];let a=[],s=[...n].reverse().findIndex(l=>l._zod.optin!=="optional"),u=s===-1?0:n.length-s;if(!t.rest){let l=i.length>n.length,d=i.length<u-1;if(l||d)return r.issues.push({...l?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:i,inst:e,origin:"array"}),r}let c=-1;for(let l of n){if(c++,c>=i.length&&c>=u)continue;let d=l._zod.run({value:i[c],issues:[]},o);d instanceof Promise?a.push(d.then(p=>xr(p,r,c))):xr(d,r,c)}if(t.rest){let l=i.slice(n.length);for(let d of l){c++;let p=t.rest._zod.run({value:d,issues:[]},o);p instanceof Promise?a.push(p.then(b=>xr(b,r,c))):xr(p,r,c)}}return a.length?Promise.all(a).then(()=>r):r}});function xr(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}var Qs=P("$ZodRecord",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!gn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a){n.value={};let s=new Set;for(let c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){s.add(typeof c=="number"?c.toString():c);let l=t.valueType._zod.run({value:o[c],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...et(c,d.issues)),n.value[c]=d.value})):(l.issues.length&&n.issues.push(...et(c,l.issues)),n.value[c]=l.value)}let u;for(let c in o)s.has(c)||(u=u??[],u.push(c));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let u=t.keyType._zod.run({value:s,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&pi.test(s)&&u.issues.length){let d=t.keyType._zod.run({value:Number(s),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(u=d)}if(u.issues.length){t.mode==="loose"?n.value[s]=o[s]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(d=>ct(d,r,Qe())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:o[s],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...et(s,d.issues)),n.value[u.value]=d.value})):(l.issues.length&&n.issues.push(...et(s,l.issues)),n.value[u.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}});var ec=P("$ZodEnum",(e,t)=>{ee.init(e,t);let n=ui(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>$s.has(typeof o)).map(o=>typeof o=="string"?br(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return r.has(a)||o.issues.push({code:"invalid_value",values:n,input:a,inst:e}),o}});function Zs(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var tc=P("$ZodOptional",(e,t)=>{ee.init(e,t),e._zod.optin="optional",e._zod.optout="optional",de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${vr(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=t.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>Zs(i,n.value)):Zs(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var nc=P("$ZodNullable",(e,t)=>{ee.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${vr(n.source)}|null)$`):void 0}),de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)});var rc=P("$ZodCustom",(e,t)=>{vt.init(e,t),ee.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Bs(i,n,r,e));Bs(o,n,r,e)}});function Bs(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(fi(o))}}var ic;var vi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function ac(){return new vi}(ic=globalThis).__zod_globalRegistry??(ic.__zod_globalRegistry=ac());var bi=globalThis.__zod_globalRegistry;function sc(e,t){return new e({type:"string",...re(t)})}function cc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function uc(e,t){return new e({type:"number",checks:[],...re(t)})}function lc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function dc(e,t){return new e({type:"boolean",...re(t)})}function fc(e,t){return new e({type:"undefined",...re(t)})}function pc(e){return new e({type:"unknown"})}function mc(e,t){return new e({type:"never",...re(t)})}function _i(e,t){return new Us({check:"greater_than",...re(t),value:e,inclusive:!0})}function bt(e){return _i(0,e)}function hc(e,t,n){let r=re(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}var ue=P("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>_r(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>bn(e,n,r),e.parseAsync=async(n,r)=>wr(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>_n(e,n,r),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]},{parent:!0}),e.with=e.check,e.clone=(n,r)=>yn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),wi=P("ZodMiniString",(e,t)=>{Sr.init(e,t),ue.init(e,t)});function H(e){return sc(wi,e)}var gc=P("ZodMiniStringFormat",(e,t)=>{hi.init(e,t),wi.init(e,t)});var zf=P("ZodMiniURL",(e,t)=>{Fs.init(e,t),gc.init(e,t)});function J(e){return cc(zf,e)}var xi=P("ZodMiniNumber",(e,t)=>{gi.init(e,t),ue.init(e,t)});function yc(e){return uc(xi,e)}var Of=P("ZodMiniNumberFormat",(e,t)=>{Hs.init(e,t),xi.init(e,t)});function jt(e){return lc(Of,e)}var vc=P("ZodMiniBoolean",(e,t)=>{yi.init(e,t),ue.init(e,t)});function $i(e){return dc(vc,e)}var Uf=P("ZodMiniUndefined",(e,t)=>{Js.init(e,t),ue.init(e,t)});function bc(e){return fc(Uf,e)}var Df=P("ZodMiniUnknown",(e,t)=>{Gs.init(e,t),ue.init(e,t)});function Rf(){return pc(Df)}var jf=P("ZodMiniNever",(e,t)=>{Vs.init(e,t),ue.init(e,t)});function Nf(e){return mc(jf,e)}var Cf=P("ZodMiniArray",(e,t)=>{qs.init(e,t),ue.init(e,t)});function V(e,t){return new Cf({type:"array",element:e,...re(t)})}var Si=P("ZodMiniObject",(e,t)=>{Ks.init(e,t),ue.init(e,t),de(e,"shape",()=>t.shape)});function be(e,t){let n={type:"object",shape:e??{},...re(t)};return new Si(n)}function _e(e,t){return new Si({type:"object",shape:e,catchall:Nf(),...re(t)})}function he(e,t){return new Si({type:"object",shape:e,catchall:Rf(),...re(t)})}function tt(e,t){return ks(e,t)}var Lf=P("ZodMiniUnion",(e,t)=>{Ws.init(e,t),ue.init(e,t)});function ut(e,t){return new Lf({type:"union",options:e,...re(t)})}var Mf=P("ZodMiniIntersection",(e,t)=>{Xs.init(e,t),ue.init(e,t)});function _c(e,t){return new Mf({type:"intersection",left:e,right:t})}var Zf=P("ZodMiniTuple",(e,t)=>{Ys.init(e,t),ue.init(e,t)});function fe(e,t,n){let r=t instanceof ee,o=r?n:t,i=r?t:null;return new Zf({type:"tuple",items:e,rest:i,...re(o)})}var Bf=P("ZodMiniRecord",(e,t)=>{Qs.init(e,t),ue.init(e,t)});function wc(e,t,n){return new Bf({type:"record",keyType:e,valueType:t,...re(n)})}var Ff=P("ZodMiniEnum",(e,t)=>{ec.init(e,t),ue.init(e,t),e.options=Object.values(t.entries)});function xc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ff({type:"enum",entries:n,...re(t)})}var Hf=P("ZodMiniOptional",(e,t)=>{tc.init(e,t),ue.init(e,t)});function X(e){return new Hf({type:"optional",innerType:e})}var Jf=P("ZodMiniNullable",(e,t)=>{nc.init(e,t),ue.init(e,t)});function Me(e){return new Jf({type:"nullable",innerType:e})}var Gf=P("ZodMiniCustom",(e,t)=>{rc.init(e,t),ue.init(e,t)});function _t(e,t){return hc(Gf,e??(()=>!0),t)}function Nt(e,t={}){let n=_t(r=>r instanceof e,t);return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Ec=he({value:he({}),channels:V(H()),allowed:X(Me(V(J())))}),uE=tt(Ec,{url:J(),actor:J()}),Sc=ut([he({url:J()}),J()]),Ct=he({actor:J()}),kr=X(Me(Ct)),kc=he({data:Nt(Blob),allowed:X(Me(V(J())))}),lE=tt(kc,{actor:J()}),Xf=he({types:X(V(H())),maxBytes:X(jt().check(bt()))}),Ir=class{constructor(t){this.graffiti=t,this.sessionEvents=this.graffiti.sessionEvents}sessionEvents;login=(...t)=>{let n=fe([X(J())]).parse(t);return this.graffiti.login(...n)};logout=(...t)=>{let n=fe([Ct]).parse(t);return this.graffiti.logout(...n)};handleToActor=(...t)=>{let n=fe([H()]).parse(t);return this.graffiti.handleToActor(...n)};actorToHandle=(...t)=>{let n=fe([J()]).parse(t);return this.graffiti.actorToHandle(...n)};post=(...t)=>{let n=fe([Ec,Ct]).parse(t);return this.graffiti.post(...n)};get=(...t)=>{let n=fe([Sc,he({}),kr]).parse(t);return this.graffiti.get(n[0],n[1],n[2])};delete=(...t)=>{let n=fe([Sc,Ct]).parse(t);return this.graffiti.delete(...n)};postMedia=(...t)=>{let n=fe([kc,Ct]).parse(t);return this.graffiti.postMedia(...n)};getMedia=(...t)=>{let n=fe([J(),Xf,kr]).parse(t);return this.graffiti.getMedia(...n)};deleteMedia=(...t)=>{let n=fe([J(),Ct]).parse(t);return this.graffiti.deleteMedia(...n)};discover=(...t)=>{let n=fe([V(H()),he({}),kr]).parse(t);return this.graffiti.discover(n[0],n[1],n[2])};continueDiscover=(...t)=>{let n=fe([H(),kr]).parse(t);return this.graffiti.continueDiscover(...n)}};function Yf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ei(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >= 0, got ${e}`)}}function Ar(e,t,n=""){let r=Yf(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;throw new Error(a+"expected Uint8Array"+s+", got "+u)}return e}function Ic(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ei(e.outputLen),Ei(e.blockLen)}function wt(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var Qf=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function ki(e){if(e===null)return"null";if(e===void 0)return"undefined";if(e===!0||e===!1)return"boolean";let t=typeof e;if(t==="string"||t==="number"||t==="bigint"||t==="symbol")return t;if(t==="function")return"Function";if(Array.isArray(e))return"Array";if(e instanceof Uint8Array)return"Uint8Array";if(e.constructor===Object)return"Object";let n=ep(e);return n||"Object"}function ep(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(Qf.includes(t))return t}var y=class{constructor(t,n,r){this.major=t,this.majorEncoded=t<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,n){return t===n||t.major===n.major&&t.name===n.name}};y.uint=new y(0,"uint",!0);y.negint=new y(1,"negint",!0);y.bytes=new y(2,"bytes",!0);y.string=new y(3,"string",!0);y.array=new y(4,"array",!1);y.map=new y(5,"map",!1);y.tag=new y(6,"tag",!1);y.float=new y(7,"float",!0);y.false=new y(7,"false",!0);y.true=new y(7,"true",!0);y.null=new y(7,"null",!0);y.undefined=new y(7,"undefined",!0);y.break=new y(7,"break",!0);var E=class{constructor(t,n,r){this.type=t,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var xn=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",tp=new TextEncoder;function Tr(e){return xn&&globalThis.Buffer.isBuffer(e)}function $n(e){return e instanceof Uint8Array?Tr(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var np=24,rp=200,Pr=xn?e=>e.length>=np?globalThis.Buffer.from(e):Ac(e):e=>e.length>=rp?tp.encode(e):Ac(e),Ze=e=>Uint8Array.from(e),Tc=xn?(e,t,n)=>Tr(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),Pc=xn?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),$n(globalThis.Buffer.concat(e,t))):(e,t)=>{let n=new Uint8Array(t),r=0;for(let o of e)r+o.length>n.length&&(o=o.subarray(0,n.length-r)),n.set(o,r),r+=o.length;return n},zc=xn?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function zr(e,t){if(Tr(e)&&Tr(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function Ac(e){let t=[],n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(o=65536+((o&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128)}return t}var op=256,Sn=class{constructor(t=op){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let n=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=n.length-(this.maxCursor-this.cursor)-1;n.set(t,o)}else{if(n){let o=n.length-(this.maxCursor-this.cursor)-1;o<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(n=zc(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=Tc(r,0,this.cursor)}else n=Pc(this.chunks,this.cursor);return t&&this.reset(),n}},Or=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let n=this.dest.subarray(0,this.cursor);return t&&this.reset(),n}};var L="CBOR decode error:",Ur="CBOR encode error:",En=[];En[23]=1;En[24]=2;En[25]=3;En[26]=5;En[27]=9;function nt(e,t,n){if(e.length-t<n)throw new Error(`${L} not enough data for type`)}var ae=[24,256,65536,4294967296,BigInt("18446744073709551616")];function we(e,t,n){nt(e,t,1);let r=e[t];if(n.strict===!0&&r<ae[0])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function xe(e,t,n){nt(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<ae[1])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function $e(e,t,n){nt(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<ae[2])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function Se(e,t,n){nt(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],o=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],i=(BigInt(r)<<BigInt(32))+BigInt(o);if(n.strict===!0&&i<ae[3])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(n.allowBigInt===!0)return i;throw new Error(`${L} integers outside of the safe integer range are not supported`)}function Oc(e,t,n,r){return new E(y.uint,we(e,t+1,r),2)}function Uc(e,t,n,r){return new E(y.uint,xe(e,t+1,r),3)}function Dc(e,t,n,r){return new E(y.uint,$e(e,t+1,r),5)}function Rc(e,t,n,r){return new E(y.uint,Se(e,t+1,r),9)}function Pe(e,t){return W(e,0,t.value)}function W(e,t,n){if(n<ae[0]){let r=Number(n);e.push([t|r])}else if(n<ae[1]){let r=Number(n);e.push([t|24,r])}else if(n<ae[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<ae[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<ae[4]){let o=[t|27,0,0,0,0,0,0,0],i=Number(r&BigInt(4294967295)),a=Number(r>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=a&255,a=a>>8,o[3]=a&255,a=a>>8,o[2]=a&255,a=a>>8,o[1]=a&255,e.push(o)}else throw new Error(`${L} encountered BigInt larger than allowable range`)}}Pe.encodedSize=function(t){return W.encodedSize(t.value)};W.encodedSize=function(t){return t<ae[0]?1:t<ae[1]?2:t<ae[2]?3:t<ae[3]?5:9};Pe.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function jc(e,t,n,r){return new E(y.negint,-1-we(e,t+1,r),2)}function Nc(e,t,n,r){return new E(y.negint,-1-xe(e,t+1,r),3)}function Cc(e,t,n,r){return new E(y.negint,-1-$e(e,t+1,r),5)}var Ii=BigInt(-1),Lc=BigInt(1);function Mc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new E(y.negint,i,9)}if(r.allowBigInt!==!0)throw new Error(`${L} integers outside of the safe integer range are not supported`);return new E(y.negint,Ii-BigInt(o),9)}function Dr(e,t){let n=t.value,r=typeof n=="bigint"?n*Ii-Lc:n*-1-1;W(e,t.type.majorEncoded,r)}Dr.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*Ii-Lc:n*-1-1;return r<ae[0]?1:r<ae[1]?2:r<ae[2]?3:r<ae[3]?5:9};Dr.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function kn(e,t,n,r){nt(e,t,n+r);let o=e.slice(t+n,t+n+r);return new E(y.bytes,o,n+r)}function Zc(e,t,n,r){return kn(e,t,1,n)}function Bc(e,t,n,r){return kn(e,t,2,we(e,t+1,r))}function Fc(e,t,n,r){return kn(e,t,3,xe(e,t+1,r))}function Hc(e,t,n,r){return kn(e,t,5,$e(e,t+1,r))}function Jc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer bytes lengths not supported`);return kn(e,t,9,o)}function Rr(e){return e.encodedBytes===void 0&&(e.encodedBytes=y.equals(e.type,y.string)?Pr(e.value):e.value),e.encodedBytes}function Lt(e,t){let n=Rr(t);W(e,t.type.majorEncoded,n.length),e.push(n)}Lt.encodedSize=function(t){let n=Rr(t);return W.encodedSize(n.length)+n.length};Lt.compareTokens=function(t,n){return ap(Rr(t),Rr(n))};function ap(e,t){return e.length<t.length?-1:e.length>t.length?1:zr(e,t)}var Gc=new TextDecoder,cp=32;function up(e,t,n){if(n-t<cp){let o="";for(let i=t;i<n;i++){let a=e[i];if(a&128)return Gc.decode(e.subarray(t,n));o+=String.fromCharCode(a)}return o}return Gc.decode(e.subarray(t,n))}function In(e,t,n,r,o){let i=n+r;nt(e,t,i);let a=new E(y.string,up(e,t+n,t+i),i);return o.retainStringBytes===!0&&(a.byteValue=e.slice(t+n,t+i)),a}function Vc(e,t,n,r){return In(e,t,1,n,r)}function qc(e,t,n,r){return In(e,t,2,we(e,t+1,r),r)}function Kc(e,t,n,r){return In(e,t,3,xe(e,t+1,r),r)}function Wc(e,t,n,r){return In(e,t,5,$e(e,t+1,r),r)}function Xc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer string lengths not supported`);return In(e,t,9,o,r)}var Yc=Lt;function Mt(e,t,n,r){return new E(y.array,r,n)}function Qc(e,t,n,r){return Mt(e,t,1,n)}function eu(e,t,n,r){return Mt(e,t,2,we(e,t+1,r))}function tu(e,t,n,r){return Mt(e,t,3,xe(e,t+1,r))}function nu(e,t,n,r){return Mt(e,t,5,$e(e,t+1,r))}function ru(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer array lengths not supported`);return Mt(e,t,9,o)}function ou(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return Mt(e,t,1,1/0)}function jr(e,t){W(e,y.array.majorEncoded,t.value)}jr.compareTokens=Pe.compareTokens;jr.encodedSize=function(t){return W.encodedSize(t.value)};function Zt(e,t,n,r){return new E(y.map,r,n)}function iu(e,t,n,r){return Zt(e,t,1,n)}function au(e,t,n,r){return Zt(e,t,2,we(e,t+1,r))}function su(e,t,n,r){return Zt(e,t,3,xe(e,t+1,r))}function cu(e,t,n,r){return Zt(e,t,5,$e(e,t+1,r))}function uu(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer map lengths not supported`);return Zt(e,t,9,o)}function lu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return Zt(e,t,1,1/0)}function Nr(e,t){W(e,y.map.majorEncoded,t.value)}Nr.compareTokens=Pe.compareTokens;Nr.encodedSize=function(t){return W.encodedSize(t.value)};function du(e,t,n,r){return new E(y.tag,n,1)}function fu(e,t,n,r){return new E(y.tag,we(e,t+1,r),2)}function pu(e,t,n,r){return new E(y.tag,xe(e,t+1,r),3)}function mu(e,t,n,r){return new E(y.tag,$e(e,t+1,r),5)}function hu(e,t,n,r){return new E(y.tag,Se(e,t+1,r),9)}function Cr(e,t){W(e,y.tag.majorEncoded,t.value)}Cr.compareTokens=Pe.compareTokens;Cr.encodedSize=function(t){return W.encodedSize(t.value)};var Ai=20,Ti=21,Pi=22,zi=23;function gu(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${L} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new E(y.null,null,1):new E(y.undefined,void 0,1)}function yu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return new E(y.break,void 0,1)}function Oi(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${L} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${L} Infinity values are not supported`)}return new E(y.float,e,t)}function vu(e,t,n,r){return Oi(Ui(e,t+1),3,r)}function bu(e,t,n,r){return Oi(Di(e,t+1),5,r)}function _u(e,t,n,r){return Oi(Su(e,t+1),9,r)}function An(e,t,n){let r=t.value;if(r===!1)e.push([y.float.majorEncoded|Ai]);else if(r===!0)e.push([y.float.majorEncoded|Ti]);else if(r===null)e.push([y.float.majorEncoded|Pi]);else if(r===void 0)e.push([y.float.majorEncoded|zi]);else{let o,i=!1;(!n||n.float64!==!0)&&(xu(r),o=Ui(Re,1),r===o||Number.isNaN(r)?(Re[0]=249,e.push(Re.slice(0,3)),i=!0):($u(r),o=Di(Re,1),r===o&&(Re[0]=250,e.push(Re.slice(0,5)),i=!0))),i||(mp(r),o=Su(Re,1),Re[0]=251,e.push(Re.slice(0,9)))}}An.encodedSize=function(t,n){let r=t.value;if(r===!1||r===!0||r===null||r===void 0)return 1;if(!n||n.float64!==!0){xu(r);let o=Ui(Re,1);if(r===o||Number.isNaN(r))return 3;if($u(r),o=Di(Re,1),r===o)return 5}return 9};var wu=new ArrayBuffer(9),ze=new DataView(wu,1),Re=new Uint8Array(wu,0);function xu(e){if(e===1/0)ze.setUint16(0,31744,!1);else if(e===-1/0)ze.setUint16(0,64512,!1);else if(Number.isNaN(e))ze.setUint16(0,32256,!1);else{ze.setFloat32(0,e);let t=ze.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)ze.setUint16(0,31744,!1);else if(n===0)ze.setUint16(0,(e&2147483648)>>16|r>>13,!1);else{let o=n-127;o<-24?ze.setUint16(0,0):o<-14?ze.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):ze.setUint16(0,(t&2147483648)>>16|o+15<<10|r>>13,!1)}}}function Ui(e,t){if(e.length-t<2)throw new Error(`${L} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,o=n&1023,i;return r===0?i=o*2**-24:r!==31?i=(o+1024)*2**(r-25):i=o===0?1/0:NaN,n&32768?-i:i}function $u(e){ze.setFloat32(0,e,!1)}function Di(e,t){if(e.length-t<4)throw new Error(`${L} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function mp(e){ze.setFloat64(0,e,!1)}function Su(e,t){if(e.length-t<8)throw new Error(`${L} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}An.compareTokens=Pe.compareTokens;function F(e,t,n){throw new Error(`${L} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Lr(e){return()=>{throw new Error(`${L} ${e}`)}}var $=[];for(let e=0;e<=23;e++)$[e]=F;$[24]=Oc;$[25]=Uc;$[26]=Dc;$[27]=Rc;$[28]=F;$[29]=F;$[30]=F;$[31]=F;for(let e=32;e<=55;e++)$[e]=F;$[56]=jc;$[57]=Nc;$[58]=Cc;$[59]=Mc;$[60]=F;$[61]=F;$[62]=F;$[63]=F;for(let e=64;e<=87;e++)$[e]=Zc;$[88]=Bc;$[89]=Fc;$[90]=Hc;$[91]=Jc;$[92]=F;$[93]=F;$[94]=F;$[95]=Lr("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)$[e]=Vc;$[120]=qc;$[121]=Kc;$[122]=Wc;$[123]=Xc;$[124]=F;$[125]=F;$[126]=F;$[127]=Lr("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)$[e]=Qc;$[152]=eu;$[153]=tu;$[154]=nu;$[155]=ru;$[156]=F;$[157]=F;$[158]=F;$[159]=ou;for(let e=160;e<=183;e++)$[e]=iu;$[184]=au;$[185]=su;$[186]=cu;$[187]=uu;$[188]=F;$[189]=F;$[190]=F;$[191]=lu;for(let e=192;e<=215;e++)$[e]=du;$[216]=fu;$[217]=pu;$[218]=mu;$[219]=hu;$[220]=F;$[221]=F;$[222]=F;$[223]=F;for(let e=224;e<=243;e++)$[e]=Lr("simple values are not supported");$[244]=F;$[245]=F;$[246]=F;$[247]=gu;$[248]=Lr("simple values are not supported");$[249]=vu;$[250]=bu;$[251]=_u;$[252]=F;$[253]=F;$[254]=F;$[255]=yu;var je=[];for(let e=0;e<24;e++)je[e]=new E(y.uint,e,1);for(let e=-1;e>=-24;e--)je[31-e]=new E(y.negint,e,1);je[64]=new E(y.bytes,new Uint8Array(0),1);je[96]=new E(y.string,"",1);je[128]=new E(y.array,0,1);je[160]=new E(y.map,0,1);je[244]=new E(y.false,!1,1);je[245]=new E(y.true,!0,1);je[246]=new E(y.null,null,1);function Ri(e){switch(e.type){case y.false:return Ze([244]);case y.true:return Ze([245]);case y.null:return Ze([246]);case y.bytes:return e.value.length?void 0:Ze([64]);case y.string:return e.value===""?Ze([96]):void 0;case y.array:return e.value===0?Ze([128]):void 0;case y.map:return e.value===0?Ze([160]):void 0;case y.uint:return e.value<24?Ze([Number(e.value)]):void 0;case y.negint:if(e.value>=-24)return Ze([31-Number(e.value)])}}var gp={float64:!1,mapSorter:bp,quickEncodeToken:Ri},Tu=Object.freeze({float64:!0,mapSorter:_p,quickEncodeToken:Ri});function yp(){let e=[];return e[y.uint.major]=Pe,e[y.negint.major]=Dr,e[y.bytes.major]=Lt,e[y.string.major]=Yc,e[y.array.major]=jr,e[y.map.major]=Nr,e[y.tag.major]=Cr,e[y.float.major]=An,e}var Bt=yp(),Mr=new Sn,Pn=class e{constructor(t,n){this.obj=t,this.parent=n}includes(t){let n=this;do if(n.obj===t)return!0;while(n=n.parent);return!1}static createCheck(t,n){if(t&&t.includes(n))throw new Error(`${Ur} object contains circular references`);return new e(n,t)}},lt={null:new E(y.null,null),undefined:new E(y.undefined,void 0),true:new E(y.true,!0),false:new E(y.false,!1),emptyArray:new E(y.array,0),emptyMap:new E(y.map,0)},Be={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new E(y.float,e):e>=0?new E(y.uint,e):new E(y.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new E(y.uint,e):new E(y.negint,e)},Uint8Array(e,t,n,r){return new E(y.bytes,e)},string(e,t,n,r){return new E(y.string,e)},boolean(e,t,n,r){return e?lt.true:lt.false},null(e,t,n,r){return lt.null},undefined(e,t,n,r){return lt.undefined},ArrayBuffer(e,t,n,r){return new E(y.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new E(y.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[lt.emptyArray,new E(y.break)]:lt.emptyArray;r=Pn.createCheck(r,e);let o=[],i=0;for(let a of e)o[i++]=Zr(a,n,r);return n.addBreakTokens?[new E(y.array,e.length),o,new E(y.break)]:[new E(y.array,e.length),o]},Object(e,t,n,r){let o=t!=="Object",i=o?e.keys():Object.keys(e),a=o?e.size:i.length,s;if(a){s=new Array(a),r=Pn.createCheck(r,e);let u=!o&&n.ignoreUndefinedProperties,c=0;for(let l of i){let d=o?e.get(l):e[l];u&&d===void 0||(s[c++]=[Zr(l,n,r),Zr(d,n,r)])}c<a&&(s.length=c)}return s?.length?(vp(s,n),n.addBreakTokens?[new E(y.map,s.length),s,new E(y.break)]:[new E(y.map,s.length),s]):n.addBreakTokens===!0?[lt.emptyMap,new E(y.break)]:lt.emptyMap}};Be.Map=Be.Object;Be.Buffer=Be.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Be[`${e}Array`]=Be.DataView;function Zr(e,t={},n){let r=ki(e),o=t&&t.typeEncoders&&t.typeEncoders[r]||Be[r];if(typeof o=="function"){let a=o(e,r,t,n);if(a!=null)return a}let i=Be[r];if(!i)throw new Error(`${Ur} unsupported type: ${r}`);return i(e,r,t,n)}function vp(e,t){t.mapSorter&&e.sort(t.mapSorter)}function bp(e,t){let n=Array.isArray(e[0])?e[0][0]:e[0],r=Array.isArray(t[0])?t[0][0]:t[0];if(n.type!==r.type)return n.type.compare(r.type);let o=n.type.major,i=Bt[o].compareTokens(n,r);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function _p(e,t){if(e[0]instanceof E&&t[0]instanceof E){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=Eu(n.value)),r._keyBytes||(r._keyBytes=Eu(r.value)),zr(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Eu(e){return zu(e,Bt,Tu)}function Tn(e,t,n,r){if(Array.isArray(t))for(let o of t)Tn(e,o,n,r);else n[t.type.major](e,t,r)}var ku=y.uint.majorEncoded,Iu=y.negint.majorEncoded,wp=y.bytes.majorEncoded,xp=y.string.majorEncoded,Au=y.array.majorEncoded,$p=y.float.majorEncoded|Ai,Sp=y.float.majorEncoded|Ti,Ep=y.float.majorEncoded|Pi,kp=y.float.majorEncoded|zi,Ip=BigInt(-1),Ap=BigInt(1);function Tp(e){return e.addBreakTokens!==!0}function Pu(e,t,n,r){let o=ki(t),i=n.typeEncoders&&n.typeEncoders[o];if(i){let a=i(t,o,n,r);if(a!=null){Tn(e,a,Bt,n);return}}switch(o){case"null":e.push([Ep]);return;case"undefined":e.push([kp]);return;case"boolean":e.push([t?Sp:$p]);return;case"number":!Number.isInteger(t)||!Number.isSafeInteger(t)?An(e,new E(y.float,t),n):t>=0?W(e,ku,t):W(e,Iu,t*-1-1);return;case"bigint":t>=BigInt(0)?W(e,ku,t):W(e,Iu,t*Ip-Ap);return;case"string":{let a=Pr(t);W(e,xp,a.length),e.push(a);return}case"Uint8Array":W(e,wp,t.length),e.push(t);return;case"Array":if(!t.length){e.push([Au]);return}r=Pn.createCheck(r,t),W(e,Au,t.length);for(let a of t)Pu(e,a,n,r);return;case"Object":case"Map":{let a=Be.Object(t,o,n,r);Tn(e,a,Bt,n)}return;default:{let a=Be[o];if(!a)throw new Error(`${Ur} unsupported type: ${o}`);let s=a(t,o,n,r);Tn(e,s,Bt,n)}}}function zu(e,t,n,r){let o=r instanceof Uint8Array,i=o?new Or(r):Mr,a=Zr(e,n);if(!Array.isArray(a)&&n.quickEncodeToken){let s=n.quickEncodeToken(a);if(s)return o?(i.push(s),i.toBytes()):s;let u=t[a.type.major];if(u.encodedSize){let c=u.encodedSize(a,n);if(o||(i=new Sn(c)),u(i,a,n),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${a} was wrong`);return o?i.toBytes():$n(i.chunks[0])}}return i.reset(),Tn(i,a,t,n),i.toBytes(!0)}function ji(e,t){return t=Object.assign({},gp,t),Tp(t)?(Mr.reset(),Pu(Mr,e,t,void 0),Mr.toBytes(!0)):zu(e,Bt,t)}var Pp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Br=class{constructor(t,n={}){this._pos=0,this.data=t,this.options=n}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let t=this.data[this._pos],n=je[t];if(n===void 0){let r=$[t];if(!r)throw new Error(`${L} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;n=r(this.data,this._pos,o,this.options)}return this._pos+=n.encodedLength,n}},zn=Symbol.for("DONE"),Fr=Symbol.for("BREAK");function zp(e,t,n){let r=[];for(let o=0;o<e.value;o++){let i=Ft(t,n);if(i===Fr){if(e.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed array`)}if(i===zn)throw new Error(`${L} found array but not enough entries (got ${o}, expected ${e.value})`);r[o]=i}return r}function Op(e,t,n){let r=n.useMaps===!0,o=n.rejectDuplicateMapKeys===!0,i=r?void 0:{},a=r?new Map:void 0;for(let s=0;s<e.value;s++){let u=Ft(t,n);if(u===Fr){if(e.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed map`)}if(u===zn)throw new Error(`${L} found map but not enough entries (got ${s} [no key], expected ${e.value})`);if(!r&&typeof u!="string")throw new Error(`${L} non-string keys not supported (got ${typeof u})`);if(o&&(r&&a.has(u)||!r&&Object.hasOwn(i,u)))throw new Error(`${L} found repeat map key "${u}"`);let c=Ft(t,n);if(c===zn)throw new Error(`${L} found map but not enough entries (got ${s} [no value], expected ${e.value})`);r?a.set(u,c):i[u]=c}return r?a:i}function Ft(e,t){if(e.done())return zn;let n=e.next();if(y.equals(n.type,y.break))return Fr;if(n.type.terminal)return n.value;if(y.equals(n.type,y.array))return zp(n,e,t);if(y.equals(n.type,y.map))return Op(n,e,t);if(y.equals(n.type,y.tag)){if(t.tags&&typeof t.tags[n.value]=="function"){let r=Ft(e,t);return t.tags[n.value](r)}throw new Error(`${L} tag not supported (${n.value})`)}throw new Error("unsupported")}function Ou(e,t){if(!(e instanceof Uint8Array))throw new Error(`${L} data to decode must be a Uint8Array`);t=Object.assign({},Pp,t);let n=$n(e),r=t.tokenizer||new Br(n,t),o=Ft(r,t);if(o===zn)throw new Error(`${L} did not find any content to decode`);if(o===Fr)throw new Error(`${L} got unexpected break`);return[o,e.subarray(r.pos())]}function Ni(e,t){let[n,r]=Ou(e,t);if(r.length>0)throw new Error(`${L} too many terminals, data makes no sense`);return n}var yk=new Uint8Array(0);function Uu(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function Ht(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}function Dp(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var o=0;o<e.length;o++){var i=e.charAt(o),a=i.charCodeAt(0);if(n[a]!==255)throw new TypeError(i+" is ambiguous");n[a]=o}var s=e.length,u=e.charAt(0),c=Math.log(s)/Math.log(256),l=Math.log(256)/Math.log(s);function d(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var g=0,v=0,k=0,A=f.length;k!==A&&f[k]===0;)k++,g++;for(var w=(A-k)*l+1>>>0,S=new Uint8Array(w);k!==A;){for(var x=f[k],O=0,M=w-1;(x!==0||O<v)&&M!==-1;M--,O++)x+=256*S[M]>>>0,S[M]=x%s>>>0,x=x/s>>>0;if(x!==0)throw new Error("Non-zero carry");v=O,k++}for(var B=w-v;B!==w&&S[B]===0;)B++;for(var ie=u.repeat(g);B<w;++B)ie+=e.charAt(S[B]);return ie}function p(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var g=0;if(f[g]!==" "){for(var v=0,k=0;f[g]===u;)v++,g++;for(var A=(f.length-g)*c+1>>>0,w=new Uint8Array(A);f[g];){var S=n[f.charCodeAt(g)];if(S===255)return;for(var x=0,O=A-1;(S!==0||x<k)&&O!==-1;O--,x++)S+=s*w[O]>>>0,w[O]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");k=x,g++}if(f[g]!==" "){for(var M=A-k;M!==A&&w[M]===0;)M++;for(var B=new Uint8Array(v+(A-M)),ie=v;M!==A;)B[ie++]=w[M++];return B}}}function b(f){var g=p(f);if(g)return g;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:p,decode:b}}var Rp=Dp,jp=Rp,Du=jp;var Ci=class{name;prefix;baseEncode;constructor(t,n,r){this.name=t,this.prefix=n,this.baseEncode=r}encode(t){if(t instanceof Uint8Array)return`${this.prefix}${this.baseEncode(t)}`;throw Error("Unknown type, must be binary type")}},Li=class{name;prefix;baseDecode;prefixCodePoint;constructor(t,n,r){this.name=t,this.prefix=n;let o=n.codePointAt(0);if(o===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=o,this.baseDecode=r}decode(t){if(typeof t=="string"){if(t.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(t)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(t.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(t){return Ru(this,t)}},Mi=class{decoders;constructor(t){this.decoders=t}or(t){return Ru(this,t)}decode(t){let n=t[0],r=this.decoders[n];if(r!=null)return r.decode(t);throw RangeError(`Unable to decode multibase string ${JSON.stringify(t)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function Ru(e,t){return new Mi({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Zi=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(t,n,r,o){this.name=t,this.prefix=n,this.baseEncode=r,this.baseDecode=o,this.encoder=new Ci(t,n,r),this.decoder=new Li(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function ju({name:e,prefix:t,encode:n,decode:r}){return new Zi(e,t,n,r)}function Jt({name:e,prefix:t,alphabet:n}){let{encode:r,decode:o}=Du(n,e);return ju({prefix:t,name:e,encode:r,decode:i=>Ht(o(i))})}function Np(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;let i=new Uint8Array(o*n/8|0),a=0,s=0,u=0;for(let c=0;c<o;++c){let l=t[e[c]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);s=s<<n|l,a+=n,a>=8&&(a-=8,i[u++]=255&s>>a)}if(a>=n||(255&s<<8-a)!==0)throw new SyntaxError("Unexpected end of data");return i}function Cp(e,t,n){let r=t[t.length-1]==="=",o=(1<<n)-1,i="",a=0,s=0;for(let u=0;u<e.length;++u)for(s=s<<8|e[u],a+=8;a>n;)a-=n,i+=t[o&s>>a];if(a!==0&&(i+=t[o&s<<n-a]),r)for(;(i.length*n&7)!==0;)i+="=";return i}function Lp(e){let t={};for(let n=0;n<e.length;++n)t[e[n]]=n;return t}function Fe({name:e,prefix:t,bitsPerChar:n,alphabet:r}){let o=Lp(r);return ju({prefix:t,name:e,encode(i){return Cp(i,r,n)},decode(i){return Np(i,o,n,e)}})}var On=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sk=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ek=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kk=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ik=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ak=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tk=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pk=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zk=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hr=Jt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dk=Jt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rt=Jt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nk=Jt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mp=Lu,Nu=128,Zp=127,Bp=~Zp,Fp=Math.pow(2,31);function Lu(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Fp;)t[n++]=e&255|Nu,e/=128;for(;e&Bp;)t[n++]=e&255|Nu,e>>>=7;return t[n]=e|0,Lu.bytes=n-r+1,t}var Hp=Bi,Jp=128,Cu=127;function Bi(e,r){var n=0,r=r||0,o=0,i=r,a,s=e.length;do{if(i>=s)throw Bi.bytes=0,new RangeError("Could not decode varint");a=e[i++],n+=o<28?(a&Cu)<<o:(a&Cu)*Math.pow(2,o),o+=7}while(a>=Jp);return Bi.bytes=i-r,n}var Gp=Math.pow(2,7),Vp=Math.pow(2,14),qp=Math.pow(2,21),Kp=Math.pow(2,28),Wp=Math.pow(2,35),Xp=Math.pow(2,42),Yp=Math.pow(2,49),Qp=Math.pow(2,56),em=Math.pow(2,63),tm=function(e){return e<Gp?1:e<Vp?2:e<qp?3:e<Kp?4:e<Wp?5:e<Xp?6:e<Yp?7:e<Qp?8:e<em?9:10},nm={encode:Mp,decode:Hp,encodingLength:tm},rm=nm,Un=rm;function Dn(e,t=0){return[Un.decode(e,t),Un.decode.bytes]}function Gt(e,t,n=0){return Un.encode(e,t,n),t}function Vt(e){return Un.encodingLength(e)}function Zu(e,t){let n=t.byteLength,r=Vt(e),o=r+Vt(n),i=new Uint8Array(o+n);return Gt(e,i,0),Gt(n,i,r),i.set(t,o),new qt(e,n,t,i)}function Bu(e){let t=Ht(e),[n,r]=Dn(t),[o,i]=Dn(t.subarray(r)),a=t.subarray(r+i);if(a.byteLength!==o)throw new Error("Incorrect length");return new qt(n,o,a,t)}function Fu(e,t){if(e===t)return!0;{let n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&Uu(e.bytes,n.bytes)}}var qt=class{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}};function Hu(e,t){let{bytes:n,version:r}=e;return r===0?am(n,Fi(e),t??rt.encoder):sm(n,Fi(e),t??On.encoder)}var Ju=new WeakMap;function Fi(e){let t=Ju.get(e);if(t==null){let n=new Map;return Ju.set(e,n),n}return t}var jn=class e{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,this.bytes=o,this["/"]=o}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:t,multihash:n}=this;if(t!==Rn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==cm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:n}=this.multihash,r=Zu(t,n);return e.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,n){let r=n;return r!=null&&t.code===r.code&&t.version===r.version&&Fu(t.multihash,r.multihash)}toString(t){return Hu(this,t)}toJSON(){return{"/":Hu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let n=t;if(n instanceof e)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){let{version:r,code:o,multihash:i,bytes:a}=n;return new e(r,o,i,a??Gu(r,o,i.bytes))}else if(n[um]===!0){let{version:r,multihash:o,code:i}=n,a=Bu(o);return e.create(r,i,a)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==Rn)throw new Error(`Version 0 CID must use dag-pb (code: ${Rn}) block encoding`);return new e(t,n,r,r.bytes)}case 1:{let o=Gu(t,n,r.bytes);return new e(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,Rn,t)}static createV1(t,n){return e.create(1,t,n)}static decode(t){let[n,r]=e.decodeFirst(t);if(r.length!==0)throw new Error("Incorrect length");return n}static decodeFirst(t){let n=e.inspectBytes(t),r=n.size-n.multihashSize,o=Ht(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");let i=o.subarray(n.multihashSize-n.digestSize),a=new qt(n.multihashCode,n.digestSize,i,o);return[n.version===0?e.createV0(a):e.createV1(n.codec,a),t.subarray(n.size)]}static inspectBytes(t){let n=0,r=()=>{let[d,p]=Dn(t.subarray(n));return n+=p,d},o=r(),i=Rn;if(o===18?(o=0,n=0):i=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let a=n,s=r(),u=r(),c=n+u,l=c-a;return{version:o,codec:i,multihashCode:s,digestSize:u,multihashSize:l,size:c}}static parse(t,n){let[r,o]=im(t,n),i=e.decode(o);if(i.version===0&&t[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Fi(i).set(r,t),i}};function im(e,t){switch(e[0]){case"Q":{let n=t??rt;return[rt.prefix,n.decode(`${rt.prefix}${e}`)]}case rt.prefix:{let n=t??rt;return[rt.prefix,n.decode(e)]}case On.prefix:{let n=t??On;return[On.prefix,n.decode(e)]}case Hr.prefix:{let n=t??Hr;return[Hr.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function am(e,t,n){let{prefix:r}=n;if(r!==rt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);let o=t.get(r);if(o==null){let i=n.encode(e).slice(1);return t.set(r,i),i}else return o}function sm(e,t,n){let{prefix:r}=n,o=t.get(r);if(o==null){let i=n.encode(e);return t.set(r,i),i}else return o}var Rn=112,cm=18;function Gu(e,t,n){let r=Vt(e),o=r+Vt(t),i=new Uint8Array(o+n.byteLength);return Gt(e,i,0),Gt(t,i,r),i.set(n,o),i}var um=Symbol.for("@ipld/js-cid/CID");var Vu=42;function lm(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function dm(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=jn.asCID(e);if(!t)return null;let n=new Uint8Array(t.bytes.byteLength+1);return n.set(t.bytes,1),[new E(y.tag,Vu),new E(y.bytes,n)]}function fm(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function pm(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}function mm(e){for(let t of e.keys())if(typeof t!="string"||t.length===0)throw new Error("Non-string Map keys are not supported by the IPLD Data Model and cannot be encoded");return null}var Hi={float64:!0,typeEncoders:{Map:mm,Object:dm,undefined:fm,number:pm}},Kk={...Hi,typeEncoders:{...Hi.typeEncoders}};function hm(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return jn.decode(e.subarray(1))}var Jr={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Jr.tags[Vu]=hm;var Wk={...Jr,tags:Jr.tags.slice()};var Ee=e=>ji(e,Hi),He=e=>Ni(lm(e),Jr);function gm(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function ym(){let e=new Map;return function(t,n){try{let o=function(a){if(r)return a;let s=e.get(t.didUrl);return s!==void 0?s:Promise.resolve(n()).then(function(u){var c;return((c=u.didResolutionMetadata)==null?void 0:c.error)!=="notFound"&&e.set(t.didUrl,u),u})},r,i=(function(){if(t.params&&t.params["no-cache"]==="true")return Promise.resolve(n()).then(function(a){return r=1,a})})();return Promise.resolve(i&&i.then?i.then(o):o(i))}catch(r){return Promise.reject(r)}}}function vm(e,t){return t()}var bm="(?:%[0-9a-fA-F]{2})",qu=`(?:[a-zA-Z0-9._-]|${bm})`,_m="([a-z0-9]+)",wm=`((?:${qu}*:)*(${qu}+))`,Ku="[a-zA-Z0-9_.:%-]",xm=`;${Ku}+=${Ku}*`,$m=`((${xm})*)`,Sm="(/[^#?]*)?",Em="([?][^#]*)?",km="(#.*)?",Im=new RegExp(`^did:${_m}:${wm}${$m}${Sm}${Em}${km}$`);function Am(e){if(e===""||!e)return null;let t=e.match(Im);if(t){let n={did:`did:${t[1]}:${t[2]}`,method:t[1],id:t[2],didUrl:e};if(t[4]){let r=t[4].slice(1).split(";");n.params={};for(let o of r){let i=o.split("=");n.params[i[0]]=i[1]}}return t[6]&&(n.path=t[6]),t[7]&&(n.query=t[7].slice(1)),t[8]&&(n.fragment=t[8].slice(1)),n}return null}var Gr={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function Tm(e){return function(t,n,r){try{return Promise.resolve(gm(function(){return Promise.resolve(e(t,n,r)).then(function(o){return{...Gr,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:o}})},function(o){return{...Gr,didResolutionMetadata:{error:"notFound",message:o.toString()}}}))}catch(o){return Promise.reject(o)}}}var Vr=class{constructor(t={},n={}){this.registry=void 0,this.cache=void 0,this.registry=t,this.cache=n.cache===!0?ym():n.cache||vm,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=Tm(n.legacyResolvers[r]))})}resolve(t,n={}){try{let r=this,o=Am(t);if(o===null)return Promise.resolve({...Gr,didResolutionMetadata:{error:"invalidDid"}});let i=r.registry[o.method];return i?Promise.resolve(r.cache(o,()=>i(o.did,o,r,n))):Promise.resolve({...Gr,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(r){return Promise.reject(r)}}};function Nn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Pm}=Object.prototype,{getPrototypeOf:Gi}=Object,{iterator:Kr,toStringTag:Xu}=Symbol,Wr=(e=>t=>{let n=Pm.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Ne=e=>(e=e.toLowerCase(),t=>Wr(t)===e),Xr=e=>t=>typeof t===e,{isArray:Wt}=Array,Kt=Xr("undefined");function Cn(e){return e!==null&&!Kt(e)&&e.constructor!==null&&!Kt(e.constructor)&&ge(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Yu=Ne("ArrayBuffer");function zm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Yu(e.buffer),t}var Om=Xr("string"),ge=Xr("function"),Qu=Xr("number"),Ln=e=>e!==null&&typeof e=="object",Um=e=>e===!0||e===!1,qr=e=>{if(Wr(e)!=="object")return!1;let t=Gi(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Xu in e)&&!(Kr in e)},Dm=e=>{if(!Ln(e)||Cn(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Rm=Ne("Date"),jm=Ne("File"),Nm=Ne("Blob"),Cm=Ne("FileList"),Lm=e=>Ln(e)&&ge(e.pipe),Mm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ge(e.append)&&((t=Wr(e))==="formdata"||t==="object"&&ge(e.toString)&&e.toString()==="[object FormData]"))},Zm=Ne("URLSearchParams"),[Bm,Fm,Hm,Jm]=["ReadableStream","Request","Response","Headers"].map(Ne),Gm=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Mn(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Wt(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Cn(e))return;let i=n?Object.getOwnPropertyNames(e):Object.keys(e),a=i.length,s;for(r=0;r<a;r++)s=i[r],t.call(null,e[s],s,e)}}function el(e,t){if(Cn(e))return null;t=t.toLowerCase();let n=Object.keys(e),r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}var $t=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,tl=e=>!Kt(e)&&e!==$t;function Ji(){let{caseless:e,skipUndefined:t}=tl(this)&&this||{},n={},r=(o,i)=>{let a=e&&el(n,i)||i;qr(n[a])&&qr(o)?n[a]=Ji(n[a],o):qr(o)?n[a]=Ji({},o):Wt(o)?n[a]=o.slice():(!t||!Kt(o))&&(n[a]=o)};for(let o=0,i=arguments.length;o<i;o++)arguments[o]&&Mn(arguments[o],r);return n}var Vm=(e,t,n,{allOwnKeys:r}={})=>(Mn(t,(o,i)=>{n&&ge(o)?Object.defineProperty(e,i,{value:Nn(o,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),e),qm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Km=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Wm=(e,t,n,r)=>{let o,i,a,s={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],(!r||r(a,e,t))&&!s[a]&&(t[a]=e[a],s[a]=!0);e=n!==!1&&Gi(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Xm=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;let r=e.indexOf(t,n);return r!==-1&&r===n},Ym=e=>{if(!e)return null;if(Wt(e))return e;let t=e.length;if(!Qu(t))return null;let n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Qm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Gi(Uint8Array)),eh=(e,t)=>{let r=(e&&e[Kr]).call(e),o;for(;(o=r.next())&&!o.done;){let i=o.value;t.call(e,i[0],i[1])}},th=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},nh=Ne("HTMLFormElement"),rh=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),Wu=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),oh=Ne("RegExp"),nl=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};Mn(n,(o,i)=>{let a;(a=t(o,i,e))!==!1&&(r[i]=a||o)}),Object.defineProperties(e,r)},ih=e=>{nl(e,(t,n)=>{if(ge(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;let r=e[n];if(ge(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},ah=(e,t)=>{let n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Wt(e)?r(e):r(String(e).split(t)),n},sh=()=>{},ch=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function uh(e){return!!(e&&ge(e.append)&&e[Xu]==="FormData"&&e[Kr])}var lh=e=>{let t=new Array(10),n=(r,o)=>{if(Ln(r)){if(t.indexOf(r)>=0)return;if(Cn(r))return r;if(!("toJSON"in r)){t[o]=r;let i=Wt(r)?[]:{};return Mn(r,(a,s)=>{let u=n(a,o+1);!Kt(u)&&(i[s]=u)}),t[o]=void 0,i}}return r};return n(e,0)},dh=Ne("AsyncFunction"),fh=e=>e&&(Ln(e)||ge(e))&&ge(e.then)&&ge(e.catch),rl=((e,t)=>e?setImmediate:t?((n,r)=>($t.addEventListener("message",({source:o,data:i})=>{o===$t&&i===n&&r.length&&r.shift()()},!1),o=>{r.push(o),$t.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",ge($t.postMessage)),ph=typeof queueMicrotask<"u"?queueMicrotask.bind($t):typeof process<"u"&&process.nextTick||rl,mh=e=>e!=null&&ge(e[Kr]),m={isArray:Wt,isArrayBuffer:Yu,isBuffer:Cn,isFormData:Mm,isArrayBufferView:zm,isString:Om,isNumber:Qu,isBoolean:Um,isObject:Ln,isPlainObject:qr,isEmptyObject:Dm,isReadableStream:Bm,isRequest:Fm,isResponse:Hm,isHeaders:Jm,isUndefined:Kt,isDate:Rm,isFile:jm,isBlob:Nm,isRegExp:oh,isFunction:ge,isStream:Lm,isURLSearchParams:Zm,isTypedArray:Qm,isFileList:Cm,forEach:Mn,merge:Ji,extend:Vm,trim:Gm,stripBOM:qm,inherits:Km,toFlatObject:Wm,kindOf:Wr,kindOfTest:Ne,endsWith:Xm,toArray:Ym,forEachEntry:eh,matchAll:th,isHTMLForm:nh,hasOwnProperty:Wu,hasOwnProp:Wu,reduceDescriptors:nl,freezeMethods:ih,toObjectSet:ah,toCamelCase:rh,noop:sh,toFiniteNumber:ch,findKey:el,global:$t,isContextDefined:tl,isSpecCompliantForm:uh,toJSONObject:lh,isAsyncFn:dh,isThenable:fh,setImmediate:rl,asap:ph,isIterable:mh};var pe=class e extends Error{static from(t,n,r,o,i,a){let s=new e(t.message,n||t.code,r,o,i);return s.cause=t,s.name=t.name,a&&Object.assign(s,a),s}constructor(t,n,r,o,i){super(t),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),o&&(this.request=o),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:m.toJSONObject(this.config),code:this.code,status:this.status}}};pe.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";pe.ERR_BAD_OPTION="ERR_BAD_OPTION";pe.ECONNABORTED="ECONNABORTED";pe.ETIMEDOUT="ETIMEDOUT";pe.ERR_NETWORK="ERR_NETWORK";pe.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";pe.ERR_DEPRECATED="ERR_DEPRECATED";pe.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";pe.ERR_BAD_REQUEST="ERR_BAD_REQUEST";pe.ERR_CANCELED="ERR_CANCELED";pe.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";pe.ERR_INVALID_URL="ERR_INVALID_URL";var j=pe;var Yr=null;function Vi(e){return m.isPlainObject(e)||m.isArray(e)}function il(e){return m.endsWith(e,"[]")?e.slice(0,-2):e}function ol(e,t,n){return e?e.concat(t).map(function(o,i){return o=il(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function hh(e){return m.isArray(e)&&!e.some(Vi)}var gh=m.toFlatObject(m,{},null,function(t){return/^is[A-Z]/.test(t)});function yh(e,t,n){if(!m.isObject(e))throw new TypeError("target must be an object");t=t||new(Yr||FormData),n=m.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(g,v){return!m.isUndefined(v[g])});let r=n.metaTokens,o=n.visitor||l,i=n.dots,a=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&m.isSpecCompliantForm(t);if(!m.isFunction(o))throw new TypeError("visitor must be a function");function c(f){if(f===null)return"";if(m.isDate(f))return f.toISOString();if(m.isBoolean(f))return f.toString();if(!u&&m.isBlob(f))throw new j("Blob is not supported. Use a Buffer instead.");return m.isArrayBuffer(f)||m.isTypedArray(f)?u&&typeof Blob=="function"?new Blob([f]):Buffer.from(f):f}function l(f,g,v){let k=f;if(f&&!v&&typeof f=="object"){if(m.endsWith(g,"{}"))g=r?g:g.slice(0,-2),f=JSON.stringify(f);else if(m.isArray(f)&&hh(f)||(m.isFileList(f)||m.endsWith(g,"[]"))&&(k=m.toArray(f)))return g=il(g),k.forEach(function(w,S){!(m.isUndefined(w)||w===null)&&t.append(a===!0?ol([g],S,i):a===null?g:g+"[]",c(w))}),!1}return Vi(f)?!0:(t.append(ol(v,g,i),c(f)),!1)}let d=[],p=Object.assign(gh,{defaultVisitor:l,convertValue:c,isVisitable:Vi});function b(f,g){if(!m.isUndefined(f)){if(d.indexOf(f)!==-1)throw Error("Circular reference detected in "+g.join("."));d.push(f),m.forEach(f,function(k,A){(!(m.isUndefined(k)||k===null)&&o.call(t,k,m.isString(A)?A.trim():A,g,p))===!0&&b(k,g?g.concat(A):[A])}),d.pop()}}if(!m.isObject(e))throw new TypeError("data must be an object");return b(e),t}var dt=yh;function al(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function sl(e,t){this._pairs=[],e&&dt(e,this,t)}var cl=sl.prototype;cl.append=function(t,n){this._pairs.push([t,n])};cl.toString=function(t){let n=t?function(r){return t.call(this,r,al)}:al;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};var Qr=sl;function vh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Zn(e,t,n){if(!t)return e;let r=n&&n.encode||vh,o=m.isFunction(n)?{serialize:n}:n,i=o&&o.serialize,a;if(i?a=i(t,o):a=m.isURLSearchParams(t)?t.toString():new Qr(t,o).toString(r),a){let s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var qi=class{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){m.forEach(this.handlers,function(r){r!==null&&t(r)})}},Ki=qi;var eo={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var ul=typeof URLSearchParams<"u"?URLSearchParams:Qr;var ll=typeof FormData<"u"?FormData:null;var dl=typeof Blob<"u"?Blob:null;var fl={isBrowser:!0,classes:{URLSearchParams:ul,FormData:ll,Blob:dl},protocols:["http","https","file","blob","url","data"]};var Yi={};tf(Yi,{hasBrowserEnv:()=>Xi,hasStandardBrowserEnv:()=>bh,hasStandardBrowserWebWorkerEnv:()=>_h,navigator:()=>Wi,origin:()=>wh});var Xi=typeof window<"u"&&typeof document<"u",Wi=typeof navigator=="object"&&navigator||void 0,bh=Xi&&(!Wi||["ReactNative","NativeScript","NS"].indexOf(Wi.product)<0),_h=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",wh=Xi&&window.location.href||"http://localhost";var Y={...Yi,...fl};function Qi(e,t){return dt(e,new Y.classes.URLSearchParams,{visitor:function(n,r,o,i){return Y.isNode&&m.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function xh(e){return m.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $h(e){let t={},n=Object.keys(e),r,o=n.length,i;for(r=0;r<o;r++)i=n[r],t[i]=e[i];return t}function Sh(e){function t(n,r,o,i){let a=n[i++];if(a==="__proto__")return!0;let s=Number.isFinite(+a),u=i>=n.length;return a=!a&&m.isArray(o)?o.length:a,u?(m.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!s):((!o[a]||!m.isObject(o[a]))&&(o[a]=[]),t(n,r,o[a],i)&&m.isArray(o[a])&&(o[a]=$h(o[a])),!s)}if(m.isFormData(e)&&m.isFunction(e.entries)){let n={};return m.forEachEntry(e,(r,o)=>{t(xh(r),o,n,0)}),n}return null}var to=Sh;function Eh(e,t,n){if(m.isString(e))try{return(t||JSON.parse)(e),m.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}var ea={transitional:eo,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){let r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=m.isObject(t);if(i&&m.isHTMLForm(t)&&(t=new FormData(t)),m.isFormData(t))return o?JSON.stringify(to(t)):t;if(m.isArrayBuffer(t)||m.isBuffer(t)||m.isStream(t)||m.isFile(t)||m.isBlob(t)||m.isReadableStream(t))return t;if(m.isArrayBufferView(t))return t.buffer;if(m.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let s;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return Qi(t,this.formSerializer).toString();if((s=m.isFileList(t))||r.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return dt(s?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),Eh(t)):t}],transformResponse:[function(t){let n=this.transitional||ea.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(m.isResponse(t)||m.isReadableStream(t))return t;if(t&&m.isString(t)&&(r&&!this.responseType||o)){let a=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t,this.parseReviver)}catch(s){if(a)throw s.name==="SyntaxError"?j.from(s,j.ERR_BAD_RESPONSE,this,null,this.response):s}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Y.classes.FormData,Blob:Y.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};m.forEach(["delete","get","head","post","put","patch"],e=>{ea.headers[e]={}});var Xt=ea;var kh=m.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),pl=e=>{let t={},n,r,o;return e&&e.split(`
3
+ `).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||t[n]&&kh[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};var ml=Symbol("internals");function Bn(e){return e&&String(e).trim().toLowerCase()}function no(e){return e===!1||e==null?e:m.isArray(e)?e.map(no):String(e)}function Ih(e){let t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}var Ah=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function ta(e,t,n,r,o){if(m.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!m.isString(t)){if(m.isString(r))return t.indexOf(r)!==-1;if(m.isRegExp(r))return r.test(t)}}function Th(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Ph(e,t){let n=m.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,a){return this[r].call(this,t,o,i,a)},configurable:!0})})}var Yt=class{constructor(t){t&&this.set(t)}set(t,n,r){let o=this;function i(s,u,c){let l=Bn(u);if(!l)throw new Error("header name must be a non-empty string");let d=m.findKey(o,l);(!d||o[d]===void 0||c===!0||c===void 0&&o[d]!==!1)&&(o[d||u]=no(s))}let a=(s,u)=>m.forEach(s,(c,l)=>i(c,l,u));if(m.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if(m.isString(t)&&(t=t.trim())&&!Ah(t))a(pl(t),n);else if(m.isObject(t)&&m.isIterable(t)){let s={},u,c;for(let l of t){if(!m.isArray(l))throw TypeError("Object iterator must return a key-value pair");s[c=l[0]]=(u=s[c])?m.isArray(u)?[...u,l[1]]:[u,l[1]]:l[1]}a(s,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=Bn(t),t){let r=m.findKey(this,t);if(r){let o=this[r];if(!n)return o;if(n===!0)return Ih(o);if(m.isFunction(n))return n.call(this,o,r);if(m.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Bn(t),t){let r=m.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||ta(this,this[r],r,n)))}return!1}delete(t,n){let r=this,o=!1;function i(a){if(a=Bn(a),a){let s=m.findKey(r,a);s&&(!n||ta(r,r[s],s,n))&&(delete r[s],o=!0)}}return m.isArray(t)?t.forEach(i):i(t),o}clear(t){let n=Object.keys(this),r=n.length,o=!1;for(;r--;){let i=n[r];(!t||ta(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){let n=this,r={};return m.forEach(this,(o,i)=>{let a=m.findKey(r,i);if(a){n[a]=no(o),delete n[i];return}let s=t?Th(i):String(i).trim();s!==i&&delete n[i],n[s]=no(o),r[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let n=Object.create(null);return m.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&m.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
4
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){let r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){let r=(this[ml]=this[ml]={accessors:{}}).accessors,o=this.prototype;function i(a){let s=Bn(a);r[s]||(Ph(o,a),r[s]=!0)}return m.isArray(t)?t.forEach(i):i(t),this}};Yt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);m.reduceDescriptors(Yt.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});m.freezeMethods(Yt);var oe=Yt;function Fn(e,t){let n=this||Xt,r=t||n,o=oe.from(r.headers),i=r.data;return m.forEach(e,function(s){i=s.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function Hn(e){return!!(e&&e.__CANCEL__)}var na=class extends j{constructor(t,n,r){super(t??"canceled",j.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}},Je=na;function Jn(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new j("Request failed with status code "+n.status,[j.ERR_BAD_REQUEST,j.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function ra(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function zh(e,t){e=e||10;let n=new Array(e),r=new Array(e),o=0,i=0,a;return t=t!==void 0?t:1e3,function(u){let c=Date.now(),l=r[i];a||(a=c),n[o]=u,r[o]=c;let d=i,p=0;for(;d!==o;)p+=n[d++],d=d%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),c-a<t)return;let b=l&&c-l;return b?Math.round(p*1e3/b):void 0}}var hl=zh;function Oh(e,t){let n=0,r=1e3/t,o,i,a=(c,l=Date.now())=>{n=l,o=null,i&&(clearTimeout(i),i=null),e(...c)};return[(...c)=>{let l=Date.now(),d=l-n;d>=r?a(c,l):(o=c,i||(i=setTimeout(()=>{i=null,a(o)},r-d)))},()=>o&&a(o)]}var gl=Oh;var Qt=(e,t,n=3)=>{let r=0,o=hl(50,250);return gl(i=>{let a=i.loaded,s=i.lengthComputable?i.total:void 0,u=a-r,c=o(u),l=a<=s;r=a;let d={loaded:a,total:s,progress:s?a/s:void 0,bytes:u,rate:c||void 0,estimated:c&&s&&l?(s-a)/c:void 0,event:i,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(d)},n)},oa=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ia=e=>(...t)=>m.asap(()=>e(...t));var yl=Y.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Y.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Y.origin),Y.navigator&&/(msie|trident)/i.test(Y.navigator.userAgent)):()=>!0;var vl=Y.hasStandardBrowserEnv?{write(e,t,n,r,o,i,a){if(typeof document>"u")return;let s=[`${e}=${encodeURIComponent(t)}`];m.isNumber(n)&&s.push(`expires=${new Date(n).toUTCString()}`),m.isString(r)&&s.push(`path=${r}`),m.isString(o)&&s.push(`domain=${o}`),i===!0&&s.push("secure"),m.isString(a)&&s.push(`SameSite=${a}`),document.cookie=s.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function aa(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function sa(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Gn(e,t,n){let r=!aa(t);return e&&(r||n==!1)?sa(e,t):t}var bl=e=>e instanceof oe?{...e}:e;function Ce(e,t){t=t||{};let n={};function r(c,l,d,p){return m.isPlainObject(c)&&m.isPlainObject(l)?m.merge.call({caseless:p},c,l):m.isPlainObject(l)?m.merge({},l):m.isArray(l)?l.slice():l}function o(c,l,d,p){if(m.isUndefined(l)){if(!m.isUndefined(c))return r(void 0,c,d,p)}else return r(c,l,d,p)}function i(c,l){if(!m.isUndefined(l))return r(void 0,l)}function a(c,l){if(m.isUndefined(l)){if(!m.isUndefined(c))return r(void 0,c)}else return r(void 0,l)}function s(c,l,d){if(d in t)return r(c,l);if(d in e)return r(void 0,c)}let u={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(c,l,d)=>o(bl(c),bl(l),d,!0)};return m.forEach(Object.keys({...e,...t}),function(l){let d=u[l]||o,p=d(e[l],t[l],l);m.isUndefined(p)&&d!==s||(n[l]=p)}),n}var ro=e=>{let t=Ce({},e),{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:i,headers:a,auth:s}=t;if(t.headers=a=oe.from(a),t.url=Zn(Gn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&a.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):""))),m.isFormData(n)){if(Y.hasStandardBrowserEnv||Y.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(m.isFunction(n.getHeaders)){let u=n.getHeaders(),c=["content-type","content-length"];Object.entries(u).forEach(([l,d])=>{c.includes(l.toLowerCase())&&a.set(l,d)})}}if(Y.hasStandardBrowserEnv&&(r&&m.isFunction(r)&&(r=r(t)),r||r!==!1&&yl(t.url))){let u=o&&i&&vl.read(i);u&&a.set(o,u)}return t};var Uh=typeof XMLHttpRequest<"u",_l=Uh&&function(e){return new Promise(function(n,r){let o=ro(e),i=o.data,a=oe.from(o.headers).normalize(),{responseType:s,onUploadProgress:u,onDownloadProgress:c}=o,l,d,p,b,f;function g(){b&&b(),f&&f(),o.cancelToken&&o.cancelToken.unsubscribe(l),o.signal&&o.signal.removeEventListener("abort",l)}let v=new XMLHttpRequest;v.open(o.method.toUpperCase(),o.url,!0),v.timeout=o.timeout;function k(){if(!v)return;let w=oe.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),x={data:!s||s==="text"||s==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:w,config:e,request:v};Jn(function(M){n(M),g()},function(M){r(M),g()},x),v=null}"onloadend"in v?v.onloadend=k:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(k)},v.onabort=function(){v&&(r(new j("Request aborted",j.ECONNABORTED,e,v)),v=null)},v.onerror=function(S){let x=S&&S.message?S.message:"Network Error",O=new j(x,j.ERR_NETWORK,e,v);O.event=S||null,r(O),v=null},v.ontimeout=function(){let S=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",x=o.transitional||eo;o.timeoutErrorMessage&&(S=o.timeoutErrorMessage),r(new j(S,x.clarifyTimeoutError?j.ETIMEDOUT:j.ECONNABORTED,e,v)),v=null},i===void 0&&a.setContentType(null),"setRequestHeader"in v&&m.forEach(a.toJSON(),function(S,x){v.setRequestHeader(x,S)}),m.isUndefined(o.withCredentials)||(v.withCredentials=!!o.withCredentials),s&&s!=="json"&&(v.responseType=o.responseType),c&&([p,f]=Qt(c,!0),v.addEventListener("progress",p)),u&&v.upload&&([d,b]=Qt(u),v.upload.addEventListener("progress",d),v.upload.addEventListener("loadend",b)),(o.cancelToken||o.signal)&&(l=w=>{v&&(r(!w||w.type?new Je(null,e,v):w),v.abort(),v=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));let A=ra(o.url);if(A&&Y.protocols.indexOf(A)===-1){r(new j("Unsupported protocol "+A+":",j.ERR_BAD_REQUEST,e));return}v.send(i||null)})};var Dh=(e,t)=>{let{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o,i=function(c){if(!o){o=!0,s();let l=c instanceof Error?c:this.reason;r.abort(l instanceof j?l:new Je(l instanceof Error?l.message:l))}},a=t&&setTimeout(()=>{a=null,i(new j(`timeout of ${t}ms exceeded`,j.ETIMEDOUT))},t),s=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(i):c.removeEventListener("abort",i)}),e=null)};e.forEach(c=>c.addEventListener("abort",i));let{signal:u}=r;return u.unsubscribe=()=>m.asap(s),u}},wl=Dh;var Rh=function*(e,t){let n=e.byteLength;if(!t||n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},jh=async function*(e,t){for await(let n of Nh(e))yield*Rh(n,t)},Nh=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},ca=(e,t,n,r)=>{let o=jh(e,t),i=0,a,s=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{let{done:c,value:l}=await o.next();if(c){s(),u.close();return}let d=l.byteLength;if(n){let p=i+=d;n(p)}u.enqueue(new Uint8Array(l))}catch(c){throw s(c),c}},cancel(u){return s(u),o.return()}},{highWaterMark:2})};var xl=64*1024,{isFunction:oo}=m,Ch=(({Request:e,Response:t})=>({Request:e,Response:t}))(m.global),{ReadableStream:$l,TextEncoder:Sl}=m.global,El=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Lh=e=>{e=m.merge.call({skipUndefined:!0},Ch,e);let{fetch:t,Request:n,Response:r}=e,o=t?oo(t):typeof fetch=="function",i=oo(n),a=oo(r);if(!o)return!1;let s=o&&oo($l),u=o&&(typeof Sl=="function"?(f=>g=>f.encode(g))(new Sl):async f=>new Uint8Array(await new n(f).arrayBuffer())),c=i&&s&&El(()=>{let f=!1,g=new n(Y.origin,{body:new $l,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!g}),l=a&&s&&El(()=>m.isReadableStream(new r("").body)),d={stream:l&&(f=>f.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!d[f]&&(d[f]=(g,v)=>{let k=g&&g[f];if(k)return k.call(g);throw new j(`Response type '${f}' is not supported`,j.ERR_NOT_SUPPORT,v)})});let p=async f=>{if(f==null)return 0;if(m.isBlob(f))return f.size;if(m.isSpecCompliantForm(f))return(await new n(Y.origin,{method:"POST",body:f}).arrayBuffer()).byteLength;if(m.isArrayBufferView(f)||m.isArrayBuffer(f))return f.byteLength;if(m.isURLSearchParams(f)&&(f=f+""),m.isString(f))return(await u(f)).byteLength},b=async(f,g)=>{let v=m.toFiniteNumber(f.getContentLength());return v??p(g)};return async f=>{let{url:g,method:v,data:k,signal:A,cancelToken:w,timeout:S,onDownloadProgress:x,onUploadProgress:O,responseType:M,headers:B,withCredentials:ie="same-origin",fetchOptions:Ae}=ro(f),h=t||fetch;M=M?(M+"").toLowerCase():"text";let _=wl([A,w&&w.toAbortSignal()],S),z=null,Z=_&&_.unsubscribe&&(()=>{_.unsubscribe()}),q;try{if(O&&c&&v!=="get"&&v!=="head"&&(q=await b(B,k))!==0){let ce=new n(g,{method:"POST",body:k,duplex:"half"}),Ut;if(m.isFormData(k)&&(Ut=ce.headers.get("content-type"))&&B.setContentType(Ut),ce.body){let[ri,fr]=oa(q,Qt(ia(O)));k=ca(ce.body,xl,ri,fr)}}m.isString(ie)||(ie=ie?"include":"omit");let C=i&&"credentials"in n.prototype,gt={...Ae,signal:_,method:v.toUpperCase(),headers:B.normalize().toJSON(),body:k,duplex:"half",credentials:C?ie:void 0};z=i&&new n(g,gt);let Te=await(i?h(z,Ae):h(g,gt)),hn=l&&(M==="stream"||M==="response");if(l&&(x||hn&&Z)){let ce={};["status","statusText","headers"].forEach(bs=>{ce[bs]=Te[bs]});let Ut=m.toFiniteNumber(Te.headers.get("content-length")),[ri,fr]=x&&oa(Ut,Qt(ia(x),!0))||[];Te=new r(ca(Te.body,xl,ri,()=>{fr&&fr(),Z&&Z()}),ce)}M=M||"text";let ne=await d[m.findKey(d,M)||"text"](Te,f);return!hn&&Z&&Z(),await new Promise((ce,Ut)=>{Jn(ce,Ut,{data:ne,headers:oe.from(Te.headers),status:Te.status,statusText:Te.statusText,config:f,request:z})})}catch(C){throw Z&&Z(),C&&C.name==="TypeError"&&/Load failed|fetch/i.test(C.message)?Object.assign(new j("Network Error",j.ERR_NETWORK,f,z),{cause:C.cause||C}):j.from(C,C&&C.code,f,z)}}},Mh=new Map,ua=e=>{let t=e&&e.env||{},{fetch:n,Request:r,Response:o}=t,i=[r,o,n],a=i.length,s=a,u,c,l=Mh;for(;s--;)u=i[s],c=l.get(u),c===void 0&&l.set(u,c=s?new Map:Lh(t)),l=c;return c},tT=ua();var la={http:Yr,xhr:_l,fetch:{get:ua}};m.forEach(la,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var kl=e=>`- ${e}`,Bh=e=>m.isFunction(e)||e===null||e===!1;function Fh(e,t){e=m.isArray(e)?e:[e];let{length:n}=e,r,o,i={};for(let a=0;a<n;a++){r=e[a];let s;if(o=r,!Bh(r)&&(o=la[(s=String(r)).toLowerCase()],o===void 0))throw new j(`Unknown adapter '${s}'`);if(o&&(m.isFunction(o)||(o=o.get(t))))break;i[s||"#"+a]=o}if(!o){let a=Object.entries(i).map(([u,c])=>`adapter ${u} `+(c===!1?"is not supported by the environment":"is not available in the build")),s=n?a.length>1?`since :
5
+ `+a.map(kl).join(`
6
+ `):" "+kl(a[0]):"as no adapter specified";throw new j("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return o}var io={getAdapter:Fh,adapters:la};function da(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Je(null,e)}function ao(e){return da(e),e.headers=oe.from(e.headers),e.data=Fn.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),io.getAdapter(e.adapter||Xt.adapter,e)(e).then(function(r){return da(e),r.data=Fn.call(e,e.transformResponse,r),r.headers=oe.from(r.headers),r},function(r){return Hn(r)||(da(e),r&&r.response&&(r.response.data=Fn.call(e,e.transformResponse,r.response),r.response.headers=oe.from(r.response.headers))),Promise.reject(r)})}var so="1.13.3";var co={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{co[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});var Il={};co.transitional=function(t,n,r){function o(i,a){return"[Axios v"+so+"] Transitional option '"+i+"'"+a+(r?". "+r:"")}return(i,a,s)=>{if(t===!1)throw new j(o(a," has been removed"+(n?" in "+n:"")),j.ERR_DEPRECATED);return n&&!Il[a]&&(Il[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,a,s):!0}};co.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Hh(e,t,n){if(typeof e!="object")throw new j("options must be an object",j.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),o=r.length;for(;o-- >0;){let i=r[o],a=t[i];if(a){let s=e[i],u=s===void 0||a(s,i,e);if(u!==!0)throw new j("option "+i+" must be "+u,j.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new j("Unknown option "+i,j.ERR_BAD_OPTION)}}var Vn={assertOptions:Hh,validators:co};var Ge=Vn.validators,en=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Ki,response:new Ki}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;let i=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?i&&!String(r.stack).endsWith(i.replace(/^.+\n.+\n/,""))&&(r.stack+=`
7
+ `+i):r.stack=i}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Ce(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Vn.assertOptions(r,{silentJSONParsing:Ge.transitional(Ge.boolean),forcedJSONParsing:Ge.transitional(Ge.boolean),clarifyTimeoutError:Ge.transitional(Ge.boolean)},!1),o!=null&&(m.isFunction(o)?n.paramsSerializer={serialize:o}:Vn.assertOptions(o,{encode:Ge.function,serialize:Ge.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Vn.assertOptions(n,{baseUrl:Ge.spelling("baseURL"),withXsrfToken:Ge.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let a=i&&m.merge(i.common,i[n.method]);i&&m.forEach(["delete","get","head","post","put","patch","common"],f=>{delete i[f]}),n.headers=oe.concat(a,i);let s=[],u=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(u=u&&g.synchronous,s.unshift(g.fulfilled,g.rejected))});let c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let l,d=0,p;if(!u){let f=[ao.bind(this),void 0];f.unshift(...s),f.push(...c),p=f.length,l=Promise.resolve(n);let g=n;for(;d<p;)l=l.then(f[d++]).then(v=>{g=v!==void 0?v:g}).catch(f[d++]).then(()=>g);return l}p=s.length;let b=n;for(;d<p;){let f=s[d++],g=s[d++];try{b=f(b)}catch(v){g.call(this,v);break}}try{l=ao.call(this,b)}catch(f){return Promise.reject(f)}for(d=0,p=c.length;d<p;)l=l.then(c[d++]).catch(c[d++]);return l}getUri(t){t=Ce(this.defaults,t);let n=Gn(t.baseURL,t.url,t.allowAbsoluteUrls);return Zn(n,t.params,t.paramsSerializer)}};m.forEach(["delete","get","head","options"],function(t){en.prototype[t]=function(n,r){return this.request(Ce(r||{},{method:t,url:n,data:(r||{}).data}))}});m.forEach(["post","put","patch"],function(t){function n(r){return function(i,a,s){return this.request(Ce(s||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:a}))}}en.prototype[t]=n(),en.prototype[t+"Form"]=n(!0)});var qn=en;var fa=class e{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(i){n=i});let r=this;this.promise.then(o=>{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i,a=new Promise(s=>{r.subscribe(s),i=s}).then(o);return a.cancel=function(){r.unsubscribe(i)},a},t(function(i,a,s){r.reason||(r.reason=new Je(i,a,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},Al=fa;function pa(e){return function(n){return e.apply(null,n)}}function ma(e){return m.isObject(e)&&e.isAxiosError===!0}var ha={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(ha).forEach(([e,t])=>{ha[t]=e});var Tl=ha;function Pl(e){let t=new qn(e),n=Nn(qn.prototype.request,t);return m.extend(n,qn.prototype,t,{allOwnKeys:!0}),m.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(Ce(e,o))},n}var te=Pl(Xt);te.Axios=qn;te.CanceledError=Je;te.CancelToken=Al;te.isCancel=Hn;te.VERSION=so;te.toFormData=dt;te.AxiosError=j;te.Cancel=te.CanceledError;te.all=function(t){return Promise.all(t)};te.spread=pa;te.isAxiosError=ma;te.mergeConfig=Ce;te.AxiosHeaders=oe;te.formToJSON=e=>to(m.isHTMLForm(e)?new FormData(e):e);te.getAdapter=io.getAdapter;te.HttpStatusCode=Tl;te.default=te;var uo=te;var{Axios:YT,AxiosError:QT,CanceledError:e0,isCancel:t0,CancelToken:n0,VERSION:r0,all:o0,Cancel:i0,isAxiosError:a0,spread:s0,toFormData:c0,AxiosHeaders:u0,HttpStatusCode:l0,formToJSON:d0,getAdapter:f0,mergeConfig:p0}=uo;function Jh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function ke(e,t,n){if(!e.s){if(n instanceof ga)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=ke.bind(null,e,t);return}if(n&&n.then){n.then(ke.bind(null,e,t),ke.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var ga=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{ke(r,1,i(this.v))}catch(a){ke(r,2,a)}return r}else return this}return this.o=function(i){try{let a=i.v;i.s&1?ke(r,1,t?t(a):a):n?ke(r,1,n(a)):ke(r,2,a)}catch(a){ke(r,2,a)}},r},e})();function tn(e){return e instanceof ga&&e.s&1}function Gh(e,t){var n;do{var r=e();if(r&&r.then)if(tn(r))r=r.v;else{n=!0;break}var o=t();if(tn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ga,a=ke.bind(null,i,2);return(n?r.then(s):o.then(u)).then(void 0,a),i;function s(c){for(r=c;o=t(),tn(o)&&(o=o.v),!!o;){if(o.then){o.then(u).then(void 0,a);return}if(r=e(),r&&r.then)if(tn(r))r=r.v;else{r.then(s).then(void 0,a);return}}ke(i,1,r)}function u(c){if(c){do{if(r=e(),r&&r.then)if(tn(r))r=r.v;else{r.then(s).then(void 0,a);return}if(c=t(),tn(c)&&(c=c.v),!c){ke(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else ke(i,1,r)}}function zl(){return{plc:function(t,n){try{let o=function(){let l=typeof u?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{contentType:l}}},r,i=null,a=`https://plc.directory/${encodeURIComponent(t)}`,s={},u=null,c=Gh(function(){function l(){r||u?.id===t||(i="resolver_error: DID document id does not match requested did")}let d=Jh(function(){return Promise.resolve(uo.get(a)).then(function(p){u=p.data})},function(p){i=`resolver_error: '"https://plc.directory/" + DID' must resolve to a valid https URL containing a JSON document: ${p}`,r=1});return d&&d.then?d.then(l):l(d)},function(){return!r&&!1});return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(r){return Promise.reject(r)}}}}var Dl=nf(Ul(),1);function Vh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var qh=function(e){try{return Promise.resolve((0,Dl.default)(e,{mode:"cors"})).then(function(t){if(t.status>=400)throw new Error(`Bad response ${t.statusText}`);return t.json()})}catch(t){return Promise.reject(t)}};function Ie(e,t,n){if(!e.s){if(n instanceof ya)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Ie.bind(null,e,t);return}if(n&&n.then){n.then(Ie.bind(null,e,t),Ie.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Kh="/.well-known/did.json",ya=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Ie(r,1,i(this.v))}catch(a){Ie(r,2,a)}return r}else return this}return this.o=function(i){try{let a=i.v;i.s&1?Ie(r,1,t?t(a):a):n?Ie(r,1,n(a)):Ie(r,2,a)}catch(a){Ie(r,2,a)}},r},e})();function rn(e){return e instanceof ya&&e.s&1}function Wh(e,t){var n;do{var r=e();if(r&&r.then)if(rn(r))r=r.v;else{n=!0;break}var o=t();if(rn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ya,a=Ie.bind(null,i,2);return(n?r.then(s):o.then(u)).then(void 0,a),i;function s(c){for(r=c;o=t(),rn(o)&&(o=o.v),!!o;){if(o.then){o.then(u).then(void 0,a);return}if(r=e(),r&&r.then)if(rn(r))r=r.v;else{r.then(s).then(void 0,a);return}}Ie(i,1,r)}function u(c){if(c){do{if(r=e(),r&&r.then)if(rn(r))r=r.v;else{r.then(s).then(void 0,a);return}if(c=t(),rn(c)&&(c=c.v),!c){Ie(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else Ie(i,1,r)}}function Rl(){return{web:function(t,n){try{let o=function(){let p=typeof l?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{contentType:p}}},r,i=null,a=decodeURIComponent(n.id)+Kh,s=n.id.split(":");s.length>1&&(a=s.map(decodeURIComponent).join("/")+"/did.json");let u=`https://${a}`,c={},l=null,d=Wh(function(){function p(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let b=Vh(function(){return Promise.resolve(qh(u)).then(function(f){l=f})},function(f){i=`resolver_error: DID must resolve to a valid https URL containing a JSON document: ${f}`,r=1});return b&&b.then?b.then(p):p(b)},function(){return!r&&!1});return Promise.resolve(d&&d.then?d.then(o):o(d))}catch(r){return Promise.reject(r)}}}}var po=class{methods={...zl(),...Rl()};resolver=new Vr(this.methods,{cache:!0});async resolve(t){if(!Object.keys(this.methods).some(r=>t.startsWith(`did:${r}:`)))throw new Error(`Unrecognized DID method: ${t}`);let{didDocument:n}=await this.resolver.resolve(t);if(!n)throw new Q(`DID not found: ${t}`);return n}};var _a;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(_a="oauth4webapi/v3.8.3");function Qn(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var ve="ERR_INVALID_ARG_VALUE",Oe="ERR_INVALID_ARG_TYPE";function K(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var Et=Symbol(),vo=Symbol(),bo=Symbol(),kt=Symbol();var mo=Symbol();var Xh=new TextEncoder,Yh=new TextDecoder;function jl(e){return typeof e=="string"?Xh.encode(e):Yh.decode(e)}var wa;Uint8Array.prototype.toBase64?wa=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):wa=t=>{t instanceof ArrayBuffer&&(t=new Uint8Array(t));let n=[];for(let r=0;r<t.byteLength;r+=32768)n.push(String.fromCharCode.apply(null,t.subarray(r,r+32768)));return btoa(n.join("")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")};var xa;Uint8Array.fromBase64?xa=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw K("The input to be decoded is not correctly encoded.",ve,t)}}:xa=e=>{try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch(t){throw K("The input to be decoded is not correctly encoded.",ve,t)}};function $a(e){return typeof e=="string"?xa(e):wa(e)}var pt=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Eo,Error.captureStackTrace?.(this,this.constructor)}},Wn=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,n?.code&&(this.code=n?.code),Error.captureStackTrace?.(this,this.constructor)}};function N(e,t,n){return new Wn(e,{code:t,cause:n})}function ho(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Sa(e){Qn(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(_a&&!t.has("user-agent")&&t.set("user-agent",_a),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',ve);return t}function Cl(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw K('"options.signal" must return or be an instance of AbortSignal',Oe);return t}}function Ll(e){return e.includes("//")?e.replace("//","/"):e}function Qh(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=Ll(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function eg(e,t){return e.pathname=Ll(`${e.pathname}/${t}`),e}async function tg(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,Oe);xo(e,r?.[Et]!==!0);let o=n(new URL(e.href)),i=Sa(r?.headers);return i.set("accept","application/json"),(r?.[kt]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Cl(o,r?.signal)})}async function Ml(e,t){return tg(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":eg(n,".well-known/openid-configuration");break;case"oauth2":Qh(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',ve)}return n},t)}function Kn(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw K(`${n} must be a number`,Oe,o);if(e>0)return;if(t){if(e!==0)throw K(`${n} must be a non-negative number`,ve,o);return}throw K(`${n} must be a positive number`,ve,o)}catch(i){throw r?N(i.message,r,o):i}}function ye(e,t,n,r){try{if(typeof e!="string")throw K(`${t} must be a string`,Oe,r);if(e.length===0)throw K(`${t} must not be empty`,ve,r)}catch(o){throw n?N(o.message,n,r):o}}async function Zl(e,t){let n=e;if(!(n instanceof URL)&&n!==yo)throw K('"expectedIssuerIdentifier" must be an instance of URL',Oe);if(!Qn(t,Response))throw K('"response" must be an instance of Response',Oe);if(t.status!==200)throw N('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',ko,t);Ra(t);let r=await rd(t);if(ye(r.issuer,'"response" body "issuer" property',G,{body:r}),n!==yo&&new URL(r.issuer).href!==n.href)throw N('"response" body "issuer" property does not match the expected value',Io,{expected:n.href,body:r,attribute:"issuer"});return r}function Bl(e){rg(e,"application/json")}function ng(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return N(n,Oa,e)}function rg(e,t){if(Ta(e)!==t)throw ng(e,t)}function og(){return $a(crypto.getRandomValues(new Uint8Array(32)))}function Fl(){return og()}function Ea(e){let t=e?.[vo];return typeof t=="number"&&Number.isFinite(t)?t:0}function ka(e){let t=e?.[bo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Ia(){return Math.floor(Date.now()/1e3)}function _o(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',Oe);ye(e.issuer,'"as.issuer"')}function wo(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',Oe);ye(e.client_id,'"client.client_id"')}function Aa(e){return ye(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function Hl(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var ig=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function xo(e,t){if(t&&e.protocol!=="https:")throw N("only requests to HTTPS are allowed",Ua,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw N("only HTTP and HTTPS requests are allowed",Da,e)}function Nl(e,t,n,r){let o;if(typeof e!="string"||!(o=ig(e)))throw N(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Pg:zg,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return xo(o,r),o}function $o(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Nl(e.mtls_endpoint_aliases[t],t,n,r):Nl(e[t],t,n,r)}function Jl(e){if(e instanceof an){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof on?e.error==="use_dpop_nonce":!1}var on=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ag,this.cause=n.cause,this.error=n.cause.error,this.status=n.response.status,this.error_description=n.cause.error_description,Object.defineProperty(this,"response",{enumerable:!1,value:n.response}),Error.captureStackTrace?.(this,this.constructor)}},Xn=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Tg,this.cause=n.cause,this.error=n.cause.get("error"),this.error_description=n.cause.get("error_description")??void 0,Error.captureStackTrace?.(this,this.constructor)}},an=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Ig,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},go="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ag="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",sg='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',cg="("+go+")\\s*=\\s*"+sg,ug="("+go+")\\s*=\\s*("+go+")",lg=new RegExp("^[,\\s]*("+go+")"),dg=new RegExp("^[,\\s]*"+cg+"[,\\s]*(.*)"),fg=new RegExp("^[,\\s]*"+ug+"[,\\s]*(.*)"),pg=new RegExp("^("+ag+")(?:$|[,\\s])(.*)");function mg(e){if(!Qn(e,Response))throw K('"response" must be an instance of Response',Oe);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(lg),i=o?.[1].toLowerCase();if(!i)return;let a=r.substring(o[0].length);if(a&&!a.match(/^[\s,]/))return;let s=a.match(/^\s+(.*)$/),u=!!s;r=s?s[1]:void 0;let c={},l;if(u)for(;r;){let p,b;if(o=r.match(dg)){if([,p,b,r]=o,b.includes("\\"))try{b=JSON.parse(`"${b}"`)}catch{}c[p.toLowerCase()]=b;continue}if(o=r.match(fg)){[,p,b,r]=o,c[p.toLowerCase()]=b;continue}if(o=r.match(pg)){if(Object.keys(c).length)break;[,l,r]=o;break}return}else r=a||void 0;let d={scheme:i,parameters:c};l&&(d.token68=l),n.push(d)}if(n.length)return n}async function hg(e){if(e.status>399&&e.status<500){Ra(e),Bl(e);try{let t=await e.clone().json();if(ho(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function Gl(e,t,n){if(e.status!==t){bg(e);let r;throw(r=await hg(e))?(await e.body?.cancel(),new on("server responded with an error in the response body",{cause:r,response:e})):N(`"response" is not a conform ${n} response (unexpected HTTP status code)`,ko,e)}}function gg(e){if(!Pa.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',ve)}function Ta(e){return e.headers.get("content-type")?.split(";")[0]}async function Vl(e,t,n,r,o,i,a){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[kt]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Cl(r,a?.signal)})}async function yg(e,t,n,r,o,i){let a=$o(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[Et]!==!0);o.set("grant_type",r);let s=Sa(i?.headers);s.set("accept","application/json"),i?.DPoP!==void 0&&(gg(i.DPoP),await i.DPoP.addProof(a,s,"POST"));let u=await Vl(e,t,n,a,o,s,i);return i?.DPoP?.cacheNonce(u,a),u}var ql=new WeakMap,vg=new WeakMap;function So(e){if(!e.id_token)return;let t=ql.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',ve);return t}async function Kl(e,t,n,r,o,i){if(_o(e),wo(t),!Qn(n,Response))throw K('"response" must be an instance of Response',Oe);await Gl(n,200,"Token Endpoint"),Ra(n);let a=await rd(n);if(ye(a.access_token,'"response" body "access_token" property',G,{body:a}),ye(a.token_type,'"response" body "token_type" property',G,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let s=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Kn(s,!0,'"response" body "expires_in" property',G,{body:a}),a.expires_in=s}if(a.refresh_token!==void 0&&ye(a.refresh_token,'"response" body "refresh_token" property',G,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw N('"response" body "scope" property must be a string',G,{body:a});if(a.id_token!==void 0){ye(a.id_token,'"response" body "id_token" property',G,{body:a});let s=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&s.push("auth_time"),t.default_max_age!==void 0&&(Kn(t.default_max_age,!0,'"client.default_max_age"'),s.push("auth_time")),r?.length&&s.push(...r);let{claims:u,jwt:c}=await Og(a.id_token,Dg.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Ea(t),ka(t),o).then(Sg.bind(void 0,s)).then(wg.bind(void 0,e)).then(_g.bind(void 0,t.client_id));if(Array.isArray(u.aud)&&u.aud.length!==1){if(u.azp===void 0)throw N('ID Token "aud" (audience) claim includes additional untrusted audiences',Ve,{claims:u,claim:"aud"});if(u.azp!==t.client_id)throw N('unexpected ID Token "azp" (authorized party) claim value',Ve,{expected:t.client_id,claims:u,claim:"azp"})}u.auth_time!==void 0&&Kn(u.auth_time,!0,'ID Token "auth_time" (authentication time)',G,{claims:u}),vg.set(n,c),ql.set(a,u)}if(i?.[a.token_type]!==void 0)i[a.token_type](n,a);else if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new pt("unsupported `token_type` value",{cause:{body:a}});return a}function bg(e){let t;if(t=mg(e))throw new an("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function _g(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw N('unexpected JWT "aud" (audience) claim value',Ve,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw N('unexpected JWT "aud" (audience) claim value',Ve,{expected:e,claims:t.claims,claim:"aud"});return t}function wg(e,t){let n=e[ja]?.(t)??e.issuer;if(t.claims.iss!==n)throw N('unexpected JWT "iss" (issuer) claim value',Ve,{expected:n,claims:t.claims,claim:"iss"});return t}var Pa=new WeakSet;function xg(e){return Pa.add(e),e}var za=Symbol();async function Wl(e,t,n,r,o,i,a){if(_o(e),wo(t),!Pa.has(r))throw K('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ve);ye(o,'"redirectUri"');let s=St(r,"code");if(!s)throw N('no authorization code in "callbackParameters"',G);let u=new URLSearchParams(a?.additionalParameters);return u.set("redirect_uri",o),u.set("code",s),i!==za&&(ye(i,'"codeVerifier"'),u.set("code_verifier",i)),yg(e,t,n,"authorization_code",u,a)}var $g={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Sg(e,t){for(let n of e)if(t.claims[n]===void 0)throw N(`JWT "${n}" (${$g[n]}) claim missing`,G,{claims:t.claims});return t}var va=Symbol(),ba=Symbol();async function Xl(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Eg(e,t,n,r.expectedNonce,r.maxAge,r[mo],r.recognizedTokenTypes):kg(e,t,n,r?.[mo],r?.recognizedTokenTypes)}async function Eg(e,t,n,r,o,i,a){let s=[];switch(r){case void 0:r=va;break;case va:break;default:ye(r,'"expectedNonce" argument'),s.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=ba;break;case ba:break;default:Kn(o,!0,'"maxAge" argument'),s.push("auth_time")}let u=await Kl(e,t,n,s,i,a);ye(u.id_token,'"response" body "id_token" property',G,{body:u});let c=So(u);if(o!==ba){let l=Ia()+Ea(t),d=ka(t);if(c.auth_time+o<l-d)throw N("too much time has elapsed since the last End-User authentication",sn,{claims:c,now:l,tolerance:d,claim:"auth_time"})}if(r===va){if(c.nonce!==void 0)throw N('unexpected ID Token "nonce" claim value',Ve,{expected:void 0,claims:c,claim:"nonce"})}else if(c.nonce!==r)throw N('unexpected ID Token "nonce" claim value',Ve,{expected:r,claims:c,claim:"nonce"});return u}async function kg(e,t,n,r,o){let i=await Kl(e,t,n,void 0,r,o),a=So(i);if(a){if(t.default_max_age!==void 0){Kn(t.default_max_age,!0,'"client.default_max_age"');let s=Ia()+Ea(t),u=ka(t);if(a.auth_time+t.default_max_age<s-u)throw N("too much time has elapsed since the last End-User authentication",sn,{claims:a,now:s,tolerance:u,claim:"auth_time"})}if(a.nonce!==void 0)throw N('unexpected ID Token "nonce" claim value',Ve,{expected:void 0,claims:a,claim:"nonce"})}return i}var Ig="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ag="OAUTH_RESPONSE_BODY_ERROR",Eo="OAUTH_UNSUPPORTED_OPERATION",Tg="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Yn="OAUTH_PARSE_ERROR",G="OAUTH_INVALID_RESPONSE";var Oa="OAUTH_RESPONSE_IS_NOT_JSON",ko="OAUTH_RESPONSE_IS_NOT_CONFORM",Ua="OAUTH_HTTP_REQUEST_FORBIDDEN",Da="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",sn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Ve="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Io="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Pg="OAUTH_MISSING_SERVER_METADATA",zg="OAUTH_INVALID_SERVER_METADATA";async function Yl(e,t,n,r,o){_o(e),wo(t),ye(r,'"token"');let i=$o(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[Et]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let s=Sa(o?.headers);return s.delete("accept"),Vl(e,t,n,i,a,s,o)}async function Ql(e){if(!Qn(e,Response))throw K('"response" must be an instance of Response',Oe);await Gl(e,200,"Revocation Endpoint")}function Ra(e){if(e.bodyUsed)throw K('"response" body has been used already',ve)}async function Og(e,t,n,r,o){let{0:i,1:a,length:s}=e.split(".");if(s===5)if(o!==void 0)e=await o(e),{0:i,1:a,length:s}=e.split(".");else throw new pt("JWE decryption is not configured",{cause:e});if(s!==3)throw N("Invalid JWT",G,e);let u;try{u=JSON.parse(jl($a(i)))}catch(d){throw N("failed to parse JWT Header body as base64url encoded JSON",Yn,d)}if(!ho(u))throw N("JWT Header must be a top level object",G,e);if(t(u),u.crit!==void 0)throw new pt('no JWT "crit" header parameter extensions are supported',{cause:{header:u}});let c;try{c=JSON.parse(jl($a(a)))}catch(d){throw N("failed to parse JWT Payload body as base64url encoded JSON",Yn,d)}if(!ho(c))throw N("JWT Payload must be a top level object",G,e);let l=Ia()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw N('unexpected JWT "exp" (expiration time) claim type',G,{claims:c});if(c.exp<=l-r)throw N('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',sn,{claims:c,now:l,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw N('unexpected JWT "iat" (issued at) claim type',G,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw N('unexpected JWT "iss" (issuer) claim type',G,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw N('unexpected JWT "nbf" (not before) claim type',G,{claims:c});if(c.nbf>l+r)throw N('unexpected JWT "nbf" (not before) claim value',sn,{claims:c,now:l,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw N('unexpected JWT "aud" (audience) claim type',G,{claims:c});return{header:u,claims:c,jwt:e}}async function Ug(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",ve,{cause:e});return e.text()}async function ed(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",ve,{cause:e});if(Ta(e)!=="application/x-www-form-urlencoded")throw K("form_post responses are expected to use the application/x-www-form-urlencoded content-type",ve,{cause:e});return Ug(e)}function Dg(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:t,reason:"authorization server metadata"});return}if(n!==void 0){if(typeof n=="string"?r.alg!==n:typeof n=="function"?!n(r.alg):!n.includes(r.alg))throw N('unexpected JWT "alg" header parameter',G,{header:r,expected:n,reason:"default value"});return}throw N('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function St(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw N(`"${t}" parameter must be provided only once`,G);return n}var td=Symbol(),Rg=Symbol();function nd(e,t,n,r){if(_o(e),wo(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw K('"parameters" must be an instance of URLSearchParams, or URL',Oe);if(St(n,"response"))throw N('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',G,{parameters:n});let o=St(n,"iss"),i=St(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw N('response parameter "iss" (issuer) missing',G,{parameters:n});if(o&&o!==e.issuer)throw N('unexpected "iss" (issuer) response parameter value',G,{expected:e.issuer,parameters:n});switch(r){case void 0:case Rg:if(i!==void 0)throw N('unexpected "state" response parameter encountered',G,{expected:void 0,parameters:n});break;case td:break;default:if(ye(r,'"expectedState" argument'),i!==r)throw N(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',G,{expected:r,parameters:n})}if(St(n,"error"))throw new Xn("authorization response from the server is an error",{cause:n});let s=St(n,"id_token"),u=St(n,"token");if(s!==void 0||u!==void 0)throw new pt("implicit and hybrid flows are not supported");return xg(new URLSearchParams(n))}async function rd(e,t=Bl){let n;try{n=await e.json()}catch(r){throw t(e),N('failed to parse "response" body as JSON',Yn,r)}if(!ho(n))throw N('"response" body must be a top level object',G,{body:n});return n}var yo=Symbol(),ja=Symbol();var tr,od;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(od="openid-client/v6.8.1",tr={"user-agent":od});var Le=e=>Ca.get(e),Ca,Na;function Ng(e){return e!==void 0?Aa(e):(Na||=new WeakMap,(t,n,r,o)=>{let i;return(i=Na.get(n))||(Cg(n.client_secret,'"metadata.client_secret"'),i=Aa(n.client_secret),Na.set(n,i)),i(t,n,r,o)})}function Cg(e,t){if(typeof e!="string")throw qe(`${t} must be a string`,rr);if(e.length===0)throw qe(`${t} must not be empty`,nr)}function Lg(){return Hl()}var cn=kt;var nr="ERR_INVALID_ARG_VALUE",rr="ERR_INVALID_ARG_TYPE";function qe(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function ad(){return Fl()}var un=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},uP=new TextDecoder;function me(e,t,n){return new un(e,{cause:t,code:n})}function er(e){if(e instanceof TypeError||e instanceof un||e instanceof on||e instanceof Xn||e instanceof an)throw e;if(e instanceof Wn)switch(e.code){case Ua:throw me("only requests to HTTPS are allowed",e,e.code);case Da:throw me("only requests to HTTP or HTTPS are allowed",e,e.code);case ko:throw me("unexpected HTTP response status code",e.cause,e.code);case Oa:throw me("unexpected response content-type",e.cause,e.code);case Yn:throw me("parsing error occured",e,e.code);case G:throw me("invalid response encountered",e,e.code);case Ve:throw me("unexpected JWT claim value encountered",e,e.code);case Io:throw me("unexpected JSON attribute value encountered",e,e.code);case sn:throw me("JWT timestamp claim value failed validation",e,e.code);default:throw me(e.message,e,e.code)}if(e instanceof pt)throw me("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw me("runtime operation error",e,Eo);case"NotSupportedError":throw me("runtime unsupported operation",e,Eo);case"TimeoutError":throw me("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw me("operation aborted",e,"OAUTH_ABORT")}throw new un("something went wrong",{cause:e})}function Mg(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[cd]=!0,!0):!1}function Zg(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function sd(e,t,n,r,o){let i=await Bg(e,o),a=new ln(i,t,n,r),s=Le(a);if(o?.[cn]&&(s.fetch=o[cn]),o?.timeout&&(s.timeout=o.timeout),o?.execute)for(let u of o.execute)u(a);return a}async function Bg(e,t){if(!(e instanceof URL))throw qe('"server" must be an instance of URL',rr);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?Ml(e,{algorithm:t?.algorithm,[kt]:t?.[cn],[Et]:t?.execute?.includes(id),signal:o,headers:new Headers(tr)}):(t?.[cn]||fetch)((xo(e,!t?.execute?.includes(id)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...tr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Zl(yo,a)).catch(er);return n&&new URL(i.issuer).href!==e.href&&(Mg(e,i,t)||Zg(e,t)||(()=>{throw new un("discovered metadata issuer does not match the expected issuer",{code:Io,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Fg(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Hg(e){Object.defineProperties(e,Fg(e))}var cd=Symbol(),ln=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw qe('"clientId" must be a non-empty string',rr);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw qe('"clientId" and "metadata.client_id" must be the same',nr);let i={...structuredClone(r),client_id:n};i[vo]=r?.[vo]??0,i[bo]=r?.[bo]??30;let a;o?a=o:typeof i.client_secret=="string"&&i.client_secret.length?a=Ng(i.client_secret):a=Lg();let s=Object.freeze(i),u=structuredClone(t);cd in t&&(u[ja]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let c=Object.freeze(u);Ca||=new WeakMap,Ca.set(this,{__proto__:null,as:c,c:s,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(Le(this).as);return Hg(t),t}clientMetadata(){return structuredClone(Le(this).c)}get timeout(){return Le(this).timeout}set timeout(t){Le(this).timeout=t}get[cn](){return Le(this).fetch}set[cn](t){Le(this).fetch=t}};Object.freeze(ln.prototype);function Jg(e){let t;if(e.expires_in!==void 0){let n=new Date;n.setSeconds(n.getSeconds()+e.expires_in),t=n.getTime()}return{expiresIn:{__proto__:null,value(){if(t){let n=Date.now();return t>n?Math.floor((t-n)/1e3):0}}},claims:{__proto__:null,value(){try{return So(this)}catch{return}}}}}function Gg(e){Object.defineProperties(e,Jg(e))}function id(e){Le(e).tlsOnly=!1}function Vg(e){return e=new URL(e),e.search="",e.hash="",e.href}function qg(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function La(e,t,n,r,o){if(Ma(e),o?.flag!==Ao&&!(t instanceof URL)&&!qg(t,"Request"))throw qe('"currentUrl" must be an instance of URL, or Request',rr);let i,a,{as:s,c:u,auth:c,fetch:l,tlsOnly:d,jarm:p,hybrid:b,nonRepudiation:f,timeout:g,decrypt:v,implicit:k}=Le(e);if(o?.flag===Ao)i=o.authResponse,a=o.redirectUri;else{if(!(t instanceof URL)){let x=t;switch(t=new URL(t.url),x.method){case"GET":break;case"POST":let O=new URLSearchParams(await ed(x));if(b)t.hash=O.toString();else for(let[M,B]of O.entries())t.searchParams.append(M,B);break;default:throw qe("unexpected Request HTTP method",nr)}}switch(a=Vg(t),!0){case!!p:i=await p(t,n?.expectedState);break;case!!b:i=await b(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!k:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=nd(s,u,t.searchParams,n?.expectedState)}catch(x){er(x)}}}let A=await Wl(s,u,c,i,a,n?.pkceCodeVerifier||za,{additionalParameters:r,[kt]:l,[Et]:!d,DPoP:o?.DPoP,headers:new Headers(tr),signal:ld(g)}).catch(er);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let w=Xl(s,u,A,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[mo]:v}),S;try{S=await w}catch(x){if(Kg(x,o))return La(e,void 0,n,r,{...o,flag:Ao,authResponse:i,redirectUri:a});er(x)}return S.id_token&&await f?.(A),Gg(S),S}function ud(e,t){Ma(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:a,implicit:s}=Le(e),u=$o(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw qe("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",nr);a&&t.set("response_mode","jwt")}for(let[c,l]of t.entries())u.searchParams.append(c,l);return u}function Ma(e){if(!(e instanceof ln))throw qe('"config" must be an instance of Configuration',rr);if(Object.getPrototypeOf(e)!==ln.prototype)throw qe("subclassing Configuration is not allowed",nr)}function ld(e){return e?AbortSignal.timeout(e*1e3):void 0}function Kg(e,t){return t?.DPoP&&t.flag!==Ao?Jl(e):!1}var Ao=Symbol();async function dd(e,t,n){Ma(e);let{as:r,c:o,auth:i,fetch:a,tlsOnly:s,timeout:u}=Le(e);return Yl(r,o,i,t,{[kt]:a,[Et]:!s,additionalParameters:new URLSearchParams(n),headers:new Headers(tr),signal:ld(u)}).then(Ql).catch(er)}var fd="oauth2:",or="graffiti-auth-oauth2-data",To=class{eventTarget=new EventTarget;constructor(){let t=this.completeOauth();(async()=>{await new Promise(r=>setTimeout(r,0)),await t;let n=new CustomEvent("initialized");this.eventTarget.dispatchEvent(n)})()}async login(...t){try{await this.login_(...t)}catch(n){let r=n instanceof Error?n:new Error("Unknown error"),o={loginId:t[1],error:r};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:o}))}}async login_(t,n,r){let o=await this.getAuthorizationConfiguration(t),i=r.map(encodeURIComponent).join(" "),a=ad(),s,u;if(typeof window<"u"){s=window.location.href;let d={loginId:n,redirectUri:s,authorizationEndpoint:t,state:a,serviceEndpoints:r};window.localStorage.setItem(or,JSON.stringify(d))}else{let p=(await import("node:http").catch(f=>{throw new Error("Unrecognized environment: cannot find window or node:http")})).createServer();try{await new Promise((f,g)=>{p.once("error",g),p.listen(0,"::1",f)})}catch{try{p.close()}catch{}throw new Error("Failed to start local oauth callback server.")}let b=p.address();if(!b){try{p.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}s=typeof b=="string"?`http://${b}`:`http://${b.family==="IPv6"?`[${b.address}]`:b.address}:${b.port}`,u=new Promise((f,g)=>{let v=setTimeout(()=>{try{p.close()}catch{}g("Oauth callback timed out.")},3e5),k=new Set;p.on("connection",w=>{k.add(w),w.on("close",()=>{k.delete(w)})});let A=async(w,S)=>{try{let x=new URL(w.url??"/",s);await this.onCallbackUrl({loginId:n,callbackUrl:x,configuration:o,expectedState:a,serviceEndpoints:r}),S.statusCode=200,S.setHeader("Content-Type","text/plain"),S.end("You may now close this window.")}catch(x){throw S.statusCode=500,S.setHeader("Content-Type","text/plain"),S.end("Error processing OAuth callback."),x}finally{clearTimeout(v),p.off("request",A);for(let x of k)x.destroy();p.close(()=>f())}};p.on("request",A)})}let c=new URL(s);c.hash="",c.search="";let l=ud(o,{scope:i,redirect_uri:c.toString(),state:a});typeof window<"u"?window.location.href=l.toString():(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await u)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(or);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(or);return}let r=Wg.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(or);return}let{loginId:o,redirectUri:i,authorizationEndpoint:a,state:s,serviceEndpoints:u}=r.data;try{let c=new URL(i),l=new URL(window.location.href);if(c.pathname!==l.pathname)return;let d=l.searchParams;return!d.has("code")&&!d.has("error")?void 0:(window.history.replaceState({},document.title,c.toString()),window.localStorage.removeItem(or),new Promise(p=>setTimeout(p,0)).then(()=>this.getAuthorizationConfiguration(a)).then(p=>this.onCallbackUrl({loginId:o,callbackUrl:l,configuration:p,expectedState:s,serviceEndpoints:u})).catch(p=>{let b=p instanceof Error?p:new Error("Unknown error"),f={loginId:o,error:b};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:f}))}))}catch(c){console.error(c)}}async onCallbackUrl(t){let{loginId:n,callbackUrl:r,configuration:o,expectedState:i,serviceEndpoints:a}=t,s=await La(o,r,{expectedState:i}),u=s.access_token,l=s.scope?.split(" ").map(decodeURIComponent)||a;if(!a.every(p=>l.includes(p)))throw new Error("Not all requested service endpoints were granted.");let d=new CustomEvent("login",{detail:{loginId:n,token:u}});this.eventTarget.dispatchEvent(d)}async logout(t,n,r){try{await this.logout_(t,n,r)}catch(o){let i=o instanceof Error?o:new Error("Unknown error"),a={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:a}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await dd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(fd))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(fd.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await sd(r,"graffiti-client")}},pd=_c(be({loginId:H()}),ut([be({token:H(),error:X(bc())}),be({error:Nt(Error)})])),md=be({logoutId:H(),error:X(Nt(Error))}),hd=X(Me(be({error:X(Nt(Error))}))),Wg=be({loginId:H(),redirectUri:J(),authorizationEndpoint:J(),state:H(),serviceEndpoints:V(J())});var Xg="https://";function Ue(e){if(!e.startsWith(Xg))throw new Error("Unrecognized storage bucket endpoint type")}async function Po(e){Ue(e);let t=`${e}/auth`,n=await fetch(t);if(!n.ok)throw new Error("Failed to get storage bucket authorization endpoint");return await n.text()}var Za=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function Ke(...e){let t=await fetch(...e);if(!t.ok){let n;try{n=await t.text()}catch{n=t.statusText}throw t.status===401?new Za(n):t.status===403?new st(n):t.status===404?new Q(n):t.status===410?new De(n):t.status===413?new Rt(n):new Error(n)}return t}var zo=class{getAuthorizationEndpoint=Po;async put(t,n,r,o){Ue(t);let i=`${t}/value/${encodeURIComponent(n)}`;await Ke(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){Ue(t);let o=`${t}/value/${encodeURIComponent(n)}`;await Ke(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){Ue(t);let o=`${t}/value/${encodeURIComponent(n)}`,i=await Ke(o),a=i.body?.getReader();if(!a)throw new Error("Failed to read value from storage bucket");let s=i.headers.get("Content-Length"),u=s?Number(s):void 0;if(!!u&&!!Number.isFinite(u)&&u>=0){let f=u;if(r!==void 0&&f>r)throw new Error("Value exceeds maximum byte limit");let g=new Uint8Array(f),v=0,k=!1;try{for(;v<=g.length;){let{done:A,value:w}=await a.read();if(A){k=!0;break}if(!w||w.length===0)continue;let S=v+w.length;if(S>g.length)throw new Error("Received more data than expected");g.set(w,v),v=S}}finally{a.releaseLock()}if(!k)throw new Error("Failed to read complete value from storage bucket");return v===f?g:g.slice(0,v)}let l=[],d=0;try{for(;;){let{done:f,value:g}=await a.read();if(f)break;if(!(!g||g.length===0)){if(d+=g.length,r!==void 0&&d>r)throw new Error("Value exceeds maximum byte limit");l.push(g.slice())}}}finally{a.releaseLock()}let p=new Uint8Array(d),b=0;for(let f of l)p.set(f,b),b+=f.length;return p}async*export(t,n){Ue(t);let r=`${t}/export`,o;for(;;){let a=await(await Ke(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),s=He(await a.arrayBuffer()),u=Yg.parse(s);for(let c of u.keys)yield{key:c};if(u.cursor)o=u.cursor;else break}}},Yg=be({keys:V(H()),cursor:X(Me(H()))});var Uo=class{getAuthorizationEndpoint=Po;cache_=null;get cache(){return this.cache_||(this.cache_=iy()),this.cache_}async send(t,n){Ue(t);let r=`${t}/send`,i=await(await Ke(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(Ee({m:n}))})).blob(),a=He(await i.arrayBuffer());return ny.parse(a).id}async get(t,n,r){let o=Oo(t,n),i=await this.cache,a=await i.messages.get(o);if(a!==void 0)return a;let s=`${t}/message/${n}`,u=null;try{u=await Ke(s,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(p){if(p instanceof Q)return await i.messages.set(o,null),null;throw p}let c=await u.blob(),l=He(await c.arrayBuffer()),d=_d.parse(l);return await i.messages.set(o,d),d}async label(t,n,r,o){if(Ue(t),o){let u=`${t}/label/${n}`;await Ke(u,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(Ee({l:r}))})}let i=await this.cache,a=Oo(t,n),s=await i.messages.get(a);s&&await i.messages.set(a,{...s,l:r})}async fetchMessageBatch(t,n,r,o,i){let a=await Ke(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r}),s=a.headers.get("Retry-After"),u=s?parseInt(s):void 0,c=u&&Number.isFinite(u)?Date.now()+u*1e3:void 0;return{response:a,waitTil:c}}async*yieldFromCache(t,n,r,o,i=0){let a=o.messageIds.slice(i);yield*await Promise.all(a.map(async u=>{let c=await t.messages.get(Oo(n,u));if(!c){try{await t.messageIds.del(r)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return c}))}async*lockedMessageStreamer(...t){if(typeof window>"u"||!await wd()){let f=this.messageStreamer(...t);for(;;){let g=await f.next();if(g.done)return g.value;yield g.value}}let n=await t[0],r=`graffiti:inbox:${n}`,o=()=>{},i=!1;if(await new Promise(f=>{window.navigator.locks.request(r,{mode:"exclusive",ifAvailable:!0},async g=>{i=!!g,f(),await new Promise(v=>o=v)})}),i)try{let f=this.messageStreamer(...t);for(;;){let g=await f.next();if(g.done)return g.value;yield g.value}}finally{o()}o(),await window.navigator.locks.request(r,()=>{});let a=t[1],s=t[5]??{},u=t[6],c=t[7],l=await this.cache,d=await l.messageIds.get(n);if(!d)throw new Error("Cache not found");if(u!==void 0&&u!==d.version)throw new De("Cursor is stale");let p=this.yieldFromCache(l,a,n,d,c);for await(let f of p)yield f;let b={numSeen:d.messageIds.length,version:d.version,messageIdsCacheKey:n,objectSchema:s};return JSON.stringify(b)}async*messageStreamer(t,n,r,o,i,a={},s,u=0){let c=await hr(a),l=await t,d=await this.cache,p=await d.messageIds.get(l);if(s!==void 0&&s!==p?.version)throw new De("Cursor is stale");let b=p?.waitTil;await vd(b);let f=p?.cursor,g;try{let x=await this.fetchMessageBatch(n,r,o,i,f);g=x.response,b=x.waitTil}catch(x){if(!(x instanceof De&&f))throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(O=>setTimeout(O,5e3)),x;if(await d.messageIds.del(l),s===void 0)p=void 0;else throw x}if(g!==void 0&&p){let x=this.yieldFromCache(d,n,l,p,u);for await(let O of x)yield O}if(g===void 0){let x=await this.fetchMessageBatch(n,r,o,i);g=x.response,b=x.waitTil}let v=g,k,A=p?.version??crypto.randomUUID(),w=p?.messageIds??[];for(;;){let x=await v.blob(),O=He(await x.arrayBuffer()),{results:M,hasMore:B,cursor:ie}=ry.parse(O);k=ie;let Ae=M.map(_=>{let z=_[It][ot];if(!c(z))throw new Error("Server returned data that does not match schema");return{..._,[It]:{..._[It],[ot]:z}}});await Promise.all(Ae.map(_=>d.messages.set(Oo(n,_[Ba]),_))),w=[...w,...Ae.map(_=>_[Ba])],await d.messageIds.set(l,{cursor:k,version:A,messageIds:w,waitTil:b}),u+=Ae.length;for(let _ of Ae)yield _;if(!B)break;await vd(b);let h=await this.fetchMessageBatch(n,r,void 0,i,k);v=h.response,b=h.waitTil}return JSON.stringify({numSeen:u,version:A,messageIdsCacheKey:l,objectSchema:a})}query(t,n,r,o){Ue(t);let i=Ee({tags:n,schema:r}),a=gd(t,"query",i);return this.lockedMessageStreamer(a,t,"query",new Uint8Array(i),o,r)}continueQuery(t,n,r){Ue(t);let o=JSON.parse(n),{messageIdsCacheKey:i,numSeen:a,objectSchema:s,version:u}=oy.parse(o);return this.lockedMessageStreamer(Promise.resolve(i),t,"query",void 0,r,s,u,a)}export(t,n){Ue(t);let r=gd(t,"export");return this.lockedMessageStreamer(r,t,"export",void 0,n)}},Qg=_e({value:he({}),channels:V(H()),allowed:X(Me(V(J()))),url:J(),actor:J()}),bd=_t(e=>e instanceof Uint8Array),ey=V(bd),ir="t",ot="o",ar="m",ty=_e({[ir]:ey,[ot]:Qg,[ar]:bd}),Ba="id",It="m",Do="l",_d=_e({[Ba]:H(),[It]:ty,[Do]:yc()}),ny=_e({id:H()}),ry=_e({results:V(_d),hasMore:$i(),cursor:H()}),oy=_e({messageIdsCacheKey:H(),version:H(),numSeen:jt().check(bt()),objectSchema:ut([he({}),$i()])});async function wd(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function Oo(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function gd(e,t,n){let r=Ee({inboxUrl:e,type:t,body:n??null});return crypto.subtle.digest("SHA-256",new Uint8Array(r)).then(o=>Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join(""))}async function yd(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function iy(){if(await wd()){let{openDB:n}=await import("./build-BXWPS7VK.js"),r=await n("graffiti-inbox-cache",1,{upgrade(o){o.objectStoreNames.contains("m")||o.createObjectStore("m"),o.objectStoreNames.contains("q")||o.createObjectStore("q")}});return{messages:{get:async o=>{try{return r.get("m",o)}catch(i){console.error("Error getting message from cache:",i),console.error("resetting cache..."),await yd();return}},set:async(o,i)=>{await r.put("m",i,o)},del:o=>r.delete("m",o)},messageIds:{get:async o=>{try{return await r.get("q",o)}catch(i){console.error("Error getting message IDs from cache:",i),console.error("resetting cache..."),await yd();return}},set:async(o,i)=>{await r.put("q",i,o)},del:o=>r.delete("q",o)}}}let e=new Map,t=new Map;return{messages:{get:async n=>e.get(n),set:async(n,r)=>{e.set(n,r)},del:async n=>{e.delete(n)}},messageIds:{get:async n=>t.get(n),set:async(n,r)=>{t.set(n,r)},del:async n=>{t.delete(n)}}}}async function vd(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var dn="base64url";var Ro=class{async encode(t,n){if(t!==dn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function xd(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function $d(e,t,n){let r=async o=>{Ar(o);let i=xd();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},r}function ay(e){if(Ic(e),typeof e.webCryptoName!="string")throw new Error("non-web hash")}var At=$d("SHA-256",64,32);var Sd=$d("SHA-512",128,64),Fa=(()=>{let e=async(t,n,r)=>{let o=xd();Ar(n,void 0,"key"),Ar(r,void 0,"message"),ay(t);let i=await o.importKey("raw",n,{name:"HMAC",hash:t.webCryptoName},!1,["sign"]);return new Uint8Array(await o.sign("HMAC",i,r))};return e.create=(t,n)=>{throw new Error("not implemented")},e})();var jo="sha2-256",sr=18,fn=32,No=class{async register(t,n){if(t!==jo)throw new Error(`Unsupported content address method: ${t}`);let r=await At(n),o=new Uint8Array(2+r.length);return o[0]=sr,o[1]=fn,o.set(r,2),o}async getMethod(t){if(t[0]===sr&&t[1]===fn&&t.length===2+fn)return jo;throw new Error("Unrecognized content address format.")}};var zd={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:le,n:Co,Gx:Ed,Gy:kd,a:Ha,d:Ja,h:sy}=zd,Pt=32,cr=64,cy=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{let t=new Error(e);throw cy(t,se),t},uy=e=>typeof e=="bigint",ly=e=>typeof e=="string",dy=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",Xe=(e,t,n="")=>{let r=dy(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;se(a+"expected Uint8Array"+s+", got "+u)}return e},Ka=e=>new Uint8Array(e),Od=e=>Uint8Array.from(e),Ud=(e,t)=>e.toString(16).padStart(t,"0"),Dd=e=>Array.from(Xe(e)).map(t=>Ud(t,2)).join(""),it={_0:48,_9:57,A:65,F:70,a:97,f:102},Id=e=>{if(e>=it._0&&e<=it._9)return e-it._0;if(e>=it.A&&e<=it.F)return e-(it.A-10);if(e>=it.a&&e<=it.f)return e-(it.a-10)},Rd=e=>{let t="hex invalid";if(!ly(e))return se(t);let n=e.length,r=n/2;if(n%2)return se(t);let o=Ka(r);for(let i=0,a=0;i<r;i++,a+=2){let s=Id(e.charCodeAt(a)),u=Id(e.charCodeAt(a+1));if(s===void 0||u===void 0)return se(t);o[i]=s*16+u}return o},fy=()=>globalThis?.crypto,py=()=>fy()?.subtle??se("crypto.subtle must be defined, consider polyfill"),ur=(...e)=>{let t=Ka(e.reduce((r,o)=>r+Xe(o).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t};var Lo=BigInt,Tt=(e,t,n,r="bad number: out of range")=>uy(e)&&t<=e&&e<n?e:se(r),I=(e,t=le)=>{let n=e%t;return n>=0n?n:t+n},jd=e=>I(e,Co),my=(e,t)=>{(e===0n||t<=0n)&&se("no inverse n="+e+" mod="+t);let n=I(e,t),r=t,o=0n,i=1n,a=1n,s=0n;for(;n!==0n;){let u=r/n,c=r%n,l=o-a*u,d=i-s*u;r=n,n=c,o=a,i=s,a=l,s=d}return r===1n?I(o,t):se("no inverse")};var Ga=e=>e instanceof at?e:se("Point expected"),Va=2n**256n,at=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=Va;this.X=Tt(t,0n,i),this.Y=Tt(n,0n,i),this.Z=Tt(r,1n,i),this.T=Tt(o,0n,i),Object.freeze(this)}static CURVE(){return zd}static fromAffine(t){return new e(t.x,t.y,1n,I(t.x*t.y))}static fromBytes(t,n=!1){let r=Ja,o=Od(Xe(t,Pt)),i=t[31];o[31]=i&-129;let a=Wa(o);Tt(a,0n,n?Va:le);let u=I(a*a),c=I(u-1n),l=I(r*u+1n),{isValid:d,value:p}=gy(c,l);d||se("bad point: y not sqrt");let b=(p&1n)===1n,f=(i&128)!==0;return!n&&p===0n&&f&&se("bad point: x==0, isLastByteOdd"),f!==b&&(p=I(-p)),new e(p,a,1n,I(p*a))}static fromHex(t,n){return e.fromBytes(Rd(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ha,n=Ja,r=this;if(r.is0())return se("bad point: ZERO");let{X:o,Y:i,Z:a,T:s}=r,u=I(o*o),c=I(i*i),l=I(a*a),d=I(l*l),p=I(u*t),b=I(l*I(p+c)),f=I(d+I(n*I(u*c)));if(b!==f)return se("bad point: equation left != right (1)");let g=I(o*i),v=I(a*s);return g!==v?se("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:o}=this,{X:i,Y:a,Z:s}=Ga(t),u=I(n*s),c=I(i*o),l=I(r*s),d=I(a*o);return u===c&&l===d}is0(){return this.equals(pn)}negate(){return new e(I(-this.X),this.Y,this.Z,I(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=Ha,i=I(t*t),a=I(n*n),s=I(2n*I(r*r)),u=I(o*i),c=t+n,l=I(I(c*c)-i-a),d=u+a,p=d-s,b=u-a,f=I(l*p),g=I(d*b),v=I(l*b),k=I(p*d);return new e(f,g,k,v)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:a,Y:s,Z:u,T:c}=Ga(t),l=Ha,d=Ja,p=I(n*a),b=I(r*s),f=I(i*d*c),g=I(o*u),v=I((n+r)*(a+s)-p-b),k=I(g-f),A=I(g+f),w=I(b-l*p),S=I(v*k),x=I(A*w),O=I(v*w),M=I(k*A);return new e(S,x,M,O)}subtract(t){return this.add(Ga(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return pn;if(Tt(t,1n,Co),t===1n)return this;if(this.equals(mt))return xy(t).p;let r=pn,o=mt;for(let i=this;t>0n;i=i.double(),t>>=1n)t&1n?r=r.add(i):n&&(o=o.add(i));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(pn))return{x:0n,y:1n};let o=my(r,le);I(r*o)!==1n&&se("invalid inverse");let i=I(t*o),a=I(n*o);return{x:i,y:a}}toBytes(){let{x:t,y:n}=this.assertValidity().toAffine(),r=Nd(n);return r[31]|=t&1n?128:0,r}toHex(){return Dd(this.toBytes())}clearCofactor(){return this.multiply(Lo(sy),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Co/2n,!1).double();return Co%2n&&(t=t.add(this)),t.is0()}},mt=new at(Ed,kd,1n,I(Ed*kd)),pn=new at(0n,1n,1n,0n);at.BASE=mt;at.ZERO=pn;var Nd=e=>Rd(Ud(Tt(e,0n,Va),cr)).reverse(),Wa=e=>Lo("0x"+Dd(Od(Xe(e)).reverse())),We=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=le;return n},hy=e=>{let n=e*e%le*e%le,r=We(n,2n)*n%le,o=We(r,1n)*e%le,i=We(o,5n)*o%le,a=We(i,10n)*i%le,s=We(a,20n)*a%le,u=We(s,40n)*s%le,c=We(u,80n)*u%le,l=We(c,80n)*u%le,d=We(l,10n)*i%le;return{pow_p_5_8:We(d,2n)*e%le,b2:n}},Ad=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,gy=(e,t)=>{let n=I(t*t*t),r=I(n*n*t),o=hy(e*r).pow_p_5_8,i=I(e*n*o),a=I(t*i*i),s=i,u=I(i*Ad),c=a===e,l=a===I(-e),d=a===I(-e*Ad);return c&&(i=s),(l||d)&&(i=u),(I(i)&1n)===1n&&(i=I(-i)),{isValid:c||l,value:i}},Mo=e=>jd(Wa(e)),Xa=(...e)=>Ya.sha512Async(ur(...e));var yy=e=>{let t=e.slice(0,Pt);t[0]&=248,t[31]&=127,t[31]|=64;let n=e.slice(Pt,cr),r=Mo(t),o=mt.multiply(r),i=o.toBytes();return{head:t,prefix:n,scalar:r,point:o,pointBytes:i}},Cd=e=>Xa(Xe(e,Pt)).then(yy);var Ld=e=>Cd(e).then(t=>t.pointBytes);var Md=e=>Xa(e.hashable).then(e.finish);var vy=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=Mo(t),a=mt.multiply(i).toBytes();return{hashable:ur(a,r,n),finish:c=>{let l=jd(i+Mo(c)*o);return Xe(ur(a,Nd(l)),cr)}}},Zd=async(e,t)=>{let n=Xe(e),r=await Cd(t),o=await Xa(r.prefix,n);return Md(vy(r,o,n))};var Bd={zip215:!0},by=(e,t,n,r=Bd)=>{e=Xe(e,cr),t=Xe(t),n=Xe(n,Pt);let{zip215:o}=r,i,a,s,u,c=Uint8Array.of();try{i=at.fromBytes(n,o),a=at.fromBytes(e.slice(0,Pt),o),s=Wa(e.slice(Pt,cr)),u=mt.multiply(s,!1),c=ur(a.toBytes(),i.toBytes(),t)}catch{}return{hashable:c,finish:d=>{if(u==null||!o&&i.isSmallOrder())return!1;let p=Mo(d);return a.add(i.multiply(p,!1)).add(u.negate()).clearCofactor().is0()}}},Fd=async(e,t,n,r=Bd)=>Md(by(e,t,n,r));var Ya={sha512Async:async e=>{let t=py(),n=ur(e);return Ka(await t.digest("SHA-512",n.buffer))},sha512:void 0};var Zo=8,_y=256,Hd=Math.ceil(_y/Zo)+1,qa=2**(Zo-1),wy=()=>{let e=[],t=mt,n=t;for(let r=0;r<Hd;r++){n=t,e.push(n);for(let o=1;o<qa;o++)n=n.add(t),e.push(n);t=n.double()}return e},Td,Pd=(e,t)=>{let n=t.negate();return e?n:t},xy=e=>{let t=Td||(Td=wy()),n=pn,r=mt,o=2**Zo,i=o,a=Lo(o-1),s=Lo(Zo);for(let u=0;u<Hd;u++){let c=Number(e&a);e>>=s,c>qa&&(c-=i,e+=1n);let l=u*qa,d=l,p=l+Math.abs(c)-1,b=u%2!==0,f=c<0;c===0?r=r.add(Pd(b,t[d])):n=n.add(Pd(f,t[p]))}return e!==0n&&se("invalid wnaf"),{p:n,f:r}};Ya.sha512Async=Sd;var zt="pk:sha2-256+ed25519",Qa=0,Bo=class{async register(t,n){if(t!==zt)throw new Error(`Unsupported channel attestation method: ${t}`);let r=await this.channelToPrivateKey(n);return await this.channelPublicIdFromPrivateKey(r)}async getMethod(t){if(t[0]===Qa)return zt;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await At(n)}async channelPublicIdFromPrivateKey(t){let n=await Ld(t),r=new Uint8Array(n.length+1);return r[0]=Qa,r.set(n,1),r}async attest(t,n,r){if(t!==zt)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),a=new TextEncoder().encode(n);return{attestation:await Zd(a,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Qa)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await Fd(t,new TextEncoder().encode(n),r.slice(1))}};var es="hmac:sha2-256",Jd=0,Fo=class{async attest(t,n){if(t!==es)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=wt(),o=await Fa(At,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=Jd,i[1]=sr,i[2]=fn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],a=r[2];if(o!==Jd||i!==sr||a!==fn)throw new Error("Unrecognized allowed ticket format");let s=await Fa(At,r.slice(3),new TextEncoder().encode(n));return t.length!==s.length?!1:s.every((u,c)=>t[c]===u)}};var ts="did:web:",Ho=class{constructor(t){this.services=t}actorToHandle=async t=>{let r=(await this.services.dids.resolve(t)).alsoKnownAs?.at(0);if(!r)throw new Q(`Handle for actor DID ${t} not found`);if(!r.startsWith(ts))throw new Error(`Handle DID ${r} is not a valid handle`);let o=r.slice(ts.length),i=await this.services.dids.resolve(r);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(t))throw new Error(`Handle ${o} does not match actor ${t}`);return o};handleToActor=async t=>{let n=`${ts}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new Q(`Actor for handle DID ${n} not found`);let i=await this.services.dids.resolve(o);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(n))throw new Error(`Actor ${o} does not match handle ${t}`);return o}};var qo="GraffitiInbox",Wo="GraffitiStorageBucket",is="#graffitiPersonalInbox",Xo="#graffitiStorageBucket",$y="#graffitiSharedInbox_",Ko=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let a=hd.safeParse(i.detail);if(!a.success)return;let s=a.data?.error;s&&console.error(s),o()})});this.services.authorization.eventTarget.addEventListener("login",this.onLogin.bind(this)),this.services.authorization.eventTarget.addEventListener("logout",this.onLogout.bind(this));let r;if(typeof window<"u"){let o=new URLSearchParams(window.location.search).get("actor");if(o)try{let i=decodeURIComponent(o),a=new URL(window.location.toString());a.searchParams.delete("actor"),window.history.replaceState({},"",a.toString()),r=this.login(i)}catch(i){console.error("Error decoding actor:",i)}}(async()=>{await new Promise(i=>setTimeout(i,0)),await r;for(let i of this.loggedInSessions){let a=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(a)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}sessionEvents=new EventTarget;inProgressLogin=void 0;inProgressLogout=void 0;async login(t){try{await this.login_(t)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n)),session:{actor:t}}});this.sessionEvents.dispatchEvent(r)}}async login_(t){if(this.loggedInSessions.find(w=>w.actor===t)){this.sessionEvents.dispatchEvent(new CustomEvent("login",{detail:{session:{actor:t}}}));return}let o=(await this.services.dids.resolve(t)).service;if(!o)throw new Error(`No services found in actor document for ${t}`);let i=o.find(w=>w.id===Xo&&w.type===Wo),a=o.find(w=>w.id===is&&w.type===qo),s=o.filter(w=>w.id.match(new RegExp(`^${$y}\\d+$`))&&w.type===qo);if(!a||!i||s.length===0)throw new Error(`Required services not found in actor document for ${t}`);let u=rs(i),c=rs(a),l=s.map(rs),d=[{endpoint:u,type:"bucket"},{endpoint:c,type:"personal-inbox"},...l.map(w=>({endpoint:w,type:"shared-inbox"}))],p=await Promise.all(d.map(async({endpoint:w,type:S})=>{let x=await(S==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(w):this.services.inboxes.getAuthorizationEndpoint(w));return{endpoint:w,authorizationEndpoint:x,type:S}})),b=new Map;p.forEach(({authorizationEndpoint:w,endpoint:S,type:x})=>{b.has(w)||b.set(w,[]),b.get(w).push({endpoint:S,type:x})});let f=[...b.entries()],v={...{actor:t},tokens:[],servicesByAuthorization:f};typeof window<"u"?window.localStorage.setItem(Jo,JSON.stringify(v)):this.inProgressLogin=v;let[k,A]=f[0];await this.services.authorization.login(k,t,A.map(w=>w.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=pd.safeParse(t.detail);if(!n.success)return;let r=n.data.loginId;try{await this.onLogin_(n.data)}catch(o){let i=new CustomEvent("login",{detail:{error:o instanceof Error?o:new Error(String(o)),session:{actor:r}}});this.sessionEvents.dispatchEvent(i)}}async onLogin_(t){if(t.error)throw t.error;let n=t.token,r=t.loginId,o;if(typeof window<"u"){let i=window.localStorage.getItem(Jo);if(!i)throw new Error("No in-progress login found");let a=JSON.parse(i);o=os.parse(a)}else{if(!this.inProgressLogin)throw new Error("No in-progress login found");o=this.inProgressLogin}if(o.actor!==r)throw new Error("Actor mismatch in login response - concurrent logins?");if(o.tokens.push(n),o.tokens.length===o.servicesByAuthorization.length){typeof window>"u"?this.inProgressLogin=void 0:window.localStorage.removeItem(Jo);let i=o.servicesByAuthorization.flatMap(([c,l],d)=>l.map(p=>({token:o.tokens[d],serviceEndpoint:p.endpoint,authorizationEndpoint:c,type:p.type}))),a={...o,storageBucket:i.find(c=>c.type==="bucket"),personalInbox:i.find(c=>c.type==="personal-inbox"),sharedInboxes:i.filter(c=>c.type==="shared-inbox")},s=this.loggedInSessions;s.push(a),this.loggedInSessions=s;let u=new CustomEvent("login",{detail:{session:{actor:r}}});this.sessionEvents.dispatchEvent(u)}else{typeof window<"u"?window.localStorage.setItem(Jo,JSON.stringify(o)):this.inProgressLogin=o;let[i,a]=o.servicesByAuthorization[o.tokens.length];await this.services.authorization.login(i,r,a.map(s=>s.endpoint))}}async logout(t){try{await this.logout_(t)}catch(n){let r=new CustomEvent("logout",{detail:{error:n instanceof Error?n:new Error(String(n)),actor:t}});this.sessionEvents.dispatchEvent(r)}}async logout_(t){let n=this.loggedInSessions.find(a=>a.actor===t);if(!n)throw new Error(`No session found for actor ${t}`);this.loggedInSessions=this.loggedInSessions.filter(a=>a.actor!==t);let r=n.tokens.pop();if(!r)throw new Error("No tokens found in session");typeof window<"u"?window.localStorage.setItem(Go,JSON.stringify(n)):this.inProgressLogout=n;let[o,i]=n.servicesByAuthorization[n.tokens.length];await this.services.authorization.logout(o,t,r)}async onLogout(t){if(!(t instanceof CustomEvent))return;let n=md.safeParse(t.detail);if(!n.success)return;let r=n.data.logoutId;try{await this.onLogout_(n.data)}catch(o){let i=new CustomEvent("logout",{detail:{error:o instanceof Error?o:new Error(String(o)),actor:r}});this.sessionEvents.dispatchEvent(i)}}async onLogout_(t){if(t.error)throw t.error;let n=t.logoutId,r;if(typeof window<"u"){let i=window.localStorage.getItem(Go);if(!i)throw new Error("No in-progress logout found");let a=JSON.parse(i);r=os.parse(a)}else{if(!this.inProgressLogout)throw new Error("No in-progress logout found");r=this.inProgressLogout}if(r.actor!==n)throw new Error("Actor mismatch in logout response - concurrent logouts?");let o=r.tokens.pop();if(o){typeof window<"u"?window.localStorage.setItem(Go,JSON.stringify(r)):this.inProgressLogout=r;let[i,a]=r.servicesByAuthorization[r.tokens.length];await this.services.authorization.logout(i,n,o)}else{typeof window>"u"?this.inProgressLogout=void 0:window.localStorage.removeItem(Go);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return Gd;let t=window.localStorage.getItem(Vo);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),window.localStorage.removeItem(Vo),[]}let r=V(ky).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),window.localStorage.removeItem(Vo),[])}set loggedInSessions(t){if(typeof window>"u"){Gd=t;return}window.localStorage.setItem(Vo,JSON.stringify(t))}resolveSession(t){let n=this.loggedInSessions.find(r=>r.actor===t.actor);if(!n){let r=new CustomEvent("logout",{detail:{actor:t.actor}});throw this.sessionEvents.dispatchEvent(r),new Error("Not logged in")}return n}},Gd=[],Jo="graffiti-login-in-progress",Go="graffiti-logout-in-progress",Vo="graffiti-sessions-logged-in",Sy=be({actor:J()}),ns=be({token:H(),serviceEndpoint:J(),authorizationEndpoint:J()}),Ey=V(fe([J(),V(be({endpoint:J(),type:xc(["bucket","personal-inbox","shared-inbox"])}))])),os=tt(Sy,{tokens:V(H()),servicesByAuthorization:Ey}),ky=tt(os,{storageBucket:ns,personalInbox:ns,sharedInboxes:V(ns)});function rs(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var Yo=32*1024,Qo=class{constructor(t){this.primitives=t}async encode(t,n){t=ds(t);let r=[...new Set(t.channels)],o=await Promise.all(r.map(g=>this.primitives.channelAttestations.attest(zt,n,g))),i=o.map(g=>g.attestation),a=o.map(g=>g.channelPublicId),s={[ss]:t.value,[cs]:i,[Kd]:wt(32)},u;if(Array.isArray(t.allowed)){let g=await Promise.all(t.allowed.map(async v=>this.primitives.allowedAttestations.attest(es,v)));s[us]=g.map(v=>v.attestation),u=g.map(v=>v.ticket)}let c=Ee(s);if(c.byteLength>Yo)throw new Error("The object is too large");let l=await this.primitives.contentAddresses.register(jo,c),d=await this.primitives.stringEncoder.encode(dn,l),p=Ay(n,d),b=[new TextEncoder().encode(p),...a];return{object:{value:t.value,channels:r,url:p,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:b,objectBytes:c,allowedTickets:u}}async validate(t,n,r,o){if(r.byteLength>Yo)throw new Error("Object is too big");let{actor:i,contentAddress:a}=fs(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let s=n.at(0);if(!s)throw new Error("No object URL tag");if(new TextDecoder().decode(s)!==t.url)throw new Error("Object URL tag does not match object URL");let u=n.slice(1),c=await this.primitives.stringEncoder.decode(a),l=await this.primitives.contentAddresses.getMethod(c),d=await this.primitives.contentAddresses.register(l,r);if(d.length!==c.length||!d.every((w,S)=>w===c[S]))throw new Error("Content address is invalid");let p=He(r),b=Iy.parse(p),f=b[ss],g=b[cs],v=b[us],k=Ee(f),A=Ee(t.value);if(k.length!==A.length||!k.every((w,S)=>w===A[S]))throw new Error("Object value does not match storage value");if(g.length!==u.length)throw new Error("Not as many channel attestations and public ids");for(let[w,S]of g.entries()){let x=u[w];if(!await this.primitives.channelAttestations.validate(S,i,x))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==u.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let w=await this.primitives.channelAttestations.getMethod(u[0]),S=await Promise.all(t.channels.map(x=>this.primitives.channelAttestations.register(w,x)));for(let[x,O]of S.entries()){let M=u[x];if(O.length!==M.length||!O.every((B,ie)=>B===M[ie]))throw new Error("Channel public id does not match expected")}}if(o){if(!v)throw new Error("Object is public but thought to be private");let w,S,x;if("recipient"in o?(w=[o.recipient],S=[o.allowedTicket],x=v.filter((O,M)=>M===o.allowedIndex)):(w=[...t.allowed??[]],S=o.allowedTickets,x=v),w.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!w.every(O=>t.allowed?.includes(O)))throw new Error("Recipient not in object allowed list");for(let[O,M]of w.entries()){let B=S.at(O),ie=x.at(O);if(!B)throw new Error("Missing allowed ticket for recipient");if(!ie)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(ie,M,B))throw new Error("Invalid allowed attestation for recipient")}}else if(v)throw new Error("Object is private but no recipient info provided")}},ss="v",cs="c",us="a",Kd="n",as=_t(e=>e instanceof Uint8Array),Iy=_e({[ss]:he({}),[cs]:V(as),[us]:X(V(as)),[Kd]:as}),ls="graffiti:";function Vd(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function qd(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function Ay(e,t){return`${ls}${Vd(e)}:${Vd(t)}`}function fs(e){if(!e.startsWith(ls))throw new Error("Invalid object URL");let n=e.slice(ls.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:qd(r),contentAddress:qd(o)}}function ds(e){return e===void 0?null:Array.isArray(e)?e.map(ds):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,ds(n)])):e}var Wd=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;constructor(e){this.useTemplateHTML=e.useTemplateHTML,this.onManualClose=e.onManualClose,this.dialog.className="graffiti-modal",this.dialog.addEventListener("click",n=>{if("pointerType"in n&&!n.pointerType)return;let r=this.dialog.getBoundingClientRect();(r.top>n.clientY||r.left>n.clientX||n.clientY>r.top+r.height||n.clientX>r.left+r.width)&&(this.close(),this.onManualClose?.())});let t=document.createElement("div");this.shadow=t.attachShadow({mode:"closed"}),this.shadow.appendChild(this.dialog),document.body.append(t)}get templates(){return this.templates_||(this.main_,this.templates_=new Promise(async e=>e(await this.useTemplateHTML())).then(e=>{let t=new DOMParser().parseFromString(e,"text/html"),n=new Map;return t.querySelectorAll("template").forEach(r=>{let o=r.id;o&&n.set(o,r)}),n})),this.templates_}get main(){return this.main_||(this.templates_,this.main_=Promise.all([import("./style-RMTPI5KV-Y5KAOOZR.js"),import("./graffiti-KV3G3O72-URO7SJIJ.js"),import("./rock-salt-LI7DAH66-KPFEBIBO.js")]).then(async([{default:e},{default:t},{default:n}])=>{let r=document.createElement("header"),o=document.createElement("button");o.className="secondary",o.textContent="Close",o?.addEventListener("click",()=>{this.close(),this.onManualClose?.()}),r.appendChild(o);let i=document.createElement("main");this.dialog.appendChild(r),this.dialog.appendChild(i);let a=new FontFace("Rock Salt",`url(${n})`,{style:"normal",weight:"400"});document.fonts.add(a),await a.load(),e=e.replace("url(graffiti.jpg)",`url(${t})`);let s=new CSSStyleSheet;return s.replace(e).then(()=>{this.shadow.adoptedStyleSheets=[s]}),i})),this.main_}async open(){await this.main,this.dialog.showModal(),this.dialog.focus()}close(){this.dialog.close()}async displayTemplate(e){let t=await this.main;t.innerHTML="";let n=(await this.templates).get(e);if(!n)throw new Error(`Template not found: ${e}`);let r=n.content.cloneNode(!0);return t.appendChild(r),t}};var Yd=_t(e=>e instanceof Uint8Array),hs="k",mn="t",vs=_e({[hs]:H(),[mn]:X(H())}),Ot="id",gs="e",lr="a",Ty=V(_e({[Ot]:H(),[gs]:X(J()),[lr]:X(J())})),ei="s",ti="n",Py=tt(vs,{[ei]:X(V(Yd)),[ti]:Ty}),dr="a",ys="i",zy=tt(vs,{[dr]:Yd,[ys]:jt().check(bt())}),Oy=ut([vs,Py,zy]),Uy=0,ps=1,ht=2,ms=3,Dy=16,ni=class{dids=new po;authorization=new To;storageBuckets=new zo;inboxes=new Uo;stringEncoder=new Ro;contentAddresses=new No;channelAttestations=new Bo;allowedAttestations=new Fo;sessions=new Ko({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new Ho({dids:this.dids});objectEncoding=new Qo({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new Wd({useTemplateHTML:()=>import("./login-dialog.html-VTDKJZBG.js").then(({template:t})=>t),onManualClose:()=>{let t=new CustomEvent("login",{detail:{error:new Error("User cancelled login"),manual:!0}});this.sessionEvents.dispatchEvent(t)}});defaultInboxEndpoints;identityCreatorEndpoint;constructor(t){this.defaultInboxEndpoints=t?.defaultInboxEndpoints??["https://graffiti.actor/i/shared"],this.identityCreatorEndpoint=t?.identityCreatorEndpoint??"https://graffiti.actor/create",this.sessionEvents.addEventListener("login",async n=>{if(!(n instanceof CustomEvent))return;let r=n.detail;if(r.error!==void 0&&!("manual"in r&&r.manual)){alert("Login failed: "+r.error.message);let o=r.session?.actor,i;if(o)try{i=await this.actorToHandle(o)}catch(a){console.error("Failed to handle actor:",a)}this.login_(i)}})}actorToHandle=this.handles.actorToHandle.bind(this.handles);handleToActor=this.handles.handleToActor.bind(this.handles);sessionEvents=this.sessions.sessionEvents;login=async t=>{try{let n;try{n=t?await this.actorToHandle(t):void 0}catch(r){console.error("Error fetching handle for actor:",r)}await this.login_(n)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n))}});this.sessionEvents.dispatchEvent(r)}};async login_(t){if(typeof window<"u"){let n;if(t!==void 0){n=await this.modal?.displayTemplate("graffiti-login-handle");let o=n?.querySelector("#username");o?.setAttribute("value",t),o?.addEventListener("focus",()=>o?.select()),setTimeout(()=>o?.focus(),0),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async i=>{i.preventDefault(),o?.setAttribute("disabled","true");let a=n?.querySelector("#graffiti-login-handle-submit");if(a?.setAttribute("disabled","true"),a&&(a.innerHTML="Logging in..."),!o?.value){alert("No handle provided"),this.login_("");return}let s=o.value;if(!s.includes(".")&&!s.startsWith("localhost")){let c=new URL(this.identityCreatorEndpoint).host;s=`${s}.${c}`}let u;try{u=await this.handleToActor(s)}catch{alert("Could not find an identity associated with that handle."),this.login_(s);return}try{await this.sessions.login(u)}catch(c){alert("Error logging in."),console.error(c),this.login_(s)}})}else n=await this.modal?.displayTemplate("graffiti-login-welcome"),n?.querySelector("#graffiti-login-existing")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),setTimeout(()=>n?.querySelector("#graffiti-login-new")?.focus(),0);let r=new URL(this.identityCreatorEndpoint);r.searchParams.set("redirect_uri",encodeURIComponent(window.location.toString())),n?.querySelector("#graffiti-login-new")?.setAttribute("href",r.toString()),await this.modal?.open()}else{let n=await import("readline").catch(a=>{throw new Error("Unrecognized environment: neither window nor readline")});console.log("If you do not already have a Graffiti handle, you can create one here:"),console.log(this.identityCreatorEndpoint);let r=n.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(a=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,s=>{r.close(),a(s||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:a,objectBytes:s,allowedTickets:u}=await this.objectEncoding.encode(n,r.actor),c=wt(),l=await this.stringEncoder.encode(dn,c);return await this.storageBuckets.put(o.storageBucket.serviceEndpoint,l,s,o.storageBucket.token),await this.announceObject(i,a,u,l,r),i};get=async(...t)=>{let[n,r,o]=t,i,a=await hr(r);if(o){let c=this.sessions.resolveSession(o);i=[c.personalInbox,...c.sharedInboxes]}else i=this.defaultInboxEndpoints.map(c=>({serviceEndpoint:c}));let s=ii(n),u=[new TextEncoder().encode(s)];for(let c of i){let l,d=this.querySingleEndpoint(c.serviceEndpoint,{tags:u,objectSchema:{}},c.token,o?.actor);for await(let p of d)p.object.url===s&&(p.tombstone?l=void 0:l=p.object);if(l){if(!a(l))throw new pr("Object exists but does not match the supplied schema");return l}}throw new Q("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ii(t),{actor:i}=fs(o);if(i!==n.actor)throw new st("Cannot delete someone else's actor");let a=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),s;for await(let f of a)f.object.url===o&&(f.tombstone?s=void 0:s=f);if(!s)throw new Q(`Object ${o} not found`);let{object:u,storageBucketKey:c,tags:l,allowedTickets:d,announcements:p,messageId:b}=s;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,c,r.storageBucket.token),await this.announceObject(u,l,d,c,n,[...p??[],{[lr]:n.actor,[Ot]:b}]),u};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),a=wt(),s=await this.stringEncoder.encode(dn,a);await this.storageBuckets.put(i.storageBucket.serviceEndpoint,s,new Uint8Array(await n.data.arrayBuffer()),i.storageBucket.token);let{url:u}=await this.post({value:{key:s,type:o,size:n.data.size},channels:[],allowed:n.allowed},r);return u};getMedia=async(...t)=>{let[n,r,o]=t,i=await this.get(n,Ry,o),{key:a,type:s,size:u}=i.value;if(r?.maxBytes&&u>r.maxBytes)throw new Rt("File size exceeds limit");if(r?.types&&!_s(s,r.types))throw new mr(`Unacceptable media type, ${s}`);let l=(await this.dids.resolve(i.actor))?.service?.find(f=>f.id===Xo&&f.type===Wo);if(!l)throw new Q(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new Q(`Actor ${i.actor} does not have a valid storage bucket endpoint`);let d=l.serviceEndpoint,p=await this.storageBuckets.get(d,a,u);return{data:new Blob([p.slice()],{type:s}),actor:i.actor,allowed:i.allowed}};deleteMedia=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),i=await this.delete(n,r);if(!("key"in i.value&&typeof i.value.key=="string"))throw new Error("Deleted object was not media: "+JSON.stringify(i,null,2));await this.storageBuckets.delete(o.storageBucket.serviceEndpoint,i.value.key,o.storageBucket.token)};async*discoverMeta(t,n,r,o){let i=new Map,a;if(o){let d=this.sessions.resolveSession(o);a=[d.personalInbox,...d.sharedInboxes]}else a=this.defaultInboxEndpoints.map(d=>({serviceEndpoint:d}));for(let d in r)if(!a.some(p=>p.serviceEndpoint===d))throw new st("Cursor does not match actor's inboxes");let s=await Promise.all(t.map(d=>this.channelAttestations.register(zt,d))),u=a.map(d=>{let p=r[d.serviceEndpoint];return this.querySingleEndpoint(d.serviceEndpoint,p?{cursor:p}:{tags:s,objectSchema:n},d.token,o?.actor)}),c=u.map(async(d,p)=>Xd(d,p)),l=c.length;for(;l>0;){let d=await Promise.race(c);if(d.error!==void 0)c[d.index]=new Promise(()=>{}),l--,yield{error:d.error,origin:a[d.index].serviceEndpoint};else if(d.result.done){let p=a[d.index];r[p.serviceEndpoint]=d.result.value,c[d.index]=new Promise(()=>{}),l--}else{c[d.index]=Xd(u[d.index],d.index);let{object:p,tombstone:b,tags:f}=d.result.value;if(b){if(i.get(p.url)===!0)continue;i.set(p.url,!0),yield{tombstone:b,object:{url:p.url}}}else{if(i.get(p.url)===!1)continue;let v=s.reduce((k,A,w)=>{for(let S of f)if(A.length===S.length&&A.every((x,O)=>S[O]===x)){k.push(w);break}return k},[]).map(k=>t[k]);v.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:a[d.index].serviceEndpoint}),i.set(p.url,!1),yield{object:{...p,channels:v}}}}}return{cursor:JSON.stringify({channels:t,cursors:r})}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let a=JSON.parse(n),s=jy.parse(a);o=s.channels,i=s.cursors}catch{return(async function*(){throw new De("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async announceObject(t,n,r,o,i,a){let s=this.sessions.resolveSession(i),u={[hs]:o},c=[],l=t.allowed;if(Array.isArray(l)){if(!r||r.length!==l.length)throw new Error("If allowed actors are specified, there must be a corresponding ticket for each allowed actor");let b=await Promise.allSettled(l.map(async(f,g)=>{let v=JSON.parse(JSON.stringify(t)),k=ai(v,[],f),w=(await this.dids.resolve(f)).service?.find(M=>M.type===qo&&M.id===is);if(!w)throw new Error(`Recipient ${f} does not have a personal inbox`);if(typeof w.serviceEndpoint!="string")throw new Error(`Recipient ${f} does not have a valid personal inbox endpoint`);let S=a?a.find(M=>M[lr]===f)?.[Ot]:void 0,x={...u,...S?{[mn]:S}:{},[dr]:r[g],[ys]:g},O=await this.inboxes.send(w.serviceEndpoint,{[ir]:n,[ot]:k,[ar]:Ee(x)});c.push({[Ot]:O,[lr]:f})}));for(let[f,g]of b.entries())if(g.status==="rejected"){let v=l[f];console.error("Error sending to recipient:",v),console.error(g.reason)}}else{let b=JSON.parse(JSON.stringify(t)),f=ai(b,[]),g=s.sharedInboxes,v=await Promise.allSettled(g.map(async k=>{let A=a?a.find(x=>x[gs]===k.serviceEndpoint)?.[Ot]:void 0,w={...u,...A?{[mn]:A}:{}},S=await this.inboxes.send(k.serviceEndpoint,{...A?{[mn]:A}:{},[ir]:n,[ot]:f,[ar]:Ee(w)});c.push({[Ot]:S,[gs]:k.serviceEndpoint})}));for(let[k,A]of v.entries())if(A.status==="rejected"){let w=g[k];console.error("Error sending to inbox:",w),console.error(A.reason)}}let d=a?a.find(b=>b[lr]===i.actor)?.[Ot]:void 0,p={...u,...r?{[ei]:r}:{},...d?{[mn]:d}:{},[ti]:c};await this.inboxes.send(s.personalInbox.serviceEndpoint,{[ir]:n,[ot]:t,[ar]:Ee(p)})}async*querySingleEndpoint(t,n,r,o){let i="tags"in n?this.inboxes.query(t,n.tags,n.objectSchema,r):this.inboxes.continueQuery(t,n.cursor,r),a=[],s=null;for(;;){for(;s===null&&a.length<Dy;){let l=await i.next();if(l.done){s=l.value;break}let d=this.processOneLabeledMessage(t,l.value,r,o).catch(p=>{throw p});a.push(d)}let u=a.shift();if(!u){if(s!==null)return s;throw new Error("Process queue empty but no return value")}let c=await u;c&&(yield c)}}async processOneLabeledMessage(t,n,r,o){let i=n.l;if(i!==ps&&i!==Uy&&i!==ht)return;let a=n.id,{o:s,m:u,t:c}=n.m,l;try{let v=He(u);l=Oy.parse(v)}catch{this.inboxes.label(t,a,ms,r);return}let{[hs]:d,[mn]:p}=l,b=ei in l?l[ei]:void 0,f=ti in l?l[ti]:void 0;if(i===ps)return{messageId:a,object:s,storageBucketKey:d,allowedTickets:b,tags:c,announcements:f};if(i===ht){if(!p)return;let v=await this.inboxes.get(t,p,r);return!v||v[It][ot].url!==s.url?void 0:(v[Do]!==ht&&this.inboxes.label(t,p,ht,r),{messageId:a,tombstone:!0,object:s,storageBucketKey:d,allowedTickets:b,tags:c,announcements:f})}let g;try{let v=s.actor,A=(await this.dids.resolve(v))?.service?.find(O=>O.id===Xo&&O.type===Wo);if(!A)throw new Q(`Actor ${v} has no storage bucket service`);if(typeof A.serviceEndpoint!="string")throw new Q(`Actor ${v} does not have a valid storage bucket endpoint`);let w=A.serviceEndpoint,S=await this.storageBuckets.get(w,d,Yo);if(dr in l&&!o)throw new st("Recipient is required when allowed ticket is present");let x=b?{allowedTickets:b}:dr in l?{recipient:o??"null",allowedTicket:l[dr],allowedIndex:l[ys]}:void 0;await this.objectEncoding.validate(s,c,S,x)}catch(v){g=v}if(p){if(g instanceof Q)return this.inboxes.get(t,p,r).then(v=>{v&&v[It][ot].url===s.url&&v[Do]!==ht&&this.inboxes.label(t,p,ht,r),this.inboxes.label(t,a,ht,r)}),{messageId:a,tombstone:!0,object:s,storageBucketKey:d,allowedTickets:b,tags:c,announcements:f};console.error("Recieved an incorrect tombstone object"),console.error(g),this.inboxes.label(t,a,ms,r)}else{if(g===void 0)return this.inboxes.label(t,a,ps,r),{messageId:a,object:s,storageBucketKey:d,tags:c,allowedTickets:b,announcements:f};g instanceof Q?this.inboxes.label(t,a,ht,r):(console.error("Recieved an incorrect object"),console.error(g),this.inboxes.label(t,a,ms,r))}}},Ry={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},jy=_e({cursors:wc(J(),H()),channels:V(H())});async function Xd(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof De||n instanceof Dt)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var Qd=class extends Ir{constructor(t){let n=new ni(t);super(n)}};export{Qd as GraffitiDecentralized};
8
8
  /*! Bundled license information:
9
9
 
10
10
  @noble/hashes/utils.js: