@graffiti-garden/implementation-decentralized 0.0.2 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/1-services/4-inboxes-tests.d.ts.map +1 -1
- package/dist/1-services/4-inboxes.d.ts +3 -3
- package/dist/1-services/4-inboxes.d.ts.map +1 -1
- package/dist/3-protocol/4-graffiti.d.ts.map +1 -1
- package/dist/3-protocol/login-dialog.html.d.ts +1 -1
- package/dist/3-protocol/login-dialog.html.d.ts.map +1 -1
- package/dist/browser/index.js +7 -7
- package/dist/browser/index.js.map +3 -3
- package/dist/browser/login-dialog.html-VTDKJZBG.js +44 -0
- package/dist/browser/login-dialog.html-VTDKJZBG.js.map +7 -0
- package/dist/browser/{style-YUTCEBZV-RWYJV575.js → style-3ALLGCD7-QNFKN6AK.js} +18 -36
- package/dist/browser/style-3ALLGCD7-QNFKN6AK.js.map +7 -0
- package/dist/cjs/1-services/4-inboxes-tests.js +2 -0
- package/dist/cjs/1-services/4-inboxes-tests.js.map +2 -2
- package/dist/cjs/1-services/4-inboxes.js +17 -8
- package/dist/cjs/1-services/4-inboxes.js.map +2 -2
- package/dist/cjs/3-protocol/4-graffiti.js +40 -12
- package/dist/cjs/3-protocol/4-graffiti.js.map +2 -2
- package/dist/cjs/3-protocol/login-dialog.html.js +9 -9
- package/dist/cjs/3-protocol/login-dialog.html.js.map +1 -1
- package/dist/esm/1-services/4-inboxes-tests.js +2 -0
- package/dist/esm/1-services/4-inboxes-tests.js.map +2 -2
- package/dist/esm/1-services/4-inboxes.js +19 -9
- package/dist/esm/1-services/4-inboxes.js.map +2 -2
- package/dist/esm/3-protocol/4-graffiti.js +41 -12
- package/dist/esm/3-protocol/4-graffiti.js.map +2 -2
- package/dist/esm/3-protocol/login-dialog.html.js +9 -9
- package/dist/esm/3-protocol/login-dialog.html.js.map +1 -1
- package/package.json +3 -3
- package/src/1-services/4-inboxes-tests.ts +2 -0
- package/src/1-services/4-inboxes.ts +25 -15
- package/src/3-protocol/4-graffiti.ts +65 -17
- package/src/3-protocol/login-dialog.html.ts +9 -9
- package/dist/browser/login-dialog.html-XUWYDNNI.js +0 -44
- package/dist/browser/login-dialog.html-XUWYDNNI.js.map +0 -7
- package/dist/browser/style-YUTCEBZV-RWYJV575.js.map +0 -7
package/dist/browser/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{a as
|
|
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]&&
|
|
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(
|
|
6
|
-
`):" "+
|
|
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 rf,b as of,c as af}from"./chunk-RFBBAUMM.js";var jl=rf((dt,Rl)=>{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 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 b(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=b(w);return w.readAsArrayBuffer(h),z}function y(h){var w=new FileReader,z=b(w),B=/charset=([A-Za-z0-9_-]+)/.exec(h.type),q=B?B[1]:"utf-8";return w.readAsText(h,q),z}function v(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(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(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})({})})(fo);fo.fetch.ponyfill=!0;delete fo.fetch.polyfill;var nn=lo.fetch?lo:fo;dt=nn.fetch;dt.default=nn.fetch;dt.fetch=nn.fetch;dt.Headers=nn.Headers;dt.Request=nn.Request;dt.Response=nn.Response;Rl.exports=dt});var sf={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"]},My={...sf,required:["value","channels"]};var at=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorForbidden",Object.setPrototypeOf(this,e.prototype)}},re=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotFound",Object.setPrototypeOf(this,e.prototype)}},Ut=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorInvalidSchema",Object.setPrototypeOf(this,e.prototype)}},mr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorSchemaMismatch",Object.setPrototypeOf(this,e.prototype)}},Dt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorTooLarge",Object.setPrototypeOf(this,e.prototype)}},hr=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 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 bs(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 gr(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 Ut(t instanceof Error?t.message:String(t))}}var cf=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 si={};function Ye(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 ws(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 br(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var _s=Symbol("evaluating");function fe(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==_s)return r===void 0&&(r=_s,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function uf(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function lf(...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 vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var df=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(vr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(vr(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}var xs=new Set(["string","number","symbol"]);function _r(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 oe(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 $s(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ss={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 Es(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=lf(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return uf(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 yr(e){return typeof e=="string"?e:e?.message}function st(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let o=yr(e.inst?._zod.def?.error?.(e))??yr(t?.error?.(e))??yr(n.customError?.(e))??yr(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 ks=(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,ws,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Is=P("$ZodError",ks),vn=P("$ZodError",ks,{Parent:Error});var pf=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=>st(u,i,Ye())));throw di(s,o?.callee),s}return a.value},wr=pf(vn),mf=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=>st(u,i,Ye())));throw di(s,o?.callee),s}return a.value},xr=mf(vn),hf=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??Is)(i.issues.map(a=>st(a,o,Ye())))}:{success:!0,data:i.value}},bn=hf(vn),gf=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=>st(a,o,Ye())))}:{success:!0,data:i.value}},_n=gf(vn);var yf="(?:(?:\\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])))",vf=new RegExp(`^${yf}$`);var As=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ts=/^-?\d+$/,pi=/^-?\d+(?:\.\d+)?$/,Ps=/^(?:true|false)$/i;var zs=/^undefined$/i;var gt=P("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),bf={number:"number",bigint:"bigint",object:"date"};var Os=P("$ZodCheckGreaterThan",(e,t)=>{gt.init(e,t);let n=bf[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 Us=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]=Ss[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=Ts)}),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 Ds=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 js={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=js;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,b=d._zod.check(a);if(b instanceof Promise&&u?.async===!1)throw new Xe;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,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}))}),Er=P("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??As(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)=>{Ds.init(e,t),Er.init(e,t)});var Bs=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}}),Fs=P("$ZodNumberFormat",(e,t)=>{Us.init(e,t),gi.init(e,t)}),yi=P("$ZodBoolean",(e,t)=>{ee.init(e,t),e._zod.pattern=Ps,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 Hs=P("$ZodUndefined",(e,t)=>{ee.init(e,t),e._zod.pattern=zs,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 Js=P("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=n=>n}),Gs=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 Ns(e,t,n){e.issues.length&&t.issues.push(...Qe(n,e.issues)),t.value[n]=e.value}var Vs=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=>Ns(c,n,a))):Ns(u,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function Sr(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 _f(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=$s(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function wf(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=>Sr(b,n,d,t,l))):Sr(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 qs=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(()=>_f(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=vr,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",y=b._zod.run({value:c[p],issues:[]},u);y instanceof Promise?l.push(y.then(v=>Sr(v,s,p,c,f))):Sr(y,s,p,c,f)}return i?wf(l,c,s,u,r.value,e):l.length?Promise.all(l).then(()=>s):s}});function Cs(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=>st(a,r,Ye())))}),t)}var Ks=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=>br(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=>Cs(u,o,e,i)):Cs(s,o,e,i)}});var Ws=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])=>Ls(n,u,c)):Ls(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 Ls(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=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 Xs=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=>$r(p,r,c))):$r(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=>$r(b,r,c))):$r(p,r,c)}}return a.length?Promise.all(a).then(()=>r):r}});function $r(e,t,n){e.issues.length&&t.issues.push(...Qe(n,e.issues)),t.value[n]=e.value}var Ys=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"&&pi.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=>st(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 Qs=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=>xs.has(typeof o)).map(o=>typeof o=="string"?_r(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 Ms(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var ec=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(`^(${br(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=>Ms(i,n.value)):Ms(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var tc=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(`^(${br(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 nc=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=>Zs(i,n,r,e));Zs(o,n,r,e)}});function Zs(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 oc;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 ic(){return new vi}(oc=globalThis).__zod_globalRegistry??(oc.__zod_globalRegistry=ic());var bi=globalThis.__zod_globalRegistry;function ac(e,t){return new e({type:"string",...oe(t)})}function sc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...oe(t)})}function cc(e,t){return new e({type:"number",checks:[],...oe(t)})}function uc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(t)})}function lc(e,t){return new e({type:"boolean",...oe(t)})}function dc(e,t){return new e({type:"undefined",...oe(t)})}function fc(e){return new e({type:"unknown"})}function pc(e,t){return new e({type:"never",...oe(t)})}function _i(e,t){return new Os({check:"greater_than",...oe(t),value:e,inclusive:!0})}function yt(e){return _i(0,e)}function mc(e,t,n){let r=oe(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)=>wr(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>bn(e,n,r),e.parseAsync=async(n,r)=>xr(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)=>{Er.init(e,t),ue.init(e,t)});function H(e){return ac(wi,e)}var hc=P("ZodMiniStringFormat",(e,t)=>{hi.init(e,t),wi.init(e,t)});var Df=P("ZodMiniURL",(e,t)=>{Bs.init(e,t),hc.init(e,t)});function J(e){return sc(Df,e)}var xi=P("ZodMiniNumber",(e,t)=>{gi.init(e,t),ue.init(e,t)});function gc(e){return cc(xi,e)}var Rf=P("ZodMiniNumberFormat",(e,t)=>{Fs.init(e,t),xi.init(e,t)});function Rt(e){return uc(Rf,e)}var yc=P("ZodMiniBoolean",(e,t)=>{yi.init(e,t),ue.init(e,t)});function $i(e){return lc(yc,e)}var jf=P("ZodMiniUndefined",(e,t)=>{Hs.init(e,t),ue.init(e,t)});function vc(e){return dc(jf,e)}var Nf=P("ZodMiniUnknown",(e,t)=>{Js.init(e,t),ue.init(e,t)});function Cf(){return fc(Nf)}var Lf=P("ZodMiniNever",(e,t)=>{Gs.init(e,t),ue.init(e,t)});function Mf(e){return pc(Lf,e)}var Zf=P("ZodMiniArray",(e,t)=>{Vs.init(e,t),ue.init(e,t)});function V(e,t){return new Zf({type:"array",element:e,...oe(t)})}var Si=P("ZodMiniObject",(e,t)=>{qs.init(e,t),ue.init(e,t),fe(e,"shape",()=>t.shape)});function ve(e,t){let n={type:"object",shape:e??{},...oe(t)};return new Si(n)}function be(e,t){return new Si({type:"object",shape:e,catchall:Mf(),...oe(t)})}function me(e,t){return new Si({type:"object",shape:e,catchall:Cf(),...oe(t)})}function et(e,t){return Es(e,t)}var Bf=P("ZodMiniUnion",(e,t)=>{Ks.init(e,t),ue.init(e,t)});function ct(e,t){return new Bf({type:"union",options:e,...oe(t)})}var Ff=P("ZodMiniIntersection",(e,t)=>{Ws.init(e,t),ue.init(e,t)});function bc(e,t){return new Ff({type:"intersection",left:e,right:t})}var Hf=P("ZodMiniTuple",(e,t)=>{Xs.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 Hf({type:"tuple",items:e,rest:i,...oe(o)})}var Jf=P("ZodMiniRecord",(e,t)=>{Ys.init(e,t),ue.init(e,t)});function _c(e,t,n){return new Jf({type:"record",keyType:e,valueType:t,...oe(n)})}var Gf=P("ZodMiniEnum",(e,t)=>{Qs.init(e,t),ue.init(e,t),e.options=Object.values(t.entries)});function wc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Gf({type:"enum",entries:n,...oe(t)})}var Vf=P("ZodMiniOptional",(e,t)=>{ec.init(e,t),ue.init(e,t)});function X(e){return new Vf({type:"optional",innerType:e})}var qf=P("ZodMiniNullable",(e,t)=>{tc.init(e,t),ue.init(e,t)});function Le(e){return new qf({type:"nullable",innerType:e})}var Kf=P("ZodMiniCustom",(e,t)=>{nc.init(e,t),ue.init(e,t)});function vt(e,t){return mc(Kf,e??(()=>!0),t)}function jt(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 Ec=me({value:me({}),channels:V(H()),allowed:X(Le(V(J())))}),pE=et(Ec,{url:J(),actor:J()}),$c=ct([me({url:J()}),J()]),Nt=me({actor:J()}),xn=X(Le(Nt)),kc=me({data:jt(Blob),allowed:X(Le(V(J())))}),mE=et(kc,{actor:J()}),ep=me({types:X(V(H())),maxBytes:X(Rt().check(yt()))});async function*Sc(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 Ir=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([Nt]).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([Ec,Nt]).parse(t);return this.graffiti.post(...n)};get=(...t)=>{let n=le([$c,me({}),xn]).parse(t);return this.graffiti.get(n[0],n[1],n[2])};delete=(...t)=>{let n=le([$c,Nt]).parse(t);return this.graffiti.delete(...n)};postMedia=(...t)=>{let n=le([kc,Nt]).parse(t);return this.graffiti.postMedia(...n)};getMedia=(...t)=>{let n=le([J(),ep,xn]).parse(t);return this.graffiti.getMedia(...n)};deleteMedia=(...t)=>{let n=le([J(),Nt]).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 Sc(r)};continueDiscover=(...t)=>{let n=le([H(),xn]).parse(t),r=this.graffiti.continueDiscover(...n);return Sc(r)}};function tp(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=tp(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 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 np=["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=rp(e);return n||"Object"}function rp(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(np.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",op=new TextEncoder;function Tr(e){return $n&&globalThis.Buffer.isBuffer(e)}function Sn(e){return e instanceof Uint8Array?Tr(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var ip=24,ap=200,Pr=$n?e=>e.length>=ip?globalThis.Buffer.from(e):Ac(e):e=>e.length>=ap?op.encode(e):Ac(e),Me=e=>Uint8Array.from(e),Tc=$n?(e,t,n)=>Tr(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),Pc=$n?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Sn(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=$n?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 sp=256,En=class{constructor(t=sp){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 M="CBOR decode error:",Ur="CBOR encode error:",kn=[];kn[23]=1;kn[24]=2;kn[25]=3;kn[26]=5;kn[27]=9;function tt(e,t,n){if(e.length-t<n)throw new Error(`${M} not enough data for type`)}var ae=[24,256,65536,4294967296,BigInt("18446744073709551616")];function _e(e,t,n){tt(e,t,1);let r=e[t];if(n.strict===!0&&r<ae[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<ae[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<ae[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<ae[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 Oc(e,t,n,r){return new k(g.uint,_e(e,t+1,r),2)}function Uc(e,t,n,r){return new k(g.uint,we(e,t+1,r),3)}function Dc(e,t,n,r){return new k(g.uint,xe(e,t+1,r),5)}function Rc(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<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(`${M} encountered BigInt larger than allowable range`)}}Te.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};Te.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function jc(e,t,n,r){return new k(g.negint,-1-_e(e,t+1,r),2)}function Nc(e,t,n,r){return new k(g.negint,-1-we(e,t+1,r),3)}function Cc(e,t,n,r){return new k(g.negint,-1-xe(e,t+1,r),5)}var Ii=BigInt(-1),Lc=BigInt(1);function Mc(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,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 In(e,t,n,r){tt(e,t,n+r);let o=e.slice(t+n,t+n+r);return new k(g.bytes,o,n+r)}function Zc(e,t,n,r){return In(e,t,1,n)}function Bc(e,t,n,r){return In(e,t,2,_e(e,t+1,r))}function Fc(e,t,n,r){return In(e,t,3,we(e,t+1,r))}function Hc(e,t,n,r){return In(e,t,5,xe(e,t+1,r))}function Jc(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 In(e,t,9,o)}function Rr(e){return e.encodedBytes===void 0&&(e.encodedBytes=g.equals(e.type,g.string)?Pr(e.value):e.value),e.encodedBytes}function Ct(e,t){let n=Rr(t);W(e,t.type.majorEncoded,n.length),e.push(n)}Ct.encodedSize=function(t){let n=Rr(t);return W.encodedSize(n.length)+n.length};Ct.compareTokens=function(t,n){return up(Rr(t),Rr(n))};function up(e,t){return e.length<t.length?-1:e.length>t.length?1:zr(e,t)}var Gc=new TextDecoder,dp=32;function fp(e,t,n){if(n-t<dp){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 An(e,t,n,r,o){let i=n+r;tt(e,t,i);let a=new k(g.string,fp(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 An(e,t,1,n,r)}function qc(e,t,n,r){return An(e,t,2,_e(e,t+1,r),r)}function Kc(e,t,n,r){return An(e,t,3,we(e,t+1,r),r)}function Wc(e,t,n,r){return An(e,t,5,xe(e,t+1,r),r)}function Xc(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 An(e,t,9,o,r)}var Yc=Ct;function Lt(e,t,n,r){return new k(g.array,r,n)}function Qc(e,t,n,r){return Lt(e,t,1,n)}function eu(e,t,n,r){return Lt(e,t,2,_e(e,t+1,r))}function tu(e,t,n,r){return Lt(e,t,3,we(e,t+1,r))}function nu(e,t,n,r){return Lt(e,t,5,xe(e,t+1,r))}function ru(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 Lt(e,t,9,o)}function ou(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.array.majorEncoded,t.value)}jr.compareTokens=Te.compareTokens;jr.encodedSize=function(t){return W.encodedSize(t.value)};function Mt(e,t,n,r){return new k(g.map,r,n)}function iu(e,t,n,r){return Mt(e,t,1,n)}function au(e,t,n,r){return Mt(e,t,2,_e(e,t+1,r))}function su(e,t,n,r){return Mt(e,t,3,we(e,t+1,r))}function cu(e,t,n,r){return Mt(e,t,5,xe(e,t+1,r))}function uu(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 Mt(e,t,9,o)}function lu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${M} indefinite length items not allowed`);return Mt(e,t,1,1/0)}function Nr(e,t){W(e,g.map.majorEncoded,t.value)}Nr.compareTokens=Te.compareTokens;Nr.encodedSize=function(t){return W.encodedSize(t.value)};function du(e,t,n,r){return new k(g.tag,n,1)}function fu(e,t,n,r){return new k(g.tag,_e(e,t+1,r),2)}function pu(e,t,n,r){return new k(g.tag,we(e,t+1,r),3)}function mu(e,t,n,r){return new k(g.tag,xe(e,t+1,r),5)}function hu(e,t,n,r){return new k(g.tag,$e(e,t+1,r),9)}function Cr(e,t){W(e,g.tag.majorEncoded,t.value)}Cr.compareTokens=Te.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(`${M} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new k(g.null,null,1):new k(g.undefined,void 0,1)}function yu(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 Oi(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 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 Tn(e,t,n){let r=t.value;if(r===!1)e.push([g.float.majorEncoded|Ai]);else if(r===!0)e.push([g.float.majorEncoded|Ti]);else if(r===null)e.push([g.float.majorEncoded|Pi]);else if(r===void 0)e.push([g.float.majorEncoded|zi]);else{let o,i=!1;(!n||n.float64!==!0)&&(xu(r),o=Ui(De,1),r===o||Number.isNaN(r)?(De[0]=249,e.push(De.slice(0,3)),i=!0):($u(r),o=Di(De,1),r===o&&(De[0]=250,e.push(De.slice(0,5)),i=!0))),i||(yp(r),o=Su(De,1),De[0]=251,e.push(De.slice(0,9)))}}Tn.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(De,1);if(r===o||Number.isNaN(r))return 3;if($u(r),o=Di(De,1),r===o)return 5}return 9};var wu=new ArrayBuffer(9),Pe=new DataView(wu,1),De=new Uint8Array(wu,0);function xu(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 Ui(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 $u(e){Pe.setFloat32(0,e,!1)}function Di(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 yp(e){Pe.setFloat64(0,e,!1)}function Su(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)}Tn.compareTokens=Te.compareTokens;function F(e,t,n){throw new Error(`${M} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Lr(e){return()=>{throw new Error(`${M} ${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 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 Ri(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 bp={float64:!1,mapSorter:xp,quickEncodeToken:Ri},Tu=Object.freeze({float64:!0,mapSorter:$p,quickEncodeToken:Ri});function _p(){let e=[];return e[g.uint.major]=Te,e[g.negint.major]=Dr,e[g.bytes.major]=Ct,e[g.string.major]=Yc,e[g.array.major]=jr,e[g.map.major]=Nr,e[g.tag.major]=Cr,e[g.float.major]=Tn,e}var Zt=_p(),Mr=new En,zn=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)}},ut={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?ut.true:ut.false},null(e,t,n,r){return ut.null},undefined(e,t,n,r){return ut.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?[ut.emptyArray,new k(g.break)]:ut.emptyArray;r=zn.createCheck(r,e);let o=[],i=0;for(let a of e)o[i++]=Zr(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=zn.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?(wp(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?[ut.emptyMap,new k(g.break)]:ut.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 Zr(e,t={},n){let r=ki(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(`${Ur} unsupported type: ${r}`);return i(e,r,t,n)}function wp(e,t){t.mapSorter&&e.sort(t.mapSorter)}function xp(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=Zt[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=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,Zt,Tu)}function Pn(e,t,n,r){if(Array.isArray(t))for(let o of t)Pn(e,o,n,r);else n[t.type.major](e,t,r)}var ku=g.uint.majorEncoded,Iu=g.negint.majorEncoded,Sp=g.bytes.majorEncoded,Ep=g.string.majorEncoded,Au=g.array.majorEncoded,kp=g.float.majorEncoded|Ai,Ip=g.float.majorEncoded|Ti,Ap=g.float.majorEncoded|Pi,Tp=g.float.majorEncoded|zi,Pp=BigInt(-1),zp=BigInt(1);function Op(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){Pn(e,a,Zt,n);return}}switch(o){case"null":e.push([Ap]);return;case"undefined":e.push([Tp]);return;case"boolean":e.push([t?Ip:kp]);return;case"number":!Number.isInteger(t)||!Number.isSafeInteger(t)?Tn(e,new k(g.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*Pp-zp);return;case"string":{let a=Pr(t);W(e,Ep,a.length),e.push(a);return}case"Uint8Array":W(e,Sp,t.length),e.push(t);return;case"Array":if(!t.length){e.push([Au]);return}r=zn.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=Ze.Object(t,o,n,r);Pn(e,a,Zt,n)}return;default:{let a=Ze[o];if(!a)throw new Error(`${Ur} unsupported type: ${o}`);let s=a(t,o,n,r);Pn(e,s,Zt,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 En(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():Sn(i.chunks[0])}}return i.reset(),Pn(i,a,t,n),i.toBytes(!0)}function ji(e,t){return t=Object.assign({},bp,t),Op(t)?(Mr.reset(),Pu(Mr,e,t,void 0),Mr.toBytes(!0)):zu(e,Zt,t)}var Up={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=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}},On=Symbol.for("DONE"),Fr=Symbol.for("BREAK");function Dp(e,t,n){let r=[];for(let o=0;o<e.value;o++){let i=Bt(t,n);if(i===Fr){if(e.value===1/0)break;throw new Error(`${M} got unexpected break to lengthed array`)}if(i===On)throw new Error(`${M} found array but not enough entries (got ${o}, expected ${e.value})`);r[o]=i}return r}function Rp(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=Bt(t,n);if(u===Fr){if(e.value===1/0)break;throw new Error(`${M} got unexpected break to lengthed map`)}if(u===On)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=Bt(t,n);if(c===On)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 Bt(e,t){if(e.done())return On;let n=e.next();if(g.equals(n.type,g.break))return Fr;if(n.type.terminal)return n.value;if(g.equals(n.type,g.array))return Dp(n,e,t);if(g.equals(n.type,g.map))return Rp(n,e,t);if(g.equals(n.type,g.tag)){if(t.tags&&typeof t.tags[n.value]=="function"){let r=Bt(e,t);return t.tags[n.value](r)}throw new Error(`${M} tag not supported (${n.value})`)}throw new Error("unsupported")}function Ou(e,t){if(!(e instanceof Uint8Array))throw new Error(`${M} data to decode must be a Uint8Array`);t=Object.assign({},Up,t);let n=Sn(e),r=t.tokenizer||new Br(n,t),o=Bt(r,t);if(o===On)throw new Error(`${M} did not find any content to decode`);if(o===Fr)throw new Error(`${M} 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(`${M} too many terminals, data makes no sense`);return n}var wk=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 Ft(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 Np(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,v=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<v)&&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");v=C,S++}for(var Z=_-v;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 v=0,S=0;f[y]===u;)v++,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(v+(I-U)),Q=v;U!==I;)Z[Q++]=_[U++];return Z}}}function b(f){var y=p(f);if(y)return y;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:p,decode:b}}var Cp=Np,Lp=Cp,Du=Lp;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 Ht({name:e,prefix:t,alphabet:n}){let{encode:r,decode:o}=Du(n,e);return ju({prefix:t,name:e,encode:r,decode:i=>Ft(o(i))})}function Mp(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 Zp(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 Bp(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=Bp(r);return ju({prefix:t,name:e,encode(i){return Zp(i,r,n)},decode(i){return Mp(i,o,n,e)}})}var Un=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ak=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Tk=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Pk=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zk=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ok=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Uk=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Dk=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Rk=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Hr=Ht({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ck=Ht({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var nt=Ht({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zk=Ht({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Fp=Lu,Nu=128,Hp=127,Jp=~Hp,Gp=Math.pow(2,31);function Lu(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Gp;)t[n++]=e&255|Nu,e/=128;for(;e&Jp;)t[n++]=e&255|Nu,e>>>=7;return t[n]=e|0,Lu.bytes=n-r+1,t}var Vp=Bi,qp=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>=qp);return Bi.bytes=i-r,n}var Kp=Math.pow(2,7),Wp=Math.pow(2,14),Xp=Math.pow(2,21),Yp=Math.pow(2,28),Qp=Math.pow(2,35),em=Math.pow(2,42),tm=Math.pow(2,49),nm=Math.pow(2,56),rm=Math.pow(2,63),om=function(e){return e<Kp?1:e<Wp?2:e<Xp?3:e<Yp?4:e<Qp?5:e<em?6:e<tm?7:e<nm?8:e<rm?9:10},im={encode:Fp,decode:Vp,encodingLength:om},am=im,Dn=am;function Rn(e,t=0){return[Dn.decode(e,t),Dn.decode.bytes]}function Jt(e,t,n=0){return Dn.encode(e,t,n),t}function Gt(e){return Dn.encodingLength(e)}function Zu(e,t){let n=t.byteLength,r=Gt(e),o=r+Gt(n),i=new Uint8Array(o+n);return Jt(e,i,0),Jt(n,i,r),i.set(t,o),new Vt(e,n,t,i)}function Bu(e){let t=Ft(e),[n,r]=Rn(t),[o,i]=Rn(t.subarray(r)),a=t.subarray(r+i);if(a.byteLength!==o)throw new Error("Incorrect length");return new Vt(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 Vt=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?um(n,Fi(e),t??nt.encoder):lm(n,Fi(e),t??Un.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 Nn=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!==jn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==dm)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[fm]===!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!==jn)throw new Error(`Version 0 CID must use dag-pb (code: ${jn}) 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,jn,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=Ft(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 Vt(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]=Rn(t.subarray(n));return n+=p,d},o=r(),i=jn;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]=cm(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 cm(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 Un.prefix:{let n=t??Un;return[Un.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 um(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 lm(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 jn=112,dm=18;function Gu(e,t,n){let r=Gt(e),o=r+Gt(t),i=new Uint8Array(o+n.byteLength);return Jt(e,i,0),Jt(t,i,r),i.set(n,o),i}var fm=Symbol.for("@ipld/js-cid/CID");var Vu=42;function pm(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function mm(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Nn.asCID(e);if(!t)return null;let n=new Uint8Array(t.bytes.byteLength+1);return n.set(t.bytes,1),[new k(g.tag,Vu),new k(g.bytes,n)]}function hm(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function gm(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 ym(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:ym,Object:mm,undefined:hm,number:gm}},Qk={...Hi,typeEncoders:{...Hi.typeEncoders}};function vm(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Nn.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]=vm;var eI={...Jr,tags:Jr.tags.slice()};var Se=e=>ji(e,Hi),Fe=e=>Ni(pm(e),Jr);function bm(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function _m(){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 wm(e,t){return t()}var xm="(?:%[0-9a-fA-F]{2})",qu=`(?:[a-zA-Z0-9._-]|${xm})`,$m="([a-z0-9]+)",Sm=`((?:${qu}*:)*(${qu}+))`,Ku="[a-zA-Z0-9_.:%-]",Em=`;${Ku}+=${Ku}*`,km=`((${Em})*)`,Im="(/[^#?]*)?",Am="([?][^#]*)?",Tm="(#.*)?",Pm=new RegExp(`^did:${$m}:${Sm}${km}${Im}${Am}${Tm}$`);function zm(e){if(e===""||!e)return null;let t=e.match(Pm);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 Om(e){return function(t,n,r){try{return Promise.resolve(bm(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?_m():n.cache||wm,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=Om(n.legacyResolvers[r]))})}resolve(t,n={}){try{let r=this,o=zm(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 Cn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Um}=Object.prototype,{getPrototypeOf:Gi}=Object,{iterator:Kr,toStringTag:Xu}=Symbol,Wr=(e=>t=>{let n=Um.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),je=e=>(e=e.toLowerCase(),t=>Wr(t)===e),Xr=e=>t=>typeof t===e,{isArray:Kt}=Array,qt=Xr("undefined");function Ln(e){return e!==null&&!qt(e)&&e.constructor!==null&&!qt(e.constructor)&&he(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Yu=je("ArrayBuffer");function Dm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Yu(e.buffer),t}var Rm=Xr("string"),he=Xr("function"),Qu=Xr("number"),Mn=e=>e!==null&&typeof e=="object",jm=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)},Nm=e=>{if(!Mn(e)||Ln(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Cm=je("Date"),Lm=je("File"),Mm=je("Blob"),Zm=je("FileList"),Bm=e=>Mn(e)&&he(e.pipe),Fm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||he(e.append)&&((t=Wr(e))==="formdata"||t==="object"&&he(e.toString)&&e.toString()==="[object FormData]"))},Hm=je("URLSearchParams"),[Jm,Gm,Vm,qm]=["ReadableStream","Request","Response","Headers"].map(je),Km=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Zn(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Kt(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Ln(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(Ln(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,tl=e=>!qt(e)&&e!==wt;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):Kt(o)?n[a]=o.slice():(!t||!qt(o))&&(n[a]=o)};for(let o=0,i=arguments.length;o<i;o++)arguments[o]&&Zn(arguments[o],r);return n}var Wm=(e,t,n,{allOwnKeys:r}={})=>(Zn(t,(o,i)=>{n&&he(o)?e[i]=Cn(o,n):e[i]=o},{allOwnKeys:r}),e),Xm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Ym=(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)},Qm=(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},eh=(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},th=e=>{if(!e)return null;if(Kt(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},nh=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Gi(Uint8Array)),rh=(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])}},oh=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},ih=je("HTMLFormElement"),ah=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),sh=je("RegExp"),nl=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};Zn(n,(o,i)=>{let a;(a=t(o,i,e))!==!1&&(r[i]=a||o)}),Object.defineProperties(e,r)},ch=e=>{nl(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+"'")})}})},uh=(e,t)=>{let n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Kt(e)?r(e):r(String(e).split(t)),n},lh=()=>{},dh=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function fh(e){return!!(e&&he(e.append)&&e[Xu]==="FormData"&&e[Kr])}var ph=e=>{let t=new Array(10),n=(r,o)=>{if(Mn(r)){if(t.indexOf(r)>=0)return;if(Ln(r))return r;if(!("toJSON"in r)){t[o]=r;let i=Kt(r)?[]:{};return Zn(r,(a,s)=>{let u=n(a,o+1);!qt(u)&&(i[s]=u)}),t[o]=void 0,i}}return r};return n(e,0)},mh=je("AsyncFunction"),hh=e=>e&&(Mn(e)||he(e))&&he(e.then)&&he(e.catch),rl=((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)),gh=typeof queueMicrotask<"u"?queueMicrotask.bind(wt):typeof process<"u"&&process.nextTick||rl,yh=e=>e!=null&&he(e[Kr]),m={isArray:Kt,isArrayBuffer:Yu,isBuffer:Ln,isFormData:Fm,isArrayBufferView:Dm,isString:Rm,isNumber:Qu,isBoolean:jm,isObject:Mn,isPlainObject:qr,isEmptyObject:Nm,isReadableStream:Jm,isRequest:Gm,isResponse:Vm,isHeaders:qm,isUndefined:qt,isDate:Cm,isFile:Lm,isBlob:Mm,isRegExp:sh,isFunction:he,isStream:Bm,isURLSearchParams:Hm,isTypedArray:nh,isFileList:Zm,forEach:Zn,merge:Ji,extend:Wm,trim:Km,stripBOM:Xm,inherits:Ym,toFlatObject:Qm,kindOf:Wr,kindOfTest:je,endsWith:eh,toArray:th,forEachEntry:rh,matchAll:oh,isHTMLForm:ih,hasOwnProperty:Wu,hasOwnProp:Wu,reduceDescriptors:nl,freezeMethods:ch,toObjectSet:uh,toCamelCase:ah,noop:lh,toFiniteNumber:dh,findKey:el,global:wt,isContextDefined:tl,isSpecCompliantForm:fh,toJSONObject:ph,isAsyncFn:mh,isThenable:hh,setImmediate:rl,asap:gh,isIterable:yh};function Wt(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(Wt,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 ol=Wt.prototype,il={};["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=>{il[e]={value:e}});Object.defineProperties(Wt,il);Object.defineProperty(ol,"isAxiosError",{value:!0});Wt.from=(e,t,n,r,o,i)=>{let a=Object.create(ol);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 Wt.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=Wt;var Yr=null;function Vi(e){return m.isPlainObject(e)||m.isArray(e)}function sl(e){return m.endsWith(e,"[]")?e.slice(0,-2):e}function al(e,t,n){return e?e.concat(t).map(function(o,i){return o=sl(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function vh(e){return m.isArray(e)&&!e.some(Vi)}var bh=m.toFlatObject(m,{},null,function(t){return/^is[A-Z]/.test(t)});function _h(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(y,v){return!m.isUndefined(v[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,v){let S=f;if(f&&!v&&typeof f=="object"){if(m.endsWith(y,"{}"))y=r?y:y.slice(0,-2),f=JSON.stringify(f);else if(m.isArray(f)&&vh(f)||(m.isFileList(f)||m.endsWith(y,"[]"))&&(S=m.toArray(f)))return y=sl(y),S.forEach(function(_,E){!(m.isUndefined(_)||_===null)&&t.append(a===!0?al([y],E,i):a===null?y:y+"[]",c(_))}),!1}return Vi(f)?!0:(t.append(al(v,y,i),c(f)),!1)}let d=[],p=Object.assign(bh,{defaultVisitor:l,convertValue:c,isVisitable:Vi});function b(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&&b(S,y?y.concat(I):[I])}),d.pop()}}if(!m.isObject(e))throw new TypeError("data must be an object");return b(e),t}var lt=_h;function cl(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function ul(e,t){this._pairs=[],e&<(e,this,t)}var ll=ul.prototype;ll.append=function(t,n){this._pairs.push([t,n])};ll.toString=function(t){let n=t?function(r){return t.call(this,r,cl)}:cl;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};var Qr=ul;function wh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Bn(e,t,n){if(!t)return e;let r=n&&n.encode||wh;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 Qr(t,n).toString(r),i){let a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+i}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 dl=typeof URLSearchParams<"u"?URLSearchParams:Qr;var fl=typeof FormData<"u"?FormData:null;var pl=typeof Blob<"u"?Blob:null;var ml={isBrowser:!0,classes:{URLSearchParams:dl,FormData:fl,Blob:pl},protocols:["http","https","file","blob","url","data"]};var Yi={};of(Yi,{hasBrowserEnv:()=>Xi,hasStandardBrowserEnv:()=>xh,hasStandardBrowserWebWorkerEnv:()=>$h,navigator:()=>Wi,origin:()=>Sh});var Xi=typeof window<"u"&&typeof document<"u",Wi=typeof navigator=="object"&&navigator||void 0,xh=Xi&&(!Wi||["ReactNative","NativeScript","NS"].indexOf(Wi.product)<0),$h=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Sh=Xi&&window.location.href||"http://localhost";var Y={...Yi,...ml};function Qi(e,t){return lt(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 Eh(e){return m.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function kh(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 Ih(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]=kh(o[a])),!s)}if(m.isFormData(e)&&m.isFunction(e.entries)){let n={};return m.forEachEntry(e,(r,o)=>{t(Eh(r),o,n,0)}),n}return null}var to=Ih;function Ah(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 lt(s?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),Ah(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"?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=>{ea.headers[e]={}});var Xt=ea;var Th=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"]),hl=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]&&Th[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};var gl=Symbol("internals");function Fn(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 Ph(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 zh=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 Oh(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Uh(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=Fn(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())&&!zh(t))a(hl(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=Fn(t),t){let r=m.findKey(this,t);if(r){let o=this[r];if(!n)return o;if(n===!0)return Ph(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=Fn(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=Fn(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?Oh(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[gl]=this[gl]={accessors:{}}).accessors,o=this.prototype;function i(a){let s=Fn(a);r[s]||(Uh(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 ie=Yt;function Hn(e,t){let n=this||Xt,r=t||n,o=ie.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 Jn(e){return!!(e&&e.__CANCEL__)}function yl(e,t,n){O.call(this,e??"canceled",O.ERR_CANCELED,t,n),this.name="CanceledError"}m.inherits(yl,O,{__CANCEL__:!0});var He=yl;function Gn(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 na(e){let t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Dh(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 vl=Dh;function Rh(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 bl=Rh;var Qt=(e,t,n=3)=>{let r=0,o=vl(50,250);return bl(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)},ra=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},oa=e=>(...t)=>m.asap(()=>e(...t));var _l=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 wl=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 ia(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function aa(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Vn(e,t,n){let r=!ia(t);return e&&(r||n==!1)?aa(e,t):t}var xl=e=>e instanceof ie?{...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(xl(c),xl(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=Ne({},e),{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:i,headers:a,auth:s}=t;if(t.headers=a=ie.from(a),t.url=Bn(Vn(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&&_l(t.url))){let u=o&&i&&wl.read(i);u&&a.set(o,u)}return t};var jh=typeof XMLHttpRequest<"u",$l=jh&&function(e){return new Promise(function(n,r){let o=ro(e),i=o.data,a=ie.from(o.headers).normalize(),{responseType:s,onUploadProgress:u,onDownloadProgress:c}=o,l,d,p,b,f;function y(){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 S(){if(!v)return;let _=ie.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),x={data:!s||s==="text"||s==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:_,config:e,request:v};Gn(function(U){n(U),y()},function(U){r(U),y()},x),v=null}"onloadend"in v?v.onloadend=S:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(S)},v.onabort=function(){v&&(r(new O("Request aborted",O.ECONNABORTED,e,v)),v=null)},v.onerror=function(E){let x=E&&E.message?E.message:"Network Error",C=new O(x,O.ERR_NETWORK,e,v);C.event=E||null,r(C),v=null},v.ontimeout=function(){let E=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",x=o.transitional||eo;o.timeoutErrorMessage&&(E=o.timeoutErrorMessage),r(new O(E,x.clarifyTimeoutError?O.ETIMEDOUT:O.ECONNABORTED,e,v)),v=null},i===void 0&&a.setContentType(null),"setRequestHeader"in v&&m.forEach(a.toJSON(),function(E,x){v.setRequestHeader(x,E)}),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=_=>{v&&(r(!_||_.type?new He(null,e,v):_),v.abort(),v=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));let I=na(o.url);if(I&&Y.protocols.indexOf(I)===-1){r(new O("Unsupported protocol "+I+":",O.ERR_BAD_REQUEST,e));return}v.send(i||null)})};var Nh=(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}},Sl=Nh;var Ch=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},Lh=async function*(e,t){for await(let n of Mh(e))yield*Ch(n,t)},Mh=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()}},sa=(e,t,n,r)=>{let o=Lh(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 El=64*1024,{isFunction:oo}=m,Zh=(({Request:e,Response:t})=>({Request:e,Response:t}))(m.global),{ReadableStream:kl,TextEncoder:Il}=m.global,Al=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Bh=e=>{e=m.merge.call({skipUndefined:!0},Zh,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(kl),u=o&&(typeof Il=="function"?(f=>y=>f.encode(y))(new Il):async f=>new Uint8Array(await new n(f).arrayBuffer())),c=i&&s&&Al(()=>{let f=!1,y=new n(Y.origin,{body:new kl,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!y}),l=a&&s&&Al(()=>m.isReadableStream(new r("").body)),d={stream:l&&(f=>f.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!d[f]&&(d[f]=(y,v)=>{let S=y&&y[f];if(S)return S.call(y);throw new O(`Response type '${f}' is not supported`,O.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,y)=>{let v=m.toFiniteNumber(f.getContentLength());return v??p(y)};return async f=>{let{url:y,method:v,data:S,signal:I,cancelToken:_,timeout:E,onDownloadProgress:x,onUploadProgress:C,responseType:U,headers:Z,withCredentials:Q="same-origin",fetchOptions:Ie}=ro(f),h=t||fetch;U=U?(U+"").toLowerCase():"text";let w=Sl([I,_&&_.toAbortSignal()],E),z=null,B=w&&w.unsubscribe&&(()=>{w.unsubscribe()}),q;try{if(C&&c&&v!=="get"&&v!=="head"&&(q=await b(Z,S))!==0){let ce=new n(y,{method:"POST",body:S,duplex:"half"}),Ot;if(m.isFormData(S)&&(Ot=ce.headers.get("content-type"))&&Z.setContentType(Ot),ce.body){let[ri,pr]=ra(q,Qt(oa(C)));S=sa(ce.body,El,ri,pr)}}m.isString(Q)||(Q=Q?"include":"omit");let L=i&&"credentials"in n.prototype,mt={...Ie,signal:w,method:v.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(vs=>{ce[vs]=Ae[vs]});let Ot=m.toFiniteNumber(Ae.headers.get("content-length")),[ri,pr]=x&&ra(Ot,Qt(oa(x),!0))||[];Ae=new r(sa(Ae.body,El,ri,()=>{pr&&pr(),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,Ot)=>{Gn(ce,Ot,{data:ne,headers:ie.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)}}},Fh=new Map,ca=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=Fh;for(;s--;)u=i[s],c=l.get(u),c===void 0&&l.set(u,c=s?new Map:Bh(t)),l=c;return c},aT=ca();var ua={http:Yr,xhr:$l,fetch:{get:ca}};m.forEach(ua,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var Tl=e=>`- ${e}`,Jh=e=>m.isFunction(e)||e===null||e===!1;function Gh(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,!Jh(r)&&(o=ua[(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(Tl).join(`
|
|
6
|
+
`):" "+Tl(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 io={getAdapter:Gh,adapters:ua};function la(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new He(null,e)}function ao(e){return la(e),e.headers=ie.from(e.headers),e.data=Hn.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 la(e),r.data=Hn.call(e,e.transformResponse,r),r.headers=ie.from(r.headers),r},function(r){return Jn(r)||(la(e),r&&r.response&&(r.response.data=Hn.call(e,e.transformResponse,r.response),r.response.headers=ie.from(r.response.headers))),Promise.reject(r)})}var so="1.13.2";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 Pl={};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 O(o(a," has been removed"+(n?" in "+n:"")),O.ERR_DEPRECATED);return n&&!Pl[a]&&(Pl[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 Vh(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 qn={assertOptions:Vh,validators:co};var Je=qn.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=Ne(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&qn.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}:qn.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),qn.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=ie.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=[ao.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 b=n;for(;d<p;){let f=s[d++],y=s[d++];try{b=f(b)}catch(v){y.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++],c[d++]);return l}getUri(t){t=Ne(this.defaults,t);let n=Vn(t.baseURL,t.url,t.allowAbsoluteUrls);return Bn(n,t.params,t.paramsSerializer)}};m.forEach(["delete","get","head","options"],function(t){en.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}))}}en.prototype[t]=n(),en.prototype[t+"Form"]=n(!0)});var Kn=en;var da=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}}},zl=da;function fa(e){return function(n){return e.apply(null,n)}}function pa(e){return m.isObject(e)&&e.isAxiosError===!0}var ma={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(ma).forEach(([e,t])=>{ma[t]=e});var Ol=ma;function Ul(e){let t=new Kn(e),n=Cn(Kn.prototype.request,t);return m.extend(n,Kn.prototype,t,{allOwnKeys:!0}),m.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Ul(Ne(e,o))},n}var te=Ul(Xt);te.Axios=Kn;te.CanceledError=He;te.CancelToken=zl;te.isCancel=Jn;te.VERSION=so;te.toFormData=lt;te.AxiosError=O;te.Cancel=te.CanceledError;te.all=function(t){return Promise.all(t)};te.spread=fa;te.isAxiosError=pa;te.mergeConfig=Ne;te.AxiosHeaders=ie;te.formToJSON=e=>to(m.isHTMLForm(e)?new FormData(e):e);te.getAdapter=io.getAdapter;te.HttpStatusCode=Ol;te.default=te;var uo=te;var{Axios:r0,AxiosError:o0,CanceledError:i0,isCancel:a0,CancelToken:s0,VERSION:c0,all:u0,Cancel:l0,isAxiosError:d0,spread:f0,toFormData:p0,AxiosHeaders:m0,HttpStatusCode:h0,formToJSON:g0,getAdapter:y0,mergeConfig:v0}=uo;function qh(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 ha)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 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{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 tn(e){return e instanceof ha&&e.s&1}function Kh(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 ha,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(),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}}Ee(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){Ee(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else Ee(i,1,r)}}function Dl(){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=Kh(function(){function l(){r||u?.id===t||(i="resolver_error: DID document id does not match requested did")}let d=qh(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 Nl=af(jl(),1);function Wh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var Xh=function(e){try{return Promise.resolve((0,Nl.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 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 Yh="/.well-known/did.json",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 rn(e){return e instanceof ga&&e.s&1}function Qh(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 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(),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}}ke(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){ke(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else ke(i,1,r)}}function Cl(){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)+Yh,s=n.id.split(":");s.length>1&&(a=s.map(decodeURIComponent).join("/")+"/did.json");let u=`https://${a}`,c={},l=null,d=Qh(function(){function p(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let b=Wh(function(){return Promise.resolve(Xh(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={...Dl(),...Cl()};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 re(`DID not found: ${t}`);return n}};var ba;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(ba="oauth4webapi/v3.8.3");function er(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(),vo=Symbol(),bo=Symbol(),St=Symbol();var mo=Symbol();var eg=new TextEncoder,tg=new TextDecoder;function Ll(e){return typeof e=="string"?eg.encode(e):tg.decode(e)}var _a;Uint8Array.prototype.toBase64?_a=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):_a=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 wa;Uint8Array.fromBase64?wa=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw K("The input to be decoded is not correctly encoded.",ye,t)}}:wa=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 xa(e){return typeof e=="string"?wa(e):_a(e)}var ft=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Eo,Error.captureStackTrace?.(this,this.constructor)}},Xn=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 Xn(e,{code:t,cause:n})}function ho(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function $a(e){er(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(ba&&!t.has("user-agent")&&t.set("user-agent",ba),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',ye);return t}function Zl(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 Bl(e){return e.includes("//")?e.replace("//","/"):e}function ng(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=Bl(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function rg(e,t){return e.pathname=Bl(`${e.pathname}/${t}`),e}async function og(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,ze);xo(e,r?.[$t]!==!0);let o=n(new URL(e.href)),i=$a(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:Zl(o,r?.signal)})}async function Fl(e,t){return og(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":rg(n,".well-known/openid-configuration");break;case"oauth2":ng(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',ye)}return n},t)}function Wn(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 Hl(e,t){let n=e;if(!(n instanceof URL)&&n!==yo)throw K('"expectedIssuerIdentifier" must be an instance of URL',ze);if(!er(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)',ko,t);Da(t);let r=await ad(t);if(ge(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 Jl(e){ag(e,"application/json")}function ig(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,za,e)}function ag(e,t){if(Aa(e)!==t)throw ig(e,t)}function sg(){return xa(crypto.getRandomValues(new Uint8Array(32)))}function Gl(){return sg()}function Sa(e){let t=e?.[vo];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ea(e){let t=e?.[bo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function ka(){return Math.floor(Date.now()/1e3)}function _o(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',ze);ge(e.issuer,'"as.issuer"')}function wo(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',ze);ge(e.client_id,'"client.client_id"')}function Ia(e){return ge(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function Vl(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var cg=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",Oa,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw N("only HTTP and HTTPS requests are allowed",Ua,e)}function Ml(e,t,n,r){let o;if(typeof e!="string"||!(o=cg(e)))throw N(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?Ug:Dg,{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?Ml(e.mtls_endpoint_aliases[t],t,n,r):Ml(e[t],t,n,r)}function ql(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=zg,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)}},Yn=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Og,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=Pg,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!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ug="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",lg='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',dg="("+go+")\\s*=\\s*"+lg,fg="("+go+")\\s*=\\s*("+go+")",pg=new RegExp("^[,\\s]*("+go+")"),mg=new RegExp("^[,\\s]*"+dg+"[,\\s]*(.*)"),hg=new RegExp("^[,\\s]*"+fg+"[,\\s]*(.*)"),gg=new RegExp("^("+ug+")(?:$|[,\\s])(.*)");function yg(e){if(!er(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(pg),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(mg)){if([,p,b,r]=o,b.includes("\\"))try{b=JSON.parse(`"${b}"`)}catch{}c[p.toLowerCase()]=b;continue}if(o=r.match(hg)){[,p,b,r]=o,c[p.toLowerCase()]=b;continue}if(o=r.match(gg)){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 vg(e){if(e.status>399&&e.status<500){Da(e),Jl(e);try{let t=await e.clone().json();if(ho(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function Kl(e,t,n){if(e.status!==t){xg(e);let r;throw(r=await vg(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 bg(e){if(!Ta.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',ye)}function Aa(e){return e.headers.get("content-type")?.split(";")[0]}async function Wl(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:Zl(r,a?.signal)})}async function _g(e,t,n,r,o,i){let a=$o(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[$t]!==!0);o.set("grant_type",r);let s=$a(i?.headers);s.set("accept","application/json"),i?.DPoP!==void 0&&(bg(i.DPoP),await i.DPoP.addProof(a,s,"POST"));let u=await Wl(e,t,n,a,o,s,i);return i?.DPoP?.cacheNonce(u,a),u}var Xl=new WeakMap,wg=new WeakMap;function So(e){if(!e.id_token)return;let t=Xl.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',ye);return t}async function Yl(e,t,n,r,o,i){if(_o(e),wo(t),!er(n,Response))throw K('"response" must be an instance of Response',ze);await Kl(n,200,"Token Endpoint"),Da(n);let a=await ad(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;Wn(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&&(Wn(t.default_max_age,!0,'"client.default_max_age"'),s.push("auth_time")),r?.length&&s.push(...r);let{claims:u,jwt:c}=await Rg(a.id_token,Ng.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Sa(t),Ea(t),o).then(Ig.bind(void 0,s)).then(Sg.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&&Wn(u.auth_time,!0,'ID Token "auth_time" (authentication time)',G,{claims:u}),wg.set(n,c),Xl.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 ft("unsupported `token_type` value",{cause:{body:a}});return a}function xg(e){let t;if(t=yg(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',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 Sg(e,t){let n=e[Ra]?.(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 Ta=new WeakSet;function Eg(e){return Ta.add(e),e}var Pa=Symbol();async function Ql(e,t,n,r,o,i,a){if(_o(e),wo(t),!Ta.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!==Pa&&(ge(i,'"codeVerifier"'),u.set("code_verifier",i)),_g(e,t,n,"authorization_code",u,a)}var kg={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 Ig(e,t){for(let n of e)if(t.claims[n]===void 0)throw N(`JWT "${n}" (${kg[n]}) claim missing`,G,{claims:t.claims});return t}var ya=Symbol(),va=Symbol();async function ed(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Ag(e,t,n,r.expectedNonce,r.maxAge,r[mo],r.recognizedTokenTypes):Tg(e,t,n,r?.[mo],r?.recognizedTokenTypes)}async function Ag(e,t,n,r,o,i,a){let s=[];switch(r){case void 0:r=ya;break;case ya:break;default:ge(r,'"expectedNonce" argument'),s.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=va;break;case va:break;default:Wn(o,!0,'"maxAge" argument'),s.push("auth_time")}let u=await Yl(e,t,n,s,i,a);ge(u.id_token,'"response" body "id_token" property',G,{body:u});let c=So(u);if(o!==va){let l=ka()+Sa(t),d=Ea(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===ya){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 Tg(e,t,n,r,o){let i=await Yl(e,t,n,void 0,r,o),a=So(i);if(a){if(t.default_max_age!==void 0){Wn(t.default_max_age,!0,'"client.default_max_age"');let s=ka()+Sa(t),u=Ea(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',Ge,{expected:void 0,claims:a,claim:"nonce"})}return i}var Pg="OAUTH_WWW_AUTHENTICATE_CHALLENGE",zg="OAUTH_RESPONSE_BODY_ERROR",Eo="OAUTH_UNSUPPORTED_OPERATION",Og="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var Qn="OAUTH_PARSE_ERROR",G="OAUTH_INVALID_RESPONSE";var za="OAUTH_RESPONSE_IS_NOT_JSON",ko="OAUTH_RESPONSE_IS_NOT_CONFORM",Oa="OAUTH_HTTP_REQUEST_FORBIDDEN",Ua="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",sn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Ge="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Io="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Ug="OAUTH_MISSING_SERVER_METADATA",Dg="OAUTH_INVALID_SERVER_METADATA";async function td(e,t,n,r,o){_o(e),wo(t),ge(r,'"token"');let i=$o(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[$t]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let s=$a(o?.headers);return s.delete("accept"),Wl(e,t,n,i,a,s,o)}async function nd(e){if(!er(e,Response))throw K('"response" must be an instance of Response',ze);await Kl(e,200,"Revocation Endpoint")}function Da(e){if(e.bodyUsed)throw K('"response" body has been used already',ye)}async function Rg(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 ft("JWE decryption is not configured",{cause:e});if(s!==3)throw N("Invalid JWT",G,e);let u;try{u=JSON.parse(Ll(xa(i)))}catch(d){throw N("failed to parse JWT Header body as base64url encoded JSON",Qn,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 ft('no JWT "crit" header parameter extensions are supported',{cause:{header:u}});let c;try{c=JSON.parse(Ll(xa(a)))}catch(d){throw N("failed to parse JWT Payload body as base64url encoded JSON",Qn,d)}if(!ho(c))throw N("JWT Payload must be a top level object",G,e);let l=ka()+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 jg(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",ye,{cause:e});return e.text()}async function rd(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",ye,{cause:e});if(Aa(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 jg(e)}function Ng(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 od=Symbol(),Cg=Symbol();function id(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',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 Cg:if(i!==void 0)throw N('unexpected "state" response parameter encountered',G,{expected:void 0,parameters:n});break;case od: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 Yn("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 ft("implicit and hybrid flows are not supported");return Eg(new URLSearchParams(n))}async function ad(e,t=Jl){let n;try{n=await e.json()}catch(r){throw t(e),N('failed to parse "response" body as JSON',Qn,r)}if(!ho(n))throw N('"response" body must be a top level object',G,{body:n});return n}var yo=Symbol(),Ra=Symbol();var nr,sd;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(sd="openid-client/v6.8.1",nr={"user-agent":sd});var Ce=e=>Na.get(e),Na,ja;function Mg(e){return e!==void 0?Ia(e):(ja||=new WeakMap,(t,n,r,o)=>{let i;return(i=ja.get(n))||(Zg(n.client_secret,'"metadata.client_secret"'),i=Ia(n.client_secret),ja.set(n,i)),i(t,n,r,o)})}function Zg(e,t){if(typeof e!="string")throw Ve(`${t} must be a string`,or);if(e.length===0)throw Ve(`${t} must not be empty`,rr)}function Bg(){return Vl()}var cn=St;var rr="ERR_INVALID_ARG_VALUE",or="ERR_INVALID_ARG_TYPE";function Ve(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function ud(){return Gl()}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)}},mP=new TextDecoder;function pe(e,t,n){return new un(e,{cause:t,code:n})}function tr(e){if(e instanceof TypeError||e instanceof un||e instanceof on||e instanceof Yn||e instanceof an)throw e;if(e instanceof Xn)switch(e.code){case Oa:throw pe("only requests to HTTPS are allowed",e,e.code);case Ua:throw pe("only requests to HTTP or HTTPS are allowed",e,e.code);case ko:throw pe("unexpected HTTP response status code",e.cause,e.code);case za:throw pe("unexpected response content-type",e.cause,e.code);case Qn: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 Io:throw pe("unexpected JSON attribute value encountered",e,e.code);case sn:throw pe("JWT timestamp claim value failed validation",e,e.code);default:throw pe(e.message,e,e.code)}if(e instanceof ft)throw pe("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw pe("runtime operation error",e,Eo);case"NotSupportedError":throw pe("runtime unsupported operation",e,Eo);case"TimeoutError":throw pe("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw pe("operation aborted",e,"OAUTH_ABORT")}throw new un("something went wrong",{cause:e})}function Fg(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[dd]=!0,!0):!1}function Hg(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function ld(e,t,n,r,o){let i=await Jg(e,o),a=new ln(i,t,n,r),s=Ce(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 Jg(e,t){if(!(e instanceof URL))throw Ve('"server" must be an instance of URL',or);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?Fl(e,{algorithm:t?.algorithm,[St]:t?.[cn],[$t]:t?.execute?.includes(cd),signal:o,headers:new Headers(nr)}):(t?.[cn]||fetch)((xo(e,!t?.execute?.includes(cd)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...nr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Hl(yo,a)).catch(tr);return n&&new URL(i.issuer).href!==e.href&&(Fg(e,i,t)||Hg(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 Gg(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Vg(e){Object.defineProperties(e,Gg(e))}var dd=Symbol(),ln=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw Ve('"clientId" must be a non-empty string',or);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',rr);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=Mg(i.client_secret):a=Bg();let s=Object.freeze(i),u=structuredClone(t);dd in t&&(u[Ra]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let c=Object.freeze(u);Na||=new WeakMap,Na.set(this,{__proto__:null,as:c,c:s,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(Ce(this).as);return Vg(t),t}clientMetadata(){return structuredClone(Ce(this).c)}get timeout(){return Ce(this).timeout}set timeout(t){Ce(this).timeout=t}get[cn](){return Ce(this).fetch}set[cn](t){Ce(this).fetch=t}};Object.freeze(ln.prototype);function qg(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 Kg(e){Object.defineProperties(e,qg(e))}function cd(e){Ce(e).tlsOnly=!1}function Wg(e){return e=new URL(e),e.search="",e.hash="",e.href}function Xg(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Ca(e,t,n,r,o){if(La(e),o?.flag!==Ao&&!(t instanceof URL)&&!Xg(t,"Request"))throw Ve('"currentUrl" must be an instance of URL, or Request',or);let i,a,{as:s,c:u,auth:c,fetch:l,tlsOnly:d,jarm:p,hybrid:b,nonRepudiation:f,timeout:y,decrypt:v,implicit:S}=Ce(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 C=new URLSearchParams(await rd(x));if(b)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",rr)}}switch(a=Wg(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!!S:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=id(s,u,t.searchParams,n?.expectedState)}catch(x){tr(x)}}}let I=await Ql(s,u,c,i,a,n?.pkceCodeVerifier||Pa,{additionalParameters:r,[St]:l,[$t]:!d,DPoP:o?.DPoP,headers:new Headers(nr),signal:pd(y)}).catch(tr);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let _=ed(s,u,I,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[mo]:v}),E;try{E=await _}catch(x){if(Yg(x,o))return Ca(e,void 0,n,r,{...o,flag:Ao,authResponse:i,redirectUri:a});tr(x)}return E.id_token&&await f?.(I),Kg(E),E}function fd(e,t){La(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:a,implicit:s}=Ce(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 Ve("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",rr);a&&t.set("response_mode","jwt")}for(let[c,l]of t.entries())u.searchParams.append(c,l);return u}function La(e){if(!(e instanceof ln))throw Ve('"config" must be an instance of Configuration',or);if(Object.getPrototypeOf(e)!==ln.prototype)throw Ve("subclassing Configuration is not allowed",rr)}function pd(e){return e?AbortSignal.timeout(e*1e3):void 0}function Yg(e,t){return t?.DPoP&&t.flag!==Ao?ql(e):!1}var Ao=Symbol();async function md(e,t,n){La(e);let{as:r,c:o,auth:i,fetch:a,tlsOnly:s,timeout:u}=Ce(e);return td(r,o,i,t,{[St]:a,[$t]:!s,additionalParameters:new URLSearchParams(n),headers:new Headers(nr),signal:pd(u)}).then(nd).catch(tr)}var hd="oauth2:",ir="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=ud(),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(ir,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 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,y)=>{let v=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(v),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=fd(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(ir);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(ir);return}let r=Qg.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(ir);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(ir),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 Ca(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 md(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(hd))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(hd.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await ld(r,"graffiti-client")}},gd=bc(ve({loginId:H()}),ct([ve({token:H(),error:X(vc())}),ve({error:jt(Error)})])),yd=ve({logoutId:H(),error:X(jt(Error))}),vd=X(Le(ve({error:X(jt(Error))}))),Qg=ve({loginId:H(),redirectUri:J(),authorizationEndpoint:J(),state:H(),serviceEndpoints:V(J())});var ey="https://";function Oe(e){if(!e.startsWith(ey))throw new Error("Unrecognized storage bucket endpoint type")}async function Po(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 Ma=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 Ma(n):t.status===403?new at(n):t.status===404?new re(n):t.status===410?new Ue(n):t.status===413?new Dt(n):new Error(n)}return t}var zo=class{getAuthorizationEndpoint=Po;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),v=0,S=!1;try{for(;v<=y.length;){let{done:I,value:_}=await a.read();if(I){S=!0;break}if(!_||_.length===0)continue;let E=v+_.length;if(E>y.length)throw new Error("Received more data than expected");y.set(_,v),v=E}}finally{a.releaseLock()}if(!S)throw new Error("Failed to read complete value from storage bucket");return v===f?y:y.slice(0,v)}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),b=0;for(let f of l)p.set(f,b),b+=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=ty.parse(s);for(let c of u.keys)yield{key:c};if(u.cursor)o=u.cursor;else break}}},ty=ve({keys:V(H()),cursor:X(Le(H()))});var Uo=class{getAuthorizationEndpoint=Po;cache_=null;get cache(){return this.cache_||(this.cache_=cy()),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 iy.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 qe(s,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(p){if(p instanceof re)return await i.messages.set(o,null),null;throw p}let c=await u.blob(),l=Fe(await c.arrayBuffer()),d=$d.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=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 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(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 Sd()){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(v=>o=v)})}),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 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 gr(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 b=p?.waitTil;await wd(b);let f=p?.cursor,y;try{let x=await this.fetchMessageBatch(n,r,o,i,f);y=x.response,b=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,b=x.waitTil}let v=y,S,I=p?.version??crypto.randomUUID(),_=p?.messageIds??[];for(;;){let x=await v.blob(),C=Fe(await x.arrayBuffer()),{results:U,hasMore:Z,cursor:Q}=ay.parse(C);S=Q;let Ie=U.map(w=>{let z=w[Et][rt];if(!c(z))throw new Error("Server returned data that does not match schema");return{...w,[Et]:{...w[Et],[rt]:z}}});await Promise.all(Ie.map(w=>d.messages.set(Oo(n,w[Za]),w))),_=[..._,...Ie.map(w=>w[Za])],await d.messageIds.set(l,{cursor:S,version:I,messageIds:_,waitTil:b}),u+=Ie.length;for(let w of Ie)yield w;if(!Z)break;await wd(b);let h=await this.fetchMessageBatch(n,r,void 0,i,S);v=h.response,b=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=bd(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}=sy.parse(o);return this.lockedMessageStreamer(Promise.resolve(i),t,"query",void 0,r,s,u,a)}export(t,n){Oe(t);let r=bd(t,"export");return this.lockedMessageStreamer(r,t,"export",void 0,n)}},ny=be({value:me({}),channels:V(H()),allowed:X(Le(V(J()))),url:J(),actor:J()}),xd=vt(e=>e instanceof Uint8Array),ry=V(xd),ar="t",rt="o",sr="m",oy=be({[ar]:ry,[rt]:ny,[sr]:xd}),Za="id",Et="m",Do="l",$d=be({[Za]:H(),[Et]:oy,[Do]:gc()}),iy=be({id:H()}),ay=be({results:V($d),hasMore:$i(),cursor:H()}),sy=be({messageIdsCacheKey:H(),version:H(),numSeen:Rt().check(yt()),objectSchema:ct([me({}),$i()])});async function Sd(){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 bd(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 _d(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function cy(){if(await Sd()){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 _d();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 _d();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 wd(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 Ed(){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 kd(e,t,n){let r=async o=>{Ar(o);let i=Ed();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 uy(e){if(Ic(e),typeof e.webCryptoName!="string")throw new Error("non-web hash")}var kt=kd("SHA-256",64,32);var Id=kd("SHA-512",128,64),Ba=(()=>{let e=async(t,n,r)=>{let o=Ed();Ar(n,void 0,"key"),Ar(r,void 0,"message"),uy(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",cr=18,fn=32,No=class{async register(t,n){if(t!==jo)throw new Error(`Unsupported content address method: ${t}`);let r=await kt(n),o=new Uint8Array(2+r.length);return o[0]=cr,o[1]=fn,o.set(r,2),o}async getMethod(t){if(t[0]===cr&&t[1]===fn&&t.length===2+fn)return jo;throw new Error("Unrecognized content address format.")}};var Dd={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:de,n:Co,Gx:Ad,Gy:Td,a:Fa,d:Ha,h:ly}=Dd,At=32,ur=64,dy=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{let t=new Error(e);throw dy(t,se),t},fy=e=>typeof e=="bigint",py=e=>typeof e=="string",my=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",We=(e,t,n="")=>{let r=my(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},qa=e=>new Uint8Array(e),Rd=e=>Uint8Array.from(e),jd=(e,t)=>e.toString(16).padStart(t,"0"),Nd=e=>Array.from(We(e)).map(t=>jd(t,2)).join(""),ot={_0:48,_9:57,A:65,F:70,a:97,f:102},Pd=e=>{if(e>=ot._0&&e<=ot._9)return e-ot._0;if(e>=ot.A&&e<=ot.F)return e-(ot.A-10);if(e>=ot.a&&e<=ot.f)return e-(ot.a-10)},Cd=e=>{let t="hex invalid";if(!py(e))return se(t);let n=e.length,r=n/2;if(n%2)return se(t);let o=qa(r);for(let i=0,a=0;i<r;i++,a+=2){let s=Pd(e.charCodeAt(a)),u=Pd(e.charCodeAt(a+1));if(s===void 0||u===void 0)return se(t);o[i]=s*16+u}return o},hy=()=>globalThis?.crypto,gy=()=>hy()?.subtle??se("crypto.subtle must be defined, consider polyfill"),lr=(...e)=>{let t=qa(e.reduce((r,o)=>r+We(o).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t};var Lo=BigInt,It=(e,t,n,r="bad number: out of range")=>fy(e)&&t<=e&&e<n?e:se(r),A=(e,t=de)=>{let n=e%t;return n>=0n?n:t+n},Ld=e=>A(e,Co),yy=(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 Ja=e=>e instanceof it?e:se("Point expected"),Ga=2n**256n,it=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=Ga;this.X=It(t,0n,i),this.Y=It(n,0n,i),this.Z=It(r,1n,i),this.T=It(o,0n,i),Object.freeze(this)}static CURVE(){return Dd}static fromAffine(t){return new e(t.x,t.y,1n,A(t.x*t.y))}static fromBytes(t,n=!1){let r=Ha,o=Rd(We(t,At)),i=t[31];o[31]=i&-129;let a=Ka(o);It(a,0n,n?Ga:de);let u=A(a*a),c=A(u-1n),l=A(r*u+1n),{isValid:d,value:p}=by(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=A(-p)),new e(p,a,1n,A(p*a))}static fromHex(t,n){return e.fromBytes(Cd(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Fa,n=Ha,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),b=A(l*A(p+c)),f=A(d+A(n*A(u*c)));if(b!==f)return se("bad point: equation left != right (1)");let y=A(o*i),v=A(a*s);return y!==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}=Ja(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=Fa,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,b=u-a,f=A(l*p),y=A(d*b),v=A(l*b),S=A(p*d);return new e(f,y,S,v)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:a,Y:s,Z:u,T:c}=Ja(t),l=Fa,d=Ha,p=A(n*a),b=A(r*s),f=A(i*d*c),y=A(o*u),v=A((n+r)*(a+s)-p-b),S=A(y-f),I=A(y+f),_=A(b-l*p),E=A(v*S),x=A(I*_),C=A(v*_),U=A(S*I);return new e(E,x,U,C)}subtract(t){return this.add(Ja(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return pn;if(It(t,1n,Co),t===1n)return this;if(this.equals(pt))return Ey(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=yy(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=Md(n);return r[31]|=t&1n?128:0,r}toHex(){return Nd(this.toBytes())}clearCofactor(){return this.multiply(Lo(ly),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Co/2n,!1).double();return Co%2n&&(t=t.add(this)),t.is0()}},pt=new it(Ad,Td,1n,A(Ad*Td)),pn=new it(0n,1n,1n,0n);it.BASE=pt;it.ZERO=pn;var Md=e=>Cd(jd(It(e,0n,Ga),ur)).reverse(),Ka=e=>Lo("0x"+Nd(Rd(We(e)).reverse())),Ke=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=de;return n},vy=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}},zd=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,by=(e,t)=>{let n=A(t*t*t),r=A(n*n*t),o=vy(e*r).pow_p_5_8,i=A(e*n*o),a=A(t*i*i),s=i,u=A(i*zd),c=a===e,l=a===A(-e),d=a===A(-e*zd);return c&&(i=s),(l||d)&&(i=u),(A(i)&1n)===1n&&(i=A(-i)),{isValid:c||l,value:i}},Mo=e=>Ld(Ka(e)),Wa=(...e)=>Xa.sha512Async(lr(...e));var _y=e=>{let t=e.slice(0,At);t[0]&=248,t[31]&=127,t[31]|=64;let n=e.slice(At,ur),r=Mo(t),o=pt.multiply(r),i=o.toBytes();return{head:t,prefix:n,scalar:r,point:o,pointBytes:i}},Zd=e=>Wa(We(e,At)).then(_y);var Bd=e=>Zd(e).then(t=>t.pointBytes);var Fd=e=>Wa(e.hashable).then(e.finish);var wy=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=Mo(t),a=pt.multiply(i).toBytes();return{hashable:lr(a,r,n),finish:c=>{let l=Ld(i+Mo(c)*o);return We(lr(a,Md(l)),ur)}}},Hd=async(e,t)=>{let n=We(e),r=await Zd(t),o=await Wa(r.prefix,n);return Fd(wy(r,o,n))};var Jd={zip215:!0},xy=(e,t,n,r=Jd)=>{e=We(e,ur),t=We(t),n=We(n,At);let{zip215:o}=r,i,a,s,u,c=Uint8Array.of();try{i=it.fromBytes(n,o),a=it.fromBytes(e.slice(0,At),o),s=Ka(e.slice(At,ur)),u=pt.multiply(s,!1),c=lr(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()}}},Gd=async(e,t,n,r=Jd)=>Fd(xy(e,t,n,r));var Xa={sha512Async:async e=>{let t=gy(),n=lr(e);return qa(await t.digest("SHA-512",n.buffer))},sha512:void 0};var Zo=8,$y=256,Vd=Math.ceil($y/Zo)+1,Va=2**(Zo-1),Sy=()=>{let e=[],t=pt,n=t;for(let r=0;r<Vd;r++){n=t,e.push(n);for(let o=1;o<Va;o++)n=n.add(t),e.push(n);t=n.double()}return e},Od,Ud=(e,t)=>{let n=t.negate();return e?n:t},Ey=e=>{let t=Od||(Od=Sy()),n=pn,r=pt,o=2**Zo,i=o,a=Lo(o-1),s=Lo(Zo);for(let u=0;u<Vd;u++){let c=Number(e&a);e>>=s,c>Va&&(c-=i,e+=1n);let l=u*Va,d=l,p=l+Math.abs(c)-1,b=u%2!==0,f=c<0;c===0?r=r.add(Ud(b,t[d])):n=n.add(Ud(f,t[p]))}return e!==0n&&se("invalid wnaf"),{p:n,f:r}};Xa.sha512Async=Id;var Tt="pk:sha2-256+ed25519",Ya=0,Bo=class{async register(t,n){if(t!==Tt)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]===Ya)return Tt;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await kt(n)}async channelPublicIdFromPrivateKey(t){let n=await Bd(t),r=new Uint8Array(n.length+1);return r[0]=Ya,r.set(n,1),r}async attest(t,n,r){if(t!==Tt)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 Hd(a,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Ya)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await Gd(t,new TextEncoder().encode(n),r.slice(1))}};var Qa="hmac:sha2-256",qd=0,Fo=class{async attest(t,n){if(t!==Qa)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=bt(),o=await Ba(kt,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=qd,i[1]=cr,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!==qd||i!==cr||a!==fn)throw new Error("Unrecognized allowed ticket format");let s=await Ba(kt,r.slice(3),new TextEncoder().encode(n));return t.length!==s.length?!1:s.every((u,c)=>t[c]===u)}};var es="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 re(`Handle for actor DID ${t} not found`);if(!r.startsWith(es))throw new Error(`Handle DID ${r} is not a valid handle`);let o=r.slice(es.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=`${es}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new re(`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",os="#graffitiPersonalInbox",Xo="#graffitiStorageBucket",ky="#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=vd.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===Xo&&_.type===Wo),a=o.find(_=>_.id===os&&_.type===qo),s=o.filter(_=>_.id.match(new RegExp(`^${ky}\\d+$`))&&_.type===qo);if(!a||!i||s.length===0)throw new Error(`Required services not found in actor document for ${t}`);let u=ns(i),c=ns(a),l=s.map(ns),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}})),b=new Map;p.forEach(({authorizationEndpoint:_,endpoint:E,type:x})=>{b.has(_)||b.set(_,[]),b.get(_).push({endpoint:E,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[S,I]=f[0];await this.services.authorization.login(S,t,I.map(_=>_.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=gd.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=rs.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=yd.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=rs.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 Kd;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(Ty).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"){Kd=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}},Kd=[],Jo="graffiti-login-in-progress",Go="graffiti-logout-in-progress",Vo="graffiti-sessions-logged-in",Iy=ve({actor:J()}),ts=ve({token:H(),serviceEndpoint:J(),authorizationEndpoint:J()}),Ay=V(le([J(),V(ve({endpoint:J(),type:wc(["bucket","personal-inbox","shared-inbox"])}))])),rs=et(Iy,{tokens:V(H()),servicesByAuthorization:Ay}),Ty=et(rs,{storageBucket:ts,personalInbox:ts,sharedInboxes:V(ts)});function ns(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=ls(t);let r=await Promise.all(t.channels.map(f=>this.primitives.channelAttestations.attest(Tt,n,f))),o=r.map(f=>f.attestation),i=r.map(f=>f.channelPublicId),a={[as]:t.value,[ss]:o,[Yd]:bt(32)},s;if(Array.isArray(t.allowed)){let f=await Promise.all(t.allowed.map(async y=>this.primitives.allowedAttestations.attest(Qa,y)));a[cs]=f.map(y=>y.attestation),s=f.map(y=>y.ticket)}let u=Se(a);if(u.byteLength>Yo)throw new Error("The object is too large");let c=await this.primitives.contentAddresses.register(jo,u),l=await this.primitives.stringEncoder.encode(dn,c),d=zy(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>Yo)throw new Error("Object is too big");let{actor:i,contentAddress:a}=ds(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),b=Py.parse(p),f=b[as],y=b[ss],v=b[cs],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(!v)throw new Error("Object is public but thought to be private");let _,E,x;if("recipient"in o?(_=[o.recipient],E=[o.allowedTicket],x=v.filter((C,U)=>U===o.allowedIndex)):(_=[...t.allowed??[]],E=o.allowedTickets,x=v),_.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(v)throw new Error("Object is private but no recipient info provided")}},as="v",ss="c",cs="a",Yd="n",is=vt(e=>e instanceof Uint8Array),Py=be({[as]:me({}),[ss]:V(is),[cs]:X(V(is)),[Yd]:is}),us="graffiti:";function Wd(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function Xd(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function zy(e,t){return`${us}${Wd(e)}:${Wd(t)}`}function ds(e){if(!e.startsWith(us))throw new Error("Invalid object URL");let n=e.slice(us.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:Xd(r),contentAddress:Xd(o)}}function ls(e){return e===void 0?null:Array.isArray(e)?e.map(ls):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,ls(n)])):e}var Qd=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-3ALLGCD7-QNFKN6AK.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 tf=vt(e=>e instanceof Uint8Array),ms="k",mn="t",ys=be({[ms]:H(),[mn]:X(H())}),zt="id",hs="e",dr="a",Oy=V(be({[zt]:H(),[hs]:X(J()),[dr]:X(J())})),ei="s",ti="n",Uy=et(ys,{[ei]:X(V(tf)),[ti]:Oy}),fr="a",gs="i",Dy=et(ys,{[fr]:tf,[gs]:Rt().check(yt())}),Ry=ct([ys,Uy,Dy]),jy=0,fs=1,Pt=2,ps=3,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 Qd({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=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 gr(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 mr("Object exists but does not match the supplied schema");return l}}throw new re("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ii(t),{actor:i}=ds(o);if(i!==n.actor)throw new at("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 re(`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??[],{[dr]:n.actor,[zt]:b}]),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,Ny,o),{key:a,type:s,size:u}=i.value;if(r?.maxBytes&&u>r.maxBytes)throw new Dt("File size exceeds limit");if(r?.types&&!bs(s,r.types))throw new hr(`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 re(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new re(`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 at("Cursor does not match actor's inboxes");let s=await Promise.all(t.map(d=>this.channelAttestations.register(Tt,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)=>ef(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]=ef(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((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]);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}),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=Cy.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={[ms]: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,y)=>{let v=JSON.parse(JSON.stringify(t)),S=ai(v,[],f),_=(await this.dids.resolve(f)).service?.find(U=>U.type===qo&&U.id===os);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[dr]===f)?.[zt]:void 0,x={...u,...E?{[mn]:E}:{},[fr]:r[y],[gs]:y},C=await this.inboxes.send(_.serviceEndpoint,{[ar]:n,[rt]:S,[sr]:Se(x)});c.push({[zt]:C,[dr]:f})}));for(let[f,y]of b.entries())if(y.status==="rejected"){let v=l[f];console.error("Error sending to recipient:",v),console.error(y.reason)}}else{let b=JSON.parse(JSON.stringify(t)),f=ai(b,[]),y=s.sharedInboxes,v=await Promise.allSettled(y.map(async S=>{let I=a?a.find(x=>x[hs]===S.serviceEndpoint)?.[zt]:void 0,_={...u,...I?{[mn]:I}:{}},E=await this.inboxes.send(S.serviceEndpoint,{...I?{[mn]:I}:{},[ar]:n,[rt]:f,[sr]:Se(_)});c.push({[zt]:E,[hs]:S.serviceEndpoint})}));for(let[S,I]of v.entries())if(I.status==="rejected"){let _=y[S];console.error("Error sending to inbox:",_),console.error(I.reason)}}let d=a?a.find(b=>b[dr]===i.actor)?.[zt]:void 0,p={...u,...r?{[ei]:r}:{},...d?{[mn]:d}:{},[ti]:c};await this.inboxes.send(s.personalInbox.serviceEndpoint,{[ar]:n,[rt]:t,[sr]: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!==fs&&u!==jy&&u!==Pt)continue;let c=s.id,{o:l,m:d,t:p}=s.m,b;try{let _=Fe(d);b=Ry.parse(_)}catch{this.inboxes.label(t,c,ps,r);continue}let{[ms]:f,[mn]:y}=b,v=ei in b?b[ei]:void 0,S=ti in b?b[ti]:void 0;if(u===fs){yield{messageId:c,object:l,storageBucketKey:f,allowedTickets:v,tags:p,announcements:S};continue}else if(u===Pt){if(!y)continue;let _=await this.inboxes.get(t,y,r);if(!_||_[Et][rt].url!==l.url)continue;_[Do]!==Pt&&this.inboxes.label(t,y,Pt,r),yield{messageId:c,tombstone:!0,object:l,storageBucketKey:f,allowedTickets:v,tags:p,announcements:S};continue}let I;try{let _=l.actor,x=(await this.dids.resolve(_))?.service?.find(Q=>Q.id===Xo&&Q.type===Wo);if(!x)throw new re(`Actor ${_} has no storage bucket service`);if(typeof x.serviceEndpoint!="string")throw new re(`Actor ${_} does not have a valid storage bucket endpoint`);let C=x.serviceEndpoint,U=await this.storageBuckets.get(C,f,Yo);if(fr in b&&!o)throw new at("Recipient is required when allowed ticket is present");let Z=v?{allowedTickets:v}:fr in b?{recipient:o??"null",allowedTicket:b[fr],allowedIndex:b[gs]}:void 0;await this.objectEncoding.validate(l,p,U,Z)}catch(_){I=_}y?I instanceof re?(this.inboxes.get(t,y,r).then(_=>{_&&_[Et][rt].url===l.url&&_[Do]!==Pt&&this.inboxes.label(t,y,Pt,r),this.inboxes.label(t,c,Pt,r)}),yield{messageId:c,tombstone:!0,object:l,storageBucketKey:f,allowedTickets:v,tags:p,announcements:S}):(console.error("Recieved an incorrect object"),console.error(I),this.inboxes.label(t,c,ps,r)):I===void 0?(this.inboxes.label(t,c,fs,r),yield{messageId:c,object:l,storageBucketKey:f,tags:p,allowedTickets:v,announcements:S}):(console.error("Recieved an incorrect object"),console.error(I),this.inboxes.label(t,c,ps,r))}}},Ny={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},Cy=be({cursors:_c(J(),H()),channels:V(H())});async function ef(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Ue||n instanceof Ut)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var nf=class extends Ir{constructor(t){let n=new ni(t);super(n)}};export{nf as GraffitiDecentralized};
|
|
8
8
|
/*! Bundled license information:
|
|
9
9
|
|
|
10
10
|
@noble/hashes/utils.js:
|