@graffiti-garden/implementation-decentralized 0.0.8 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/1-services/1-authorization.d.ts.map +1 -1
  2. package/dist/1-services/2-dids.d.ts +1 -3
  3. package/dist/1-services/2-dids.d.ts.map +1 -1
  4. package/dist/1-services/3-storage-buckets.d.ts.map +1 -1
  5. package/dist/1-services/4-inboxes.d.ts.map +1 -1
  6. package/dist/1-services/utilities.d.ts.map +1 -1
  7. package/dist/2-primitives/1-string-encoding.d.ts.map +1 -1
  8. package/dist/2-primitives/2-content-addresses.d.ts.map +1 -1
  9. package/dist/2-primitives/3-channel-attestations.d.ts.map +1 -1
  10. package/dist/2-primitives/4-allowed-attestations.d.ts.map +1 -1
  11. package/dist/3-protocol/1-sessions.d.ts.map +1 -1
  12. package/dist/3-protocol/2-handles.d.ts.map +1 -1
  13. package/dist/3-protocol/3-object-encoding.d.ts.map +1 -1
  14. package/dist/3-protocol/4-graffiti.d.ts +4 -0
  15. package/dist/3-protocol/4-graffiti.d.ts.map +1 -1
  16. package/dist/3-protocol/browser-storage.d.ts +4 -0
  17. package/dist/3-protocol/browser-storage.d.ts.map +1 -0
  18. package/dist/browser/ajv-LGNUXWV5.js +9 -0
  19. package/dist/browser/ajv-LGNUXWV5.js.map +7 -0
  20. package/dist/browser/{build-BXWPS7VK.js → build-DM3HADDZ.js} +2 -2
  21. package/dist/browser/chunk-O4MIY67H.js +2 -0
  22. package/dist/browser/{graffiti-KV3G3O72-URO7SJIJ.js → graffiti-KV3G3O72-TAZN6KIP.js} +2 -2
  23. package/dist/browser/index.js +13 -10
  24. package/dist/browser/index.js.map +4 -4
  25. package/dist/browser/{login-dialog.html-VTDKJZBG.js → login-dialog.html-E6VRKMXH.js} +2 -2
  26. package/dist/browser/{rock-salt-LI7DAH66-KPFEBIBO.js → rock-salt-LI7DAH66-TZP5ZWGV.js} +2 -2
  27. package/dist/browser/{style-BOBMBTYJ-ORUSIJTZ.js → style-BOBMBTYJ-GXWKT5M3.js} +2 -2
  28. package/dist/cjs/1-services/2-dids.js +4 -1
  29. package/dist/cjs/1-services/2-dids.js.map +2 -2
  30. package/dist/cjs/3-protocol/1-sessions.js +6 -6
  31. package/dist/cjs/3-protocol/1-sessions.js.map +2 -2
  32. package/dist/cjs/3-protocol/2-handles.js +1 -0
  33. package/dist/cjs/3-protocol/2-handles.js.map +1 -1
  34. package/dist/cjs/3-protocol/3-object-encoding.js +1 -0
  35. package/dist/cjs/3-protocol/3-object-encoding.js.map +1 -1
  36. package/dist/cjs/3-protocol/4-graffiti.js +81 -7
  37. package/dist/cjs/3-protocol/4-graffiti.js.map +3 -3
  38. package/dist/cjs/3-protocol/browser-storage.js +59 -0
  39. package/dist/cjs/3-protocol/browser-storage.js.map +7 -0
  40. package/dist/esm/1-services/2-dids.js +4 -1
  41. package/dist/esm/1-services/2-dids.js.map +2 -2
  42. package/dist/esm/3-protocol/1-sessions.js +10 -6
  43. package/dist/esm/3-protocol/1-sessions.js.map +2 -2
  44. package/dist/esm/3-protocol/2-handles.js +1 -0
  45. package/dist/esm/3-protocol/2-handles.js.map +1 -1
  46. package/dist/esm/3-protocol/3-object-encoding.js +1 -0
  47. package/dist/esm/3-protocol/3-object-encoding.js.map +1 -1
  48. package/dist/esm/3-protocol/4-graffiti.js +81 -7
  49. package/dist/esm/3-protocol/4-graffiti.js.map +3 -3
  50. package/dist/esm/3-protocol/browser-storage.js +29 -0
  51. package/dist/esm/3-protocol/browser-storage.js.map +7 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/package.json +12 -10
  54. package/src/1-services/2-dids.ts +6 -3
  55. package/src/3-protocol/1-sessions.ts +9 -6
  56. package/src/3-protocol/4-graffiti.ts +124 -5
  57. package/src/3-protocol/browser-storage.ts +37 -0
  58. package/dist/browser/ajv-U35FOJ27.js +0 -9
  59. package/dist/browser/ajv-U35FOJ27.js.map +0 -7
  60. package/dist/browser/chunk-RFBBAUMM.js +0 -2
  61. /package/dist/browser/{build-BXWPS7VK.js.map → build-DM3HADDZ.js.map} +0 -0
  62. /package/dist/browser/{chunk-RFBBAUMM.js.map → chunk-O4MIY67H.js.map} +0 -0
  63. /package/dist/browser/{graffiti-KV3G3O72-URO7SJIJ.js.map → graffiti-KV3G3O72-TAZN6KIP.js.map} +0 -0
  64. /package/dist/browser/{login-dialog.html-VTDKJZBG.js.map → login-dialog.html-E6VRKMXH.js.map} +0 -0
  65. /package/dist/browser/{rock-salt-LI7DAH66-KPFEBIBO.js.map → rock-salt-LI7DAH66-TZP5ZWGV.js.map} +0 -0
  66. /package/dist/browser/{style-BOBMBTYJ-ORUSIJTZ.js.map → style-BOBMBTYJ-GXWKT5M3.js.map} +0 -0
@@ -1,16 +1,19 @@
1
- import{a as ef,b as tf,c as nf}from"./chunk-RFBBAUMM.js";var Ul=ef((ft,Ol)=>{var fo=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,po=(function(){function e(){this.fetch=!1,this.DOMException=fo.DOMException}return e.prototype=fo,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 b={next:function(){var O=h.shift();return{done:O===void 0,value:O}}};return o.iterable&&(b[Symbol.iterator]=function(){return b}),b}function d(h){this.map={},h instanceof d?h.forEach(function(b,O){this.append(O,b)},this):Array.isArray(h)?h.forEach(function(b){if(b.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+b.length);this.append(b[0],b[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(b){this.append(b,h[b])},this)}d.prototype.append=function(h,b){h=u(h),b=c(b);var O=this.map[h];this.map[h]=O?O+", "+b:b},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,b){this.map[u(h)]=c(b)},d.prototype.forEach=function(h,b){for(var O in this.map)this.map.hasOwnProperty(O)&&h.call(b,this.map[O],O,this)},d.prototype.keys=function(){var h=[];return this.forEach(function(b,O){h.push(O)}),l(h)},d.prototype.values=function(){var h=[];return this.forEach(function(b){h.push(b)}),l(h)},d.prototype.entries=function(){var h=[];return this.forEach(function(b,O){h.push([O,b])}),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 _(h){return new Promise(function(b,O){h.onload=function(){b(h.result)},h.onerror=function(){O(h.error)}})}function f(h){var b=new FileReader,O=_(b);return b.readAsArrayBuffer(h),O}function y(h){var b=new FileReader,O=_(b),Z=/charset=([A-Za-z0-9_-]+)/.exec(h.type),q=Z?Z[1]:"utf-8";return b.readAsText(h,q),O}function v(h){for(var b=new Uint8Array(h),O=new Array(b.length),Z=0;Z<b.length;Z++)O[Z]=String.fromCharCode(b[Z]);return O.join("")}function k(h){if(h.slice)return h.slice(0);var b=new Uint8Array(h.byteLength);return b.set(new Uint8Array(h)),b.buffer}function A(){return this.bodyUsed=!1,this._initBody=function(h){this.bodyUsed=this.bodyUsed,this._bodyInit=h,h?typeof h=="string"?this._bodyText=h:o.blob&&Blob.prototype.isPrototypeOf(h)?this._bodyBlob=h:o.formData&&FormData.prototype.isPrototypeOf(h)?this._bodyFormData=h:o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)?this._bodyText=h.toString():o.arrayBuffer&&o.blob&&i(h)?(this._bodyArrayBuffer=k(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||s(h))?this._bodyArrayBuffer=k(h):this._bodyText=h=Object.prototype.toString.call(h):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof h=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o.searchParams&&URLSearchParams.prototype.isPrototypeOf(h)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o.blob&&(this.blob=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var h=p(this);return h||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(o.blob)return this.blob().then(f);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return 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(U)}),this.json=function(){return this.text().then(JSON.parse)},this}var w=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function S(h){var b=h.toUpperCase();return w.indexOf(b)>-1?b:h}function x(h,b){if(!(this instanceof x))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');b=b||{};var O=b.body;if(h instanceof x){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,b.headers||(this.headers=new d(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!O&&h._bodyInit!=null&&(O=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);if(this.credentials=b.credentials||this.credentials||"same-origin",(b.headers||!this.headers)&&(this.headers=new d(b.headers)),this.method=S(b.method||this.method||"GET"),this.mode=b.mode||this.mode||null,this.signal=b.signal||this.signal||(function(){if("AbortController"in r){var z=new AbortController;return z.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&O)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(O),(this.method==="GET"||this.method==="HEAD")&&(b.cache==="no-store"||b.cache==="no-cache")){var Z=/([?&])_=[^&]*/;if(Z.test(this.url))this.url=this.url.replace(Z,"$1_="+new Date().getTime());else{var q=/\?/;this.url+=(q.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}x.prototype.clone=function(){return new x(this,{body:this._bodyInit})};function U(h){var b=new FormData;return h.trim().split("&").forEach(function(O){if(O){var Z=O.split("="),q=Z.shift().replace(/\+/g," "),z=Z.join("=").replace(/\+/g," ");b.append(decodeURIComponent(q),decodeURIComponent(z))}}),b}function M(h){var b=new d,O=h.replace(/\r?\n[\t ]+/g," ");return O.split("\r").map(function(Z){return Z.indexOf(`
2
- `)===0?Z.substr(1,Z.length):Z}).forEach(function(Z){var q=Z.split(":"),z=q.shift().trim();if(z){var gt=q.join(":").trim();try{b.append(z,gt)}catch(Te){console.warn("Response "+Te.message)}}}),b}A.call(x.prototype);function B(h,b){if(!(this instanceof B))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(b||(b={}),this.type="default",this.status=b.status===void 0?200:b.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=b.statusText===void 0?"":""+b.statusText,this.headers=new d(b.headers),this.url=b.url||"",this._initBody(h)}A.call(B.prototype),B.prototype.clone=function(){return new B(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},B.error=function(){var h=new B(null,{status:200,statusText:""});return h.ok=!1,h.status=0,h.type="error",h};var ie=[301,302,303,307,308];B.redirect=function(h,b){if(ie.indexOf(b)===-1)throw new RangeError("Invalid status code");return new B(null,{status:b,headers:{location:h}})},n.DOMException=r.DOMException;try{new n.DOMException}catch{n.DOMException=function(b,O){this.message=b,this.name=O;var Z=Error(b);this.stack=Z.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function Ae(h,b){return new Promise(function(O,Z){var q=new x(h,b);if(q.signal&&q.signal.aborted)return Z(new n.DOMException("Aborted","AbortError"));var z=new XMLHttpRequest;function gt(){z.abort()}z.onload=function(){var ne={statusText:z.statusText,headers:M(z.getAllResponseHeaders()||"")};q.url.indexOf("file://")===0&&(z.status<200||z.status>599)?ne.status=200:ne.status=z.status,ne.url="responseURL"in z?z.responseURL:ne.headers.get("X-Request-URL");var ce="response"in z?z.response:z.responseText;setTimeout(function(){O(new B(ce,ne))},0)},z.onerror=function(){setTimeout(function(){Z(new TypeError("Network request failed"))},0)},z.ontimeout=function(){setTimeout(function(){Z(new TypeError("Network request timed out"))},0)},z.onabort=function(){setTimeout(function(){Z(new n.DOMException("Aborted","AbortError"))},0)};function Te(ne){try{return ne===""&&r.location.href?r.location.href:ne}catch{return ne}}if(z.open(q.method,Te(q.url),!0),q.credentials==="include"?z.withCredentials=!0:q.credentials==="omit"&&(z.withCredentials=!1),"responseType"in z&&(o.blob?z.responseType="blob":o.arrayBuffer&&(z.responseType="arraybuffer")),b&&typeof b.headers=="object"&&!(b.headers instanceof d||r.Headers&&b.headers instanceof r.Headers)){var yn=[];Object.getOwnPropertyNames(b.headers).forEach(function(ne){yn.push(u(ne)),z.setRequestHeader(ne,c(b.headers[ne]))}),q.headers.forEach(function(ne,ce){yn.indexOf(ce)===-1&&z.setRequestHeader(ce,ne)})}else q.headers.forEach(function(ne,ce){z.setRequestHeader(ce,ne)});q.signal&&(q.signal.addEventListener("abort",gt),z.onreadystatechange=function(){z.readyState===4&&q.signal.removeEventListener("abort",gt)}),z.send(typeof q._bodyInit>"u"?null:q._bodyInit)})}return Ae.polyfill=!0,r.fetch||(r.fetch=Ae,r.Headers=d,r.Request=x,r.Response=B),n.Headers=d,n.Request=x,n.Response=B,n.fetch=Ae,n})({})})(po);po.fetch.ponyfill=!0;delete po.fetch.polyfill;var on=fo.fetch?fo:po;ft=on.fetch;ft.default=on.fetch;ft.fetch=on.fetch;ft.Headers=on.Headers;ft.Request=on.Request;ft.Response=on.Response;Ol.exports=ft});var rf={type:"object",properties:{value:{type:"object"},channels:{type:"array",items:{type:"string"}},allowed:{type:"array",items:{type:"string"},nullable:!0},url:{type:"string"},actor:{type:"string"}},additionalProperties:!1,required:["value","channels","actor","url"]},Cy={...rf,required:["value","channels"]};var st=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorForbidden",Object.setPrototypeOf(this,e.prototype)}},Q=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotFound",Object.setPrototypeOf(this,e.prototype)}},Rt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorInvalidSchema",Object.setPrototypeOf(this,e.prototype)}},hr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorSchemaMismatch",Object.setPrototypeOf(this,e.prototype)}},jt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorTooLarge",Object.setPrototypeOf(this,e.prototype)}},gr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotAcceptable",Object.setPrototypeOf(this,e.prototype)}},Re=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorCursorExpired",Object.setPrototypeOf(this,e.prototype)}};function ai(e){return typeof e=="string"?e:e.url}function si(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 ii;async function yr(e){if(!ii){let{default:t}=await import("./ajv-U35FOJ27.js");ii=new t({strict:!1})}try{return ii.compile(e)}catch(t){throw new Rt(t instanceof Error?t.message:String(t))}}var of=Object.freeze({status:"aborted"});function P(e,t,n){function r(s,u){if(s._zod||Object.defineProperty(s,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),s._zod.traits.has(e))return;s._zod.traits.add(e),t(s,u);let c=a.prototype,l=Object.keys(c);for(let d=0;d<l.length;d++){let p=l[d];p in s||(s[p]=c[p].bind(s))}}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function a(s){var u;let c=n?.Parent?new i:this;r(c,s),(u=c._zod).deferred??(u.deferred=[]);for(let l of c._zod.deferred)l();return c}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:s=>n?.Parent&&s instanceof n.Parent?!0:s?._zod?.traits?.has(e)}),Object.defineProperty(a,"name",{value:e}),a}var Ye=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};var ci={};function Qe(e){return e&&Object.assign(ci,e),ci}function li(e){let t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function xs(e,t){return typeof t=="bigint"?t.toString():t}function di(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 ws=Symbol("evaluating");function de(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ws)return r===void 0&&(r=ws,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function af(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function sf(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}var fi="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function _r(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var cf=di(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function vn(e){if(_r(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(_r(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}var $s=new Set(["string","number","symbol"]);function wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _n(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function re(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Ss(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Es={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ks(e,t){if(!vn(t))throw new Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let i=e._zod.def.shape;for(let a in t)if(Object.getOwnPropertyDescriptor(i,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=sf(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return af(this,"shape",i),i}});return _n(e,o)}function yt(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function et(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function vr(e){return typeof e=="string"?e:e?.message}function ct(e,t,n){let r={...e,path:e.path??[]};if(!e.message){let o=vr(e.inst?._zod.def?.error?.(e))??vr(t?.error?.(e))??vr(n.customError?.(e))??vr(n.localeError?.(e))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function pi(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}var Is=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,xs,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},As=P("$ZodError",Is),bn=P("$ZodError",Is,{Parent:Error});var lf=e=>(t,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ye;if(a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>ct(u,i,Qe())));throw fi(s,o?.callee),s}return a.value},xr=lf(bn),df=e=>async(t,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise&&(a=await a),a.issues.length){let s=new(o?.Err??e)(a.issues.map(u=>ct(u,i,Qe())));throw fi(s,o?.callee),s}return a.value},$r=df(bn),ff=e=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ye;return i.issues.length?{success:!1,error:new(e??As)(i.issues.map(a=>ct(a,o,Qe())))}:{success:!0,data:i.value}},wn=ff(bn),pf=e=>async(t,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=t._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(a=>ct(a,o,Qe())))}:{success:!0,data:i.value}},xn=pf(bn);var mf="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",hf=new RegExp(`^${mf}$`);var Ts=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var Ps=/^-?\d+$/,mi=/^-?\d+(?:\.\d+)?$/,zs=/^(?:true|false)$/i;var Os=/^undefined$/i;var vt=P("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gf={number:"number",bigint:"bigint",object:"date"};var Us=P("$ZodCheckGreaterThan",(e,t)=>{vt.init(e,t);let n=gf[typeof t.value];e._zod.onattach.push(r=>{let o=r._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}});var Ds=P("$ZodCheckNumberFormat",(e,t)=>{vt.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Es[t.format];e._zod.onattach.push(a=>{let s=a._zod.bag;s.format=t.format,s.minimum=o,s.maximum=i,n&&(s.pattern=Ps)}),e._zod.check=a=>{let s=a.value;if(n){if(!Number.isInteger(s)){a.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?a.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):a.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<o&&a.issues.push({origin:"number",input:s,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),s>i&&a.issues.push({origin:"number",input:s,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Rs=P("$ZodCheckStringFormat",(e,t)=>{var n,r;vt.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})});var Ns={major:4,minor:3,patch:6};var ee=P("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Ns;let r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(let o of r)for(let i of o._zod.onattach)i(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(a,s,u)=>{let c=yt(a),l;for(let d of s){if(d._zod.def.when){if(!d._zod.def.when(a))continue}else if(c)continue;let p=a.issues.length,_=d._zod.check(a);if(_ instanceof Promise&&u?.async===!1)throw new Ye;if(l||_ instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await _,a.issues.length!==p&&(c||(c=yt(a,p)))});else{if(a.issues.length===p)continue;c||(c=yt(a,p))}}return l?l.then(()=>a):a},i=(a,s,u)=>{if(yt(a))return a.aborted=!0,a;let c=o(s,r,u);if(c instanceof Promise){if(u.async===!1)throw new Ye;return c.then(l=>e._zod.parse(l,u))}return e._zod.parse(c,u)};e._zod.run=(a,s)=>{if(s.skipChecks)return e._zod.parse(a,s);if(s.direction==="backward"){let c=e._zod.parse({value:a.value,issues:[]},{...s,skipChecks:!0});return c instanceof Promise?c.then(l=>i(l,a,s)):i(c,a,s)}let u=e._zod.parse(a,s);if(u instanceof Promise){if(s.async===!1)throw new Ye;return u.then(c=>o(c,r,s))}return o(u,r,s)}}de(e,"~standard",()=>({validate:o=>{try{let i=wn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return xn(e,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},vendor:"zod",version:1}))}),kr=P("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Ts(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),gi=P("$ZodStringFormat",(e,t)=>{Rs.init(e,t),kr.init(e,t)});var Fs=P("$ZodURL",(e,t)=>{gi.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 yi=P("$ZodNumber",(e,t)=>{ee.init(e,t),e._zod.pattern=e._zod.bag.pattern??mi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),Hs=P("$ZodNumberFormat",(e,t)=>{Ds.init(e,t),yi.init(e,t)}),vi=P("$ZodBoolean",(e,t)=>{ee.init(e,t),e._zod.pattern=zs,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}});var Js=P("$ZodUndefined",(e,t)=>{ee.init(e,t),e._zod.pattern=Os,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),n}});var Gs=P("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=n=>n}),Vs=P("$ZodNever",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function Cs(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}var qs=P("$ZodArray",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),n;n.value=Array(o.length);let i=[];for(let a=0;a<o.length;a++){let s=o[a],u=t.element._zod.run({value:s,issues:[]},r);u instanceof Promise?i.push(u.then(c=>Cs(c,n,a))):Cs(u,n,a)}return i.length?Promise.all(i).then(()=>n):n}});function Er(e,t,n,r,o){if(e.issues.length){if(o&&!(n in r))return;t.issues.push(...et(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function yf(e){let t=Object.keys(e.shape);for(let r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);let n=Ss(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function vf(e,t,n,r,o,i){let a=[],s=o.keySet,u=o.catchall._zod,c=u.def.type,l=u.optout==="optional";for(let d in t){if(s.has(d))continue;if(c==="never"){a.push(d);continue}let p=u.run({value:t[d],issues:[]},r);p instanceof Promise?e.push(p.then(_=>Er(_,n,d,t,l))):Er(p,n,d,t,l)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var Ks=P("$ZodObject",(e,t)=>{if(ee.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let s=t.shape;Object.defineProperty(t,"shape",{get:()=>{let u={...s};return Object.defineProperty(t,"shape",{value:u}),u}})}let r=di(()=>yf(t));de(e._zod,"propValues",()=>{let s=t.shape,u={};for(let c in s){let l=s[c]._zod;if(l.values){u[c]??(u[c]=new Set);for(let d of l.values)u[c].add(d)}}return u});let o=_r,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 _=d[p],f=_._zod.optout==="optional",y=_._zod.run({value:c[p],issues:[]},u);y instanceof Promise?l.push(y.then(v=>Er(v,s,p,c,f))):Er(y,s,p,c,f)}return i?vf(l,c,s,u,r.value,e):l.length?Promise.all(l).then(()=>s):s}});function Ls(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!yt(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(a=>ct(a,r,Qe())))}),t)}var Ws=P("$ZodUnion",(e,t)=>{ee.init(e,t),de(e._zod,"optin",()=>t.options.some(o=>o._zod.optin==="optional")?"optional":void 0),de(e._zod,"optout",()=>t.options.some(o=>o._zod.optout==="optional")?"optional":void 0),de(e._zod,"values",()=>{if(t.options.every(o=>o._zod.values))return new Set(t.options.flatMap(o=>Array.from(o._zod.values)))}),de(e._zod,"pattern",()=>{if(t.options.every(o=>o._zod.pattern)){let o=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>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=>Ls(u,o,e,i)):Ls(s,o,e,i)}});var Xs=P("$ZodIntersection",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),a=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([u,c])=>Ms(n,u,c)):Ms(n,i,a)}});function hi(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(vn(e)&&vn(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=hi(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=hi(o,i);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Ms(e,t,n){let r=new Map,o;for(let s of t.issues)if(s.code==="unrecognized_keys"){o??(o=s);for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else e.issues.push(s);for(let s of n.issues)if(s.code==="unrecognized_keys")for(let u of s.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else e.issues.push(s);let i=[...r].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&o&&e.issues.push({...o,keys:i}),yt(e))return e;let a=hi(t.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return e.value=a.data,e}var Ys=P("$ZodTuple",(e,t)=>{ee.init(e,t);let n=t.items;e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({input:i,inst:e,expected:"tuple",code:"invalid_type"}),r;r.value=[];let a=[],s=[...n].reverse().findIndex(l=>l._zod.optin!=="optional"),u=s===-1?0:n.length-s;if(!t.rest){let l=i.length>n.length,d=i.length<u-1;if(l||d)return r.issues.push({...l?{code:"too_big",maximum:n.length,inclusive:!0}:{code:"too_small",minimum:n.length},input:i,inst:e,origin:"array"}),r}let c=-1;for(let l of n){if(c++,c>=i.length&&c>=u)continue;let d=l._zod.run({value:i[c],issues:[]},o);d instanceof Promise?a.push(d.then(p=>Sr(p,r,c))):Sr(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(_=>Sr(_,r,c))):Sr(p,r,c)}}return a.length?Promise.all(a).then(()=>r):r}});function Sr(e,t,n){e.issues.length&&t.issues.push(...et(n,e.issues)),t.value[n]=e.value}var Qs=P("$ZodRecord",(e,t)=>{ee.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!vn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a){n.value={};let s=new Set;for(let c of a)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){s.add(typeof c=="number"?c.toString():c);let l=t.valueType._zod.run({value:o[c],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...et(c,d.issues)),n.value[c]=d.value})):(l.issues.length&&n.issues.push(...et(c,l.issues)),n.value[c]=l.value)}let u;for(let c in o)s.has(c)||(u=u??[],u.push(c));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:u})}else{n.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let u=t.keyType._zod.run({value:s,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&mi.test(s)&&u.issues.length){let d=t.keyType._zod.run({value:Number(s),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(u=d)}if(u.issues.length){t.mode==="loose"?n.value[s]=o[s]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(d=>ct(d,r,Qe())),input:s,path:[s],inst:e});continue}let l=t.valueType._zod.run({value:o[s],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...et(s,d.issues)),n.value[u.value]=d.value})):(l.issues.length&&n.issues.push(...et(s,l.issues)),n.value[u.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}});var ec=P("$ZodEnum",(e,t)=>{ee.init(e,t);let n=li(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>$s.has(typeof o)).map(o=>typeof o=="string"?wr(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let a=o.value;return r.has(a)||o.issues.push({code:"invalid_value",values:n,input:a,inst:e}),o}});function Zs(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var tc=P("$ZodOptional",(e,t)=>{ee.init(e,t),e._zod.optin="optional",e._zod.optout="optional",de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${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=>Zs(i,n.value)):Zs(o,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var nc=P("$ZodNullable",(e,t)=>{ee.init(e,t),de(e._zod,"optin",()=>t.innerType._zod.optin),de(e._zod,"optout",()=>t.innerType._zod.optout),de(e._zod,"pattern",()=>{let n=t.innerType._zod.pattern;return n?new RegExp(`^(${br(n.source)}|null)$`):void 0}),de(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)});var rc=P("$ZodCustom",(e,t)=>{vt.init(e,t),ee.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then(i=>Bs(i,n,r,e));Bs(o,n,r,e)}});function Bs(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),t.issues.push(pi(o))}}var ic;var _i=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){let r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){let n=t._zod.parent;if(n){let r={...this.get(n)??{}};delete r.id;let o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function ac(){return new _i}(ic=globalThis).__zod_globalRegistry??(ic.__zod_globalRegistry=ac());var bi=globalThis.__zod_globalRegistry;function sc(e,t){return new e({type:"string",...re(t)})}function cc(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...re(t)})}function uc(e,t){return new e({type:"number",checks:[],...re(t)})}function lc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...re(t)})}function dc(e,t){return new e({type:"boolean",...re(t)})}function fc(e,t){return new e({type:"undefined",...re(t)})}function pc(e){return new e({type:"unknown"})}function mc(e,t){return new e({type:"never",...re(t)})}function wi(e,t){return new Us({check:"greater_than",...re(t),value:e,inclusive:!0})}function _t(e){return wi(0,e)}function hc(e,t,n){let r=re(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}var ue=P("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");ee.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>xr(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>wn(e,n,r),e.parseAsync=async(n,r)=>$r(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>xn(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)=>_n(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),xi=P("ZodMiniString",(e,t)=>{kr.init(e,t),ue.init(e,t)});function H(e){return sc(xi,e)}var gc=P("ZodMiniStringFormat",(e,t)=>{gi.init(e,t),xi.init(e,t)});var zf=P("ZodMiniURL",(e,t)=>{Fs.init(e,t),gc.init(e,t)});function J(e){return cc(zf,e)}var $i=P("ZodMiniNumber",(e,t)=>{yi.init(e,t),ue.init(e,t)});function yc(e){return uc($i,e)}var Of=P("ZodMiniNumberFormat",(e,t)=>{Hs.init(e,t),$i.init(e,t)});function Nt(e){return lc(Of,e)}var vc=P("ZodMiniBoolean",(e,t)=>{vi.init(e,t),ue.init(e,t)});function Si(e){return dc(vc,e)}var Uf=P("ZodMiniUndefined",(e,t)=>{Js.init(e,t),ue.init(e,t)});function _c(e){return fc(Uf,e)}var Df=P("ZodMiniUnknown",(e,t)=>{Gs.init(e,t),ue.init(e,t)});function Rf(){return pc(Df)}var jf=P("ZodMiniNever",(e,t)=>{Vs.init(e,t),ue.init(e,t)});function Nf(e){return mc(jf,e)}var Cf=P("ZodMiniArray",(e,t)=>{qs.init(e,t),ue.init(e,t)});function V(e,t){return new Cf({type:"array",element:e,...re(t)})}var Ei=P("ZodMiniObject",(e,t)=>{Ks.init(e,t),ue.init(e,t),de(e,"shape",()=>t.shape)});function _e(e,t){let n={type:"object",shape:e??{},...re(t)};return new Ei(n)}function be(e,t){return new Ei({type:"object",shape:e,catchall:Nf(),...re(t)})}function he(e,t){return new Ei({type:"object",shape:e,catchall:Rf(),...re(t)})}function tt(e,t){return ks(e,t)}var Lf=P("ZodMiniUnion",(e,t)=>{Ws.init(e,t),ue.init(e,t)});function ut(e,t){return new Lf({type:"union",options:e,...re(t)})}var Mf=P("ZodMiniIntersection",(e,t)=>{Xs.init(e,t),ue.init(e,t)});function bc(e,t){return new Mf({type:"intersection",left:e,right:t})}var Zf=P("ZodMiniTuple",(e,t)=>{Ys.init(e,t),ue.init(e,t)});function fe(e,t,n){let r=t instanceof ee,o=r?n:t,i=r?t:null;return new Zf({type:"tuple",items:e,rest:i,...re(o)})}var Bf=P("ZodMiniRecord",(e,t)=>{Qs.init(e,t),ue.init(e,t)});function wc(e,t,n){return new Bf({type:"record",keyType:e,valueType:t,...re(n)})}var Ff=P("ZodMiniEnum",(e,t)=>{ec.init(e,t),ue.init(e,t),e.options=Object.values(t.entries)});function xc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Ff({type:"enum",entries:n,...re(t)})}var Hf=P("ZodMiniOptional",(e,t)=>{tc.init(e,t),ue.init(e,t)});function X(e){return new Hf({type:"optional",innerType:e})}var Jf=P("ZodMiniNullable",(e,t)=>{nc.init(e,t),ue.init(e,t)});function Ze(e){return new Jf({type:"nullable",innerType:e})}var Gf=P("ZodMiniCustom",(e,t)=>{rc.init(e,t),ue.init(e,t)});function bt(e,t){return hc(Gf,e??(()=>!0),t)}function Ct(e,t={}){let n=bt(r=>r instanceof e,t);return n._zod.bag.Class=e,n._zod.check=r=>{r.value instanceof e||r.issues.push({code:"invalid_type",expected:e.name,input:r.value,inst:n,path:[...n._zod.def.path??[]]})},n}var Ec=he({value:he({}),channels:V(H()),allowed:X(Ze(V(J())))}),uE=tt(Ec,{url:J(),actor:J()}),Sc=ut([he({url:J()}),J()]),Lt=he({actor:J()}),Ar=X(Ze(Lt)),kc=he({data:Ct(Blob),allowed:X(Ze(V(J())))}),lE=tt(kc,{actor:J()}),Xf=he({types:X(V(H())),maxBytes:X(Nt().check(_t()))}),Tr=class{constructor(t){this.graffiti=t,this.sessionEvents=this.graffiti.sessionEvents}sessionEvents;login=(...t)=>{let n=fe([X(J())]).parse(t);return this.graffiti.login(...n)};logout=(...t)=>{let n=fe([Lt]).parse(t);return this.graffiti.logout(...n)};handleToActor=(...t)=>{let n=fe([H()]).parse(t);return this.graffiti.handleToActor(...n)};actorToHandle=(...t)=>{let n=fe([J()]).parse(t);return this.graffiti.actorToHandle(...n)};post=(...t)=>{let n=fe([Ec,Lt]).parse(t);return this.graffiti.post(...n)};get=(...t)=>{let n=fe([Sc,he({}),Ar]).parse(t);return this.graffiti.get(n[0],n[1],n[2])};delete=(...t)=>{let n=fe([Sc,Lt]).parse(t);return this.graffiti.delete(...n)};postMedia=(...t)=>{let n=fe([kc,Lt]).parse(t);return this.graffiti.postMedia(...n)};getMedia=(...t)=>{let n=fe([J(),Xf,Ar]).parse(t);return this.graffiti.getMedia(...n)};deleteMedia=(...t)=>{let n=fe([J(),Lt]).parse(t);return this.graffiti.deleteMedia(...n)};discover=(...t)=>{let n=fe([V(H()),he({}),Ar]).parse(t);return this.graffiti.discover(n[0],n[1],n[2])};continueDiscover=(...t)=>{let n=fe([H(),Ar]).parse(t);return this.graffiti.continueDiscover(...n)}};function Yf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ki(e,t=""){if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new Error(`${n}expected integer >= 0, got ${e}`)}}function Pr(e,t,n=""){let r=Yf(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;throw new Error(a+"expected Uint8Array"+s+", got "+u)}return e}function Ic(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ki(e.outputLen),ki(e.blockLen)}function wt(e=32){let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return t.getRandomValues(new Uint8Array(e))}var Qf=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function Ii(e){if(e===null)return"null";if(e===void 0)return"undefined";if(e===!0||e===!1)return"boolean";let t=typeof e;if(t==="string"||t==="number"||t==="bigint"||t==="symbol")return t;if(t==="function")return"Function";if(Array.isArray(e))return"Array";if(e instanceof Uint8Array)return"Uint8Array";if(e.constructor===Object)return"Object";let n=ep(e);return n||"Object"}function ep(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(Qf.includes(t))return t}var 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 E=class{constructor(t,n,r){this.type=t,this.value=n,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};var Sn=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",tp=new TextEncoder;function zr(e){return Sn&&globalThis.Buffer.isBuffer(e)}function En(e){return e instanceof Uint8Array?zr(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var np=24,rp=200,Or=Sn?e=>e.length>=np?globalThis.Buffer.from(e):Ac(e):e=>e.length>=rp?tp.encode(e):Ac(e),Be=e=>Uint8Array.from(e),Tc=Sn?(e,t,n)=>zr(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),Pc=Sn?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),En(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=Sn?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function Ur(e,t){if(zr(e)&&zr(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function Ac(e){let t=[],n=0;for(let r=0;r<e.length;r++){let o=e.charCodeAt(r);o<128?t[n++]=o:o<2048?(t[n++]=o>>6|192,t[n++]=o&63|128):(o&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(o=65536+((o&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=o>>18|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128,t[n++]=o&63|128):(o>=55296&&o<=57343&&(o=65533),t[n++]=o>>12|224,t[n++]=o>>6&63|128,t[n++]=o&63|128)}return t}var op=256,kn=class{constructor(t=op){this.chunkSize=t,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(t){let n=this.chunks[this.chunks.length-1];if(this.cursor+t.length<=this.maxCursor+1){let o=n.length-(this.maxCursor-this.cursor)-1;n.set(t,o)}else{if(n){let o=n.length-(this.maxCursor-this.cursor)-1;o<n.length&&(this.chunks[this.chunks.length-1]=n.subarray(0,o),this.maxCursor=this.cursor-1)}t.length<64&&t.length<this.chunkSize?(n=zc(this.chunkSize),this.chunks.push(n),this.maxCursor+=n.length,this._initReuseChunk===null&&(this._initReuseChunk=n),n.set(t,0)):(this.chunks.push(t),this.maxCursor+=t.length)}this.cursor+=t.length}toBytes(t=!1){let n;if(this.chunks.length===1){let r=this.chunks[0];t&&this.cursor>r.length/2?(n=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):n=Tc(r,0,this.cursor)}else n=Pc(this.chunks,this.cursor);return t&&this.reset(),n}},Dr=class{constructor(t){this.dest=t,this.cursor=0,this.chunks=[t]}reset(){this.cursor=0}push(t){if(this.cursor+t.length>this.dest.length)throw new Error("write out of bounds, destination buffer is too small");this.dest.set(t,this.cursor),this.cursor+=t.length}toBytes(t=!1){let n=this.dest.subarray(0,this.cursor);return t&&this.reset(),n}};var L="CBOR decode error:",Rr="CBOR encode error:",In=[];In[23]=1;In[24]=2;In[25]=3;In[26]=5;In[27]=9;function nt(e,t,n){if(e.length-t<n)throw new Error(`${L} not enough data for type`)}var ae=[24,256,65536,4294967296,BigInt("18446744073709551616")];function we(e,t,n){nt(e,t,1);let r=e[t];if(n.strict===!0&&r<ae[0])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function xe(e,t,n){nt(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<ae[1])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function $e(e,t,n){nt(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<ae[2])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);return r}function Se(e,t,n){nt(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],o=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],i=(BigInt(r)<<BigInt(32))+BigInt(o);if(n.strict===!0&&i<ae[3])throw new Error(`${L} integer encoded in more bytes than necessary (strict decode)`);if(i<=Number.MAX_SAFE_INTEGER)return Number(i);if(n.allowBigInt===!0)return i;throw new Error(`${L} integers outside of the safe integer range are not supported`)}function Oc(e,t,n,r){return new E(g.uint,we(e,t+1,r),2)}function Uc(e,t,n,r){return new E(g.uint,xe(e,t+1,r),3)}function Dc(e,t,n,r){return new E(g.uint,$e(e,t+1,r),5)}function Rc(e,t,n,r){return new E(g.uint,Se(e,t+1,r),9)}function Pe(e,t){return W(e,0,t.value)}function W(e,t,n){if(n<ae[0]){let r=Number(n);e.push([t|r])}else if(n<ae[1]){let r=Number(n);e.push([t|24,r])}else if(n<ae[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<ae[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<ae[4]){let o=[t|27,0,0,0,0,0,0,0],i=Number(r&BigInt(4294967295)),a=Number(r>>BigInt(32)&BigInt(4294967295));o[8]=i&255,i=i>>8,o[7]=i&255,i=i>>8,o[6]=i&255,i=i>>8,o[5]=i&255,o[4]=a&255,a=a>>8,o[3]=a&255,a=a>>8,o[2]=a&255,a=a>>8,o[1]=a&255,e.push(o)}else throw new Error(`${L} encountered BigInt larger than allowable range`)}}Pe.encodedSize=function(t){return W.encodedSize(t.value)};W.encodedSize=function(t){return t<ae[0]?1:t<ae[1]?2:t<ae[2]?3:t<ae[3]?5:9};Pe.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function jc(e,t,n,r){return new E(g.negint,-1-we(e,t+1,r),2)}function Nc(e,t,n,r){return new E(g.negint,-1-xe(e,t+1,r),3)}function Cc(e,t,n,r){return new E(g.negint,-1-$e(e,t+1,r),5)}var Ai=BigInt(-1),Lc=BigInt(1);function Mc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new E(g.negint,i,9)}if(r.allowBigInt!==!0)throw new Error(`${L} integers outside of the safe integer range are not supported`);return new E(g.negint,Ai-BigInt(o),9)}function jr(e,t){let n=t.value,r=typeof n=="bigint"?n*Ai-Lc:n*-1-1;W(e,t.type.majorEncoded,r)}jr.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*Ai-Lc:n*-1-1;return r<ae[0]?1:r<ae[1]?2:r<ae[2]?3:r<ae[3]?5:9};jr.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function An(e,t,n,r){nt(e,t,n+r);let o=e.slice(t+n,t+n+r);return new E(g.bytes,o,n+r)}function Zc(e,t,n,r){return An(e,t,1,n)}function Bc(e,t,n,r){return An(e,t,2,we(e,t+1,r))}function Fc(e,t,n,r){return An(e,t,3,xe(e,t+1,r))}function Hc(e,t,n,r){return An(e,t,5,$e(e,t+1,r))}function Jc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer bytes lengths not supported`);return An(e,t,9,o)}function Nr(e){return e.encodedBytes===void 0&&(e.encodedBytes=g.equals(e.type,g.string)?Or(e.value):e.value),e.encodedBytes}function Mt(e,t){let n=Nr(t);W(e,t.type.majorEncoded,n.length),e.push(n)}Mt.encodedSize=function(t){let n=Nr(t);return W.encodedSize(n.length)+n.length};Mt.compareTokens=function(t,n){return ap(Nr(t),Nr(n))};function ap(e,t){return e.length<t.length?-1:e.length>t.length?1:Ur(e,t)}var Gc=new TextDecoder,cp=32;function up(e,t,n){if(n-t<cp){let o="";for(let i=t;i<n;i++){let a=e[i];if(a&128)return Gc.decode(e.subarray(t,n));o+=String.fromCharCode(a)}return o}return Gc.decode(e.subarray(t,n))}function Tn(e,t,n,r,o){let i=n+r;nt(e,t,i);let a=new E(g.string,up(e,t+n,t+i),i);return o.retainStringBytes===!0&&(a.byteValue=e.slice(t+n,t+i)),a}function Vc(e,t,n,r){return Tn(e,t,1,n,r)}function qc(e,t,n,r){return Tn(e,t,2,we(e,t+1,r),r)}function Kc(e,t,n,r){return Tn(e,t,3,xe(e,t+1,r),r)}function Wc(e,t,n,r){return Tn(e,t,5,$e(e,t+1,r),r)}function Xc(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer string lengths not supported`);return Tn(e,t,9,o,r)}var Yc=Mt;function Zt(e,t,n,r){return new E(g.array,r,n)}function Qc(e,t,n,r){return Zt(e,t,1,n)}function eu(e,t,n,r){return Zt(e,t,2,we(e,t+1,r))}function tu(e,t,n,r){return Zt(e,t,3,xe(e,t+1,r))}function nu(e,t,n,r){return Zt(e,t,5,$e(e,t+1,r))}function ru(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer array lengths not supported`);return Zt(e,t,9,o)}function ou(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return Zt(e,t,1,1/0)}function Cr(e,t){W(e,g.array.majorEncoded,t.value)}Cr.compareTokens=Pe.compareTokens;Cr.encodedSize=function(t){return W.encodedSize(t.value)};function Bt(e,t,n,r){return new E(g.map,r,n)}function iu(e,t,n,r){return Bt(e,t,1,n)}function au(e,t,n,r){return Bt(e,t,2,we(e,t+1,r))}function su(e,t,n,r){return Bt(e,t,3,xe(e,t+1,r))}function cu(e,t,n,r){return Bt(e,t,5,$e(e,t+1,r))}function uu(e,t,n,r){let o=Se(e,t+1,r);if(typeof o=="bigint")throw new Error(`${L} 64-bit integer map lengths not supported`);return Bt(e,t,9,o)}function lu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return Bt(e,t,1,1/0)}function Lr(e,t){W(e,g.map.majorEncoded,t.value)}Lr.compareTokens=Pe.compareTokens;Lr.encodedSize=function(t){return W.encodedSize(t.value)};function du(e,t,n,r){return new E(g.tag,n,1)}function fu(e,t,n,r){return new E(g.tag,we(e,t+1,r),2)}function pu(e,t,n,r){return new E(g.tag,xe(e,t+1,r),3)}function mu(e,t,n,r){return new E(g.tag,$e(e,t+1,r),5)}function hu(e,t,n,r){return new E(g.tag,Se(e,t+1,r),9)}function Mr(e,t){W(e,g.tag.majorEncoded,t.value)}Mr.compareTokens=Pe.compareTokens;Mr.encodedSize=function(t){return W.encodedSize(t.value)};var Ti=20,Pi=21,zi=22,Oi=23;function gu(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${L} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new E(g.null,null,1):new E(g.undefined,void 0,1)}function yu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${L} indefinite length items not allowed`);return new E(g.break,void 0,1)}function Ui(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${L} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${L} Infinity values are not supported`)}return new E(g.float,e,t)}function vu(e,t,n,r){return Ui(Di(e,t+1),3,r)}function _u(e,t,n,r){return Ui(Ri(e,t+1),5,r)}function bu(e,t,n,r){return Ui(Su(e,t+1),9,r)}function Pn(e,t,n){let r=t.value;if(r===!1)e.push([g.float.majorEncoded|Ti]);else if(r===!0)e.push([g.float.majorEncoded|Pi]);else if(r===null)e.push([g.float.majorEncoded|zi]);else if(r===void 0)e.push([g.float.majorEncoded|Oi]);else{let o,i=!1;(!n||n.float64!==!0)&&(xu(r),o=Di(je,1),r===o||Number.isNaN(r)?(je[0]=249,e.push(je.slice(0,3)),i=!0):($u(r),o=Ri(je,1),r===o&&(je[0]=250,e.push(je.slice(0,5)),i=!0))),i||(mp(r),o=Su(je,1),je[0]=251,e.push(je.slice(0,9)))}}Pn.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=Di(je,1);if(r===o||Number.isNaN(r))return 3;if($u(r),o=Ri(je,1),r===o)return 5}return 9};var wu=new ArrayBuffer(9),ze=new DataView(wu,1),je=new Uint8Array(wu,0);function xu(e){if(e===1/0)ze.setUint16(0,31744,!1);else if(e===-1/0)ze.setUint16(0,64512,!1);else if(Number.isNaN(e))ze.setUint16(0,32256,!1);else{ze.setFloat32(0,e);let t=ze.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)ze.setUint16(0,31744,!1);else if(n===0)ze.setUint16(0,(e&2147483648)>>16|r>>13,!1);else{let o=n-127;o<-24?ze.setUint16(0,0):o<-14?ze.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):ze.setUint16(0,(t&2147483648)>>16|o+15<<10|r>>13,!1)}}}function Di(e,t){if(e.length-t<2)throw new Error(`${L} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,o=n&1023,i;return r===0?i=o*2**-24:r!==31?i=(o+1024)*2**(r-25):i=o===0?1/0:NaN,n&32768?-i:i}function $u(e){ze.setFloat32(0,e,!1)}function Ri(e,t){if(e.length-t<4)throw new Error(`${L} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function mp(e){ze.setFloat64(0,e,!1)}function Su(e,t){if(e.length-t<8)throw new Error(`${L} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}Pn.compareTokens=Pe.compareTokens;function F(e,t,n){throw new Error(`${L} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Zr(e){return()=>{throw new Error(`${L} ${e}`)}}var $=[];for(let e=0;e<=23;e++)$[e]=F;$[24]=Oc;$[25]=Uc;$[26]=Dc;$[27]=Rc;$[28]=F;$[29]=F;$[30]=F;$[31]=F;for(let e=32;e<=55;e++)$[e]=F;$[56]=jc;$[57]=Nc;$[58]=Cc;$[59]=Mc;$[60]=F;$[61]=F;$[62]=F;$[63]=F;for(let e=64;e<=87;e++)$[e]=Zc;$[88]=Bc;$[89]=Fc;$[90]=Hc;$[91]=Jc;$[92]=F;$[93]=F;$[94]=F;$[95]=Zr("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]=Zr("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]=Zr("simple values are not supported");$[244]=F;$[245]=F;$[246]=F;$[247]=gu;$[248]=Zr("simple values are not supported");$[249]=vu;$[250]=_u;$[251]=bu;$[252]=F;$[253]=F;$[254]=F;$[255]=yu;var Ne=[];for(let e=0;e<24;e++)Ne[e]=new E(g.uint,e,1);for(let e=-1;e>=-24;e--)Ne[31-e]=new E(g.negint,e,1);Ne[64]=new E(g.bytes,new Uint8Array(0),1);Ne[96]=new E(g.string,"",1);Ne[128]=new E(g.array,0,1);Ne[160]=new E(g.map,0,1);Ne[244]=new E(g.false,!1,1);Ne[245]=new E(g.true,!0,1);Ne[246]=new E(g.null,null,1);function ji(e){switch(e.type){case g.false:return Be([244]);case g.true:return Be([245]);case g.null:return Be([246]);case g.bytes:return e.value.length?void 0:Be([64]);case g.string:return e.value===""?Be([96]):void 0;case g.array:return e.value===0?Be([128]):void 0;case g.map:return e.value===0?Be([160]):void 0;case g.uint:return e.value<24?Be([Number(e.value)]):void 0;case g.negint:if(e.value>=-24)return Be([31-Number(e.value)])}}var gp={float64:!1,mapSorter:_p,quickEncodeToken:ji},Tu=Object.freeze({float64:!0,mapSorter:bp,quickEncodeToken:ji});function yp(){let e=[];return e[g.uint.major]=Pe,e[g.negint.major]=jr,e[g.bytes.major]=Mt,e[g.string.major]=Yc,e[g.array.major]=Cr,e[g.map.major]=Lr,e[g.tag.major]=Mr,e[g.float.major]=Pn,e}var Ft=yp(),Br=new kn,On=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(`${Rr} object contains circular references`);return new e(n,t)}},lt={null:new E(g.null,null),undefined:new E(g.undefined,void 0),true:new E(g.true,!0),false:new E(g.false,!1),emptyArray:new E(g.array,0),emptyMap:new E(g.map,0)},Fe={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new E(g.float,e):e>=0?new E(g.uint,e):new E(g.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new E(g.uint,e):new E(g.negint,e)},Uint8Array(e,t,n,r){return new E(g.bytes,e)},string(e,t,n,r){return new E(g.string,e)},boolean(e,t,n,r){return e?lt.true:lt.false},null(e,t,n,r){return lt.null},undefined(e,t,n,r){return lt.undefined},ArrayBuffer(e,t,n,r){return new E(g.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new E(g.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[lt.emptyArray,new E(g.break)]:lt.emptyArray;r=On.createCheck(r,e);let o=[],i=0;for(let a of e)o[i++]=Fr(a,n,r);return n.addBreakTokens?[new E(g.array,e.length),o,new E(g.break)]:[new E(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=On.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++]=[Fr(l,n,r),Fr(d,n,r)])}c<a&&(s.length=c)}return s?.length?(vp(s,n),n.addBreakTokens?[new E(g.map,s.length),s,new E(g.break)]:[new E(g.map,s.length),s]):n.addBreakTokens===!0?[lt.emptyMap,new E(g.break)]:lt.emptyMap}};Fe.Map=Fe.Object;Fe.Buffer=Fe.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))Fe[`${e}Array`]=Fe.DataView;function Fr(e,t={},n){let r=Ii(e),o=t&&t.typeEncoders&&t.typeEncoders[r]||Fe[r];if(typeof o=="function"){let a=o(e,r,t,n);if(a!=null)return a}let i=Fe[r];if(!i)throw new Error(`${Rr} unsupported type: ${r}`);return i(e,r,t,n)}function vp(e,t){t.mapSorter&&e.sort(t.mapSorter)}function _p(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=Ft[o].compareTokens(n,r);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function bp(e,t){if(e[0]instanceof E&&t[0]instanceof E){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=Eu(n.value)),r._keyBytes||(r._keyBytes=Eu(r.value)),Ur(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Eu(e){return zu(e,Ft,Tu)}function zn(e,t,n,r){if(Array.isArray(t))for(let o of t)zn(e,o,n,r);else n[t.type.major](e,t,r)}var ku=g.uint.majorEncoded,Iu=g.negint.majorEncoded,wp=g.bytes.majorEncoded,xp=g.string.majorEncoded,Au=g.array.majorEncoded,$p=g.float.majorEncoded|Ti,Sp=g.float.majorEncoded|Pi,Ep=g.float.majorEncoded|zi,kp=g.float.majorEncoded|Oi,Ip=BigInt(-1),Ap=BigInt(1);function Tp(e){return e.addBreakTokens!==!0}function Pu(e,t,n,r){let o=Ii(t),i=n.typeEncoders&&n.typeEncoders[o];if(i){let a=i(t,o,n,r);if(a!=null){zn(e,a,Ft,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)?Pn(e,new E(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*Ip-Ap);return;case"string":{let a=Or(t);W(e,xp,a.length),e.push(a);return}case"Uint8Array":W(e,wp,t.length),e.push(t);return;case"Array":if(!t.length){e.push([Au]);return}r=On.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=Fe.Object(t,o,n,r);zn(e,a,Ft,n)}return;default:{let a=Fe[o];if(!a)throw new Error(`${Rr} unsupported type: ${o}`);let s=a(t,o,n,r);zn(e,s,Ft,n)}}}function zu(e,t,n,r){let o=r instanceof Uint8Array,i=o?new Dr(r):Br,a=Fr(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 kn(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():En(i.chunks[0])}}return i.reset(),zn(i,a,t,n),i.toBytes(!0)}function Ni(e,t){return t=Object.assign({},gp,t),Tp(t)?(Br.reset(),Pu(Br,e,t,void 0),Br.toBytes(!0)):zu(e,Ft,t)}var Pp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},Hr=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=Ne[t];if(n===void 0){let r=$[t];if(!r)throw new Error(`${L} no decoder for major type ${t>>>5} (byte 0x${t.toString(16).padStart(2,"0")})`);let o=t&31;n=r(this.data,this._pos,o,this.options)}return this._pos+=n.encodedLength,n}},Un=Symbol.for("DONE"),Jr=Symbol.for("BREAK");function zp(e,t,n){let r=[];for(let o=0;o<e.value;o++){let i=Ht(t,n);if(i===Jr){if(e.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed array`)}if(i===Un)throw new Error(`${L} found array but not enough entries (got ${o}, expected ${e.value})`);r[o]=i}return r}function Op(e,t,n){let r=n.useMaps===!0,o=n.rejectDuplicateMapKeys===!0,i=r?void 0:{},a=r?new Map:void 0;for(let s=0;s<e.value;s++){let u=Ht(t,n);if(u===Jr){if(e.value===1/0)break;throw new Error(`${L} got unexpected break to lengthed map`)}if(u===Un)throw new Error(`${L} found map but not enough entries (got ${s} [no key], expected ${e.value})`);if(!r&&typeof u!="string")throw new Error(`${L} non-string keys not supported (got ${typeof u})`);if(o&&(r&&a.has(u)||!r&&Object.hasOwn(i,u)))throw new Error(`${L} found repeat map key "${u}"`);let c=Ht(t,n);if(c===Un)throw new Error(`${L} found map but not enough entries (got ${s} [no value], expected ${e.value})`);r?a.set(u,c):i[u]=c}return r?a:i}function Ht(e,t){if(e.done())return Un;let n=e.next();if(g.equals(n.type,g.break))return Jr;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=Ht(e,t);return t.tags[n.value](r)}throw new Error(`${L} tag not supported (${n.value})`)}throw new Error("unsupported")}function Ou(e,t){if(!(e instanceof Uint8Array))throw new Error(`${L} data to decode must be a Uint8Array`);t=Object.assign({},Pp,t);let n=En(e),r=t.tokenizer||new Hr(n,t),o=Ht(r,t);if(o===Un)throw new Error(`${L} did not find any content to decode`);if(o===Jr)throw new Error(`${L} got unexpected break`);return[o,e.subarray(r.pos())]}function Ci(e,t){let[n,r]=Ou(e,t);if(r.length>0)throw new Error(`${L} too many terminals, data makes no sense`);return n}var yk=new Uint8Array(0);function Uu(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0}function Jt(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,v=0,k=0,A=f.length;k!==A&&f[k]===0;)k++,y++;for(var w=(A-k)*l+1>>>0,S=new Uint8Array(w);k!==A;){for(var x=f[k],U=0,M=w-1;(x!==0||U<v)&&M!==-1;M--,U++)x+=256*S[M]>>>0,S[M]=x%s>>>0,x=x/s>>>0;if(x!==0)throw new Error("Non-zero carry");v=U,k++}for(var B=w-v;B!==w&&S[B]===0;)B++;for(var ie=u.repeat(y);B<w;++B)ie+=e.charAt(S[B]);return ie}function p(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var v=0,k=0;f[y]===u;)v++,y++;for(var A=(f.length-y)*c+1>>>0,w=new Uint8Array(A);f[y];){var S=n[f.charCodeAt(y)];if(S===255)return;for(var x=0,U=A-1;(S!==0||x<k)&&U!==-1;U--,x++)S+=s*w[U]>>>0,w[U]=S%256>>>0,S=S/256>>>0;if(S!==0)throw new Error("Non-zero carry");k=x,y++}if(f[y]!==" "){for(var M=A-k;M!==A&&w[M]===0;)M++;for(var B=new Uint8Array(v+(A-M)),ie=v;M!==A;)B[ie++]=w[M++];return B}}}function _(f){var y=p(f);if(y)return y;throw new Error(`Non-${t} character`)}return{encode:d,decodeUnsafe:p,decode:_}}var Rp=Dp,jp=Rp,Du=jp;var Li=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")}},Mi=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)}},Zi=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 Zi({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Bi=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 Li(t,n,r),this.decoder=new Mi(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 Bi(e,t,n,r)}function Gt({name:e,prefix:t,alphabet:n}){let{encode:r,decode:o}=Du(n,e);return ju({prefix:t,name:e,encode:r,decode:i=>Jt(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 He({name:e,prefix:t,bitsPerChar:n,alphabet:r}){let o=Lp(r);return ju({prefix:t,name:e,encode(i){return Cp(i,r,n)},decode(i){return Np(i,o,n,e)}})}var Dn=He({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sk=He({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ek=He({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),kk=He({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ik=He({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ak=He({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Tk=He({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pk=He({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),zk=He({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Gr=Gt({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Dk=Gt({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var rt=Gt({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Nk=Gt({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Mp=Lu,Nu=128,Zp=127,Bp=~Zp,Fp=Math.pow(2,31);function Lu(e,t,n){t=t||[],n=n||0;for(var r=n;e>=Fp;)t[n++]=e&255|Nu,e/=128;for(;e&Bp;)t[n++]=e&255|Nu,e>>>=7;return t[n]=e|0,Lu.bytes=n-r+1,t}var Hp=Fi,Jp=128,Cu=127;function Fi(e,r){var n=0,r=r||0,o=0,i=r,a,s=e.length;do{if(i>=s)throw Fi.bytes=0,new RangeError("Could not decode varint");a=e[i++],n+=o<28?(a&Cu)<<o:(a&Cu)*Math.pow(2,o),o+=7}while(a>=Jp);return Fi.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,Rn=rm;function jn(e,t=0){return[Rn.decode(e,t),Rn.decode.bytes]}function Vt(e,t,n=0){return Rn.encode(e,t,n),t}function qt(e){return Rn.encodingLength(e)}function Zu(e,t){let n=t.byteLength,r=qt(e),o=r+qt(n),i=new Uint8Array(o+n);return Vt(e,i,0),Vt(n,i,r),i.set(t,o),new Kt(e,n,t,i)}function Bu(e){let t=Jt(e),[n,r]=jn(t),[o,i]=jn(t.subarray(r)),a=t.subarray(r+i);if(a.byteLength!==o)throw new Error("Incorrect length");return new Kt(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 Kt=class{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=r,this.bytes=o}};function Hu(e,t){let{bytes:n,version:r}=e;return r===0?am(n,Hi(e),t??rt.encoder):sm(n,Hi(e),t??Dn.encoder)}var Ju=new WeakMap;function Hi(e){let t=Ju.get(e);if(t==null){let n=new Map;return Ju.set(e,n),n}return t}var Cn=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!==Nn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==cm)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return e.createV0(n)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:t,digest:n}=this.multihash,r=Zu(t,n);return e.createV1(this.code,r)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(t){return e.equals(this,t)}static equals(t,n){let r=n;return r!=null&&t.code===r.code&&t.version===r.version&&Fu(t.multihash,r.multihash)}toString(t){return Hu(this,t)}toJSON(){return{"/":Hu(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(t){if(t==null)return null;let n=t;if(n instanceof e)return n;if(n["/"]!=null&&n["/"]===n.bytes||n.asCID===n){let{version:r,code:o,multihash:i,bytes:a}=n;return new e(r,o,i,a??Gu(r,o,i.bytes))}else if(n[um]===!0){let{version:r,multihash:o,code:i}=n,a=Bu(o);return e.create(r,i,a)}else return null}static create(t,n,r){if(typeof n!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(t){case 0:{if(n!==Nn)throw new Error(`Version 0 CID must use dag-pb (code: ${Nn}) 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,Nn,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=Jt(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 Kt(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]=jn(t.subarray(n));return n+=p,d},o=r(),i=Nn;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 Hi(i).set(r,t),i}};function im(e,t){switch(e[0]){case"Q":{let n=t??rt;return[rt.prefix,n.decode(`${rt.prefix}${e}`)]}case rt.prefix:{let n=t??rt;return[rt.prefix,n.decode(e)]}case Dn.prefix:{let n=t??Dn;return[Dn.prefix,n.decode(e)]}case Gr.prefix:{let n=t??Gr;return[Gr.prefix,n.decode(e)]}default:{if(t==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}}function am(e,t,n){let{prefix:r}=n;if(r!==rt.prefix)throw Error(`Cannot string encode V0 in ${n.name} encoding`);let o=t.get(r);if(o==null){let i=n.encode(e).slice(1);return t.set(r,i),i}else return o}function sm(e,t,n){let{prefix:r}=n,o=t.get(r);if(o==null){let i=n.encode(e);return t.set(r,i),i}else return o}var Nn=112,cm=18;function Gu(e,t,n){let r=qt(e),o=r+qt(t),i=new Uint8Array(o+n.byteLength);return Vt(e,i,0),Vt(t,i,r),i.set(n,o),i}var um=Symbol.for("@ipld/js-cid/CID");var Vu=42;function lm(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function dm(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Cn.asCID(e);if(!t)return null;let n=new Uint8Array(t.bytes.byteLength+1);return n.set(t.bytes,1),[new E(g.tag,Vu),new E(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 Ji={float64:!0,typeEncoders:{Map:mm,Object:dm,undefined:fm,number:pm}},Kk={...Ji,typeEncoders:{...Ji.typeEncoders}};function hm(e){if(e[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Cn.decode(e.subarray(1))}var Vr={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};Vr.tags[Vu]=hm;var Wk={...Vr,tags:Vr.tags.slice()};var Ee=e=>Ni(e,Ji),Je=e=>Ci(lm(e),Vr);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 _m="(?:%[0-9a-fA-F]{2})",qu=`(?:[a-zA-Z0-9._-]|${_m})`,bm="([a-z0-9]+)",wm=`((?:${qu}*:)*(${qu}+))`,Ku="[a-zA-Z0-9_.:%-]",xm=`;${Ku}+=${Ku}*`,$m=`((${xm})*)`,Sm="(/[^#?]*)?",Em="([?][^#]*)?",km="(#.*)?",Im=new RegExp(`^did:${bm}:${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 qr={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{...qr,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:o}})},function(o){return{...qr,didResolutionMetadata:{error:"notFound",message:o.toString()}}}))}catch(o){return Promise.reject(o)}}}var Kr=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({...qr,didResolutionMetadata:{error:"invalidDid"}});let i=r.registry[o.method];return i?Promise.resolve(r.cache(o,()=>i(o.did,o,r,n))):Promise.resolve({...qr,didResolutionMetadata:{error:"unsupportedDidMethod"}})}catch(r){return Promise.reject(r)}}};function Ln(e,t){return function(){return e.apply(t,arguments)}}var{toString:Pm}=Object.prototype,{getPrototypeOf:Vi}=Object,{iterator:Xr,toStringTag:Xu}=Symbol,Yr=(e=>t=>{let n=Pm.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Ce=e=>(e=e.toLowerCase(),t=>Yr(t)===e),Qr=e=>t=>typeof t===e,{isArray:Xt}=Array,Wt=Qr("undefined");function Mn(e){return e!==null&&!Wt(e)&&e.constructor!==null&&!Wt(e.constructor)&&ge(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Yu=Ce("ArrayBuffer");function zm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Yu(e.buffer),t}var Om=Qr("string"),ge=Qr("function"),Qu=Qr("number"),Zn=e=>e!==null&&typeof e=="object",Um=e=>e===!0||e===!1,Wr=e=>{if(Yr(e)!=="object")return!1;let t=Vi(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Xu in e)&&!(Xr in e)},Dm=e=>{if(!Zn(e)||Mn(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},Rm=Ce("Date"),jm=Ce("File"),Nm=Ce("Blob"),Cm=Ce("FileList"),Lm=e=>Zn(e)&&ge(e.pipe),Mm=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||ge(e.append)&&((t=Yr(e))==="formdata"||t==="object"&&ge(e.toString)&&e.toString()==="[object FormData]"))},Zm=Ce("URLSearchParams"),[Bm,Fm,Hm,Jm]=["ReadableStream","Request","Response","Headers"].map(Ce),Gm=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Bn(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Xt(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(Mn(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(Mn(e))return null;t=t.toLowerCase();let n=Object.keys(e),r=n.length,o;for(;r-- >0;)if(o=n[r],t===o.toLowerCase())return o;return null}var $t=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,tl=e=>!Wt(e)&&e!==$t;function Gi(){let{caseless:e,skipUndefined:t}=tl(this)&&this||{},n={},r=(o,i)=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;let a=e&&el(n,i)||i;Wr(n[a])&&Wr(o)?n[a]=Gi(n[a],o):Wr(o)?n[a]=Gi({},o):Xt(o)?n[a]=o.slice():(!t||!Wt(o))&&(n[a]=o)};for(let o=0,i=arguments.length;o<i;o++)arguments[o]&&Bn(arguments[o],r);return n}var Vm=(e,t,n,{allOwnKeys:r}={})=>(Bn(t,(o,i)=>{n&&ge(o)?Object.defineProperty(e,i,{value:Ln(o,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),e),qm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Km=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},Wm=(e,t,n,r)=>{let o,i,a,s={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],(!r||r(a,e,t))&&!s[a]&&(t[a]=e[a],s[a]=!0);e=n!==!1&&Vi(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(Xt(e))return e;let t=e.length;if(!Qu(t))return null;let n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Qm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&Vi(Uint8Array)),eh=(e,t)=>{let r=(e&&e[Xr]).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=Ce("HTMLFormElement"),rh=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),Wu=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),oh=Ce("RegExp"),nl=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};Bn(n,(o,i)=>{let a;(a=t(o,i,e))!==!1&&(r[i]=a||o)}),Object.defineProperties(e,r)},ih=e=>{nl(e,(t,n)=>{if(ge(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;let r=e[n];if(ge(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},ah=(e,t)=>{let n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Xt(e)?r(e):r(String(e).split(t)),n},sh=()=>{},ch=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function uh(e){return!!(e&&ge(e.append)&&e[Xu]==="FormData"&&e[Xr])}var lh=e=>{let t=new Array(10),n=(r,o)=>{if(Zn(r)){if(t.indexOf(r)>=0)return;if(Mn(r))return r;if(!("toJSON"in r)){t[o]=r;let i=Xt(r)?[]:{};return Bn(r,(a,s)=>{let u=n(a,o+1);!Wt(u)&&(i[s]=u)}),t[o]=void 0,i}}return r};return n(e,0)},dh=Ce("AsyncFunction"),fh=e=>e&&(Zn(e)||ge(e))&&ge(e.then)&&ge(e.catch),rl=((e,t)=>e?setImmediate:t?((n,r)=>($t.addEventListener("message",({source:o,data:i})=>{o===$t&&i===n&&r.length&&r.shift()()},!1),o=>{r.push(o),$t.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",ge($t.postMessage)),ph=typeof queueMicrotask<"u"?queueMicrotask.bind($t):typeof process<"u"&&process.nextTick||rl,mh=e=>e!=null&&ge(e[Xr]),m={isArray:Xt,isArrayBuffer:Yu,isBuffer:Mn,isFormData:Mm,isArrayBufferView:zm,isString:Om,isNumber:Qu,isBoolean:Um,isObject:Zn,isPlainObject:Wr,isEmptyObject:Dm,isReadableStream:Bm,isRequest:Fm,isResponse:Hm,isHeaders:Jm,isUndefined:Wt,isDate:Rm,isFile:jm,isBlob:Nm,isRegExp:oh,isFunction:ge,isStream:Lm,isURLSearchParams:Zm,isTypedArray:Qm,isFileList:Cm,forEach:Bn,merge:Gi,extend:Vm,trim:Gm,stripBOM:qm,inherits:Km,toFlatObject:Wm,kindOf:Yr,kindOfTest:Ce,endsWith:Xm,toArray:Ym,forEachEntry:eh,matchAll:th,isHTMLForm:nh,hasOwnProperty:Wu,hasOwnProp:Wu,reduceDescriptors:nl,freezeMethods:ih,toObjectSet:ah,toCamelCase:rh,noop:sh,toFiniteNumber:ch,findKey:el,global:$t,isContextDefined:tl,isSpecCompliantForm:uh,toJSONObject:lh,isAsyncFn:dh,isThenable:fh,setImmediate:rl,asap:ph,isIterable:mh};var pe=class e extends Error{static from(t,n,r,o,i,a){let s=new e(t.message,n||t.code,r,o,i);return s.cause=t,s.name=t.name,a&&Object.assign(s,a),s}constructor(t,n,r,o,i){super(t),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),o&&(this.request=o),i&&(this.response=i,this.status=i.status)}toJSON(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:m.toJSONObject(this.config),code:this.code,status:this.status}}};pe.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";pe.ERR_BAD_OPTION="ERR_BAD_OPTION";pe.ECONNABORTED="ECONNABORTED";pe.ETIMEDOUT="ETIMEDOUT";pe.ERR_NETWORK="ERR_NETWORK";pe.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";pe.ERR_DEPRECATED="ERR_DEPRECATED";pe.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";pe.ERR_BAD_REQUEST="ERR_BAD_REQUEST";pe.ERR_CANCELED="ERR_CANCELED";pe.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";pe.ERR_INVALID_URL="ERR_INVALID_URL";var N=pe;var eo=null;function qi(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(qi)}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(eo||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 N("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 k=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)&&hh(f)||(m.isFileList(f)||m.endsWith(y,"[]"))&&(k=m.toArray(f)))return y=il(y),k.forEach(function(w,S){!(m.isUndefined(w)||w===null)&&t.append(a===!0?ol([y],S,i):a===null?y:y+"[]",c(w))}),!1}return qi(f)?!0:(t.append(ol(v,y,i),c(f)),!1)}let d=[],p=Object.assign(gh,{defaultVisitor:l,convertValue:c,isVisitable:qi});function _(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(k,A){(!(m.isUndefined(k)||k===null)&&o.call(t,k,m.isString(A)?A.trim():A,y,p))===!0&&_(k,y?y.concat(A):[A])}),d.pop()}}if(!m.isObject(e))throw new TypeError("data must be an object");return _(e),t}var dt=yh;function al(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function sl(e,t){this._pairs=[],e&&dt(e,this,t)}var cl=sl.prototype;cl.append=function(t,n){this._pairs.push([t,n])};cl.toString=function(t){let n=t?function(r){return t.call(this,r,al)}:al;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};var to=sl;function vh(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Fn(e,t,n){if(!t)return e;let r=n&&n.encode||vh,o=m.isFunction(n)?{serialize:n}:n,i=o&&o.serialize,a;if(i?a=i(t,o):a=m.isURLSearchParams(t)?t.toString():new to(t,o).toString(r),a){let s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+a}return e}var Ki=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)})}},Wi=Ki;var Yt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0};var ul=typeof URLSearchParams<"u"?URLSearchParams:to;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 Qi={};tf(Qi,{hasBrowserEnv:()=>Yi,hasStandardBrowserEnv:()=>_h,hasStandardBrowserWebWorkerEnv:()=>bh,navigator:()=>Xi,origin:()=>wh});var Yi=typeof window<"u"&&typeof document<"u",Xi=typeof navigator=="object"&&navigator||void 0,_h=Yi&&(!Xi||["ReactNative","NativeScript","NS"].indexOf(Xi.product)<0),bh=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",wh=Yi&&window.location.href||"http://localhost";var Y={...Qi,...fl};function ea(e,t){return dt(e,new Y.classes.URLSearchParams,{visitor:function(n,r,o,i){return Y.isNode&&m.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}function xh(e){return m.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function $h(e){let t={},n=Object.keys(e),r,o=n.length,i;for(r=0;r<o;r++)i=n[r],t[i]=e[i];return t}function Sh(e){function t(n,r,o,i){let a=n[i++];if(a==="__proto__")return!0;let s=Number.isFinite(+a),u=i>=n.length;return a=!a&&m.isArray(o)?o.length:a,u?(m.hasOwnProp(o,a)?o[a]=[o[a],r]:o[a]=r,!s):((!o[a]||!m.isObject(o[a]))&&(o[a]=[]),t(n,r,o[a],i)&&m.isArray(o[a])&&(o[a]=$h(o[a])),!s)}if(m.isFormData(e)&&m.isFunction(e.entries)){let n={};return m.forEachEntry(e,(r,o)=>{t(xh(r),o,n,0)}),n}return null}var no=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 ta={transitional:Yt,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(no(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 ea(t,this.formSerializer).toString();if((s=m.isFileList(t))||r.indexOf("multipart/form-data")>-1){let u=this.env&&this.env.FormData;return dt(s?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),Eh(t)):t}],transformResponse:[function(t){let n=this.transitional||ta.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"?N.from(s,N.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=>{ta.headers[e]={}});var Qt=ta;var kh=m.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),pl=e=>{let t={},n,r,o;return e&&e.split(`
3
- `).forEach(function(a){o=a.indexOf(":"),n=a.substring(0,o).trim().toLowerCase(),r=a.substring(o+1).trim(),!(!n||t[n]&&kh[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};var ml=Symbol("internals");function Hn(e){return e&&String(e).trim().toLowerCase()}function ro(e){return e===!1||e==null?e:m.isArray(e)?e.map(ro):String(e)}function Ih(e){let t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}var Ah=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function na(e,t,n,r,o){if(m.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!m.isString(t)){if(m.isString(r))return t.indexOf(r)!==-1;if(m.isRegExp(r))return r.test(t)}}function Th(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Ph(e,t){let n=m.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,a){return this[r].call(this,t,o,i,a)},configurable:!0})})}var en=class{constructor(t){t&&this.set(t)}set(t,n,r){let o=this;function i(s,u,c){let l=Hn(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]=ro(s))}let a=(s,u)=>m.forEach(s,(c,l)=>i(c,l,u));if(m.isPlainObject(t)||t instanceof this.constructor)a(t,n);else if(m.isString(t)&&(t=t.trim())&&!Ah(t))a(pl(t),n);else if(m.isObject(t)&&m.isIterable(t)){let s={},u,c;for(let l of t){if(!m.isArray(l))throw TypeError("Object iterator must return a key-value pair");s[c=l[0]]=(u=s[c])?m.isArray(u)?[...u,l[1]]:[u,l[1]]:l[1]}a(s,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=Hn(t),t){let r=m.findKey(this,t);if(r){let o=this[r];if(!n)return o;if(n===!0)return Ih(o);if(m.isFunction(n))return n.call(this,o,r);if(m.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=Hn(t),t){let r=m.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||na(this,this[r],r,n)))}return!1}delete(t,n){let r=this,o=!1;function i(a){if(a=Hn(a),a){let s=m.findKey(r,a);s&&(!n||na(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||na(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]=ro(o),delete n[i];return}let s=t?Th(i):String(i).trim();s!==i&&delete n[i],n[s]=ro(o),r[s]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let n=Object.create(null);return m.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&m.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
4
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){let r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){let r=(this[ml]=this[ml]={accessors:{}}).accessors,o=this.prototype;function i(a){let s=Hn(a);r[s]||(Ph(o,a),r[s]=!0)}return m.isArray(t)?t.forEach(i):i(t),this}};en.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);m.reduceDescriptors(en.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});m.freezeMethods(en);var oe=en;function Jn(e,t){let n=this||Qt,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 Gn(e){return!!(e&&e.__CANCEL__)}var ra=class extends N{constructor(t,n,r){super(t??"canceled",N.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}},Ge=ra;function Vn(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new N("Request failed with status code "+n.status,[N.ERR_BAD_REQUEST,N.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function oa(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 _=l&&c-l;return _?Math.round(p*1e3/_):void 0}}var hl=zh;function Oh(e,t){let n=0,r=1e3/t,o,i,a=(c,l=Date.now())=>{n=l,o=null,i&&(clearTimeout(i),i=null),e(...c)};return[(...c)=>{let l=Date.now(),d=l-n;d>=r?a(c,l):(o=c,i||(i=setTimeout(()=>{i=null,a(o)},r-d)))},()=>o&&a(o)]}var gl=Oh;var tn=(e,t,n=3)=>{let r=0,o=hl(50,250);return gl(i=>{let a=i.loaded,s=i.lengthComputable?i.total:void 0,u=a-r,c=o(u),l=a<=s;r=a;let d={loaded:a,total:s,progress:s?a/s:void 0,bytes:u,rate:c||void 0,estimated:c&&s&&l?(s-a)/c:void 0,event:i,lengthComputable:s!=null,[t?"download":"upload"]:!0};e(d)},n)},ia=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},aa=e=>(...t)=>m.asap(()=>e(...t));var yl=Y.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Y.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Y.origin),Y.navigator&&/(msie|trident)/i.test(Y.navigator.userAgent)):()=>!0;var vl=Y.hasStandardBrowserEnv?{write(e,t,n,r,o,i,a){if(typeof document>"u")return;let s=[`${e}=${encodeURIComponent(t)}`];m.isNumber(n)&&s.push(`expires=${new Date(n).toUTCString()}`),m.isString(r)&&s.push(`path=${r}`),m.isString(o)&&s.push(`domain=${o}`),i===!0&&s.push("secure"),m.isString(a)&&s.push(`SameSite=${a}`),document.cookie=s.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.match(new RegExp("(?:^|; )"+e+"=([^;]*)"));return t?decodeURIComponent(t[1]):null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function sa(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function ca(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function qn(e,t,n){let r=!sa(t);return e&&(r||n==!1)?ca(e,t):t}var _l=e=>e instanceof oe?{...e}:e;function Le(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){if(l==="__proto__"||l==="constructor"||l==="prototype")return;let d=m.hasOwnProp(u,l)?u[l]:o,p=d(e[l],t[l],l);m.isUndefined(p)&&d!==s||(n[l]=p)}),n}var oo=e=>{let t=Le({},e),{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:i,headers:a,auth:s}=t;if(t.headers=a=oe.from(a),t.url=Fn(qn(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),s&&a.set("Authorization","Basic "+btoa((s.username||"")+":"+(s.password?unescape(encodeURIComponent(s.password)):""))),m.isFormData(n)){if(Y.hasStandardBrowserEnv||Y.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(m.isFunction(n.getHeaders)){let u=n.getHeaders(),c=["content-type","content-length"];Object.entries(u).forEach(([l,d])=>{c.includes(l.toLowerCase())&&a.set(l,d)})}}if(Y.hasStandardBrowserEnv&&(r&&m.isFunction(r)&&(r=r(t)),r||r!==!1&&yl(t.url))){let u=o&&i&&vl.read(i);u&&a.set(o,u)}return t};var Uh=typeof XMLHttpRequest<"u",bl=Uh&&function(e){return new Promise(function(n,r){let o=oo(e),i=o.data,a=oe.from(o.headers).normalize(),{responseType:s,onUploadProgress:u,onDownloadProgress:c}=o,l,d,p,_,f;function y(){_&&_(),f&&f(),o.cancelToken&&o.cancelToken.unsubscribe(l),o.signal&&o.signal.removeEventListener("abort",l)}let v=new XMLHttpRequest;v.open(o.method.toUpperCase(),o.url,!0),v.timeout=o.timeout;function k(){if(!v)return;let w=oe.from("getAllResponseHeaders"in v&&v.getAllResponseHeaders()),x={data:!s||s==="text"||s==="json"?v.responseText:v.response,status:v.status,statusText:v.statusText,headers:w,config:e,request:v};Vn(function(M){n(M),y()},function(M){r(M),y()},x),v=null}"onloadend"in v?v.onloadend=k:v.onreadystatechange=function(){!v||v.readyState!==4||v.status===0&&!(v.responseURL&&v.responseURL.indexOf("file:")===0)||setTimeout(k)},v.onabort=function(){v&&(r(new N("Request aborted",N.ECONNABORTED,e,v)),v=null)},v.onerror=function(S){let x=S&&S.message?S.message:"Network Error",U=new N(x,N.ERR_NETWORK,e,v);U.event=S||null,r(U),v=null},v.ontimeout=function(){let S=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",x=o.transitional||Yt;o.timeoutErrorMessage&&(S=o.timeoutErrorMessage),r(new N(S,x.clarifyTimeoutError?N.ETIMEDOUT:N.ECONNABORTED,e,v)),v=null},i===void 0&&a.setContentType(null),"setRequestHeader"in v&&m.forEach(a.toJSON(),function(S,x){v.setRequestHeader(x,S)}),m.isUndefined(o.withCredentials)||(v.withCredentials=!!o.withCredentials),s&&s!=="json"&&(v.responseType=o.responseType),c&&([p,f]=tn(c,!0),v.addEventListener("progress",p)),u&&v.upload&&([d,_]=tn(u),v.upload.addEventListener("progress",d),v.upload.addEventListener("loadend",_)),(o.cancelToken||o.signal)&&(l=w=>{v&&(r(!w||w.type?new Ge(null,e,v):w),v.abort(),v=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));let A=oa(o.url);if(A&&Y.protocols.indexOf(A)===-1){r(new N("Unsupported protocol "+A+":",N.ERR_BAD_REQUEST,e));return}v.send(i||null)})};var Dh=(e,t)=>{let{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o,i=function(c){if(!o){o=!0,s();let l=c instanceof Error?c:this.reason;r.abort(l instanceof N?l:new Ge(l instanceof Error?l.message:l))}},a=t&&setTimeout(()=>{a=null,i(new N(`timeout of ${t}ms exceeded`,N.ETIMEDOUT))},t),s=()=>{e&&(a&&clearTimeout(a),a=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(i):c.removeEventListener("abort",i)}),e=null)};e.forEach(c=>c.addEventListener("abort",i));let{signal:u}=r;return u.unsubscribe=()=>m.asap(s),u}},wl=Dh;var Rh=function*(e,t){let n=e.byteLength;if(!t||n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},jh=async function*(e,t){for await(let n of Nh(e))yield*Rh(n,t)},Nh=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}let t=e.getReader();try{for(;;){let{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},ua=(e,t,n,r)=>{let o=jh(e,t),i=0,a,s=u=>{a||(a=!0,r&&r(u))};return new ReadableStream({async pull(u){try{let{done:c,value:l}=await o.next();if(c){s(),u.close();return}let d=l.byteLength;if(n){let p=i+=d;n(p)}u.enqueue(new Uint8Array(l))}catch(c){throw s(c),c}},cancel(u){return s(u),o.return()}},{highWaterMark:2})};var xl=64*1024,{isFunction:io}=m,Ch=(({Request:e,Response:t})=>({Request:e,Response:t}))(m.global),{ReadableStream:$l,TextEncoder:Sl}=m.global,El=(e,...t)=>{try{return!!e(...t)}catch{return!1}},Lh=e=>{e=m.merge.call({skipUndefined:!0},Ch,e);let{fetch:t,Request:n,Response:r}=e,o=t?io(t):typeof fetch=="function",i=io(n),a=io(r);if(!o)return!1;let s=o&&io($l),u=o&&(typeof Sl=="function"?(f=>y=>f.encode(y))(new Sl):async f=>new Uint8Array(await new n(f).arrayBuffer())),c=i&&s&&El(()=>{let f=!1,y=new n(Y.origin,{body:new $l,method:"POST",get duplex(){return f=!0,"half"}}).headers.has("Content-Type");return f&&!y}),l=a&&s&&El(()=>m.isReadableStream(new r("").body)),d={stream:l&&(f=>f.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!d[f]&&(d[f]=(y,v)=>{let k=y&&y[f];if(k)return k.call(y);throw new N(`Response type '${f}' is not supported`,N.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},_=async(f,y)=>{let v=m.toFiniteNumber(f.getContentLength());return v??p(y)};return async f=>{let{url:y,method:v,data:k,signal:A,cancelToken:w,timeout:S,onDownloadProgress:x,onUploadProgress:U,responseType:M,headers:B,withCredentials:ie="same-origin",fetchOptions:Ae}=oo(f),h=t||fetch;M=M?(M+"").toLowerCase():"text";let b=wl([A,w&&w.toAbortSignal()],S),O=null,Z=b&&b.unsubscribe&&(()=>{b.unsubscribe()}),q;try{if(U&&c&&v!=="get"&&v!=="head"&&(q=await _(B,k))!==0){let ce=new n(y,{method:"POST",body:k,duplex:"half"}),Dt;if(m.isFormData(k)&&(Dt=ce.headers.get("content-type"))&&B.setContentType(Dt),ce.body){let[oi,mr]=ia(q,tn(aa(U)));k=ua(ce.body,xl,oi,mr)}}m.isString(ie)||(ie=ie?"include":"omit");let z=i&&"credentials"in n.prototype,gt={...Ae,signal:b,method:v.toUpperCase(),headers:B.normalize().toJSON(),body:k,duplex:"half",credentials:z?ie:void 0};O=i&&new n(y,gt);let Te=await(i?h(O,Ae):h(y,gt)),yn=l&&(M==="stream"||M==="response");if(l&&(x||yn&&Z)){let ce={};["status","statusText","headers"].forEach(_s=>{ce[_s]=Te[_s]});let Dt=m.toFiniteNumber(Te.headers.get("content-length")),[oi,mr]=x&&ia(Dt,tn(aa(x),!0))||[];Te=new r(ua(Te.body,xl,oi,()=>{mr&&mr(),Z&&Z()}),ce)}M=M||"text";let ne=await d[m.findKey(d,M)||"text"](Te,f);return!yn&&Z&&Z(),await new Promise((ce,Dt)=>{Vn(ce,Dt,{data:ne,headers:oe.from(Te.headers),status:Te.status,statusText:Te.statusText,config:f,request:O})})}catch(z){throw Z&&Z(),z&&z.name==="TypeError"&&/Load failed|fetch/i.test(z.message)?Object.assign(new N("Network Error",N.ERR_NETWORK,f,O,z&&z.response),{cause:z.cause||z}):N.from(z,z&&z.code,f,O,z&&z.response)}}},Mh=new Map,la=e=>{let t=e&&e.env||{},{fetch:n,Request:r,Response:o}=t,i=[r,o,n],a=i.length,s=a,u,c,l=Mh;for(;s--;)u=i[s],c=l.get(u),c===void 0&&l.set(u,c=s?new Map:Lh(t)),l=c;return c},tT=la();var da={http:eo,xhr:bl,fetch:{get:la}};m.forEach(da,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});var kl=e=>`- ${e}`,Bh=e=>m.isFunction(e)||e===null||e===!1;function Fh(e,t){e=m.isArray(e)?e:[e];let{length:n}=e,r,o,i={};for(let a=0;a<n;a++){r=e[a];let s;if(o=r,!Bh(r)&&(o=da[(s=String(r)).toLowerCase()],o===void 0))throw new N(`Unknown adapter '${s}'`);if(o&&(m.isFunction(o)||(o=o.get(t))))break;i[s||"#"+a]=o}if(!o){let a=Object.entries(i).map(([u,c])=>`adapter ${u} `+(c===!1?"is not supported by the environment":"is not available in the build")),s=n?a.length>1?`since :
5
- `+a.map(kl).join(`
6
- `):" "+kl(a[0]):"as no adapter specified";throw new N("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return o}var ao={getAdapter:Fh,adapters:da};function fa(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Ge(null,e)}function so(e){return fa(e),e.headers=oe.from(e.headers),e.data=Jn.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),ao.getAdapter(e.adapter||Qt.adapter,e)(e).then(function(r){return fa(e),r.data=Jn.call(e,e.transformResponse,r),r.headers=oe.from(r.headers),r},function(r){return Gn(r)||(fa(e),r&&r.response&&(r.response.data=Jn.call(e,e.transformResponse,r.response),r.response.headers=oe.from(r.response.headers))),Promise.reject(r)})}var co="1.13.5";var uo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{uo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});var Il={};uo.transitional=function(t,n,r){function o(i,a){return"[Axios v"+co+"] Transitional option '"+i+"'"+a+(r?". "+r:"")}return(i,a,s)=>{if(t===!1)throw new N(o(a," has been removed"+(n?" in "+n:"")),N.ERR_DEPRECATED);return n&&!Il[a]&&(Il[a]=!0,console.warn(o(a," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,a,s):!0}};uo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Hh(e,t,n){if(typeof e!="object")throw new N("options must be an object",N.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 N("option "+i+" must be "+u,N.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new N("Unknown option "+i,N.ERR_BAD_OPTION)}}var Kn={assertOptions:Hh,validators:uo};var Oe=Kn.validators,nn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Wi,response:new Wi}}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=Le(this.defaults,n);let{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Kn.assertOptions(r,{silentJSONParsing:Oe.transitional(Oe.boolean),forcedJSONParsing:Oe.transitional(Oe.boolean),clarifyTimeoutError:Oe.transitional(Oe.boolean),legacyInterceptorReqResOrdering:Oe.transitional(Oe.boolean)},!1),o!=null&&(m.isFunction(o)?n.paramsSerializer={serialize:o}:Kn.assertOptions(o,{encode:Oe.function,serialize:Oe.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Kn.assertOptions(n,{baseUrl:Oe.spelling("baseURL"),withXsrfToken:Oe.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){if(typeof y.runWhen=="function"&&y.runWhen(n)===!1)return;u=u&&y.synchronous;let v=n.transitional||Yt;v&&v.legacyInterceptorReqResOrdering?s.unshift(y.fulfilled,y.rejected):s.push(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=[so.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 _=n;for(;d<p;){let f=s[d++],y=s[d++];try{_=f(_)}catch(v){y.call(this,v);break}}try{l=so.call(this,_)}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=Le(this.defaults,t);let n=qn(t.baseURL,t.url,t.allowAbsoluteUrls);return Fn(n,t.params,t.paramsSerializer)}};m.forEach(["delete","get","head","options"],function(t){nn.prototype[t]=function(n,r){return this.request(Le(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(Le(s||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:a}))}}nn.prototype[t]=n(),nn.prototype[t+"Form"]=n(!0)});var Wn=nn;var pa=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 Ge(i,a,s),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;let n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){let t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new e(function(o){t=o}),cancel:t}}},Al=pa;function ma(e){return function(n){return e.apply(null,n)}}function ha(e){return m.isObject(e)&&e.isAxiosError===!0}var ga={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(ga).forEach(([e,t])=>{ga[t]=e});var Tl=ga;function Pl(e){let t=new Wn(e),n=Ln(Wn.prototype.request,t);return m.extend(n,Wn.prototype,t,{allOwnKeys:!0}),m.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return Pl(Le(e,o))},n}var te=Pl(Qt);te.Axios=Wn;te.CanceledError=Ge;te.CancelToken=Al;te.isCancel=Gn;te.VERSION=co;te.toFormData=dt;te.AxiosError=N;te.Cancel=te.CanceledError;te.all=function(t){return Promise.all(t)};te.spread=ma;te.isAxiosError=ha;te.mergeConfig=Le;te.AxiosHeaders=oe;te.formToJSON=e=>no(m.isHTMLForm(e)?new FormData(e):e);te.getAdapter=ao.getAdapter;te.HttpStatusCode=Tl;te.default=te;var lo=te;var{Axios:QT,AxiosError:e0,CanceledError:t0,isCancel:n0,CancelToken:r0,VERSION:o0,all:i0,Cancel:a0,isAxiosError:s0,spread:c0,toFormData:u0,AxiosHeaders:l0,HttpStatusCode:d0,formToJSON:f0,getAdapter:p0,mergeConfig:m0}=lo;function Jh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function ke(e,t,n){if(!e.s){if(n instanceof ya)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 ya=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{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 ya&&e.s&1}function Gh(e,t){var n;do{var r=e();if(r&&r.then)if(rn(r))r=r.v;else{n=!0;break}var o=t();if(rn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ya,a=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 zl(){return{plc:function(t,n){try{let o=function(){let l=typeof u?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:u,didDocumentMetadata:s,didResolutionMetadata:{contentType:l}}},r,i=null,a=`https://plc.directory/${encodeURIComponent(t)}`,s={},u=null,c=Gh(function(){function l(){r||u?.id===t||(i="resolver_error: DID document id does not match requested did")}let d=Jh(function(){return Promise.resolve(lo.get(a)).then(function(p){u=p.data})},function(p){i=`resolver_error: '"https://plc.directory/" + DID' must resolve to a valid https URL containing a JSON document: ${p}`,r=1});return d&&d.then?d.then(l):l(d)},function(){return!r&&!1});return Promise.resolve(c&&c.then?c.then(o):o(c))}catch(r){return Promise.reject(r)}}}}var Dl=nf(Ul(),1);function Vh(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var qh=function(e){try{return Promise.resolve((0,Dl.default)(e,{mode:"cors"})).then(function(t){if(t.status>=400)throw new Error(`Bad response ${t.statusText}`);return t.json()})}catch(t){return Promise.reject(t)}};function Ie(e,t,n){if(!e.s){if(n instanceof va)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Ie.bind(null,e,t);return}if(n&&n.then){n.then(Ie.bind(null,e,t),Ie.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Kh="/.well-known/did.json",va=(function(){function e(){}return e.prototype.then=function(t,n){let r=new e,o=this.s;if(o){let i=o&1?t:n;if(i){try{Ie(r,1,i(this.v))}catch(a){Ie(r,2,a)}return r}else return this}return this.o=function(i){try{let a=i.v;i.s&1?Ie(r,1,t?t(a):a):n?Ie(r,1,n(a)):Ie(r,2,a)}catch(a){Ie(r,2,a)}},r},e})();function an(e){return e instanceof va&&e.s&1}function Wh(e,t){var n;do{var r=e();if(r&&r.then)if(an(r))r=r.v;else{n=!0;break}var o=t();if(an(o)&&(o=o.v),!o)return r}while(!o.then);let i=new va,a=Ie.bind(null,i,2);return(n?r.then(s):o.then(u)).then(void 0,a),i;function s(c){for(r=c;o=t(),an(o)&&(o=o.v),!!o;){if(o.then){o.then(u).then(void 0,a);return}if(r=e(),r&&r.then)if(an(r))r=r.v;else{r.then(s).then(void 0,a);return}}Ie(i,1,r)}function u(c){if(c){do{if(r=e(),r&&r.then)if(an(r))r=r.v;else{r.then(s).then(void 0,a);return}if(c=t(),an(c)&&(c=c.v),!c){Ie(i,1,r);return}}while(!c.then);c.then(u).then(void 0,a)}else Ie(i,1,r)}}function Rl(){return{web:function(t,n){try{let o=function(){let p=typeof l?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:c,didResolutionMetadata:{contentType:p}}},r,i=null,a=decodeURIComponent(n.id)+Kh,s=n.id.split(":");s.length>1&&(a=s.map(decodeURIComponent).join("/")+"/did.json");let u=`https://${a}`,c={},l=null,d=Wh(function(){function p(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let _=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 _&&_.then?_.then(p):p(_)},function(){return!r&&!1});return Promise.resolve(d&&d.then?d.then(o):o(d))}catch(r){return Promise.reject(r)}}}}var mo=class{methods={...zl(),...Rl()};resolver=new Kr(this.methods,{cache:!0});async resolve(t){if(!Object.keys(this.methods).some(r=>t.startsWith(`did:${r}:`)))throw new Error(`Unrecognized DID method: ${t}`);let{didDocument:n}=await this.resolver.resolve(t);if(!n)throw new Q(`DID not found: ${t}`);return n}};var wa;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(wa="oauth4webapi/v3.8.5");function tr(e,t){if(e==null)return!1;try{return e instanceof t||Object.getPrototypeOf(e)[Symbol.toStringTag]===t.prototype[Symbol.toStringTag]}catch{return!1}}var ve="ERR_INVALID_ARG_VALUE",Ue="ERR_INVALID_ARG_TYPE";function K(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var Et=Symbol(),_o=Symbol(),bo=Symbol(),kt=Symbol();var ho=Symbol();var Xh=new TextEncoder,Yh=new TextDecoder;function jl(e){return typeof e=="string"?Xh.encode(e):Yh.decode(e)}var xa;Uint8Array.prototype.toBase64?xa=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):xa=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.",ve,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.",ve,t)}};function Sa(e){return typeof e=="string"?$a(e):xa(e)}var pt=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=ko,Error.captureStackTrace?.(this,this.constructor)}},Yn=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 C(e,t,n){return new Yn(e,{code:t,cause:n})}function go(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Ea(e){tr(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if(wa&&!t.has("user-agent")&&t.set("user-agent",wa),t.has("authorization"))throw K('"options.headers" must not include the "authorization" header name',ve);return t}function Cl(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw K('"options.signal" must return or be an instance of AbortSignal',Ue);return t}}function Ll(e){return e.includes("//")?e.replace("//","/"):e}function Qh(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=Ll(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function eg(e,t){return e.pathname=Ll(`${e.pathname}/${t}`),e}async function tg(e,t,n,r){if(!(e instanceof URL))throw K(`"${t}" must be an instance of URL`,Ue);$o(e,r?.[Et]!==!0);let o=n(new URL(e.href)),i=Ea(r?.headers);return i.set("accept","application/json"),(r?.[kt]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:Cl(o,r?.signal)})}async function Ml(e,t){return tg(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":eg(n,".well-known/openid-configuration");break;case"oauth2":Qh(n,".well-known/oauth-authorization-server");break;default:throw K('"options.algorithm" must be "oidc" (default), or "oauth2"',ve)}return n},t)}function Xn(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw K(`${n} must be a number`,Ue,o);if(e>0)return;if(t){if(e!==0)throw K(`${n} must be a non-negative number`,ve,o);return}throw K(`${n} must be a positive number`,ve,o)}catch(i){throw r?C(i.message,r,o):i}}function ye(e,t,n,r){try{if(typeof e!="string")throw K(`${t} must be a string`,Ue,r);if(e.length===0)throw K(`${t} must not be empty`,ve,r)}catch(o){throw n?C(o.message,n,r):o}}async function Zl(e,t){let n=e;if(!(n instanceof URL)&&n!==vo)throw K('"expectedIssuerIdentifier" must be an instance of URL',Ue);if(!tr(t,Response))throw K('"response" must be an instance of Response',Ue);if(t.status!==200)throw C('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Io,t);ja(t);let r=await rd(t);if(ye(r.issuer,'"response" body "issuer" property',G,{body:r}),n!==vo&&new URL(r.issuer).href!==n.href)throw C('"response" body "issuer" property does not match the expected value',Ao,{expected:n.href,body:r,attribute:"issuer"});return r}function Bl(e){rg(e,"application/json")}function ng(e,...t){let n='"response" content-type must be ';if(t.length>2){let r=t.pop();n+=`${t.join(", ")}, or ${r}`}else t.length===2?n+=`${t[0]} or ${t[1]}`:n+=t[0];return C(n,Ua,e)}function rg(e,t){if(Pa(e)!==t)throw ng(e,t)}function og(){return Sa(crypto.getRandomValues(new Uint8Array(32)))}function Fl(){return og()}function ka(e){let t=e?.[_o];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ia(e){let t=e?.[bo];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Aa(){return Math.floor(Date.now()/1e3)}function wo(e){if(typeof e!="object"||e===null)throw K('"as" must be an object',Ue);ye(e.issuer,'"as.issuer"')}function xo(e){if(typeof e!="object"||e===null)throw K('"client" must be an object',Ue);ye(e.client_id,'"client.client_id"')}function Ta(e){return ye(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function Hl(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var ig=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function $o(e,t){if(t&&e.protocol!=="https:")throw C("only requests to HTTPS are allowed",Da,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw C("only HTTP and HTTPS requests are allowed",Ra,e)}function Nl(e,t,n,r){let o;if(typeof e!="string"||!(o=ig(e)))throw C(`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 $o(o,r),o}function So(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?Nl(e.mtls_endpoint_aliases[t],t,n,r):Nl(e[t],t,n,r)}function Jl(e){if(e instanceof cn){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof sn?e.error==="use_dpop_nonce":!1}var sn=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)}},Qn=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)}},cn=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)}},yo="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",ag="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",sg='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',cg="("+yo+")\\s*=\\s*"+sg,ug="("+yo+")\\s*=\\s*("+yo+")",lg=new RegExp("^[,\\s]*("+yo+")"),dg=new RegExp("^[,\\s]*"+cg+"[,\\s]*(.*)"),fg=new RegExp("^[,\\s]*"+ug+"[,\\s]*(.*)"),pg=new RegExp("^("+ag+")(?:$|[,\\s])(.*)");function mg(e){if(!tr(e,Response))throw K('"response" must be an instance of Response',Ue);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,_;if(o=r.match(dg)){if([,p,_,r]=o,_.includes("\\"))try{_=JSON.parse(`"${_}"`)}catch{}c[p.toLowerCase()]=_;continue}if(o=r.match(fg)){[,p,_,r]=o,c[p.toLowerCase()]=_;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){ja(e),Bl(e);try{let t=await e.clone().json();if(go(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function Gl(e,t,n){if(e.status!==t){_g(e);let r;throw(r=await hg(e))?(await e.body?.cancel(),new sn("server responded with an error in the response body",{cause:r,response:e})):C(`"response" is not a conform ${n} response (unexpected HTTP status code)`,Io,e)}}function gg(e){if(!za.has(e))throw K('"options.DPoP" is not a valid DPoPHandle',ve)}function Pa(e){return e.headers.get("content-type")?.split(";")[0]}async function Vl(e,t,n,r,o,i,a){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(a?.[kt]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:Cl(r,a?.signal)})}async function yg(e,t,n,r,o,i){let a=So(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[Et]!==!0);o.set("grant_type",r);let s=Ea(i?.headers);s.set("accept","application/json"),i?.DPoP!==void 0&&(gg(i.DPoP),await i.DPoP.addProof(a,s,"POST"));let u=await Vl(e,t,n,a,o,s,i);return i?.DPoP?.cacheNonce(u,a),u}var ql=new WeakMap,vg=new WeakMap;function Eo(e){if(!e.id_token)return;let t=ql.get(e);if(!t)throw K('"ref" was already garbage collected or did not resolve from the proper sources',ve);return t}async function Kl(e,t,n,r,o,i){if(wo(e),xo(t),!tr(n,Response))throw K('"response" must be an instance of Response',Ue);await Gl(n,200,"Token Endpoint"),ja(n);let a=await rd(n);if(ye(a.access_token,'"response" body "access_token" property',G,{body:a}),ye(a.token_type,'"response" body "token_type" property',G,{body:a}),a.token_type=a.token_type.toLowerCase(),a.expires_in!==void 0){let s=typeof a.expires_in!="number"?parseFloat(a.expires_in):a.expires_in;Xn(s,!0,'"response" body "expires_in" property',G,{body:a}),a.expires_in=s}if(a.refresh_token!==void 0&&ye(a.refresh_token,'"response" body "refresh_token" property',G,{body:a}),a.scope!==void 0&&typeof a.scope!="string")throw C('"response" body "scope" property must be a string',G,{body:a});if(a.id_token!==void 0){ye(a.id_token,'"response" body "id_token" property',G,{body:a});let s=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&s.push("auth_time"),t.default_max_age!==void 0&&(Xn(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"),ka(t),Ia(t),o).then(Sg.bind(void 0,s)).then(wg.bind(void 0,e)).then(bg.bind(void 0,t.client_id));if(Array.isArray(u.aud)&&u.aud.length!==1){if(u.azp===void 0)throw C('ID Token "aud" (audience) claim includes additional untrusted audiences',Ve,{claims:u,claim:"aud"});if(u.azp!==t.client_id)throw C('unexpected ID Token "azp" (authorized party) claim value',Ve,{expected:t.client_id,claims:u,claim:"azp"})}u.auth_time!==void 0&&Xn(u.auth_time,!0,'ID Token "auth_time" (authentication time)',G,{claims:u}),vg.set(n,c),ql.set(a,u)}if(i?.[a.token_type]!==void 0)i[a.token_type](n,a);else if(a.token_type!=="dpop"&&a.token_type!=="bearer")throw new pt("unsupported `token_type` value",{cause:{body:a}});return a}function _g(e){let t;if(t=mg(e))throw new cn("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function bg(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw C('unexpected JWT "aud" (audience) claim value',Ve,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw C('unexpected JWT "aud" (audience) claim value',Ve,{expected:e,claims:t.claims,claim:"aud"});return t}function wg(e,t){let n=e[Na]?.(t)??e.issuer;if(t.claims.iss!==n)throw C('unexpected JWT "iss" (issuer) claim value',Ve,{expected:n,claims:t.claims,claim:"iss"});return t}var za=new WeakSet;function xg(e){return za.add(e),e}var Oa=Symbol();async function Wl(e,t,n,r,o,i,a){if(wo(e),xo(t),!za.has(r))throw K('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',ve);ye(o,'"redirectUri"');let s=St(r,"code");if(!s)throw C('no authorization code in "callbackParameters"',G);let u=new URLSearchParams(a?.additionalParameters);return u.set("redirect_uri",o),u.set("code",s),i!==Oa&&(ye(i,'"codeVerifier"'),u.set("code_verifier",i)),yg(e,t,n,"authorization_code",u,a)}var $g={aud:"audience",c_hash:"code hash",client_id:"client id",exp:"expiration time",iat:"issued at",iss:"issuer",jti:"jwt id",nonce:"nonce",s_hash:"state hash",sub:"subject",ath:"access token hash",htm:"http method",htu:"http uri",cnf:"confirmation",auth_time:"authentication time"};function Sg(e,t){for(let n of e)if(t.claims[n]===void 0)throw C(`JWT "${n}" (${$g[n]}) claim missing`,G,{claims:t.claims});return t}var _a=Symbol(),ba=Symbol();async function Xl(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?Eg(e,t,n,r.expectedNonce,r.maxAge,r[ho],r.recognizedTokenTypes):kg(e,t,n,r?.[ho],r?.recognizedTokenTypes)}async function Eg(e,t,n,r,o,i,a){let s=[];switch(r){case void 0:r=_a;break;case _a:break;default:ye(r,'"expectedNonce" argument'),s.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=ba;break;case ba:break;default:Xn(o,!0,'"maxAge" argument'),s.push("auth_time")}let u=await Kl(e,t,n,s,i,a);ye(u.id_token,'"response" body "id_token" property',G,{body:u});let c=Eo(u);if(o!==ba){let l=Aa()+ka(t),d=Ia(t);if(c.auth_time+o<l-d)throw C("too much time has elapsed since the last End-User authentication",un,{claims:c,now:l,tolerance:d,claim:"auth_time"})}if(r===_a){if(c.nonce!==void 0)throw C('unexpected ID Token "nonce" claim value',Ve,{expected:void 0,claims:c,claim:"nonce"})}else if(c.nonce!==r)throw C('unexpected ID Token "nonce" claim value',Ve,{expected:r,claims:c,claim:"nonce"});return u}async function kg(e,t,n,r,o){let i=await Kl(e,t,n,void 0,r,o),a=Eo(i);if(a){if(t.default_max_age!==void 0){Xn(t.default_max_age,!0,'"client.default_max_age"');let s=Aa()+ka(t),u=Ia(t);if(a.auth_time+t.default_max_age<s-u)throw C("too much time has elapsed since the last End-User authentication",un,{claims:a,now:s,tolerance:u,claim:"auth_time"})}if(a.nonce!==void 0)throw C('unexpected ID Token "nonce" claim value',Ve,{expected:void 0,claims:a,claim:"nonce"})}return i}var Ig="OAUTH_WWW_AUTHENTICATE_CHALLENGE",Ag="OAUTH_RESPONSE_BODY_ERROR",ko="OAUTH_UNSUPPORTED_OPERATION",Tg="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var er="OAUTH_PARSE_ERROR",G="OAUTH_INVALID_RESPONSE";var Ua="OAUTH_RESPONSE_IS_NOT_JSON",Io="OAUTH_RESPONSE_IS_NOT_CONFORM",Da="OAUTH_HTTP_REQUEST_FORBIDDEN",Ra="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",un="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Ve="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Ao="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var Pg="OAUTH_MISSING_SERVER_METADATA",zg="OAUTH_INVALID_SERVER_METADATA";async function Yl(e,t,n,r,o){wo(e),xo(t),ye(r,'"token"');let i=So(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[Et]!==!0),a=new URLSearchParams(o?.additionalParameters);a.set("token",r);let s=Ea(o?.headers);return s.delete("accept"),Vl(e,t,n,i,a,s,o)}async function Ql(e){if(!tr(e,Response))throw K('"response" must be an instance of Response',Ue);await Gl(e,200,"Revocation Endpoint")}function ja(e){if(e.bodyUsed)throw K('"response" body has been used already',ve)}async function Og(e,t,n,r,o){let{0:i,1:a,length:s}=e.split(".");if(s===5)if(o!==void 0)e=await o(e),{0:i,1:a,length:s}=e.split(".");else throw new pt("JWE decryption is not configured",{cause:e});if(s!==3)throw C("Invalid JWT",G,e);let u;try{u=JSON.parse(jl(Sa(i)))}catch(d){throw C("failed to parse JWT Header body as base64url encoded JSON",er,d)}if(!go(u))throw C("JWT Header must be a top level object",G,e);if(t(u),u.crit!==void 0)throw new pt('no JWT "crit" header parameter extensions are supported',{cause:{header:u}});let c;try{c=JSON.parse(jl(Sa(a)))}catch(d){throw C("failed to parse JWT Payload body as base64url encoded JSON",er,d)}if(!go(c))throw C("JWT Payload must be a top level object",G,e);let l=Aa()+n;if(c.exp!==void 0){if(typeof c.exp!="number")throw C('unexpected JWT "exp" (expiration time) claim type',G,{claims:c});if(c.exp<=l-r)throw C('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',un,{claims:c,now:l,tolerance:r,claim:"exp"})}if(c.iat!==void 0&&typeof c.iat!="number")throw C('unexpected JWT "iat" (issued at) claim type',G,{claims:c});if(c.iss!==void 0&&typeof c.iss!="string")throw C('unexpected JWT "iss" (issuer) claim type',G,{claims:c});if(c.nbf!==void 0){if(typeof c.nbf!="number")throw C('unexpected JWT "nbf" (not before) claim type',G,{claims:c});if(c.nbf>l+r)throw C('unexpected JWT "nbf" (not before) claim value',un,{claims:c,now:l,tolerance:r,claim:"nbf"})}if(c.aud!==void 0&&typeof c.aud!="string"&&!Array.isArray(c.aud))throw C('unexpected JWT "aud" (audience) claim type',G,{claims:c});return{header:u,claims:c,jwt:e}}async function Ug(e){if(e.bodyUsed)throw K("form_post Request instances must contain a readable body",ve,{cause:e});return e.text()}async function ed(e){if(e.method!=="POST")throw K("form_post responses are expected to use the POST method",ve,{cause:e});if(Pa(e)!=="application/x-www-form-urlencoded")throw K("form_post responses are expected to use the application/x-www-form-urlencoded content-type",ve,{cause:e});return Ug(e)}function Dg(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw C('unexpected JWT "alg" header parameter',G,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw C('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 C('unexpected JWT "alg" header parameter',G,{header:r,expected:n,reason:"default value"});return}throw C('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function St(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw C(`"${t}" parameter must be provided only once`,G);return n}var td=Symbol(),Rg=Symbol();function nd(e,t,n,r){if(wo(e),xo(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw K('"parameters" must be an instance of URLSearchParams, or URL',Ue);if(St(n,"response"))throw C('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',G,{parameters:n});let o=St(n,"iss"),i=St(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw C('response parameter "iss" (issuer) missing',G,{parameters:n});if(o&&o!==e.issuer)throw C('unexpected "iss" (issuer) response parameter value',G,{expected:e.issuer,parameters:n});switch(r){case void 0:case Rg:if(i!==void 0)throw C('unexpected "state" response parameter encountered',G,{expected:void 0,parameters:n});break;case td:break;default:if(ye(r,'"expectedState" argument'),i!==r)throw C(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',G,{expected:r,parameters:n})}if(St(n,"error"))throw new Qn("authorization response from the server is an error",{cause:n});let s=St(n,"id_token"),u=St(n,"token");if(s!==void 0||u!==void 0)throw new pt("implicit and hybrid flows are not supported");return xg(new URLSearchParams(n))}async function rd(e,t=Bl){let n;try{n=await e.json()}catch(r){throw t(e),C('failed to parse "response" body as JSON',er,r)}if(!go(n))throw C('"response" body must be a top level object',G,{body:n});return n}var vo=Symbol(),Na=Symbol();var rr,od;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(od="openid-client/v6.8.2",rr={"user-agent":od});var Me=e=>La.get(e),La,Ca;function Ng(e){return e!==void 0?Ta(e):(Ca||=new WeakMap,(t,n,r,o)=>{let i;return(i=Ca.get(n))||(Cg(n.client_secret,'"metadata.client_secret"'),i=Ta(n.client_secret),Ca.set(n,i)),i(t,n,r,o)})}function Cg(e,t){if(typeof e!="string")throw qe(`${t} must be a string`,ir);if(e.length===0)throw qe(`${t} must not be empty`,or)}function Lg(){return Hl()}var ln=kt;var or="ERR_INVALID_ARG_VALUE",ir="ERR_INVALID_ARG_TYPE";function qe(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function ad(){return Fl()}var dn=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},lP=new TextDecoder;function me(e,t,n){return new dn(e,{cause:t,code:n})}function nr(e){if(e instanceof TypeError||e instanceof dn||e instanceof sn||e instanceof Qn||e instanceof cn)throw e;if(e instanceof Yn)switch(e.code){case Da:throw me("only requests to HTTPS are allowed",e,e.code);case Ra:throw me("only requests to HTTP or HTTPS are allowed",e,e.code);case Io:throw me("unexpected HTTP response status code",e.cause,e.code);case Ua:throw me("unexpected response content-type",e.cause,e.code);case er:throw me("parsing error occured",e,e.code);case G:throw me("invalid response encountered",e,e.code);case Ve:throw me("unexpected JWT claim value encountered",e,e.code);case Ao:throw me("unexpected JSON attribute value encountered",e,e.code);case un:throw me("JWT timestamp claim value failed validation",e,e.code);default:throw me(e.message,e,e.code)}if(e instanceof pt)throw me("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw me("runtime operation error",e,ko);case"NotSupportedError":throw me("runtime unsupported operation",e,ko);case"TimeoutError":throw me("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw me("operation aborted",e,"OAUTH_ABORT")}throw new dn("something went wrong",{cause:e})}function Mg(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[cd]=!0,!0):!1}function Zg(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function sd(e,t,n,r,o){let i=await Bg(e,o),a=new fn(i,t,n,r),s=Me(a);if(o?.[ln]&&(s.fetch=o[ln]),o?.timeout&&(s.timeout=o.timeout),o?.execute)for(let u of o.execute)u(a);return a}async function Bg(e,t){if(!(e instanceof URL))throw qe('"server" must be an instance of URL',ir);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?Ml(e,{algorithm:t?.algorithm,[kt]:t?.[ln],[Et]:t?.execute?.includes(id),signal:o,headers:new Headers(rr)}):(t?.[ln]||fetch)(($o(e,!t?.execute?.includes(id)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...rr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(a=>Zl(vo,a)).catch(nr);return n&&new URL(i.issuer).href!==e.href&&(Mg(e,i,t)||Zg(e,t)||(()=>{throw new dn("discovered metadata issuer does not match the expected issuer",{code:Ao,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Fg(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Hg(e){Object.defineProperties(e,Fg(e))}var cd=Symbol(),fn=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw qe('"clientId" must be a non-empty string',ir);if(typeof r=="string"&&(r={client_secret:r}),r?.client_id!==void 0&&n!==r.client_id)throw qe('"clientId" and "metadata.client_id" must be the same',or);let i={...structuredClone(r),client_id:n};i[_o]=r?.[_o]??0,i[bo]=r?.[bo]??30;let a;o?a=o:typeof i.client_secret=="string"&&i.client_secret.length?a=Ng(i.client_secret):a=Lg();let s=Object.freeze(i),u=structuredClone(t);cd in t&&(u[Na]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let c=Object.freeze(u);La||=new WeakMap,La.set(this,{__proto__:null,as:c,c:s,auth:a,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(Me(this).as);return Hg(t),t}clientMetadata(){return structuredClone(Me(this).c)}get timeout(){return Me(this).timeout}set timeout(t){Me(this).timeout=t}get[ln](){return Me(this).fetch}set[ln](t){Me(this).fetch=t}};Object.freeze(fn.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 Eo(this)}catch{return}}}}}function Gg(e){Object.defineProperties(e,Jg(e))}function id(e){Me(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 Ma(e,t,n,r,o){if(Za(e),o?.flag!==To&&!(t instanceof URL)&&!qg(t,"Request"))throw qe('"currentUrl" must be an instance of URL, or Request',ir);let i,a,{as:s,c:u,auth:c,fetch:l,tlsOnly:d,jarm:p,hybrid:_,nonRepudiation:f,timeout:y,decrypt:v,implicit:k}=Me(e);if(o?.flag===To)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 U=new URLSearchParams(await ed(x));if(_)t.hash=U.toString();else for(let[M,B]of U.entries())t.searchParams.append(M,B);break;default:throw qe("unexpected Request HTTP method",or)}}switch(a=Vg(t),!0){case!!p:i=await p(t,n?.expectedState);break;case!!_:i=await _(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!k:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=nd(s,u,t.searchParams,n?.expectedState)}catch(x){nr(x)}}}let A=await Wl(s,u,c,i,a,n?.pkceCodeVerifier||Oa,{additionalParameters:r,[kt]:l,[Et]:!d,DPoP:o?.DPoP,headers:new Headers(rr),signal:ld(y)}).catch(nr);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let w=Xl(s,u,A,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[ho]:v}),S;try{S=await w}catch(x){if(Kg(x,o))return Ma(e,void 0,n,r,{...o,flag:To,authResponse:i,redirectUri:a});nr(x)}return S.id_token&&await f?.(A),Gg(S),S}function ud(e,t){Za(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:a,implicit:s}=Me(e),u=So(n,"authorization_endpoint",!1,o);if(t=new URLSearchParams(t),t.has("client_id")||t.set("client_id",r.client_id),!t.has("request_uri")&&!t.has("request")){if(t.has("response_type")||t.set("response_type",i?"code id_token":s?"id_token":"code"),s&&!t.has("nonce"))throw qe("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",or);a&&t.set("response_mode","jwt")}for(let[c,l]of t.entries())u.searchParams.append(c,l);return u}function Za(e){if(!(e instanceof fn))throw qe('"config" must be an instance of Configuration',ir);if(Object.getPrototypeOf(e)!==fn.prototype)throw qe("subclassing Configuration is not allowed",or)}function ld(e){return e?AbortSignal.timeout(e*1e3):void 0}function Kg(e,t){return t?.DPoP&&t.flag!==To?Jl(e):!1}var To=Symbol();async function dd(e,t,n){Za(e);let{as:r,c:o,auth:i,fetch:a,tlsOnly:s,timeout:u}=Me(e);return Yl(r,o,i,t,{[kt]:a,[Et]:!s,additionalParameters:new URLSearchParams(n),headers:new Headers(rr),signal:ld(u)}).then(Ql).catch(nr)}var fd="oauth2:",ar="graffiti-auth-oauth2-data",Po=class{eventTarget=new EventTarget;constructor(){let t=this.completeOauth();(async()=>{await new Promise(r=>setTimeout(r,0)),await t;let n=new CustomEvent("initialized");this.eventTarget.dispatchEvent(n)})()}async login(...t){try{await this.login_(...t)}catch(n){let r=n instanceof Error?n:new Error("Unknown error"),o={loginId:t[1],error:r};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:o}))}}async login_(t,n,r){let o=await this.getAuthorizationConfiguration(t),i=r.map(encodeURIComponent).join(" "),a=ad(),s,u;if(typeof window<"u"){s=window.location.href;let d={loginId:n,redirectUri:s,authorizationEndpoint:t,state:a,serviceEndpoints:r};window.localStorage.setItem(ar,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 _=p.address();if(!_){try{p.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}s=typeof _=="string"?`http://${_}`:`http://${_.family==="IPv6"?`[${_.address}]`:_.address}:${_.port}`,u=new Promise((f,y)=>{let v=setTimeout(()=>{try{p.close()}catch{}y("Oauth callback timed out.")},3e5),k=new Set;p.on("connection",w=>{k.add(w),w.on("close",()=>{k.delete(w)})});let A=async(w,S)=>{try{let x=new URL(w.url??"/",s);await this.onCallbackUrl({loginId:n,callbackUrl:x,configuration:o,expectedState:a,serviceEndpoints:r}),S.statusCode=200,S.setHeader("Content-Type","text/plain"),S.end("You may now close this window.")}catch(x){throw S.statusCode=500,S.setHeader("Content-Type","text/plain"),S.end("Error processing OAuth callback."),x}finally{clearTimeout(v),p.off("request",A);for(let x of k)x.destroy();p.close(()=>f())}};p.on("request",A)})}let c=new URL(s);c.hash="",c.search="";let l=ud(o,{scope:i,redirect_uri:c.toString(),state:a});typeof window<"u"?window.location.href=l.toString():(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await u)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(ar);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(ar);return}let r=Wg.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(ar);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(ar),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 _=p instanceof Error?p:new Error("Unknown error"),f={loginId:o,error:_};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 Ma(o,r,{expectedState:i}),u=s.access_token,l=s.scope?.split(" ").map(decodeURIComponent)||a;if(!a.every(p=>l.includes(p)))throw new Error("Not all requested service endpoints were granted.");let d=new CustomEvent("login",{detail:{loginId:n,token:u}});this.eventTarget.dispatchEvent(d)}async logout(t,n,r){try{await this.logout_(t,n,r)}catch(o){let i=o instanceof Error?o:new Error("Unknown error"),a={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:a}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await dd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(fd))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(fd.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await sd(r,"graffiti-client")}},pd=bc(_e({loginId:H()}),ut([_e({token:H(),error:X(_c())}),_e({error:Ct(Error)})])),md=_e({logoutId:H(),error:X(Ct(Error))}),hd=X(Ze(_e({error:X(Ct(Error))}))),Wg=_e({loginId:H(),redirectUri:J(),authorizationEndpoint:J(),state:H(),serviceEndpoints:V(J())});var Xg="https://";function De(e){if(!e.startsWith(Xg))throw new Error("Unrecognized storage bucket endpoint type")}async function zo(e){De(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 It=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function Ke(...e){let t=await fetch(...e);if(!t.ok){let n;try{n=await t.text()}catch{n=t.statusText}throw t.status===401?new It(n):t.status===403?new st(n):t.status===404?new Q(n):t.status===410?new Re(n):t.status===413?new jt(n):new Error(n)}return t}var Oo=class{getAuthorizationEndpoint=zo;async put(t,n,r,o){De(t);let i=`${t}/value/${encodeURIComponent(n)}`;await Ke(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){De(t);let o=`${t}/value/${encodeURIComponent(n)}`;await Ke(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){De(t);let o=`${t}/value/${encodeURIComponent(n)}`,i=await Ke(o),a=i.body?.getReader();if(!a)throw new Error("Failed to read value from storage bucket");let s=i.headers.get("Content-Length"),u=s?Number(s):void 0;if(!!u&&!!Number.isFinite(u)&&u>=0){let f=u;if(r!==void 0&&f>r)throw new Error("Value exceeds maximum byte limit");let y=new Uint8Array(f),v=0,k=!1;try{for(;v<=y.length;){let{done:A,value:w}=await a.read();if(A){k=!0;break}if(!w||w.length===0)continue;let S=v+w.length;if(S>y.length)throw new Error("Received more data than expected");y.set(w,v),v=S}}finally{a.releaseLock()}if(!k)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),_=0;for(let f of l)p.set(f,_),_+=f.length;return p}async*export(t,n){De(t);let r=`${t}/export`,o;for(;;){let a=await(await Ke(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),s=Je(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=_e({keys:V(H()),cursor:X(Ze(H()))});var Do=class{getAuthorizationEndpoint=zo;cache_=null;get cache(){return this.cache_||(this.cache_=iy()),this.cache_}async send(t,n){De(t);let r=`${t}/send`,i=await(await Ke(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(Ee({m:n}))})).blob(),a=Je(await i.arrayBuffer());return ny.parse(a).id}async get(t,n,r){let o=Uo(t,n),i=await this.cache,a=await i.messages.get(o);if(a!==void 0)return a;let s=`${t}/message/${n}`,u=null;try{u=await Ke(s,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(p){if(p instanceof Q)return await i.messages.set(o,null),null;throw p}let c=await u.blob(),l=Je(await c.arrayBuffer()),d=bd.parse(l);return await i.messages.set(o,d),d}async label(t,n,r,o){if(De(t),o){let u=`${t}/label/${n}`;await Ke(u,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(Ee({l:r}))})}let i=await this.cache,a=Uo(t,n),s=await i.messages.get(a);s&&await i.messages.set(a,{...s,l:r})}async fetchMessageBatch(t,n,r,o,i){let a=await Ke(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r}),s=a.headers.get("Retry-After"),u=s?parseInt(s):void 0,c=u&&Number.isFinite(u)?Date.now()+u*1e3:void 0;return{response:a,waitTil:c}}async*yieldFromCache(t,n,r,o,i=0){let a=o.messageIds.slice(i);yield*await Promise.all(a.map(async u=>{let c=await t.messages.get(Uo(n,u));if(!c){try{await t.messageIds.del(r)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return c}))}async*lockedMessageStreamer(...t){if(typeof window>"u"||!await wd()){let f=this.messageStreamer(...t);for(;;){let 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 Re("Cursor is stale");let p=this.yieldFromCache(l,a,n,d,c);for await(let f of p)yield f;let _={numSeen:d.messageIds.length,version:d.version,messageIdsCacheKey:n,objectSchema:s};return JSON.stringify(_)}async*messageStreamer(t,n,r,o,i,a={},s,u=0){let c=await yr(a),l=await t,d=await this.cache,p=await d.messageIds.get(l);if(s!==void 0&&s!==p?.version)throw new Re("Cursor is stale");let _=p?.waitTil;await vd(_);let f=p?.cursor,y;try{let x=await this.fetchMessageBatch(n,r,o,i,f);y=x.response,_=x.waitTil}catch(x){if(!(x instanceof Re&&f))throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(U=>setTimeout(U,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 U of x)yield U}if(y===void 0){let x=await this.fetchMessageBatch(n,r,o,i);y=x.response,_=x.waitTil}let v=y,k,A=p?.version??crypto.randomUUID(),w=p?.messageIds??[];for(;;){let x=await v.blob(),U=Je(await x.arrayBuffer()),{results:M,hasMore:B,cursor:ie}=ry.parse(U);k=ie;let Ae=M.map(b=>{let O=b[At][ot];if(!c(O))throw new Error("Server returned data that does not match schema");return{...b,[At]:{...b[At],[ot]:O}}});await Promise.all(Ae.map(b=>d.messages.set(Uo(n,b[Ba]),b))),w=[...w,...Ae.map(b=>b[Ba])],await d.messageIds.set(l,{cursor:k,version:A,messageIds:w,waitTil:_}),u+=Ae.length;for(let b of Ae)yield b;if(!B)break;await vd(_);let h=await this.fetchMessageBatch(n,r,void 0,i,k);v=h.response,_=h.waitTil}return JSON.stringify({numSeen:u,version:A,messageIdsCacheKey:l,objectSchema:a})}query(t,n,r,o){De(t);let i=Ee({tags:n,schema:r}),a=gd(t,"query",i);return this.lockedMessageStreamer(a,t,"query",new Uint8Array(i),o,r)}continueQuery(t,n,r){De(t);let o=JSON.parse(n),{messageIdsCacheKey:i,numSeen:a,objectSchema:s,version:u}=oy.parse(o);return this.lockedMessageStreamer(Promise.resolve(i),t,"query",void 0,r,s,u,a)}export(t,n){De(t);let r=gd(t,"export");return this.lockedMessageStreamer(r,t,"export",void 0,n)}},Qg=be({value:he({}),channels:V(H()),allowed:X(Ze(V(J()))),url:J(),actor:J()}),_d=bt(e=>e instanceof Uint8Array),ey=V(_d),sr="t",ot="o",cr="m",ty=be({[sr]:ey,[ot]:Qg,[cr]:_d}),Ba="id",At="m",Ro="l",bd=be({[Ba]:H(),[At]:ty,[Ro]:yc()}),ny=be({id:H()}),ry=be({results:V(bd),hasMore:Si(),cursor:H()}),oy=be({messageIdsCacheKey:H(),version:H(),numSeen:Nt().check(_t()),objectSchema:ut([he({}),Si()])});async function wd(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function Uo(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function gd(e,t,n){let r=Ee({inboxUrl:e,type:t,body:n??null});return crypto.subtle.digest("SHA-256",new Uint8Array(r)).then(o=>Array.from(new Uint8Array(o)).map(i=>i.toString(16).padStart(2,"0")).join(""))}async function yd(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function iy(){if(await wd()){let{openDB:n}=await import("./build-BXWPS7VK.js"),r=await n("graffiti-inbox-cache",1,{upgrade(o){o.objectStoreNames.contains("m")||o.createObjectStore("m"),o.objectStoreNames.contains("q")||o.createObjectStore("q")}});return{messages:{get:async o=>{try{return r.get("m",o)}catch(i){console.error("Error getting message from cache:",i),console.error("resetting cache..."),await yd();return}},set:async(o,i)=>{await r.put("m",i,o)},del:o=>r.delete("m",o)},messageIds:{get:async o=>{try{return await r.get("q",o)}catch(i){console.error("Error getting message IDs from cache:",i),console.error("resetting cache..."),await yd();return}},set:async(o,i)=>{await r.put("q",i,o)},del:o=>r.delete("q",o)}}}let e=new Map,t=new Map;return{messages:{get:async n=>e.get(n),set:async(n,r)=>{e.set(n,r)},del:async n=>{e.delete(n)}},messageIds:{get:async n=>t.get(n),set:async(n,r)=>{t.set(n,r)},del:async n=>{t.delete(n)}}}}async function vd(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var pn="base64url";var jo=class{async encode(t,n){if(t!==pn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function xd(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function $d(e,t,n){let r=async o=>{Pr(o);let i=xd();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},r}function ay(e){if(Ic(e),typeof e.webCryptoName!="string")throw new Error("non-web hash")}var Tt=$d("SHA-256",64,32);var Sd=$d("SHA-512",128,64),Fa=(()=>{let e=async(t,n,r)=>{let o=xd();Pr(n,void 0,"key"),Pr(r,void 0,"message"),ay(t);let i=await o.importKey("raw",n,{name:"HMAC",hash:t.webCryptoName},!1,["sign"]);return new Uint8Array(await o.sign("HMAC",i,r))};return e.create=(t,n)=>{throw new Error("not implemented")},e})();var No="sha2-256",ur=18,mn=32,Co=class{async register(t,n){if(t!==No)throw new Error(`Unsupported content address method: ${t}`);let r=await Tt(n),o=new Uint8Array(2+r.length);return o[0]=ur,o[1]=mn,o.set(r,2),o}async getMethod(t){if(t[0]===ur&&t[1]===mn&&t.length===2+mn)return No;throw new Error("Unrecognized content address format.")}};var zd={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:le,n:Lo,Gx:Ed,Gy:kd,a:Ha,d:Ja,h:sy}=zd,zt=32,lr=64,cy=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},se=(e="")=>{let t=new Error(e);throw cy(t,se),t},uy=e=>typeof e=="bigint",ly=e=>typeof e=="string",dy=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",Xe=(e,t,n="")=>{let r=dy(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let a=n&&`"${n}" `,s=i?` of length ${t}`:"",u=r?`length=${o}`:`type=${typeof e}`;se(a+"expected Uint8Array"+s+", got "+u)}return e},Ka=e=>new Uint8Array(e),Od=e=>Uint8Array.from(e),Ud=(e,t)=>e.toString(16).padStart(t,"0"),Dd=e=>Array.from(Xe(e)).map(t=>Ud(t,2)).join(""),it={_0:48,_9:57,A:65,F:70,a:97,f:102},Id=e=>{if(e>=it._0&&e<=it._9)return e-it._0;if(e>=it.A&&e<=it.F)return e-(it.A-10);if(e>=it.a&&e<=it.f)return e-(it.a-10)},Rd=e=>{let t="hex invalid";if(!ly(e))return se(t);let n=e.length,r=n/2;if(n%2)return se(t);let o=Ka(r);for(let i=0,a=0;i<r;i++,a+=2){let s=Id(e.charCodeAt(a)),u=Id(e.charCodeAt(a+1));if(s===void 0||u===void 0)return se(t);o[i]=s*16+u}return o},fy=()=>globalThis?.crypto,py=()=>fy()?.subtle??se("crypto.subtle must be defined, consider polyfill"),dr=(...e)=>{let t=Ka(e.reduce((r,o)=>r+Xe(o).length,0)),n=0;return e.forEach(r=>{t.set(r,n),n+=r.length}),t};var Mo=BigInt,Pt=(e,t,n,r="bad number: out of range")=>uy(e)&&t<=e&&e<n?e:se(r),I=(e,t=le)=>{let n=e%t;return n>=0n?n:t+n},jd=e=>I(e,Lo),my=(e,t)=>{(e===0n||t<=0n)&&se("no inverse n="+e+" mod="+t);let n=I(e,t),r=t,o=0n,i=1n,a=1n,s=0n;for(;n!==0n;){let u=r/n,c=r%n,l=o-a*u,d=i-s*u;r=n,n=c,o=a,i=s,a=l,s=d}return r===1n?I(o,t):se("no inverse")};var Ga=e=>e instanceof at?e:se("Point expected"),Va=2n**256n,at=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=Va;this.X=Pt(t,0n,i),this.Y=Pt(n,0n,i),this.Z=Pt(r,1n,i),this.T=Pt(o,0n,i),Object.freeze(this)}static CURVE(){return zd}static fromAffine(t){return new e(t.x,t.y,1n,I(t.x*t.y))}static fromBytes(t,n=!1){let r=Ja,o=Od(Xe(t,zt)),i=t[31];o[31]=i&-129;let a=Wa(o);Pt(a,0n,n?Va:le);let u=I(a*a),c=I(u-1n),l=I(r*u+1n),{isValid:d,value:p}=gy(c,l);d||se("bad point: y not sqrt");let _=(p&1n)===1n,f=(i&128)!==0;return!n&&p===0n&&f&&se("bad point: x==0, isLastByteOdd"),f!==_&&(p=I(-p)),new e(p,a,1n,I(p*a))}static fromHex(t,n){return e.fromBytes(Rd(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Ha,n=Ja,r=this;if(r.is0())return se("bad point: ZERO");let{X:o,Y:i,Z:a,T:s}=r,u=I(o*o),c=I(i*i),l=I(a*a),d=I(l*l),p=I(u*t),_=I(l*I(p+c)),f=I(d+I(n*I(u*c)));if(_!==f)return se("bad point: equation left != right (1)");let y=I(o*i),v=I(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}=Ga(t),u=I(n*s),c=I(i*o),l=I(r*s),d=I(a*o);return u===c&&l===d}is0(){return this.equals(hn)}negate(){return new e(I(-this.X),this.Y,this.Z,I(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=Ha,i=I(t*t),a=I(n*n),s=I(2n*I(r*r)),u=I(o*i),c=t+n,l=I(I(c*c)-i-a),d=u+a,p=d-s,_=u-a,f=I(l*p),y=I(d*_),v=I(l*_),k=I(p*d);return new e(f,y,k,v)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:a,Y:s,Z:u,T:c}=Ga(t),l=Ha,d=Ja,p=I(n*a),_=I(r*s),f=I(i*d*c),y=I(o*u),v=I((n+r)*(a+s)-p-_),k=I(y-f),A=I(y+f),w=I(_-l*p),S=I(v*k),x=I(A*w),U=I(v*w),M=I(k*A);return new e(S,x,M,U)}subtract(t){return this.add(Ga(t).negate())}multiply(t,n=!0){if(!n&&(t===0n||this.is0()))return hn;if(Pt(t,1n,Lo),t===1n)return this;if(this.equals(mt))return xy(t).p;let r=hn,o=mt;for(let i=this;t>0n;i=i.double(),t>>=1n)t&1n?r=r.add(i):n&&(o=o.add(i));return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(hn))return{x:0n,y:1n};let o=my(r,le);I(r*o)!==1n&&se("invalid inverse");let i=I(t*o),a=I(n*o);return{x:i,y:a}}toBytes(){let{x:t,y:n}=this.assertValidity().toAffine(),r=Nd(n);return r[31]|=t&1n?128:0,r}toHex(){return Dd(this.toBytes())}clearCofactor(){return this.multiply(Mo(sy),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Lo/2n,!1).double();return Lo%2n&&(t=t.add(this)),t.is0()}},mt=new at(Ed,kd,1n,I(Ed*kd)),hn=new at(0n,1n,1n,0n);at.BASE=mt;at.ZERO=hn;var Nd=e=>Rd(Ud(Pt(e,0n,Va),lr)).reverse(),Wa=e=>Mo("0x"+Dd(Od(Xe(e)).reverse())),We=(e,t)=>{let n=e;for(;t-- >0n;)n*=n,n%=le;return n},hy=e=>{let n=e*e%le*e%le,r=We(n,2n)*n%le,o=We(r,1n)*e%le,i=We(o,5n)*o%le,a=We(i,10n)*i%le,s=We(a,20n)*a%le,u=We(s,40n)*s%le,c=We(u,80n)*u%le,l=We(c,80n)*u%le,d=We(l,10n)*i%le;return{pow_p_5_8:We(d,2n)*e%le,b2:n}},Ad=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,gy=(e,t)=>{let n=I(t*t*t),r=I(n*n*t),o=hy(e*r).pow_p_5_8,i=I(e*n*o),a=I(t*i*i),s=i,u=I(i*Ad),c=a===e,l=a===I(-e),d=a===I(-e*Ad);return c&&(i=s),(l||d)&&(i=u),(I(i)&1n)===1n&&(i=I(-i)),{isValid:c||l,value:i}},Zo=e=>jd(Wa(e)),Xa=(...e)=>Ya.sha512Async(dr(...e));var yy=e=>{let t=e.slice(0,zt);t[0]&=248,t[31]&=127,t[31]|=64;let n=e.slice(zt,lr),r=Zo(t),o=mt.multiply(r),i=o.toBytes();return{head:t,prefix:n,scalar:r,point:o,pointBytes:i}},Cd=e=>Xa(Xe(e,zt)).then(yy);var Ld=e=>Cd(e).then(t=>t.pointBytes);var Md=e=>Xa(e.hashable).then(e.finish);var vy=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=Zo(t),a=mt.multiply(i).toBytes();return{hashable:dr(a,r,n),finish:c=>{let l=jd(i+Zo(c)*o);return Xe(dr(a,Nd(l)),lr)}}},Zd=async(e,t)=>{let n=Xe(e),r=await Cd(t),o=await Xa(r.prefix,n);return Md(vy(r,o,n))};var Bd={zip215:!0},_y=(e,t,n,r=Bd)=>{e=Xe(e,lr),t=Xe(t),n=Xe(n,zt);let{zip215:o}=r,i,a,s,u,c=Uint8Array.of();try{i=at.fromBytes(n,o),a=at.fromBytes(e.slice(0,zt),o),s=Wa(e.slice(zt,lr)),u=mt.multiply(s,!1),c=dr(a.toBytes(),i.toBytes(),t)}catch{}return{hashable:c,finish:d=>{if(u==null||!o&&i.isSmallOrder())return!1;let p=Zo(d);return a.add(i.multiply(p,!1)).add(u.negate()).clearCofactor().is0()}}},Fd=async(e,t,n,r=Bd)=>Md(_y(e,t,n,r));var Ya={sha512Async:async e=>{let t=py(),n=dr(e);return Ka(await t.digest("SHA-512",n.buffer))},sha512:void 0};var Bo=8,by=256,Hd=Math.ceil(by/Bo)+1,qa=2**(Bo-1),wy=()=>{let e=[],t=mt,n=t;for(let r=0;r<Hd;r++){n=t,e.push(n);for(let o=1;o<qa;o++)n=n.add(t),e.push(n);t=n.double()}return e},Td,Pd=(e,t)=>{let n=t.negate();return e?n:t},xy=e=>{let t=Td||(Td=wy()),n=hn,r=mt,o=2**Bo,i=o,a=Mo(o-1),s=Mo(Bo);for(let u=0;u<Hd;u++){let c=Number(e&a);e>>=s,c>qa&&(c-=i,e+=1n);let l=u*qa,d=l,p=l+Math.abs(c)-1,_=u%2!==0,f=c<0;c===0?r=r.add(Pd(_,t[d])):n=n.add(Pd(f,t[p]))}return e!==0n&&se("invalid wnaf"),{p:n,f:r}};Ya.sha512Async=Sd;var Ot="pk:sha2-256+ed25519",Qa=0,Fo=class{async register(t,n){if(t!==Ot)throw new Error(`Unsupported channel attestation method: ${t}`);let r=await this.channelToPrivateKey(n);return await this.channelPublicIdFromPrivateKey(r)}async getMethod(t){if(t[0]===Qa)return Ot;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await Tt(n)}async channelPublicIdFromPrivateKey(t){let n=await Ld(t),r=new Uint8Array(n.length+1);return r[0]=Qa,r.set(n,1),r}async attest(t,n,r){if(t!==Ot)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),a=new TextEncoder().encode(n);return{attestation:await Zd(a,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==Qa)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await Fd(t,new TextEncoder().encode(n),r.slice(1))}};var es="hmac:sha2-256",Jd=0,Ho=class{async attest(t,n){if(t!==es)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=wt(),o=await Fa(Tt,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=Jd,i[1]=ur,i[2]=mn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],a=r[2];if(o!==Jd||i!==ur||a!==mn)throw new Error("Unrecognized allowed ticket format");let s=await Fa(Tt,r.slice(3),new TextEncoder().encode(n));return t.length!==s.length?!1:s.every((u,c)=>t[c]===u)}};var ts="did:web:",Jo=class{constructor(t){this.services=t}actorToHandle=async t=>{let r=(await this.services.dids.resolve(t)).alsoKnownAs?.at(0);if(!r)throw new Q(`Handle for actor DID ${t} not found`);if(!r.startsWith(ts))throw new Error(`Handle DID ${r} is not a valid handle`);let o=r.slice(ts.length),i=await this.services.dids.resolve(r);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(t))throw new Error(`Handle ${o} does not match actor ${t}`);return o};handleToActor=async t=>{let n=`${ts}${t}`,o=(await this.services.dids.resolve(n)).alsoKnownAs?.at(0);if(!o)throw new Q(`Actor for handle DID ${n} not found`);let i=await this.services.dids.resolve(o);if(!i.alsoKnownAs||!i.alsoKnownAs.includes(n))throw new Error(`Actor ${o} does not match handle ${t}`);return o}};var Ko="GraffitiInbox",Xo="GraffitiStorageBucket",is="#graffitiPersonalInbox",Yo="#graffitiStorageBucket",$y="#graffitiSharedInbox_",Wo=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let a=hd.safeParse(i.detail);if(!a.success)return;let s=a.data?.error;s&&console.error(s),o()})});this.services.authorization.eventTarget.addEventListener("login",this.onLogin.bind(this)),this.services.authorization.eventTarget.addEventListener("logout",this.onLogout.bind(this));let r;if(typeof window<"u"){let o=new URLSearchParams(window.location.search).get("actor");if(o)try{let i=decodeURIComponent(o),a=new URL(window.location.toString());a.searchParams.delete("actor"),window.history.replaceState({},"",a.toString()),r=this.login(i)}catch(i){console.error("Error decoding actor:",i)}}(async()=>{await new Promise(i=>setTimeout(i,0)),await r;for(let i of this.loggedInSessions){let a=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(a)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}sessionEvents=new EventTarget;inProgressLogin=void 0;inProgressLogout=void 0;async login(t){try{await this.login_(t)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n)),session:{actor:t}}});this.sessionEvents.dispatchEvent(r)}}async login_(t){if(this.loggedInSessions.find(w=>w.actor===t)){this.sessionEvents.dispatchEvent(new CustomEvent("login",{detail:{session:{actor:t}}}));return}let o=(await this.services.dids.resolve(t)).service;if(!o)throw new Error(`No services found in actor document for ${t}`);let i=o.find(w=>w.id===Yo&&w.type===Xo),a=o.find(w=>w.id===is&&w.type===Ko),s=o.filter(w=>w.id.match(new RegExp(`^${$y}\\d+$`))&&w.type===Ko);if(!a||!i||s.length===0)throw new Error(`Required services not found in actor document for ${t}`);let u=rs(i),c=rs(a),l=s.map(rs),d=[{endpoint:u,type:"bucket"},{endpoint:c,type:"personal-inbox"},...l.map(w=>({endpoint:w,type:"shared-inbox"}))],p=await Promise.all(d.map(async({endpoint:w,type:S})=>{let x=await(S==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(w):this.services.inboxes.getAuthorizationEndpoint(w));return{endpoint:w,authorizationEndpoint:x,type:S}})),_=new Map;p.forEach(({authorizationEndpoint:w,endpoint:S,type:x})=>{_.has(w)||_.set(w,[]),_.get(w).push({endpoint:S,type:x})});let f=[..._.entries()],v={...{actor:t},tokens:[],servicesByAuthorization:f};typeof window<"u"?window.localStorage.setItem(Go,JSON.stringify(v)):this.inProgressLogin=v;let[k,A]=f[0];await this.services.authorization.login(k,t,A.map(w=>w.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=pd.safeParse(t.detail);if(!n.success)return;let r=n.data.loginId;try{await this.onLogin_(n.data)}catch(o){let i=new CustomEvent("login",{detail:{error:o instanceof Error?o:new Error(String(o)),session:{actor:r}}});this.sessionEvents.dispatchEvent(i)}}async onLogin_(t){if(t.error)throw t.error;let n=t.token,r=t.loginId,o;if(typeof window<"u"){let i=window.localStorage.getItem(Go);if(!i)throw new Error("No in-progress login found");let a=JSON.parse(i);o=os.parse(a)}else{if(!this.inProgressLogin)throw new Error("No in-progress login found");o=this.inProgressLogin}if(o.actor!==r)throw new Error("Actor mismatch in login response - concurrent logins?");if(o.tokens.push(n),o.tokens.length===o.servicesByAuthorization.length){typeof window>"u"?this.inProgressLogin=void 0:window.localStorage.removeItem(Go);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(Go,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 It?void 0: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(Vo,JSON.stringify(n)):this.inProgressLogout=n;let[o,i]=n.servicesByAuthorization[n.tokens.length];await this.services.authorization.logout(o,t,r)}async onLogout(t){if(!(t instanceof CustomEvent))return;let n=md.safeParse(t.detail);if(!n.success)return;let r=n.data.logoutId;try{await this.onLogout_(n.data)}catch(o){let i=new CustomEvent("logout",{detail:{error:o instanceof Error?o:new Error(String(o)),actor:r}});this.sessionEvents.dispatchEvent(i)}}async onLogout_(t){if(t.error)throw t.error;let n=t.logoutId,r;if(typeof window<"u"){let i=window.localStorage.getItem(Vo);if(!i)throw new Error("No in-progress logout found");let a=JSON.parse(i);r=os.parse(a)}else{if(!this.inProgressLogout)throw new Error("No in-progress logout found");r=this.inProgressLogout}if(r.actor!==n)throw new Error("Actor mismatch in logout response - concurrent logouts?");let o=r.tokens.pop();if(o){typeof window<"u"?window.localStorage.setItem(Vo,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(Vo);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return Gd;let t=window.localStorage.getItem(qo);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),window.localStorage.removeItem(qo),[]}let r=V(ky).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),window.localStorage.removeItem(qo),[])}set loggedInSessions(t){if(typeof window>"u"){Gd=t;return}window.localStorage.setItem(qo,JSON.stringify(t))}resolveSession(t){let n=this.loggedInSessions.find(r=>r.actor===t.actor);if(!n){let r=new CustomEvent("logout",{detail:{actor:t.actor}});throw this.sessionEvents.dispatchEvent(r),new Error("Not logged in")}return n}},Gd=[],Go="graffiti-login-in-progress",Vo="graffiti-logout-in-progress",qo="graffiti-sessions-logged-in",Sy=_e({actor:J()}),ns=_e({token:H(),serviceEndpoint:J(),authorizationEndpoint:J()}),Ey=V(fe([J(),V(_e({endpoint:J(),type:xc(["bucket","personal-inbox","shared-inbox"])}))])),os=tt(Sy,{tokens:V(H()),servicesByAuthorization:Ey}),ky=tt(os,{storageBucket:ns,personalInbox:ns,sharedInboxes:V(ns)});function rs(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var Qo=32*1024,ei=class{constructor(t){this.primitives=t}async encode(t,n){t=ds(t);let r=[...new Set(t.channels)],o=await Promise.all(r.map(y=>this.primitives.channelAttestations.attest(Ot,n,y))),i=o.map(y=>y.attestation),a=o.map(y=>y.channelPublicId),s={[ss]:t.value,[cs]:i,[Kd]:wt(32)},u;if(Array.isArray(t.allowed)){let y=await Promise.all(t.allowed.map(async v=>this.primitives.allowedAttestations.attest(es,v)));s[us]=y.map(v=>v.attestation),u=y.map(v=>v.ticket)}let c=Ee(s);if(c.byteLength>Qo)throw new Error("The object is too large");let l=await this.primitives.contentAddresses.register(No,c),d=await this.primitives.stringEncoder.encode(pn,l),p=Ay(n,d),_=[new TextEncoder().encode(p),...a];return{object:{value:t.value,channels:r,url:p,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:_,objectBytes:c,allowedTickets:u}}async validate(t,n,r,o){if(r.byteLength>Qo)throw new Error("Object is too big");let{actor:i,contentAddress:a}=fs(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let s=n.at(0);if(!s)throw new Error("No object URL tag");if(new TextDecoder().decode(s)!==t.url)throw new Error("Object URL tag does not match object URL");let u=n.slice(1),c=await this.primitives.stringEncoder.decode(a),l=await this.primitives.contentAddresses.getMethod(c),d=await this.primitives.contentAddresses.register(l,r);if(d.length!==c.length||!d.every((w,S)=>w===c[S]))throw new Error("Content address is invalid");let p=Je(r),_=Iy.parse(p),f=_[ss],y=_[cs],v=_[us],k=Ee(f),A=Ee(t.value);if(k.length!==A.length||!k.every((w,S)=>w===A[S]))throw new Error("Object value does not match storage value");if(y.length!==u.length)throw new Error("Not as many channel attestations and public ids");for(let[w,S]of y.entries()){let x=u[w];if(!await this.primitives.channelAttestations.validate(S,i,x))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==u.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let w=await this.primitives.channelAttestations.getMethod(u[0]),S=await Promise.all(t.channels.map(x=>this.primitives.channelAttestations.register(w,x)));for(let[x,U]of S.entries()){let M=u[x];if(U.length!==M.length||!U.every((B,ie)=>B===M[ie]))throw new Error("Channel public id does not match expected")}}if(o){if(!v)throw new Error("Object is public but thought to be private");let w,S,x;if("recipient"in o?(w=[o.recipient],S=[o.allowedTicket],x=v.filter((U,M)=>M===o.allowedIndex)):(w=[...t.allowed??[]],S=o.allowedTickets,x=v),w.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!w.every(U=>t.allowed?.includes(U)))throw new Error("Recipient not in object allowed list");for(let[U,M]of w.entries()){let B=S.at(U),ie=x.at(U);if(!B)throw new Error("Missing allowed ticket for recipient");if(!ie)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(ie,M,B))throw new Error("Invalid allowed attestation for recipient")}}else if(v)throw new Error("Object is private but no recipient info provided")}},ss="v",cs="c",us="a",Kd="n",as=bt(e=>e instanceof Uint8Array),Iy=be({[ss]:he({}),[cs]:V(as),[us]:X(V(as)),[Kd]:as}),ls="graffiti:";function Vd(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function qd(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function Ay(e,t){return`${ls}${Vd(e)}:${Vd(t)}`}function fs(e){if(!e.startsWith(ls))throw new Error("Invalid object URL");let n=e.slice(ls.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:qd(r),contentAddress:qd(o)}}function ds(e){return e===void 0?null:Array.isArray(e)?e.map(ds):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,ds(n)])):e}var Wd=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;displayTemplateSeq=0;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-BOBMBTYJ-ORUSIJTZ.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=++this.displayTemplateSeq,n=()=>{if(t!==this.displayTemplateSeq)throw new Error(`displayTemplate(${e}) overridden by concurrent call`)},r=await this.main;n();let o=(await this.templates).get(e);if(n(),!o)throw new Error(`Template not found: ${e}`);let i=o.content.cloneNode(!0);return r.replaceChildren(i),r}};var Yd=bt(e=>e instanceof Uint8Array),hs="k",gn="t",vs=be({[hs]:H(),[gn]:X(H())}),Ut="id",gs="e",fr="a",Ty=V(be({[Ut]:H(),[gs]:X(J()),[fr]:X(J())})),ti="s",ni="n",Py=tt(vs,{[ti]:X(V(Yd)),[ni]:Ty}),pr="a",ys="i",zy=tt(vs,{[pr]:Yd,[ys]:Nt().check(_t())}),Oy=ut([vs,Py,zy]),Uy=0,ps=1,ht=2,ms=3,Dy=16,ri=class{dids=new mo;authorization=new Po;storageBuckets=new Oo;inboxes=new Do;stringEncoder=new jo;contentAddresses=new Co;channelAttestations=new Fo;allowedAttestations=new Ho;sessions=new Wo({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new Jo({dids:this.dids});objectEncoding=new ei({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new Wd({useTemplateHTML:()=>import("./login-dialog.html-VTDKJZBG.js").then(({template:t})=>t),onManualClose:()=>{let t=new CustomEvent("login",{detail:{error:new Error("User cancelled login"),manual:!0}});this.sessionEvents.dispatchEvent(t)}});defaultInboxEndpoints;identityCreatorEndpoint;constructor(t){this.defaultInboxEndpoints=t?.defaultInboxEndpoints??["https://graffiti.actor/i/shared"],this.identityCreatorEndpoint=t?.identityCreatorEndpoint??"https://graffiti.actor/create",this.sessionEvents.addEventListener("login",async n=>{if(!(n instanceof CustomEvent))return;let r=n.detail;if(r.error!==void 0&&!("manual"in r&&r.manual)){alert("Login failed: "+r.error.message);let o=r.session?.actor,i;if(o)try{i=await this.actorToHandle(o)}catch(a){console.error("Failed to handle actor:",a)}this.login_(i)}});for(let n of["post","get","delete","postMedia","getMedia","deleteMedia"]){let r=this[n];this[n]=async(...o)=>{try{return await r(...o)}catch(i){let a=o[o.length-1];throw await this.tryLogoutIfUnauthorized(i,a),i}}}}actorToHandle=this.handles.actorToHandle.bind(this.handles);handleToActor=this.handles.handleToActor.bind(this.handles);sessionEvents=this.sessions.sessionEvents;login=async t=>{try{let n;try{n=t?await this.actorToHandle(t):void 0}catch(r){console.error("Error fetching handle for actor:",r)}await this.login_(n)}catch(n){let r=new CustomEvent("login",{detail:{error:n instanceof Error?n:new Error(String(n))}});this.sessionEvents.dispatchEvent(r)}};async login_(t){if(typeof window<"u"){let n;if(t!==void 0){n=await this.modal?.displayTemplate("graffiti-login-handle");let o=n?.querySelector("#username");o?.setAttribute("value",t),o?.addEventListener("focus",()=>o?.select()),setTimeout(()=>o?.focus(),0),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async i=>{i.preventDefault(),o?.setAttribute("disabled","true");let a=n?.querySelector("#graffiti-login-handle-submit");if(a?.setAttribute("disabled","true"),a&&(a.innerHTML="Logging in..."),!o?.value){alert("No handle provided"),this.login_("");return}let s=o.value;if(!s.includes(".")&&!s.startsWith("localhost")){let c=new URL(this.identityCreatorEndpoint).host;s=`${s}.${c}`}let u;try{u=await this.handleToActor(s)}catch{alert("Could not find an identity associated with that handle."),this.login_(s);return}try{await this.sessions.login(u)}catch(c){alert("Error logging in."),console.error(c),this.login_(s)}})}else n=await this.modal?.displayTemplate("graffiti-login-welcome"),n?.querySelector("#graffiti-login-existing")?.addEventListener("click",o=>{o.preventDefault(),this.login_("")}),setTimeout(()=>n?.querySelector("#graffiti-login-new")?.focus(),0);let r=new URL(this.identityCreatorEndpoint);r.searchParams.set("redirect_uri",encodeURIComponent(window.location.toString())),n?.querySelector("#graffiti-login-new")?.setAttribute("href",r.toString()),await this.modal?.open()}else{let n=await import("readline").catch(a=>{throw new Error("Unrecognized environment: neither window nor readline")});console.log("If you do not already have a Graffiti handle, you can create one here:"),console.log(this.identityCreatorEndpoint);let r=n.createInterface({input:process.stdin,output:process.stdout}),o=await new Promise(a=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,s=>{r.close(),a(s||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:a,objectBytes:s,allowedTickets:u}=await this.objectEncoding.encode(n,r.actor),c=wt(),l=await this.stringEncoder.encode(pn,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 yr(r);if(o){let c=this.sessions.resolveSession(o);i=[c.personalInbox,...c.sharedInboxes]}else i=this.defaultInboxEndpoints.map(c=>({serviceEndpoint:c}));let s=ai(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 hr("Object exists but does not match the supplied schema");return l}}throw new Q("Object not found")};delete=async(t,n)=>{let r=this.sessions.resolveSession(n),o=ai(t),{actor:i}=fs(o);if(i!==n.actor)throw new st("Cannot delete someone else's actor");let a=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),s;for await(let f of a)f.object.url===o&&(f.tombstone?s=void 0:s=f);if(!s)throw new Q(`Object ${o} not found`);let{object:u,storageBucketKey:c,tags:l,allowedTickets:d,announcements:p,messageId:_}=s;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,c,r.storageBucket.token),await this.announceObject(u,l,d,c,n,[...p??[],{[fr]:n.actor,[Ut]:_}]),u};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),a=wt(),s=await this.stringEncoder.encode(pn,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 jt("File size exceeds limit");if(r?.types&&!bs(s,r.types))throw new gr(`Unacceptable media type, ${s}`);let l=(await this.dids.resolve(i.actor))?.service?.find(f=>f.id===Yo&&f.type===Xo);if(!l)throw new Q(`Actor ${i.actor} has no storage bucket service`);if(typeof l.serviceEndpoint!="string")throw new Q(`Actor ${i.actor} does not have a valid storage bucket endpoint`);let d=l.serviceEndpoint,p=await this.storageBuckets.get(d,a,u);return{data:new Blob([p.slice()],{type:s}),actor:i.actor,allowed:i.allowed}};deleteMedia=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),i=await this.delete(n,r);if(!("key"in i.value&&typeof i.value.key=="string"))throw new Error("Deleted object was not media: "+JSON.stringify(i,null,2));await this.storageBuckets.delete(o.storageBucket.serviceEndpoint,i.value.key,o.storageBucket.token)};async*discoverMeta(t,n,r,o){let i=new Map,a;if(o){let d=this.sessions.resolveSession(o);a=[d.personalInbox,...d.sharedInboxes]}else a=this.defaultInboxEndpoints.map(d=>({serviceEndpoint:d}));for(let d in r)if(!a.some(p=>p.serviceEndpoint===d))throw new st("Cursor does not match actor's inboxes");let s=await Promise.all(t.map(d=>this.channelAttestations.register(Ot,d))),u=a.map(d=>{let p=r[d.serviceEndpoint];return this.querySingleEndpoint(d.serviceEndpoint,p?{cursor:p}:{tags:s,objectSchema:n},d.token,o?.actor)}),c=u.map(async(d,p)=>Xd(d,p)),l=c.length;try{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},this.tryLogoutIfUnauthorized(d.error,o);else if(d.result.done){let p=a[d.index];r[p.serviceEndpoint]=d.result.value,c[d.index]=new Promise(()=>{}),l--}else{c[d.index]=Xd(u[d.index],d.index);let{object:p,tombstone:_,tags:f}=d.result.value;if(_){if(i.get(p.url)===!0)continue;i.set(p.url,!0),yield{tombstone:_,object:{url:p.url}}}else{if(i.get(p.url)===!1)continue;let v=s.reduce((k,A,w)=>{for(let S of f)if(A.length===S.length&&A.every((x,U)=>S[U]===x)){k.push(w);break}return k},[]).map(k=>t[k]);v.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:a[d.index].serviceEndpoint}),i.set(p.url,!1),yield{object:{...p,channels:v}}}}}}catch(d){throw this.tryLogoutIfUnauthorized(d,o),d}finally{await Promise.all(u.map(async d=>{await d.return("")}))}return{cursor:JSON.stringify({channels:t,cursors:r})}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let a=JSON.parse(n),s=jy.parse(a);o=s.channels,i=s.cursors}catch{return(async function*(){throw new Re("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async tryLogoutIfUnauthorized(t,n){t instanceof It&&n&&await this.sessions.logout(n.actor)}async announceObject(t,n,r,o,i,a){let s=this.sessions.resolveSession(i),u={[hs]:o},c=[],l=t.allowed;if(Array.isArray(l)){if(!r||r.length!==l.length)throw new Error("If allowed actors are specified, there must be a corresponding ticket for each allowed actor");let _=await Promise.allSettled(l.map(async(f,y)=>{let v=JSON.parse(JSON.stringify(t)),k=si(v,[],f),w=(await this.dids.resolve(f)).service?.find(M=>M.type===Ko&&M.id===is);if(!w)throw new Error(`Recipient ${f} does not have a personal inbox`);if(typeof w.serviceEndpoint!="string")throw new Error(`Recipient ${f} does not have a valid personal inbox endpoint`);let S=a?a.find(M=>M[fr]===f)?.[Ut]:void 0,x={...u,...S?{[gn]:S}:{},[pr]:r[y],[ys]:y},U=await this.inboxes.send(w.serviceEndpoint,{[sr]:n,[ot]:k,[cr]:Ee(x)});c.push({[Ut]:U,[fr]:f})}));for(let[f,y]of _.entries())if(y.status==="rejected"){let v=l[f];console.error("Error sending to recipient:",v),console.error(y.reason)}}else{let _=JSON.parse(JSON.stringify(t)),f=si(_,[]),y=s.sharedInboxes,v=await Promise.allSettled(y.map(async k=>{let A=a?a.find(x=>x[gs]===k.serviceEndpoint)?.[Ut]:void 0,w={...u,...A?{[gn]:A}:{}},S=await this.inboxes.send(k.serviceEndpoint,{...A?{[gn]:A}:{},[sr]:n,[ot]:f,[cr]:Ee(w)});c.push({[Ut]:S,[gs]:k.serviceEndpoint})}));for(let[k,A]of v.entries())if(A.status==="rejected"){let w=y[k];console.error("Error sending to inbox:",w),console.error(A.reason)}}let d=a?a.find(_=>_[fr]===i.actor)?.[Ut]:void 0,p={...u,...r?{[ti]:r}:{},...d?{[gn]:d}:{},[ni]:c};await this.inboxes.send(s.personalInbox.serviceEndpoint,{[sr]:n,[ot]:t,[cr]:Ee(p)})}async*querySingleEndpoint(t,n,r,o){let i="tags"in n?this.inboxes.query(t,n.tags,n.objectSchema,r):this.inboxes.continueQuery(t,n.cursor,r),a=[],s=null;try{for(;;){for(;s===null&&a.length<Dy;){let l=await i.next();if(l.done){s=l.value;break}let d=this.processOneLabeledMessage(t,l.value,r,o).catch(p=>{throw p});a.push(d)}let u=a.shift();if(!u){if(s!==null)return s;throw new Error("Process queue empty but no return value")}let c=await u;c&&(yield c)}}finally{await i.return("")}}async processOneLabeledMessage(t,n,r,o){let i=n.l;if(i!==ps&&i!==Uy&&i!==ht)return;let a=n.id,{o:s,m:u,t:c}=n.m,l;try{let v=Je(u);l=Oy.parse(v)}catch{this.inboxes.label(t,a,ms,r);return}let{[hs]:d,[gn]:p}=l,_=ti in l?l[ti]:void 0,f=ni in l?l[ni]:void 0;if(i===ps)return{messageId:a,object:s,storageBucketKey:d,allowedTickets:_,tags:c,announcements:f};if(i===ht){if(!p)return;let v=await this.inboxes.get(t,p,r);return!v||v[At][ot].url!==s.url?void 0:(v[Ro]!==ht&&this.inboxes.label(t,p,ht,r),{messageId:a,tombstone:!0,object:s,storageBucketKey:d,allowedTickets:_,tags:c,announcements:f})}let y;try{let v=s.actor,A=(await this.dids.resolve(v))?.service?.find(U=>U.id===Yo&&U.type===Xo);if(!A)throw new Q(`Actor ${v} has no storage bucket service`);if(typeof A.serviceEndpoint!="string")throw new Q(`Actor ${v} does not have a valid storage bucket endpoint`);let w=A.serviceEndpoint,S=await this.storageBuckets.get(w,d,Qo);if(pr in l&&!o)throw new st("Recipient is required when allowed ticket is present");let x=_?{allowedTickets:_}:pr in l?{recipient:o??"null",allowedTicket:l[pr],allowedIndex:l[ys]}:void 0;await this.objectEncoding.validate(s,c,S,x)}catch(v){y=v}if(p){if(y instanceof Q)return this.inboxes.get(t,p,r).then(v=>{v&&v[At][ot].url===s.url&&v[Ro]!==ht&&this.inboxes.label(t,p,ht,r),this.inboxes.label(t,a,ht,r)}),{messageId:a,tombstone:!0,object:s,storageBucketKey:d,allowedTickets:_,tags:c,announcements:f};console.error("Recieved an incorrect tombstone object"),console.error(y),this.inboxes.label(t,a,ms,r)}else{if(y===void 0)return this.inboxes.label(t,a,ps,r),{messageId:a,object:s,storageBucketKey:d,tags:c,allowedTickets:_,announcements:f};y instanceof Q?this.inboxes.label(t,a,ht,r):(console.error("Recieved an incorrect object"),console.error(y),this.inboxes.label(t,a,ms,r))}}},Ry={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},jy=be({cursors:wc(J(),H()),channels:V(H())});async function Xd(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Re||n instanceof Rt)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var Qd=class extends Tr{constructor(t){let n=new ri(t);super(n)}};export{Qd as GraffitiDecentralized};
1
+ import{a as Uf,b as Mf,c as Nf}from"./chunk-O4MIY67H.js";var cd=Uf((yt,ad)=>{var xo=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof global<"u"&&global,Eo=(function(){function e(){this.fetch=!1,this.DOMException=xo.DOMException}return e.prototype=xo,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 s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=ArrayBuffer.isView||function(h){return h&&s.indexOf(Object.prototype.toString.call(h))>-1};function c(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 u(h){return typeof h!="string"&&(h=String(h)),h}function l(h){var E={next:function(){var C=h.shift();return{done:C===void 0,value:C}}};return o.iterable&&(E[Symbol.iterator]=function(){return E}),E}function d(h){this.map={},h instanceof d?h.forEach(function(E,C){this.append(C,E)},this):Array.isArray(h)?h.forEach(function(E){if(E.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+E.length);this.append(E[0],E[1])},this):h&&Object.getOwnPropertyNames(h).forEach(function(E){this.append(E,h[E])},this)}d.prototype.append=function(h,E){h=c(h),E=u(E);var C=this.map[h];this.map[h]=C?C+", "+E:E},d.prototype.delete=function(h){delete this.map[c(h)]},d.prototype.get=function(h){return h=c(h),this.has(h)?this.map[h]:null},d.prototype.has=function(h){return this.map.hasOwnProperty(c(h))},d.prototype.set=function(h,E){this.map[c(h)]=u(E)},d.prototype.forEach=function(h,E){for(var C in this.map)this.map.hasOwnProperty(C)&&h.call(E,this.map[C],C,this)},d.prototype.keys=function(){var h=[];return this.forEach(function(E,C){h.push(C)}),l(h)},d.prototype.values=function(){var h=[];return this.forEach(function(E){h.push(E)}),l(h)},d.prototype.entries=function(){var h=[];return this.forEach(function(E,C){h.push([C,E])}),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 m(h){return new Promise(function(E,C){h.onload=function(){E(h.result)},h.onerror=function(){C(h.error)}})}function w(h){var E=new FileReader,C=m(E);return E.readAsArrayBuffer(h),C}function x(h){var E=new FileReader,C=m(E),N=/charset=([A-Za-z0-9_-]+)/.exec(h.type),G=N?N[1]:"utf-8";return E.readAsText(h,G),C}function _(h){for(var E=new Uint8Array(h),C=new Array(E.length),N=0;N<E.length;N++)C[N]=String.fromCharCode(E[N]);return C.join("")}function g(h){if(h.slice)return h.slice(0);var E=new Uint8Array(h.byteLength);return E.set(new Uint8Array(h)),E.buffer}function v(){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=g(h.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):o.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(h)||a(h))?this._bodyArrayBuffer=g(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(w);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var h=p(this);if(h)return h;if(this._bodyBlob)return x(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(_(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},o.formData&&(this.formData=function(){return this.text().then(O)}),this.json=function(){return this.text().then(JSON.parse)},this}var b=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function S(h){var E=h.toUpperCase();return b.indexOf(E)>-1?E:h}function A(h,E){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');E=E||{};var C=E.body;if(h instanceof A){if(h.bodyUsed)throw new TypeError("Already read");this.url=h.url,this.credentials=h.credentials,E.headers||(this.headers=new d(h.headers)),this.method=h.method,this.mode=h.mode,this.signal=h.signal,!C&&h._bodyInit!=null&&(C=h._bodyInit,h.bodyUsed=!0)}else this.url=String(h);if(this.credentials=E.credentials||this.credentials||"same-origin",(E.headers||!this.headers)&&(this.headers=new d(E.headers)),this.method=S(E.method||this.method||"GET"),this.mode=E.mode||this.mode||null,this.signal=E.signal||this.signal||(function(){if("AbortController"in r){var M=new AbortController;return M.signal}})(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&C)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(C),(this.method==="GET"||this.method==="HEAD")&&(E.cache==="no-store"||E.cache==="no-cache")){var N=/([?&])_=[^&]*/;if(N.test(this.url))this.url=this.url.replace(N,"$1_="+new Date().getTime());else{var G=/\?/;this.url+=(G.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}A.prototype.clone=function(){return new A(this,{body:this._bodyInit})};function O(h){var E=new FormData;return h.trim().split("&").forEach(function(C){if(C){var N=C.split("="),G=N.shift().replace(/\+/g," "),M=N.join("=").replace(/\+/g," ");E.append(decodeURIComponent(G),decodeURIComponent(M))}}),E}function D(h){var E=new d,C=h.replace(/\r?\n[\t ]+/g," ");return C.split("\r").map(function(N){return N.indexOf(`
2
+ `)===0?N.substr(1,N.length):N}).forEach(function(N){var G=N.split(":"),M=G.shift().trim();if(M){var ut=G.join(":").trim();try{E.append(M,ut)}catch(zn){console.warn("Response "+zn.message)}}}),E}v.call(A.prototype);function L(h,E){if(!(this instanceof L))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(E||(E={}),this.type="default",this.status=E.status===void 0?200:E.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=E.statusText===void 0?"":""+E.statusText,this.headers=new d(E.headers),this.url=E.url||"",this._initBody(h)}v.call(L.prototype),L.prototype.clone=function(){return new L(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},L.error=function(){var h=new L(null,{status:200,statusText:""});return h.ok=!1,h.status=0,h.type="error",h};var ne=[301,302,303,307,308];L.redirect=function(h,E){if(ne.indexOf(E)===-1)throw new RangeError("Invalid status code");return new L(null,{status:E,headers:{location:h}})},n.DOMException=r.DOMException;try{new n.DOMException}catch{n.DOMException=function(E,C){this.message=E,this.name=C;var N=Error(E);this.stack=N.stack},n.DOMException.prototype=Object.create(Error.prototype),n.DOMException.prototype.constructor=n.DOMException}function H(h,E){return new Promise(function(C,N){var G=new A(h,E);if(G.signal&&G.signal.aborted)return N(new n.DOMException("Aborted","AbortError"));var M=new XMLHttpRequest;function ut(){M.abort()}M.onload=function(){var K={statusText:M.statusText,headers:D(M.getAllResponseHeaders()||"")};G.url.indexOf("file://")===0&&(M.status<200||M.status>599)?K.status=200:K.status=M.status,K.url="responseURL"in M?M.responseURL:K.headers.get("X-Request-URL");var W="response"in M?M.response:M.responseText;setTimeout(function(){C(new L(W,K))},0)},M.onerror=function(){setTimeout(function(){N(new TypeError("Network request failed"))},0)},M.ontimeout=function(){setTimeout(function(){N(new TypeError("Network request timed out"))},0)},M.onabort=function(){setTimeout(function(){N(new n.DOMException("Aborted","AbortError"))},0)};function zn(K){try{return K===""&&r.location.href?r.location.href:K}catch{return K}}if(M.open(G.method,zn(G.url),!0),G.credentials==="include"?M.withCredentials=!0:G.credentials==="omit"&&(M.withCredentials=!1),"responseType"in M&&(o.blob?M.responseType="blob":o.arrayBuffer&&(M.responseType="arraybuffer")),E&&typeof E.headers=="object"&&!(E.headers instanceof d||r.Headers&&E.headers instanceof r.Headers)){var In=[];Object.getOwnPropertyNames(E.headers).forEach(function(K){In.push(c(K)),M.setRequestHeader(K,u(E.headers[K]))}),G.headers.forEach(function(K,W){In.indexOf(W)===-1&&M.setRequestHeader(W,K)})}else G.headers.forEach(function(K,W){M.setRequestHeader(W,K)});G.signal&&(G.signal.addEventListener("abort",ut),M.onreadystatechange=function(){M.readyState===4&&G.signal.removeEventListener("abort",ut)}),M.send(typeof G._bodyInit>"u"?null:G._bodyInit)})}return H.polyfill=!0,r.fetch||(r.fetch=H,r.Headers=d,r.Request=A,r.Response=L),n.Headers=d,n.Request=A,n.Response=L,n.fetch=H,n})({})})(Eo);Eo.fetch.ponyfill=!0;delete Eo.fetch.polyfill;var _n=xo.fetch?xo:Eo;yt=_n.fetch;yt.default=_n.fetch;yt.fetch=_n.fetch;yt.Headers=_n.Headers;yt.Request=_n.Request;yt.Response=_n.Response;ad.exports=yt});var Lf={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"]},$w={...Lf,required:["value","channels"]};var dt=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)}},Ft=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)}},Ht=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorTooLarge",Object.setPrototypeOf(this,e.prototype)}},kr=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorNotAcceptable",Object.setPrototypeOf(this,e.prototype)}},Ce=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorCursorExpired",Object.setPrototypeOf(this,e.prototype)}};function wi(e){return typeof e=="string"?e:e.url}function _i(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 La(e,t){let[n,r]=e.toLowerCase().split(";")[0].split("/");return!n||!r?!1:t.some(o=>{let[i,s]=o.toLowerCase().split(";")[0].split("/");return!i||!s?!1:(i===n||i==="*")&&(s===r||s==="*")})}var yi;async function Or(e){if(!yi){let{default:t}=await import("./ajv-LGNUXWV5.js");yi=new t({strict:!1})}try{return yi.compile(e)}catch(t){throw new Ft(t instanceof Error?t.message:String(t))}}var Ba;function I(e,t,n){function r(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let u=s.prototype,l=Object.keys(u);for(let d=0;d<l.length;d++){let p=l[d];p in a||(a[p]=u[p].bind(a))}}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let u=n?.Parent?new i:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var et=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(Ba=globalThis).__zod_globalConfig??(Ba.__zod_globalConfig={});var bi=globalThis.__zod_globalConfig;function tt(e){return e&&Object.assign(bi,e),bi}function Za(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 Fa(e,t){return typeof t=="bigint"?t.toString():t}function Ha(e){return{get value(){{let n=e();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function $r(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var ja=Symbol("evaluating");function fe(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==ja)return r===void 0&&(r=ja,r=n()),r},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Bf(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jf(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}var Ei="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ir(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dn(e){if(Ir(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let n=t.prototype;return!(Ir(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}var Ga=new Set(["string","number","symbol"]);function vi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cr(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 qa(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}var Ja={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 Ka(e,t){if(!Dn(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 s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=jf(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Bf(this,"shape",i),i}});return Cr(e,o)}function vt(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 Va(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function je(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function zr(e){return typeof e=="string"?e:e?.message}function nt(e,t,n){let r=e.message?e.message:zr(e.inst?._zod.def?.error?.(e))??zr(t?.error?.(e))??zr(n.customError?.(e))??zr(n.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=r,t?.reportInput&&(a.input=s),a}function Si(...e){let[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}var Wa=(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,Fa,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Xa=I("$ZodError",Wa),Un=I("$ZodError",Wa,{Parent:Error});var Ff=e=>(t,n,r,o)=>{let i=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new et;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>nt(c,i,tt())));throw Ei(a,o?.callee),a}return s.value},Dr=Ff(Un),Hf=e=>async(t,n,r,o)=>{let i=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>nt(c,i,tt())));throw Ei(a,o?.callee),a}return s.value},Ur=Hf(Un),Gf=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 et;return i.issues.length?{success:!1,error:new(e??Xa)(i.issues.map(s=>nt(s,o,tt())))}:{success:!0,data:i.value}},Mn=Gf(Un),qf=e=>async(t,n,r)=>{let o=r?{...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(s=>nt(s,o,tt())))}:{success:!0,data:i.value}},Nn=qf(Un);var Ya=/^https?$/;var Jf="(?:(?:\\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])))",Kf=new RegExp(`^${Jf}$`);var Qa=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)};var ec=/^-?\d+$/,Ai=/^-?\d+(?:\.\d+)?$/,tc=/^(?:true|false)$/i;var nc=/^undefined$/i;var St=I("$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 rc=I("$ZodCheckGreaterThan",(e,t)=>{St.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 oc=I("$ZodCheckNumberFormat",(e,t)=>{St.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Ja[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,n&&(a.pattern=ec)}),e._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,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}):s.issues.push({input:a,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}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var ic=I("$ZodCheckStringFormat",(e,t)=>{var n,r;St.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 ac={major:4,minor:4,patch:3};var se=I("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ac;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=(s,a,c)=>{let u=vt(s),l;for(let d of a){if(d._zod.def.when){if(Va(s)||!d._zod.def.when(s))continue}else if(u)continue;let p=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new et;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(u||(u=vt(s,p)))});else{if(s.issues.length===p)continue;u||(u=vt(s,p))}}return l?l.then(()=>s):s},i=(s,a,c)=>{if(vt(s))return s.aborted=!0,s;let u=o(a,r,c);if(u instanceof Promise){if(c.async===!1)throw new et;return u.then(l=>e._zod.parse(l,c))}return e._zod.parse(u,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let u=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return u instanceof Promise?u.then(l=>i(l,s,a)):i(u,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new et;return c.then(u=>o(u,r,a))}return o(c,r,a)}}fe(e,"~standard",()=>({validate:o=>{try{let i=Mn(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Nn(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),Pi=I("$ZodString",(e,t)=>{se.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Qa(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}}),ki=I("$ZodStringFormat",(e,t)=>{ic.init(e,t),Pi.init(e,t)});var gc=I("$ZodURL",(e,t)=>{ki.init(e,t),e._zod.check=n=>{try{let r=n.value.trim();if(!t.normalize&&t.protocol?.source===Ya.source&&!/^https?:\/\//i.test(r)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}let 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 Oi=I("$ZodNumber",(e,t)=>{se.init(e,t),e._zod.pattern=e._zod.bag.pattern??Ai,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}}),yc=I("$ZodNumberFormat",(e,t)=>{oc.init(e,t),Oi.init(e,t)}),wc=I("$ZodBoolean",(e,t)=>{se.init(e,t),e._zod.pattern=tc,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 _c=I("$ZodUndefined",(e,t)=>{se.init(e,t),e._zod.pattern=nc,e._zod.values=new Set([void 0]),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 bc=I("$ZodUnknown",(e,t)=>{se.init(e,t),e._zod.parse=n=>n}),xc=I("$ZodNever",(e,t)=>{se.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function cc(e,t,n){e.issues.length&&t.issues.push(...je(n,e.issues)),t.value[n]=e.value}var Ec=I("$ZodArray",(e,t)=>{se.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 s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},r);c instanceof Promise?i.push(c.then(u=>cc(u,n,s))):cc(c,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function Mr(e,t,n,r,o,i){let s=n in r;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...je(n,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?s&&(t.value[n]=void 0):t.value[n]=e.value}function Wf(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=qa(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Xf(e,t,n,r,o,i){let s=[],a=o.keySet,c=o.catchall._zod,u=c.def.type,l=c.optin==="optional",d=c.optout==="optional";for(let p in t){if(p==="__proto__"||a.has(p))continue;if(u==="never"){s.push(p);continue}let m=c.run({value:t[p],issues:[]},r);m instanceof Promise?e.push(m.then(w=>Mr(w,n,p,t,l,d))):Mr(m,n,p,t,l,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}var vc=I("$ZodObject",(e,t)=>{if(se.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let r=Ha(()=>Wf(t));fe(e._zod,"propValues",()=>{let a=t.shape,c={};for(let u in a){let l=a[u]._zod;if(l.values){c[u]??(c[u]=new Set);for(let d of l.values)c[u].add(d)}}return c});let o=Ir,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=r.value);let u=a.value;if(!o(u))return a.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),a;a.value={};let l=[],d=s.shape;for(let p of s.keys){let m=d[p],w=m._zod.optin==="optional",x=m._zod.optout==="optional",_=m._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?l.push(_.then(g=>Mr(g,a,p,u,w,x))):Mr(_,a,p,u,w,x)}return i?Xf(l,u,a,c,r.value,e):l.length?Promise.all(l).then(()=>a):a}});function uc(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=>!vt(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(s=>nt(s,r,tt())))}),t)}var Sc=I("$ZodUnion",(e,t)=>{se.init(e,t),fe(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),fe(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),fe(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),fe(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){let r=t.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>$r(o.source)).join("|")})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>uc(a,r,e,o)):uc(s,r,e,o)}});var Ac=I("$ZodIntersection",(e,t)=>{se.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>lc(n,c,u)):lc(n,i,s)}});function Ti(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(Dn(e)&&Dn(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 s=Ti(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.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],s=Ti(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function lc(e,t,n){let r=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else e.issues.push(a);for(let a of n.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else e.issues.push(a);let i=[...r].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),vt(e))return e;let s=Ti(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var Rc=I("$ZodTuple",(e,t)=>{se.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 s=[],a=dc(n,"optin"),c=dc(n,"optout");if(!t.rest){if(i.length<a)return r.issues.push({code:"too_small",minimum:a,inclusive:!0,input:i,inst:e,origin:"array"}),r;i.length>n.length&&r.issues.push({code:"too_big",maximum:n.length,inclusive:!0,input:i,inst:e,origin:"array"})}let u=new Array(n.length);for(let l=0;l<n.length;l++){let d=n[l]._zod.run({value:i[l],issues:[]},o);d instanceof Promise?s.push(d.then(p=>{u[l]=p})):u[l]=d}if(t.rest){let l=n.length-1,d=i.slice(n.length);for(let p of d){l++;let m=t.rest._zod.run({value:p,issues:[]},o);m instanceof Promise?s.push(m.then(w=>fc(w,r,l))):fc(m,r,l)}}return s.length?Promise.all(s).then(()=>pc(u,r,n,i,c)):pc(u,r,n,i,c)}});function dc(e,t){for(let n=e.length-1;n>=0;n--)if(e[n]._zod[t]!=="optional")return n+1;return 0}function fc(e,t,n){e.issues.length&&t.issues.push(...je(n,e.issues)),t.value[n]=e.value}function pc(e,t,n,r,o){for(let i=0;i<n.length;i++){let s=e[i],a=i<r.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...je(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=r.length&&(n[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}var Tc=I("$ZodRecord",(e,t)=>{se.init(e,t),e._zod.parse=(n,r)=>{let o=n.value;if(!Dn(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:e}),n;let i=[],s=t.keyType._zod.values;if(s){n.value={};let a=new Set;for(let u of s)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){a.add(typeof u=="number"?u.toString():u);let l=t.keyType._zod.run({value:u,issues:[]},r);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(l.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>nt(m,r,tt())),input:u,path:[u],inst:e});continue}let d=l.value,p=t.valueType._zod.run({value:o[u],issues:[]},r);p instanceof Promise?i.push(p.then(m=>{m.issues.length&&n.issues.push(...je(u,m.issues)),n.value[d]=m.value})):(p.issues.length&&n.issues.push(...je(u,p.issues)),n.value[d]=p.value)}let c;for(let u in o)a.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:e,keys:c})}else{n.value={};for(let a of Reflect.ownKeys(o)){if(a==="__proto__"||!Object.prototype.propertyIsEnumerable.call(o,a))continue;let c=t.keyType._zod.run({value:a,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&Ai.test(a)&&c.issues.length){let d=t.keyType._zod.run({value:Number(a),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(c=d)}if(c.issues.length){t.mode==="loose"?n.value[a]=o[a]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(d=>nt(d,r,tt())),input:a,path:[a],inst:e});continue}let l=t.valueType._zod.run({value:o[a],issues:[]},r);l instanceof Promise?i.push(l.then(d=>{d.issues.length&&n.issues.push(...je(a,d.issues)),n.value[c.value]=d.value})):(l.issues.length&&n.issues.push(...je(a,l.issues)),n.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}});var Pc=I("$ZodEnum",(e,t)=>{se.init(e,t);let n=Za(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(o=>Ga.has(typeof o)).map(o=>typeof o=="string"?vi(o):o.toString()).join("|")})$`),e._zod.parse=(o,i)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}});function hc(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var kc=I("$ZodOptional",(e,t)=>{se.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(`^(${$r(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){let o=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>hc(s,o)):hc(i,o)}return n.value===void 0?n:t.innerType._zod.run(n,r)}});var Oc=I("$ZodNullable",(e,t)=>{se.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(`^(${$r(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 zc=I("$ZodCustom",(e,t)=>{St.init(e,t),se.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=>mc(i,n,r,e));mc(o,n,r,e)}});function mc(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(Si(o))}}function Ic(e,t){return new e({type:"string",...oe(t)})}function $c(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 Dc(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...oe(t)})}function Uc(e,t){return new e({type:"boolean",...oe(t)})}function Mc(e,t){return new e({type:"undefined",...oe(t)})}function Nc(e){return new e({type:"unknown"})}function Lc(e,t){return new e({type:"never",...oe(t)})}function zi(e,t){return new rc({check:"greater_than",...oe(t),value:e,inclusive:!0})}function At(e){return zi(0,e)}function Bc(e,t,n){let r=oe(n);return r.abort??(r.abort=!0),new e({type:"custom",check:"custom",fn:t,...r})}var le=I("ZodMiniType",(e,t)=>{if(!e._zod)throw new Error("Uninitialized schema in ZodMiniType.");se.init(e,t),e.def=t,e.type=t.type,e.parse=(n,r)=>Dr(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>Mn(e,n,r),e.parseAsync=async(n,r)=>Ur(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>Nn(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)=>Cr(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.apply=n=>n(e)}),Zc=I("ZodMiniString",(e,t)=>{Pi.init(e,t),le.init(e,t)});function B(e){return Ic(Zc,e)}var ep=I("ZodMiniStringFormat",(e,t)=>{ki.init(e,t),Zc.init(e,t)});var tp=I("ZodMiniURL",(e,t)=>{gc.init(e,t),ep.init(e,t)});function Z(e){return $c(tp,e)}var Fc=I("ZodMiniNumber",(e,t)=>{Oi.init(e,t),le.init(e,t)});function Hc(e){return Cc(Fc,e)}var np=I("ZodMiniNumberFormat",(e,t)=>{yc.init(e,t),Fc.init(e,t)});function qt(e){return Dc(np,e)}var rp=I("ZodMiniBoolean",(e,t)=>{wc.init(e,t),le.init(e,t)});function Ii(e){return Uc(rp,e)}var op=I("ZodMiniUndefined",(e,t)=>{_c.init(e,t),le.init(e,t)});function Gc(e){return Mc(op,e)}var ip=I("ZodMiniUnknown",(e,t)=>{bc.init(e,t),le.init(e,t)});function sp(){return Nc(ip)}var ap=I("ZodMiniNever",(e,t)=>{xc.init(e,t),le.init(e,t)});function cp(e){return Lc(ap,e)}var up=I("ZodMiniArray",(e,t)=>{Ec.init(e,t),le.init(e,t)});function J(e,t){return new up({type:"array",element:e,...oe(t)})}var $i=I("ZodMiniObject",(e,t)=>{vc.init(e,t),le.init(e,t),fe(e,"shape",()=>t.shape)});function be(e,t){let n={type:"object",shape:e??{},...oe(t)};return new $i(n)}function xe(e,t){return new $i({type:"object",shape:e,catchall:cp(),...oe(t)})}function me(e,t){return new $i({type:"object",shape:e,catchall:sp(),...oe(t)})}function rt(e,t){return Ka(e,t)}var lp=I("ZodMiniUnion",(e,t)=>{Sc.init(e,t),le.init(e,t)});function ft(e,t){return new lp({type:"union",options:e,...oe(t)})}var dp=I("ZodMiniIntersection",(e,t)=>{Ac.init(e,t),le.init(e,t)});function qc(e,t){return new dp({type:"intersection",left:e,right:t})}var fp=I("ZodMiniTuple",(e,t)=>{Rc.init(e,t),le.init(e,t)});function pe(e,t,n){let r=t instanceof se,o=r?n:t,i=r?t:null;return new fp({type:"tuple",items:e,rest:i,...oe(o)})}var jc=I("ZodMiniRecord",(e,t)=>{Tc.init(e,t),le.init(e,t)});function Jc(e,t,n){return!t||!t._zod?new jc({type:"record",keyType:B(),valueType:e,...oe(t)}):new jc({type:"record",keyType:e,valueType:t,...oe(n)})}var pp=I("ZodMiniEnum",(e,t)=>{Pc.init(e,t),le.init(e,t),e.options=Object.values(t.entries)});function Kc(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new pp({type:"enum",entries:n,...oe(t)})}var hp=I("ZodMiniOptional",(e,t)=>{kc.init(e,t),le.init(e,t)});function ee(e){return new hp({type:"optional",innerType:e})}var mp=I("ZodMiniNullable",(e,t)=>{Oc.init(e,t),le.init(e,t)});function Ze(e){return new mp({type:"nullable",innerType:e})}var gp=I("ZodMiniCustom",(e,t)=>{zc.init(e,t),le.init(e,t)});function Rt(e,t){return Bc(gp,e??(()=>!0),t)}function Jt(e,t={}){let n=Rt(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 Wc=me({value:me({}),channels:J(B()),allowed:ee(Ze(J(Z())))}),yE=rt(Wc,{url:Z(),actor:Z()}),Vc=ft([me({url:Z()}),Z()]),Kt=me({actor:Z()}),Nr=ee(Ze(Kt)),Xc=me({data:Jt(Blob),allowed:ee(Ze(J(Z())))}),wE=rt(Xc,{actor:Z()}),wp=me({types:ee(J(B())),maxBytes:ee(qt().check(At()))}),Lr=class{constructor(t){this.graffiti=t,this.sessionEvents=this.graffiti.sessionEvents}sessionEvents;login=(...t)=>{let n=pe([ee(Z())]).parse(t);return this.graffiti.login(...n)};logout=(...t)=>{let n=pe([Kt]).parse(t);return this.graffiti.logout(...n)};handleToActor=(...t)=>{let n=pe([B()]).parse(t);return this.graffiti.handleToActor(...n)};actorToHandle=(...t)=>{let n=pe([Z()]).parse(t);return this.graffiti.actorToHandle(...n)};post=(...t)=>{let n=pe([Wc,Kt]).parse(t);return this.graffiti.post(...n)};get=(...t)=>{let n=pe([Vc,me({}),Nr]).parse(t);return this.graffiti.get(n[0],n[1],n[2])};delete=(...t)=>{let n=pe([Vc,Kt]).parse(t);return this.graffiti.delete(...n)};postMedia=(...t)=>{let n=pe([Xc,Kt]).parse(t);return this.graffiti.postMedia(...n)};getMedia=(...t)=>{let n=pe([Z(),wp,Nr]).parse(t);return this.graffiti.getMedia(...n)};deleteMedia=(...t)=>{let n=pe([Z(),Kt]).parse(t);return this.graffiti.deleteMedia(...n)};discover=(...t)=>{let n=pe([J(B()),me({}),Nr]).parse(t);return this.graffiti.discover(n[0],n[1],n[2])};continueDiscover=(...t)=>{let n=pe([B(),Nr]).parse(t);return this.graffiti.continueDiscover(...n)}};function _p(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Br(e,t=""){if(typeof e!="number"){let n=t&&`"${t}" `;throw new TypeError(`${n}expected number, got ${typeof e}`)}if(!Number.isSafeInteger(e)||e<0){let n=t&&`"${t}" `;throw new RangeError(`${n}expected integer >= 0, got ${e}`)}}function jr(e,t,n=""){let r=_p(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):new TypeError(u)}return e}function Yc(e){if(typeof e!="function"||typeof e.create!="function")throw new TypeError("Hash must wrapped by utils.createHasher");if(Br(e.outputLen),Br(e.blockLen),e.outputLen<1)throw new Error('"outputLen" must be >= 1');if(e.blockLen<1)throw new Error('"blockLen" must be >= 1')}function Tt(e=32){Br(e,"bytesLength");let t=typeof globalThis=="object"?globalThis.crypto:null;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(e>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}var bp=["Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","Tagged"];function Ci(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=xp(e);return n||"Object"}function xp(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(bp.includes(t))return t}var y=class{constructor(t,n,r){this.major=t,this.majorEncoded=t<<5,this.name=n,this.terminal=r}toString(){return`Type[${this.major}].${this.name}`}compare(t){return this.major<t.major?-1:this.major>t.major?1:0}static equals(t,n){return t===n||t.major===n.major&&t.name===n.name}};y.uint=new y(0,"uint",!0);y.negint=new y(1,"negint",!0);y.bytes=new y(2,"bytes",!0);y.string=new y(3,"string",!0);y.array=new y(4,"array",!1);y.map=new y(5,"map",!1);y.tag=new y(6,"tag",!1);y.float=new y(7,"float",!0);y.false=new y(7,"false",!0);y.true=new y(7,"true",!0);y.null=new y(7,"null",!0);y.undefined=new y(7,"undefined",!0);y.break=new y(7,"break",!0);var T=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 Ln=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer=="function",Ep=new TextEncoder;function Zr(e){return Ln&&globalThis.Buffer.isBuffer(e)}function Bn(e){return e instanceof Uint8Array?Zr(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var vp=24,Sp=200,Fr=Ln?e=>e.length>=vp?globalThis.Buffer.from(e):Qc(e):e=>e.length>=Sp?Ep.encode(e):Qc(e),Fe=e=>Uint8Array.from(e),eu=Ln?(e,t,n)=>Zr(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),tu=Ln?(e,t)=>(e=e.map(n=>n instanceof Uint8Array?n:globalThis.Buffer.from(n)),Bn(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},nu=Ln?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function Hr(e,t){if(Zr(e)&&Zr(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 Qc(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 Ap=256,jn=class{constructor(t=Ap){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=nu(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=eu(r,0,this.cursor)}else n=tu(this.chunks,this.cursor);return t&&this.reset(),n}},Gr=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 z="CBOR decode error:",qr="CBOR encode error:",Zn=[];Zn[23]=1;Zn[24]=2;Zn[25]=3;Zn[26]=5;Zn[27]=9;function ot(e,t,n){if(e.length-t<n)throw new Error(`${z} not enough data for type`)}var ae=[24,256,65536,4294967296,BigInt("18446744073709551616")];function Ee(e,t,n){ot(e,t,1);let r=e[t];if(n.strict===!0&&r<ae[0])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return r}function ve(e,t,n){ot(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<ae[1])throw new Error(`${z} integer encoded in more bytes than necessary (strict decode)`);return r}function Se(e,t,n){ot(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(`${z} integer encoded in more bytes than necessary (strict decode)`);return r}function Ae(e,t,n){ot(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(`${z} 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(`${z} integers outside of the safe integer range are not supported`)}function ru(e,t,n,r){return new T(y.uint,Ee(e,t+1,r),2)}function ou(e,t,n,r){return new T(y.uint,ve(e,t+1,r),3)}function iu(e,t,n,r){return new T(y.uint,Se(e,t+1,r),5)}function su(e,t,n,r){return new T(y.uint,Ae(e,t+1,r),9)}function Oe(e,t){return X(e,0,t.value)}function X(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)),s=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]=s&255,s=s>>8,o[3]=s&255,s=s>>8,o[2]=s&255,s=s>>8,o[1]=s&255,e.push(o)}else throw new Error(`${z} encountered BigInt larger than allowable range`)}}Oe.encodedSize=function(t){return X.encodedSize(t.value)};X.encodedSize=function(t){return t<ae[0]?1:t<ae[1]?2:t<ae[2]?3:t<ae[3]?5:9};Oe.compareTokens=function(t,n){return t.value<n.value?-1:t.value>n.value?1:0};function au(e,t,n,r){return new T(y.negint,-1-Ee(e,t+1,r),2)}function cu(e,t,n,r){return new T(y.negint,-1-ve(e,t+1,r),3)}function uu(e,t,n,r){return new T(y.negint,-1-Se(e,t+1,r),5)}var Di=BigInt(-1),lu=BigInt(1);function du(e,t,n,r){let o=Ae(e,t+1,r);if(typeof o!="bigint"){let i=-1-o;if(i>=Number.MIN_SAFE_INTEGER)return new T(y.negint,i,9)}if(r.allowBigInt!==!0)throw new Error(`${z} integers outside of the safe integer range are not supported`);return new T(y.negint,Di-BigInt(o),9)}function Jr(e,t){let n=t.value,r=typeof n=="bigint"?n*Di-lu:n*-1-1;X(e,t.type.majorEncoded,r)}Jr.encodedSize=function(t){let n=t.value,r=typeof n=="bigint"?n*Di-lu:n*-1-1;return r<ae[0]?1:r<ae[1]?2:r<ae[2]?3:r<ae[3]?5:9};Jr.compareTokens=function(t,n){return t.value<n.value?1:t.value>n.value?-1:0};function Fn(e,t,n,r){ot(e,t,n+r);let o=e.slice(t+n,t+n+r);return new T(y.bytes,o,n+r)}function fu(e,t,n,r){return Fn(e,t,1,n)}function pu(e,t,n,r){return Fn(e,t,2,Ee(e,t+1,r))}function hu(e,t,n,r){return Fn(e,t,3,ve(e,t+1,r))}function mu(e,t,n,r){return Fn(e,t,5,Se(e,t+1,r))}function gu(e,t,n,r){let o=Ae(e,t+1,r);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer bytes lengths not supported`);return Fn(e,t,9,o)}function Kr(e){return e.encodedBytes===void 0&&(e.encodedBytes=y.equals(e.type,y.string)?Fr(e.value):e.value),e.encodedBytes}function Vt(e,t){let n=Kr(t);X(e,t.type.majorEncoded,n.length),e.push(n)}Vt.encodedSize=function(t){let n=Kr(t);return X.encodedSize(n.length)+n.length};Vt.compareTokens=function(t,n){return Tp(Kr(t),Kr(n))};function Tp(e,t){return e.length<t.length?-1:e.length>t.length?1:Hr(e,t)}var yu=new TextDecoder,kp=32;function Op(e,t,n){if(n-t<kp){let o="";for(let i=t;i<n;i++){let s=e[i];if(s&128)return yu.decode(e.subarray(t,n));o+=String.fromCharCode(s)}return o}return yu.decode(e.subarray(t,n))}function Hn(e,t,n,r,o){let i=n+r;ot(e,t,i);let s=new T(y.string,Op(e,t+n,t+i),i);return o.retainStringBytes===!0&&(s.byteValue=e.slice(t+n,t+i)),s}function wu(e,t,n,r){return Hn(e,t,1,n,r)}function _u(e,t,n,r){return Hn(e,t,2,Ee(e,t+1,r),r)}function bu(e,t,n,r){return Hn(e,t,3,ve(e,t+1,r),r)}function xu(e,t,n,r){return Hn(e,t,5,Se(e,t+1,r),r)}function Eu(e,t,n,r){let o=Ae(e,t+1,r);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer string lengths not supported`);return Hn(e,t,9,o,r)}var vu=Vt;function Wt(e,t,n,r){return new T(y.array,r,n)}function Su(e,t,n,r){return Wt(e,t,1,n)}function Au(e,t,n,r){return Wt(e,t,2,Ee(e,t+1,r))}function Ru(e,t,n,r){return Wt(e,t,3,ve(e,t+1,r))}function Tu(e,t,n,r){return Wt(e,t,5,Se(e,t+1,r))}function Pu(e,t,n,r){let o=Ae(e,t+1,r);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer array lengths not supported`);return Wt(e,t,9,o)}function ku(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Wt(e,t,1,1/0)}function Vr(e,t){X(e,y.array.majorEncoded,t.value)}Vr.compareTokens=Oe.compareTokens;Vr.encodedSize=function(t){return X.encodedSize(t.value)};function Xt(e,t,n,r){return new T(y.map,r,n)}function Ou(e,t,n,r){return Xt(e,t,1,n)}function zu(e,t,n,r){return Xt(e,t,2,Ee(e,t+1,r))}function Iu(e,t,n,r){return Xt(e,t,3,ve(e,t+1,r))}function $u(e,t,n,r){return Xt(e,t,5,Se(e,t+1,r))}function Cu(e,t,n,r){let o=Ae(e,t+1,r);if(typeof o=="bigint")throw new Error(`${z} 64-bit integer map lengths not supported`);return Xt(e,t,9,o)}function Du(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return Xt(e,t,1,1/0)}function Wr(e,t){X(e,y.map.majorEncoded,t.value)}Wr.compareTokens=Oe.compareTokens;Wr.encodedSize=function(t){return X.encodedSize(t.value)};function Uu(e,t,n,r){return new T(y.tag,n,1)}function Mu(e,t,n,r){return new T(y.tag,Ee(e,t+1,r),2)}function Nu(e,t,n,r){return new T(y.tag,ve(e,t+1,r),3)}function Lu(e,t,n,r){return new T(y.tag,Se(e,t+1,r),5)}function Bu(e,t,n,r){return new T(y.tag,Ae(e,t+1,r),9)}function Xr(e,t){X(e,y.tag.majorEncoded,t.value)}Xr.compareTokens=Oe.compareTokens;Xr.encodedSize=function(t){return X.encodedSize(t.value)};var Ui=20,Mi=21,Ni=22,Li=23;function ju(e,t,n,r){if(r.allowUndefined===!1)throw new Error(`${z} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new T(y.null,null,1):new T(y.undefined,void 0,1)}function Zu(e,t,n,r){if(r.allowIndefinite===!1)throw new Error(`${z} indefinite length items not allowed`);return new T(y.break,void 0,1)}function Bi(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw new Error(`${z} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw new Error(`${z} Infinity values are not supported`)}return new T(y.float,e,t)}function Fu(e,t,n,r){return Bi(ji(e,t+1),3,r)}function Hu(e,t,n,r){return Bi(Zi(e,t+1),5,r)}function Gu(e,t,n,r){return Bi(Vu(e,t+1),9,r)}function Gn(e,t,n){let r=t.value;if(r===!1)e.push([y.float.majorEncoded|Ui]);else if(r===!0)e.push([y.float.majorEncoded|Mi]);else if(r===null)e.push([y.float.majorEncoded|Ni]);else if(r===void 0)e.push([y.float.majorEncoded|Li]);else{let o,i=!1;(!n||n.float64!==!0)&&(Ju(r),o=ji(De,1),r===o||Number.isNaN(r)?(De[0]=249,e.push(De.slice(0,3)),i=!0):(Ku(r),o=Zi(De,1),r===o&&(De[0]=250,e.push(De.slice(0,5)),i=!0))),i||(Dp(r),o=Vu(De,1),De[0]=251,e.push(De.slice(0,9)))}}Gn.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){Ju(r);let o=ji(De,1);if(r===o||Number.isNaN(r))return 3;if(Ku(r),o=Zi(De,1),r===o)return 5}return 9};var qu=new ArrayBuffer(9),ze=new DataView(qu,1),De=new Uint8Array(qu,0);function Ju(e){if(e===1/0)ze.setUint16(0,31744,!1);else if(e===-1/0)ze.setUint16(0,64512,!1);else if(Number.isNaN(e))ze.setUint16(0,32256,!1);else{ze.setFloat32(0,e);let t=ze.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)ze.setUint16(0,31744,!1);else if(n===0)ze.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let o=n-127;o<-24?ze.setUint16(0,0):o<-14?ze.setUint16(0,(t&2147483648)>>16|1<<24+o,!1):ze.setUint16(0,(t&2147483648)>>16|o+15<<10|r>>13,!1)}}}function ji(e,t){if(e.length-t<2)throw new Error(`${z} 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 Ku(e){ze.setFloat32(0,e,!1)}function Zi(e,t){if(e.length-t<4)throw new Error(`${z} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function Dp(e){ze.setFloat64(0,e,!1)}function Vu(e,t){if(e.length-t<8)throw new Error(`${z} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}Gn.compareTokens=Oe.compareTokens;function j(e,t,n){throw new Error(`${z} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Yr(e){return()=>{throw new Error(`${z} ${e}`)}}var R=[];for(let e=0;e<=23;e++)R[e]=j;R[24]=ru;R[25]=ou;R[26]=iu;R[27]=su;R[28]=j;R[29]=j;R[30]=j;R[31]=j;for(let e=32;e<=55;e++)R[e]=j;R[56]=au;R[57]=cu;R[58]=uu;R[59]=du;R[60]=j;R[61]=j;R[62]=j;R[63]=j;for(let e=64;e<=87;e++)R[e]=fu;R[88]=pu;R[89]=hu;R[90]=mu;R[91]=gu;R[92]=j;R[93]=j;R[94]=j;R[95]=Yr("indefinite length bytes/strings are not supported");for(let e=96;e<=119;e++)R[e]=wu;R[120]=_u;R[121]=bu;R[122]=xu;R[123]=Eu;R[124]=j;R[125]=j;R[126]=j;R[127]=Yr("indefinite length bytes/strings are not supported");for(let e=128;e<=151;e++)R[e]=Su;R[152]=Au;R[153]=Ru;R[154]=Tu;R[155]=Pu;R[156]=j;R[157]=j;R[158]=j;R[159]=ku;for(let e=160;e<=183;e++)R[e]=Ou;R[184]=zu;R[185]=Iu;R[186]=$u;R[187]=Cu;R[188]=j;R[189]=j;R[190]=j;R[191]=Du;for(let e=192;e<=215;e++)R[e]=Uu;R[216]=Mu;R[217]=Nu;R[218]=Lu;R[219]=Bu;R[220]=j;R[221]=j;R[222]=j;R[223]=j;for(let e=224;e<=243;e++)R[e]=Yr("simple values are not supported");R[244]=j;R[245]=j;R[246]=j;R[247]=ju;R[248]=Yr("simple values are not supported");R[249]=Fu;R[250]=Hu;R[251]=Gu;R[252]=j;R[253]=j;R[254]=j;R[255]=Zu;var Ue=[];for(let e=0;e<24;e++)Ue[e]=new T(y.uint,e,1);for(let e=-1;e>=-24;e--)Ue[31-e]=new T(y.negint,e,1);Ue[64]=new T(y.bytes,new Uint8Array(0),1);Ue[96]=new T(y.string,"",1);Ue[128]=new T(y.array,0,1);Ue[160]=new T(y.map,0,1);Ue[244]=new T(y.false,!1,1);Ue[245]=new T(y.true,!0,1);Ue[246]=new T(y.null,null,1);function Fi(e){switch(e.type){case y.false:return Fe([244]);case y.true:return Fe([245]);case y.null:return Fe([246]);case y.bytes:return e.value.length?void 0:Fe([64]);case y.string:return e.value===""?Fe([96]):void 0;case y.array:return e.value===0?Fe([128]):void 0;case y.map:return e.value===0?Fe([160]):void 0;case y.uint:return e.value<24?Fe([Number(e.value)]):void 0;case y.negint:if(e.value>=-24)return Fe([31-Number(e.value)])}}var Mp={float64:!1,mapSorter:Bp,quickEncodeToken:Fi},el=Object.freeze({mapSorter:jp,quickEncodeToken:Fi});function Np(){let e=[];return e[y.uint.major]=Oe,e[y.negint.major]=Jr,e[y.bytes.major]=Vt,e[y.string.major]=vu,e[y.array.major]=Vr,e[y.map.major]=Wr,e[y.tag.major]=Xr,e[y.float.major]=Gn,e}var Qt=Np(),Qr=new jn,Jn=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(`${qr} object contains circular references`);return new e(n,t)}},pt={null:new T(y.null,null),undefined:new T(y.undefined,void 0),true:new T(y.true,!0),false:new T(y.false,!1),emptyArray:new T(y.array,0),emptyMap:new T(y.map,0)},He={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new T(y.float,e):e>=0?new T(y.uint,e):new T(y.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new T(y.uint,e):new T(y.negint,e)},Uint8Array(e,t,n,r){return new T(y.bytes,e)},string(e,t,n,r){return new T(y.string,e)},boolean(e,t,n,r){return e?pt.true:pt.false},null(e,t,n,r){return pt.null},undefined(e,t,n,r){return pt.undefined},ArrayBuffer(e,t,n,r){return new T(y.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new T(y.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[pt.emptyArray,new T(y.break)]:pt.emptyArray;r=Jn.createCheck(r,e);let o=[],i=0;for(let s of e)o[i++]=Yt(s,n,r);return n.addBreakTokens?[new T(y.array,e.length),o,new T(y.break)]:[new T(y.array,e.length),o]},Object(e,t,n,r){let o=t!=="Object",i=o?e.keys():Object.keys(e),s=o?e.size:i.length,a;if(s){a=new Array(s),r=Jn.createCheck(r,e);let c=!o&&n.ignoreUndefinedProperties,u=0;for(let l of i){let d=o?e.get(l):e[l];c&&d===void 0||(a[u++]=[Yt(l,n,r),Yt(d,n,r)])}u<s&&(a.length=u)}return a?.length?(Lp(a,n),n.addBreakTokens?[new T(y.map,a.length),a,new T(y.break)]:[new T(y.map,a.length),a]):n.addBreakTokens===!0?[pt.emptyMap,new T(y.break)]:pt.emptyMap},Tagged(e,t,n,r){return[new T(y.tag,e.tag),Yt(e.value,n,r)]}};He.Map=He.Object;He.Buffer=He.Uint8Array;for(let e of"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" "))He[`${e}Array`]=He.DataView;function Yt(e,t={},n){let r=Ci(e),o=t&&t.typeEncoders&&t.typeEncoders[r]||He[r];if(typeof o=="function"){let s=o(e,r,t,n);if(s!=null)return s}let i=He[r];if(!i)throw new Error(`${qr} unsupported type: ${r}`);return i(e,r,t,n)}function Lp(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=Qt[o].compareTokens(n,r);return i===0&&console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"),i}function jp(e,t){if(e[0]instanceof T&&t[0]instanceof T){let n=e[0],r=t[0];return n._keyBytes||(n._keyBytes=Wu(n.value)),r._keyBytes||(r._keyBytes=Wu(r.value)),Hr(n._keyBytes,r._keyBytes)}throw new Error("rfc8949MapSorter: complex key types are not supported yet")}function Wu(e){return nl(e,Qt,el)}function qn(e,t,n,r){if(Array.isArray(t))for(let o of t)qn(e,o,n,r);else n[t.type.major](e,t,r)}var Xu=y.uint.majorEncoded,Yu=y.negint.majorEncoded,Zp=y.bytes.majorEncoded,Fp=y.string.majorEncoded,Qu=y.array.majorEncoded,Hp=y.float.majorEncoded|Ui,Gp=y.float.majorEncoded|Mi,qp=y.float.majorEncoded|Ni,Jp=y.float.majorEncoded|Li,Kp=BigInt(-1),Vp=BigInt(1);function Wp(e){return e.addBreakTokens!==!0}function tl(e,t,n,r){let o=Ci(t),i=n.typeEncoders&&n.typeEncoders[o];if(i){let s=i(t,o,n,r);if(s!=null){qn(e,s,Qt,n);return}}switch(o){case"null":e.push([qp]);return;case"undefined":e.push([Jp]);return;case"boolean":e.push([t?Gp:Hp]);return;case"number":!Number.isInteger(t)||!Number.isSafeInteger(t)?Gn(e,new T(y.float,t),n):t>=0?X(e,Xu,t):X(e,Yu,t*-1-1);return;case"bigint":t>=BigInt(0)?X(e,Xu,t):X(e,Yu,t*Kp-Vp);return;case"string":{let s=Fr(t);X(e,Fp,s.length),e.push(s);return}case"Uint8Array":X(e,Zp,t.length),e.push(t);return;case"Array":if(!t.length){e.push([Qu]);return}r=Jn.createCheck(r,t),X(e,Qu,t.length);for(let s of t)tl(e,s,n,r);return;case"Object":case"Map":{let s=He.Object(t,o,n,r);qn(e,s,Qt,n)}return;default:{let s=He[o];if(!s)throw new Error(`${qr} unsupported type: ${o}`);let a=s(t,o,n,r);qn(e,a,Qt,n)}}}function nl(e,t,n,r){let o=r instanceof Uint8Array,i=o?new Gr(r):Qr,s=Yt(e,n);if(!Array.isArray(s)&&n.quickEncodeToken){let a=n.quickEncodeToken(s);if(a)return o?(i.push(a),i.toBytes()):a;let c=t[s.type.major];if(c.encodedSize){let u=c.encodedSize(s,n);if(o||(i=new jn(u)),c(i,s,n),i.chunks.length!==1)throw new Error(`Unexpected error: pre-calculated length for ${s} was wrong`);return o?i.toBytes():Bn(i.chunks[0])}}return i.reset(),qn(i,s,t,n),i.toBytes(!0)}function Hi(e,t){return t=Object.assign({},Mp,t),Wp(t)?(Qr.reset(),tl(Qr,e,t,void 0),Qr.toBytes(!0)):nl(e,Qt,t)}var Xp={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0},eo=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=Ue[t];if(n===void 0){let r=R[t];if(!r)throw new Error(`${z} 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}},ht=Symbol.for("DONE"),en=Symbol.for("BREAK");function Yp(e,t,n){let r=[];for(let o=0;o<e.value;o++){let i=mt(t,n);if(i===en){if(e.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed array`)}if(i===ht)throw new Error(`${z} found array but not enough entries (got ${o}, expected ${e.value})`);r[o]=i}return r}function Qp(e,t,n){let r=n.useMaps===!0,o=n.rejectDuplicateMapKeys===!0,i=r?void 0:{},s=r?new Map:void 0;for(let a=0;a<e.value;a++){let c=mt(t,n);if(c===en){if(e.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed map`)}if(c===ht)throw new Error(`${z} found map but not enough entries (got ${a} [no key], expected ${e.value})`);if(!r&&typeof c!="string")throw new Error(`${z} non-string keys not supported (got ${typeof c})`);if(o&&(r&&s.has(c)||!r&&Object.hasOwn(i,c)))throw new Error(`${z} found repeat map key "${c}"`);let u=mt(t,n);if(u===ht)throw new Error(`${z} found map but not enough entries (got ${a} [no value], expected ${e.value})`);r?s.set(c,u):i[c]=u}return r?s:i}function*eh(e,t,n){for(let r=0;r<e.value;r++){let o=mt(t,n);if(o===en){if(e.value===1/0)break;throw new Error(`${z} got unexpected break to lengthed map`)}if(o===ht)throw new Error(`${z} found map but not enough entries (got ${r} [no key], expected ${e.value})`);let i=mt(t,n);if(i===ht)throw new Error(`${z} found map but not enough entries (got ${r} [no value], expected ${e.value})`);yield[o,i]}}function th(e,t){let n=!1,r=function(){if(n)throw new Error(`${z} tag decode() may only be called once`);n=!0;let o=mt(e,t);if(o===ht)throw new Error(`${z} tag content missing`);if(o===en)throw new Error(`${z} got unexpected break in tag content`);return o};return r.entries=function(){if(n)throw new Error(`${z} tag decode() may only be called once`);n=!0;let o=e.next();if(!y.equals(o.type,y.map))throw new Error(`${z} entries() requires map content, got ${o.type.name}`);let i=[];for(let s of eh(o,e,t))i.push(s);return i},Object.defineProperty(r,"_called",{get(){return n},enumerable:!1}),r}function mt(e,t){if(e.done())return ht;let n=e.next();if(y.equals(n.type,y.break))return en;if(n.type.terminal)return n.value;if(y.equals(n.type,y.array))return Yp(n,e,t);if(y.equals(n.type,y.map))return Qp(n,e,t);if(y.equals(n.type,y.tag)){if(t.tags&&typeof t.tags[n.value]=="function"){let r=th(e,t),o=t.tags[n.value](r);if(!r._called)throw new Error(`${z} tag decoder must call decode() or entries()`);return o}throw new Error(`${z} tag not supported (${n.value})`)}throw new Error("unsupported")}function rl(e,t){if(!(e instanceof Uint8Array))throw new Error(`${z} data to decode must be a Uint8Array`);t=Object.assign({},Xp,t);let n=Bn(e),r=t.tokenizer||new eo(n,t),o=mt(r,t);if(o===ht)throw new Error(`${z} did not find any content to decode`);if(o===en)throw new Error(`${z} got unexpected break`);return[o,e.subarray(r.pos())]}function Gi(e,t){let[n,r]=rl(e,t);if(r.length>0)throw new Error(`${z} too many terminals, data makes no sense`);return n}var to=class e{constructor(t,n){if(typeof t!="number"||!Number.isInteger(t)||t<0)throw new TypeError("Tagged: tag must be a non-negative integer");this.tag=t,this.value=n}static decoder(t){return n=>new e(t,n())}static preserve(...t){let n={};for(let r of t)n[r]=e.decoder(r);return n}};Object.defineProperty(to.prototype,Symbol.toStringTag,{value:"Tagged"});var Tv=new Uint8Array(0);function ol(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 tn(e){if(e instanceof Uint8Array&&e.constructor.name==="Uint8Array")return kt(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return kt(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));throw new Error("Unknown type, must be binary type")}function rh(e){return e?.buffer instanceof ArrayBuffer}function kt(e){return rh(e)?e:e.slice()}function oh(e,t,n){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),o=0;o<r.length;o++)r[o]=255;for(var i=0;i<e.length;i++){var s=e.charAt(i),a=s.charCodeAt(0);if(r[a]!==255)throw new TypeError(s+" is ambiguous");if(r[a]=i,n){var c=s.toLowerCase().charCodeAt(0),u=s.toUpperCase().charCodeAt(0);c!==a&&(r[c]=i),u!==a&&(r[u]=i)}}var l=e.length,d=e.charAt(0),p=Math.log(l)/Math.log(256),m=Math.log(256)/Math.log(l);function w(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var v=0,b=0,S=0,A=g.length;S!==A&&g[S]===0;)S++,v++;for(var O=(A-S)*m+1>>>0,D=new Uint8Array(O);S!==A;){for(var L=g[S],ne=0,H=O-1;(L!==0||ne<b)&&H!==-1;H--,ne++)L+=256*D[H]>>>0,D[H]=L%l>>>0,L=L/l>>>0;if(L!==0)throw new Error("Non-zero carry");b=ne,S++}for(var h=O-b;h!==O&&D[h]===0;)h++;for(var E=d.repeat(v);h<O;++h)E+=e.charAt(D[h]);return E}function x(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var v=0;if(g[v]!==" "){for(var b=0,S=0;g[v]===d;)b++,v++;for(var A=(g.length-v)*p+1>>>0,O=new Uint8Array(A);g[v];){var D=r[g.charCodeAt(v)];if(D===255)return;for(var L=0,ne=A-1;(D!==0||L<S)&&ne!==-1;ne--,L++)D+=l*O[ne]>>>0,O[ne]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");S=L,v++}if(g[v]!==" "){for(var H=A-S;H!==A&&O[H]===0;)H++;for(var h=new Uint8Array(b+(A-H)),E=b;H!==A;)h[E++]=O[H++];return h}}}function _(g){var v=x(g);if(v)return v;throw new Error(`Non-${t} character`)}return{encode:w,decodeUnsafe:x,decode:_}}var ih=oh,sh=ih,il=sh;var qi=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")}},Ji=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 sl(this,t)}},Ki=class{decoders;constructor(t){this.decoders=t}or(t){return sl(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 sl(e,t){return new Ki({...e.decoders??{[e.prefix]:e},...t.decoders??{[t.prefix]:t}})}var Vi=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 qi(t,n,r),this.decoder=new Ji(t,n,o)}encode(t){return this.encoder.encode(t)}decode(t){return this.decoder.decode(t)}};function al({name:e,prefix:t,encode:n,decode:r}){return new Vi(e,t,n,r)}function nn({name:e,prefix:t,alphabet:n,caseInsensitive:r=!1}){let{encode:o,decode:i}=il(n,e,r);return al({prefix:t,name:e,encode:o,decode:s=>tn(i(s))})}function ah(e,t,n,r){let o=e.length;for(;e[o-1]==="=";)--o;let i=new Uint8Array(o*n/8|0),s=0,a=0,c=0;for(let u=0;u<o;++u){let l=t[e[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);a=a<<n|l,s+=n,s>=8&&(s-=8,i[c++]=255&a>>s)}if(s>=n||(255&a<<8-s)!==0)throw new SyntaxError("Unexpected end of data");return i}function ch(e,t,n){let r=t[t.length-1]==="=",o=(1<<n)-1,i="",s=0,a=0;for(let c=0;c<e.length;++c)for(a=a<<8|e[c],s+=8;s>n;)s-=n,i+=t[o&a>>s];if(s!==0&&(i+=t[o&a<<n-s]),r)for(;(i.length*n&7)!==0;)i+="=";return i}function uh(e,t){let n={};for(let r=0;r<e.length;++r)if(n[e[r]]=r,t){let o=e[r].toLowerCase(),i=e[r].toUpperCase();o!==e[r]&&(n[o]=r),i!==e[r]&&(n[i]=r)}return n}function Ge({name:e,prefix:t,bitsPerChar:n,alphabet:r,caseInsensitive:o=!1}){let i=uh(r,o);return al({prefix:t,name:e,encode(s){return ch(s,r,n)},decode(s){return ah(s,i,n,e)}})}var Kn=Ge({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5,caseInsensitive:!0}),Cv=Ge({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5,caseInsensitive:!0}),Dv=Ge({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5,caseInsensitive:!0}),Uv=Ge({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5,caseInsensitive:!0}),Mv=Ge({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5,caseInsensitive:!0}),Nv=Ge({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5,caseInsensitive:!0}),Lv=Ge({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5,caseInsensitive:!0}),Bv=Ge({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5,caseInsensitive:!0}),jv=Ge({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var no=nn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz",caseInsensitive:!0}),Hv=nn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",caseInsensitive:!0});var it=nn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Jv=nn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var lh=ll,cl=128,dh=127,fh=~dh,ph=Math.pow(2,31);function ll(e,t,n){t=t||[],n=n||0;for(var r=n;e>=ph;)t[n++]=e&255|cl,e/=128;for(;e&fh;)t[n++]=e&255|cl,e>>>=7;return t[n]=e|0,ll.bytes=n-r+1,t}var hh=Wi,mh=128,ul=127;function Wi(e,r){var n=0,r=r||0,o=0,i=r,s,a=e.length;do{if(i>=a)throw Wi.bytes=0,new RangeError("Could not decode varint");s=e[i++],n+=o<28?(s&ul)<<o:(s&ul)*Math.pow(2,o),o+=7}while(s>=mh);return Wi.bytes=i-r,n}var gh=Math.pow(2,7),yh=Math.pow(2,14),wh=Math.pow(2,21),_h=Math.pow(2,28),bh=Math.pow(2,35),xh=Math.pow(2,42),Eh=Math.pow(2,49),vh=Math.pow(2,56),Sh=Math.pow(2,63),Ah=function(e){return e<gh?1:e<yh?2:e<wh?3:e<_h?4:e<bh?5:e<xh?6:e<Eh?7:e<vh?8:e<Sh?9:10},Rh={encode:lh,decode:hh,encodingLength:Ah},Th=Rh,Vn=Th;function Wn(e,t=0){return[Vn.decode(e,t),Vn.decode.bytes]}function rn(e,t,n=0){return Vn.encode(e,t,n),t}function on(e){return Vn.encodingLength(e)}function fl(e,t){let n=t.byteLength,r=on(e),o=r+on(n),i=new Uint8Array(o+n);return rn(e,i,0),rn(n,i,r),i.set(t,o),new sn(e,n,t,i)}function pl(e){let t=tn(e),[n,r]=Wn(t),[o,i]=Wn(t.subarray(r)),s=t.subarray(r+i);if(s.byteLength!==o)throw new Error("Incorrect length");return new sn(n,o,s,t)}function hl(e,t){if(e===t)return!0;{let n=t;return e.code===n.code&&e.size===n.size&&n.bytes instanceof Uint8Array&&ol(e.bytes,n.bytes)}}var sn=class{code;size;digest;bytes;constructor(t,n,r,o){this.code=t,this.size=n,this.digest=kt(r),this.bytes=kt(o)}};function ml(e,t){let{bytes:n,version:r}=e;return r===0?Oh(n,Xi(e),t??it.encoder):zh(n,Xi(e),t??Kn.encoder)}var gl=new WeakMap;function Xi(e){let t=gl.get(e);if(t==null){let n=new Map;return gl.set(e,n),n}return t}var Yn=class e{code;version;multihash;bytes;"/";constructor(t,n,r,o){this.code=n,this.version=t,this.multihash=r,this.bytes=kt(o),this["/"]=this.bytes}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!==Xn)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(n.code!==Ih)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=fl(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&&hl(t.multihash,r.multihash)}toString(t){return ml(this,t)}toJSON(){return{"/":ml(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:s}=n;return new e(r,o,i,s??yl(r,o,i.bytes))}else if(n[$h]===!0){let{version:r,multihash:o,code:i}=n,s=pl(o);return e.create(r,i,s)}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!==Xn)throw new Error(`Version 0 CID must use dag-pb (code: ${Xn}) block encoding`);return new e(t,n,r,r.bytes)}case 1:{let o=yl(t,n,r.bytes);return new e(t,n,r,o)}default:throw new Error("Invalid version")}}static createV0(t){return e.create(0,Xn,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=tn(t.subarray(r,r+n.multihashSize));if(o.byteLength!==n.multihashSize)throw new Error("Incorrect length");let i=o.subarray(n.multihashSize-n.digestSize),s=new sn(n.multihashCode,n.digestSize,i,o);return[n.version===0?e.createV0(s):e.createV1(n.codec,s),t.subarray(n.size)]}static inspectBytes(t){let n=0,r=()=>{let[d,p]=Wn(t.subarray(n));return n+=p,d},o=r(),i=Xn;if(o===18?(o=0,n=0):i=r(),o!==0&&o!==1)throw new RangeError(`Invalid CID version ${o}`);let s=n,a=r(),c=r(),u=n+c,l=u-s;return{version:o,codec:i,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(t,n){let[r,o]=kh(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 Xi(i).set(r,t),i}};function kh(e,t){switch(e[0]){case"Q":{let n=t??it;return[it.prefix,n.decode(`${it.prefix}${e}`)]}case it.prefix:{let n=t??it;return[it.prefix,n.decode(e)]}case Kn.prefix:{let n=t??Kn;return[Kn.prefix,n.decode(e)]}case no.prefix:{let n=t??no;return[no.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 Oh(e,t,n){let{prefix:r}=n;if(r!==it.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 zh(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 Xn=112,Ih=18;function yl(e,t,n){let r=on(e),o=r+on(t),i=new Uint8Array(o+n.byteLength);return rn(e,i,0),rn(t,i,r),i.set(n,o),i}var $h=Symbol.for("@ipld/js-cid/CID");var wl=42;function Ch(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}function Dh(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;let t=Yn.asCID(e);if(!t)return null;let n=new Uint8Array(t.bytes.byteLength+1);return n.set(t.bytes,1),[new T(y.tag,wl),new T(y.bytes,n)]}function Uh(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")}function Mh(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 Nh(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 Yi={float64:!0,typeEncoders:{Map:Nh,Object:Dh,undefined:Uh,number:Mh}},iS={...Yi,typeEncoders:{...Yi.typeEncoders}};function Lh(e){let t=e();if(t[0]!==0)throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return Yn.decode(t.subarray(1))}var Qi={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:{[wl]:Lh}},sS={...Qi,tags:{...Qi.tags}};var Re=e=>Hi(e,Yi),qe=e=>Gi(Ch(e),Qi);function Bh(){let e=new Map;return async(t,n)=>{if(t.params&&t.params["no-cache"]==="true")return await n();let r=e.get(t.didUrl);if(r!==void 0)return r;let o=await n();return o.didResolutionMetadata?.error!=="notFound"&&e.set(t.didUrl,o),o}}function jh(e,t){return t()}var Zh="(?:%[0-9a-fA-F]{2})",_l=`(?:[a-zA-Z0-9._-]|${Zh})`,Fh="([a-z0-9]+)",Hh=`((?:${_l}*:)*(${_l}+))`,bl="[a-zA-Z0-9_.:%-]",Gh=`;${bl}+=${bl}*`,qh=`((${Gh})*)`,Jh="(/[^#?]*)?",Kh="([?][^#]*)?",Vh="(#.*)?",Wh=new RegExp(`^did:${Fh}:${Hh}${qh}${Jh}${Kh}${Vh}$`);function Xh(e){if(e===""||!e)return null;let t=e.match(Wh);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 ro={didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};function Yh(e){return async(t,n,r)=>{try{let o=await e(t,n,r);return{...ro,didResolutionMetadata:{contentType:"application/did+ld+json"},didDocument:o}}catch(o){return{...ro,didResolutionMetadata:{error:"notFound",message:o.toString()}}}}}var oo=class{constructor(t={},n={}){this.registry=t,this.cache=n.cache===!0?Bh():n.cache||jh,n.legacyResolvers&&Object.keys(n.legacyResolvers).map(r=>{this.registry[r]||(this.registry[r]=Yh(n.legacyResolvers[r]))})}async resolve(t,n={}){let r=Xh(t);if(r===null)return{...ro,didResolutionMetadata:{error:"invalidDid"}};let o=this.registry[r.method];return o?this.cache(r,()=>o(r.did,r,this,n)):{...ro,didResolutionMetadata:{error:"unsupportedDidMethod"}}}};function Qn(e,t){return function(){return e.apply(t,arguments)}}var{toString:Qh}=Object.prototype,{getPrototypeOf:an}=Object,{iterator:tr,toStringTag:vl}=Symbol,so=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),er=(e,t)=>{let n=e,r=[];for(;n!=null&&n!==Object.prototype;){if(r.indexOf(n)!==-1)return!1;if(r.push(n),so(n,t))return!0;n=an(n)}return!1},em=(e,t)=>e!=null&&er(e,t)?e[t]:void 0,ts=(e=>t=>{let n=Qh.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Me=e=>(e=e.toLowerCase(),t=>ts(t)===e),ao=e=>t=>typeof t===e,{isArray:zt}=Array,cn=ao("undefined");function un(e){return e!==null&&!cn(e)&&e.constructor!==null&&!cn(e.constructor)&&ge(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}var Sl=Me("ArrayBuffer");function tm(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Sl(e.buffer),t}var nm=ao("string"),ge=ao("function"),Al=ao("number"),ln=e=>e!==null&&typeof e=="object",rm=e=>e===!0||e===!1,io=e=>{if(!ln(e))return!1;let t=an(e);return(t===null||t===Object.prototype||an(t)===null)&&!er(e,vl)&&!er(e,tr)},om=e=>{if(!ln(e)||un(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},im=Me("Date"),sm=Me("File"),am=e=>!!(e&&typeof e.uri<"u"),cm=e=>e&&typeof e.getParts<"u",um=Me("Blob"),lm=Me("FileList"),dm=e=>ln(e)&&ge(e.pipe);function fm(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}var xl=fm(),El=typeof xl.FormData<"u"?xl.FormData:void 0,pm=e=>{if(!e)return!1;if(El&&e instanceof El)return!0;let t=an(e);if(!t||t===Object.prototype||!ge(e.append))return!1;let n=ts(e);return n==="formdata"||n==="object"&&ge(e.toString)&&e.toString()==="[object FormData]"},hm=Me("URLSearchParams"),[mm,gm,ym,wm]=["ReadableStream","Request","Response","Headers"].map(Me),_m=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function nr(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),zt(e))for(r=0,o=e.length;r<o;r++)t.call(null,e[r],r,e);else{if(un(e))return;let i=n?Object.getOwnPropertyNames(e):Object.keys(e),s=i.length,a;for(r=0;r<s;r++)a=i[r],t.call(null,e[a],a,e)}}function Rl(e,t){if(un(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 Ot=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tl=e=>!cn(e)&&e!==Ot;function es(...e){let{caseless:t,skipUndefined:n}=Tl(this)&&this||{},r={},o=(i,s)=>{if(s==="__proto__"||s==="constructor"||s==="prototype")return;let a=t&&typeof s=="string"&&Rl(r,s)||s,c=so(r,a)?r[a]:void 0;io(c)&&io(i)?r[a]=es(c,i):io(i)?r[a]=es({},i):zt(i)?r[a]=i.slice():(!n||!cn(i))&&(r[a]=i)};for(let i=0,s=e.length;i<s;i++){let a=e[i];if(!a||un(a)||(nr(a,o),typeof a!="object"||zt(a)))continue;let c=Object.getOwnPropertySymbols(a);for(let u=0;u<c.length;u++){let l=c[u];zm.call(a,l)&&o(a[l],l)}}return r}var bm=(e,t,n,{allOwnKeys:r}={})=>(nr(t,(o,i)=>{n&&ge(o)?Object.defineProperty(e,i,{__proto__:null,value:Qn(o,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:o,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),e),xm=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),Em=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),n&&Object.assign(e.prototype,n)},vm=(e,t,n,r)=>{let o,i,s,a={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!a[s]&&(t[s]=e[s],a[s]=!0);e=n!==!1&&an(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},Sm=(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},Am=e=>{if(!e)return null;if(zt(e))return e;let t=e.length;if(!Al(t))return null;let n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},Rm=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&an(Uint8Array)),Tm=(e,t)=>{let r=(e&&e[tr]).call(e),o;for(;(o=r.next())&&!o.done;){let i=o.value;t.call(e,i[0],i[1])}},Pm=(e,t)=>{let n,r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},km=Me("HTMLFormElement"),Om=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),{propertyIsEnumerable:zm}=Object.prototype,Im=Me("RegExp"),Pl=(e,t)=>{let n=Object.getOwnPropertyDescriptors(e),r={};nr(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},$m=e=>{Pl(e,(t,n)=>{if(ge(e)&&["arguments","caller","callee"].includes(n))return!1;let r=e[n];if(ge(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Cm=(e,t)=>{let n={},r=o=>{o.forEach(i=>{n[i]=!0})};return zt(e)?r(e):r(String(e).split(t)),n},Dm=()=>{},Um=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function Mm(e){return!!(e&&ge(e.append)&&e[vl]==="FormData"&&e[tr])}var Nm=e=>{let t=new WeakSet,n=r=>{if(ln(r)){if(t.has(r))return;if(un(r))return r;if(!("toJSON"in r)){t.add(r);let o=zt(r)?[]:{};return nr(r,(i,s)=>{let a=n(i);!cn(a)&&(o[s]=a)}),t.delete(r),o}}return r};return n(e)},Lm=Me("AsyncFunction"),Bm=e=>e&&(ln(e)||ge(e))&&ge(e.then)&&ge(e.catch),kl=((e,t)=>e?setImmediate:t?((n,r)=>(Ot.addEventListener("message",({source:o,data:i})=>{o===Ot&&i===n&&r.length&&r.shift()()},!1),o=>{r.push(o),Ot.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",ge(Ot.postMessage)),jm=typeof queueMicrotask<"u"?queueMicrotask.bind(Ot):typeof process<"u"&&process.nextTick||kl,Ol=e=>e!=null&&ge(e[tr]),Zm=e=>e!=null&&er(e,tr)&&Ol(e),f={isArray:zt,isArrayBuffer:Sl,isBuffer:un,isFormData:pm,isArrayBufferView:tm,isString:nm,isNumber:Al,isBoolean:rm,isObject:ln,isPlainObject:io,isEmptyObject:om,isReadableStream:mm,isRequest:gm,isResponse:ym,isHeaders:wm,isUndefined:cn,isDate:im,isFile:sm,isReactNativeBlob:am,isReactNative:cm,isBlob:um,isRegExp:Im,isFunction:ge,isStream:dm,isURLSearchParams:hm,isTypedArray:Rm,isFileList:lm,forEach:nr,merge:es,extend:bm,trim:_m,stripBOM:xm,inherits:Em,toFlatObject:vm,kindOf:ts,kindOfTest:Me,endsWith:Sm,toArray:Am,forEachEntry:Tm,matchAll:Pm,isHTMLForm:km,hasOwnProperty:so,hasOwnProp:so,hasOwnInPrototypeChain:er,getSafeProp:em,reduceDescriptors:Pl,freezeMethods:$m,toObjectSet:Cm,toCamelCase:Om,noop:Dm,toFiniteNumber:Um,findKey:Rl,global:Ot,isContextDefined:Tl,isSpecCompliantForm:Mm,toJSONObject:Nm,isAsyncFn:Lm,isThenable:Bm,setImmediate:kl,asap:jm,isIterable:Ol,isSafeIterable:Zm};var Fm=f.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"]),zl=e=>{let t={},n,r,o;return e&&e.split(`
3
+ `).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&Fm[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t};function Hm(e){let t=0,n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(r!==9&&r!==32)break;t+=1}for(;n>t;){let r=e.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return t===0&&n===e.length?e:e.slice(t,n)}var Gm=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),qm=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function ns(e,t){return f.isArray(e)?e.map(n=>ns(n,t)):Hm(String(e).replace(t,""))}var Il=e=>ns(e,Gm),Jm=e=>ns(e,qm);function co(e){let t=Object.create(null);return f.forEach(e.toJSON(),(n,r)=>{t[r]=Jm(n)}),t}var $l=Symbol("internals");function rr(e){return e&&String(e).trim().toLowerCase()}function uo(e){return e===!1||e==null?e:f.isArray(e)?e.map(uo):Il(String(e))}function Km(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 Vm=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function rs(e,t,n,r,o){if(f.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!f.isString(t)){if(f.isString(r))return t.indexOf(r)!==-1;if(f.isRegExp(r))return r.test(t)}}function Wm(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function Xm(e,t){let n=f.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{__proto__:null,value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}var dn=class{constructor(t){t&&this.set(t)}set(t,n,r){let o=this;function i(a,c,u){let l=rr(c);if(!l)return;let d=f.findKey(o,l);(!d||o[d]===void 0||u===!0||u===void 0&&o[d]!==!1)&&(o[d||c]=uo(a))}let s=(a,c)=>f.forEach(a,(u,l)=>i(u,l,c));if(f.isPlainObject(t)||t instanceof this.constructor)s(t,n);else if(f.isString(t)&&(t=t.trim())&&!Vm(t))s(zl(t),n);else if(f.isObject(t)&&f.isSafeIterable(t)){let a=Object.create(null),c,u;for(let l of t){if(!f.isArray(l))throw new TypeError("Object iterator must return a key-value pair");u=l[0],f.hasOwnProp(a,u)?(c=a[u],a[u]=f.isArray(c)?[...c,l[1]]:[c,l[1]]):a[u]=l[1]}s(a,n)}else t!=null&&i(n,t,r);return this}get(t,n){if(t=rr(t),t){let r=f.findKey(this,t);if(r){let o=this[r];if(!n)return o;if(n===!0)return Km(o);if(f.isFunction(n))return n.call(this,o,r);if(f.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=rr(t),t){let r=f.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||rs(this,this[r],r,n)))}return!1}delete(t,n){let r=this,o=!1;function i(s){if(s=rr(s),s){let a=f.findKey(r,s);a&&(!n||rs(r,r[a],a,n))&&(delete r[a],o=!0)}}return f.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||rs(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){let n=this,r={};return f.forEach(this,(o,i)=>{let s=f.findKey(r,i);if(s){n[s]=uo(o),delete n[i];return}let a=t?Wm(i):String(i).trim();a!==i&&delete n[i],n[a]=uo(o),r[a]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){let n=Object.create(null);return f.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&f.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[$l]=this[$l]={accessors:{}}).accessors,o=this.prototype;function i(s){let a=rr(s);r[a]||(Xm(o,s),r[a]=!0)}return f.isArray(t)?t.forEach(i):i(t),this}};dn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);f.reduceDescriptors(dn.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});f.freezeMethods(dn);var te=dn;var Ym="[REDACTED ****]";function Qm(e){if(f.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(f.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}function eg(e,t){let n=new Set(t.map(i=>String(i).toLowerCase())),r=[],o=i=>{if(i===null||typeof i!="object"||f.isBuffer(i))return i;if(r.indexOf(i)!==-1)return;i instanceof te&&(i=i.toJSON()),r.push(i);let s;if(f.isArray(i))s=[],i.forEach((a,c)=>{let u=o(a);f.isUndefined(u)||(s[c]=u)});else{if(!f.isPlainObject(i)&&Qm(i))return r.pop(),i;s=Object.create(null);for(let[a,c]of Object.entries(i)){let u=n.has(a.toLowerCase())?Ym:o(c);f.isUndefined(u)||(s[a]=u)}}return r.pop(),s};return o(e)}var ce=class e extends Error{static from(t,n,r,o,i,s){let a=new e(t.message,n||t.code,r,o,i);return Object.defineProperty(a,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),a.name=t.name,t.status!=null&&a.status==null&&(a.status=t.status),s&&Object.assign(a,s),a}constructor(t,n,r,o,i){super(t),Object.defineProperty(this,"message",{__proto__:null,value:t,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),o&&(this.request=o),i&&(this.response=i,this.status=i.status)}toJSON(){let t=this.config,n=t&&f.hasOwnProp(t,"redact")?t.redact:void 0,r=f.isArray(n)&&n.length>0?eg(t,n):f.toJSONObject(t);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:r,code:this.code,status:this.status}}};ce.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE";ce.ERR_BAD_OPTION="ERR_BAD_OPTION";ce.ECONNABORTED="ECONNABORTED";ce.ETIMEDOUT="ETIMEDOUT";ce.ECONNREFUSED="ECONNREFUSED";ce.ERR_NETWORK="ERR_NETWORK";ce.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS";ce.ERR_DEPRECATED="ERR_DEPRECATED";ce.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE";ce.ERR_BAD_REQUEST="ERR_BAD_REQUEST";ce.ERR_CANCELED="ERR_CANCELED";ce.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT";ce.ERR_INVALID_URL="ERR_INVALID_URL";ce.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var P=ce;var lo=null;var ss=100;function is(e){return f.isPlainObject(e)||f.isArray(e)}function Cl(e){return f.endsWith(e,"[]")?e.slice(0,-2):e}function os(e,t,n){return e?e.concat(t).map(function(o,i){return o=Cl(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function tg(e){return f.isArray(e)&&!e.some(is)}var ng=f.toFlatObject(f,{},null,function(t){return/^is[A-Z]/.test(t)});function rg(e,t,n){if(!f.isObject(e))throw new TypeError("target must be an object");t=t||new(lo||FormData),n=f.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(v,b){return!f.isUndefined(b[v])});let r=n.metaTokens,o=n.visitor||w,i=n.dots,s=n.indexes,a=n.Blob||typeof Blob<"u"&&Blob,c=n.maxDepth===void 0?ss:n.maxDepth,u=a&&f.isSpecCompliantForm(t),l=[];if(!f.isFunction(o))throw new TypeError("visitor must be a function");function d(g){if(g===null)return"";if(f.isDate(g))return g.toISOString();if(f.isBoolean(g))return g.toString();if(!u&&f.isBlob(g))throw new P("Blob is not supported. Use a Buffer instead.");if(f.isArrayBuffer(g)||f.isTypedArray(g)){if(u&&typeof a=="function")return new a([g]);if(typeof Buffer<"u")return Buffer.from(g);throw new P("Blob is not supported. Use a Buffer instead.",P.ERR_NOT_SUPPORT)}return g}function p(g){if(g>c)throw new P("Object is too deeply nested ("+g+" levels). Max depth: "+c,P.ERR_FORM_DATA_DEPTH_EXCEEDED)}function m(g,v){if(c===1/0)return JSON.stringify(g);let b=[];return JSON.stringify(g,function(A,O){if(!f.isObject(O))return O;for(;b.length&&b[b.length-1]!==this;)b.pop();return b.push(O),p(v+b.length-1),O})}function w(g,v,b){let S=g;if(f.isReactNative(t)&&f.isReactNativeBlob(g))return t.append(os(b,v,i),d(g)),!1;if(g&&!b&&typeof g=="object"){if(f.endsWith(v,"{}"))v=r?v:v.slice(0,-2),g=m(g,1);else if(f.isArray(g)&&tg(g)||(f.isFileList(g)||f.endsWith(v,"[]"))&&(S=f.toArray(g)))return v=Cl(v),S.forEach(function(O,D){!(f.isUndefined(O)||O===null)&&t.append(s===!0?os([v],D,i):s===null?v:v+"[]",d(O))}),!1}return is(g)?!0:(t.append(os(b,v,i),d(g)),!1)}let x=Object.assign(ng,{defaultVisitor:w,convertValue:d,isVisitable:is});function _(g,v,b=0){if(!f.isUndefined(g)){if(p(b),l.indexOf(g)!==-1)throw new Error("Circular reference detected in "+v.join("."));l.push(g),f.forEach(g,function(A,O){(!(f.isUndefined(A)||A===null)&&o.call(t,A,f.isString(O)?O.trim():O,v,x))===!0&&_(A,v?v.concat(O):[O],b+1)}),l.pop()}}if(!f.isObject(e))throw new TypeError("data must be an object");return _(e),t}var gt=rg;function Dl(e){let t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,function(r){return t[r]})}function Ul(e,t){this._pairs=[],e&&gt(e,this,t)}var Ml=Ul.prototype;Ml.append=function(t,n){this._pairs.push([t,n])};Ml.toString=function(t){let n=t?r=>t.call(this,r,Dl):Dl;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};var fo=Ul;function og(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function or(e,t,n){if(!t)return e;e=e||"";let r=f.isFunction(n)?{serialize:n}:n,o=f.getSafeProp(r,"encode")||og,i=f.getSafeProp(r,"serialize"),s;if(i?s=i(t,r):s=f.isURLSearchParams(t)?t.toString():new fo(t,r).toString(o),s){let a=e.indexOf("#");a!==-1&&(e=e.slice(0,a)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}var as=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){f.forEach(this.handlers,function(r){r!==null&&t(r)})}},cs=as;var fn={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0};var Nl=typeof URLSearchParams<"u"?URLSearchParams:fo;var Ll=typeof FormData<"u"?FormData:null;var Bl=typeof Blob<"u"?Blob:null;var jl={isBrowser:!0,classes:{URLSearchParams:Nl,FormData:Ll,Blob:Bl},protocols:["http","https","file","blob","url","data"]};var ds={};Mf(ds,{hasBrowserEnv:()=>ls,hasStandardBrowserEnv:()=>ig,hasStandardBrowserWebWorkerEnv:()=>sg,navigator:()=>us,origin:()=>ag});var ls=typeof window<"u"&&typeof document<"u",us=typeof navigator=="object"&&navigator||void 0,ig=ls&&(!us||["ReactNative","NativeScript","NS"].indexOf(us.product)<0),sg=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ag=ls&&window.location.href||"http://localhost";var Y={...ds,...jl};function fs(e,t){return gt(e,new Y.classes.URLSearchParams,{visitor:function(n,r,o,i){return Y.isNode&&f.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}var Zl=ss;function Fl(e){if(e>Zl)throw new P("FormData field is too deeply nested ("+e+" levels). Max depth: "+Zl,P.ERR_FORM_DATA_DEPTH_EXCEEDED)}function cg(e){let t=[],n=/\w+|\[(\w*)]/g,r;for(;(r=n.exec(e))!==null;)Fl(t.length),t.push(r[0]==="[]"?"":r[1]||r[0]);return t}function ug(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 lg(e){function t(n,r,o,i){Fl(i);let s=n[i++];if(s==="__proto__")return!0;let a=Number.isFinite(+s),c=i>=n.length;return s=!s&&f.isArray(o)?o.length:s,c?(f.hasOwnProp(o,s)?o[s]=f.isArray(o[s])?o[s].concat(r):[o[s],r]:o[s]=r,!a):((!f.hasOwnProp(o,s)||!f.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&f.isArray(o[s])&&(o[s]=ug(o[s])),!a)}if(f.isFormData(e)&&f.isFunction(e.entries)){let n={};return f.forEachEntry(e,(r,o)=>{t(cg(r),o,n,0)}),n}return null}var po=lg;var pn=(e,t)=>e!=null&&f.hasOwnProp(e,t)?e[t]:void 0;function dg(e,t,n){if(f.isString(e))try{return(t||JSON.parse)(e),f.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}var ps={transitional:fn,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){let r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=f.isObject(t);if(i&&f.isHTMLForm(t)&&(t=new FormData(t)),f.isFormData(t))return o?JSON.stringify(po(t)):t;if(f.isArrayBuffer(t)||f.isBuffer(t)||f.isStream(t)||f.isFile(t)||f.isBlob(t)||f.isReadableStream(t))return t;if(f.isArrayBufferView(t))return t.buffer;if(f.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let a;if(i){let c=pn(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return fs(t,c).toString();if((a=f.isFileList(t))||r.indexOf("multipart/form-data")>-1){let u=pn(this,"env"),l=u&&u.FormData;return gt(a?{"files[]":t}:t,l&&new l,c)}}return i||o?(n.setContentType("application/json",!1),dg(t)):t}],transformResponse:[function(t){let n=pn(this,"transitional")||ps.transitional,r=n&&n.forcedJSONParsing,o=pn(this,"responseType"),i=o==="json";if(f.isResponse(t)||f.isReadableStream(t))return t;if(t&&f.isString(t)&&(r&&!o||i)){let a=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(t,pn(this,"parseReviver"))}catch(c){if(a)throw c.name==="SyntaxError"?P.from(c,P.ERR_BAD_RESPONSE,this,null,pn(this,"response")):c}}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}}};f.forEach(["delete","get","head","post","put","patch","query"],e=>{ps.headers[e]={}});var hn=ps;function ir(e,t){let n=this||hn,r=t||n,o=te.from(r.headers),i=r.data;return f.forEach(e,function(a){i=a.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function sr(e){return!!(e&&e.__CANCEL__)}var hs=class extends P{constructor(t,n,r){super(t??"canceled",P.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}},Je=hs;function ar(e,t,n){let r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new P("Request failed with status code "+n.status,n.status>=400&&n.status<500?P.ERR_BAD_REQUEST:P.ERR_BAD_RESPONSE,n.config,n.request,n))}function ms(e){let t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}function fg(e,t){e=e||10;let n=new Array(e),r=new Array(e),o=0,i=0,s;return t=t!==void 0?t:1e3,function(c){let u=Date.now(),l=r[i];s||(s=u),n[o]=c,r[o]=u;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),u-s<t)return;let m=l&&u-l;return m?Math.round(p*1e3/m):void 0}}var Hl=fg;function pg(e,t){let n=0,r=1e3/t,o,i,s=(u,l=Date.now())=>{n=l,o=null,i&&(clearTimeout(i),i=null),e(...u)};return[(...u)=>{let l=Date.now(),d=l-n;d>=r?s(u,l):(o=u,i||(i=setTimeout(()=>{i=null,s(o)},r-d)))},()=>o&&s(o)]}var Gl=pg;var mn=(e,t,n=3)=>{let r=0,o=Hl(50,250);return Gl(i=>{if(!i||typeof i.loaded!="number")return;let s=i.loaded,a=i.lengthComputable?i.total:void 0,c=a!=null?Math.min(s,a):s,u=Math.max(0,c-r),l=o(u);r=Math.max(r,c);let d={loaded:c,total:a,progress:a?c/a:void 0,bytes:u,rate:l||void 0,estimated:l&&a?(a-c)/l:void 0,event:i,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(d)},n)},gs=(e,t)=>{let n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},ys=e=>(...t)=>f.asap(()=>e(...t));var ql=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 Jl=Y.hasStandardBrowserEnv?{write(e,t,n,r,o,i,s){if(typeof document>"u")return;let a=[`${e}=${encodeURIComponent(t)}`];f.isNumber(n)&&a.push(`expires=${new Date(n).toUTCString()}`),f.isString(r)&&a.push(`path=${r}`),f.isString(o)&&a.push(`domain=${o}`),i===!0&&a.push("secure"),f.isString(s)&&a.push(`SameSite=${s}`),document.cookie=a.join("; ")},read(e){if(typeof document>"u")return null;let t=document.cookie.split(";");for(let n=0;n<t.length;n++){let r=t[n].replace(/^\s+/,""),o=r.indexOf("=");if(o!==-1&&r.slice(0,o)===e)try{return decodeURIComponent(r.slice(o+1))}catch{return r.slice(o+1)}}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read(){return null},remove(){}};function ws(e){return typeof e!="string"?!1:/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function _s(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}var hg=/^https?:(?!\/\/)/i,mg=/[\t\n\r]/g;function gg(e){let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t)}function yg(e){return gg(e).replace(mg,"")}function Kl(e,t){if(typeof e=="string"&&hg.test(yg(e)))throw new P('Invalid URL: missing "//" after protocol',P.ERR_INVALID_URL,t)}function cr(e,t,n,r){Kl(t,r);let o=!ws(t);return e&&(o||n===!1)?(Kl(e,r),_s(e,t)):t}var Vl=e=>e instanceof te?{...e}:e;function Ne(e,t){e=e||{},t=t||{};let n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(l,d,p,m){return f.isPlainObject(l)&&f.isPlainObject(d)?f.merge.call({caseless:m},l,d):f.isPlainObject(d)?f.merge({},d):f.isArray(d)?d.slice():d}function o(l,d,p,m){if(f.isUndefined(d)){if(!f.isUndefined(l))return r(void 0,l,p,m)}else return r(l,d,p,m)}function i(l,d){if(!f.isUndefined(d))return r(void 0,d)}function s(l,d){if(f.isUndefined(d)){if(!f.isUndefined(l))return r(void 0,l)}else return r(void 0,d)}function a(l){let d=f.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!f.isUndefined(d))if(f.isPlainObject(d)){if(f.hasOwnProp(d,l))return d[l]}else return;let p=f.hasOwnProp(e,"transitional")?e.transitional:void 0;if(f.isPlainObject(p)&&f.hasOwnProp(p,l))return p[l]}function c(l,d,p){if(f.hasOwnProp(t,p))return r(l,d);if(f.hasOwnProp(e,p))return r(void 0,l)}let u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:c,headers:(l,d,p)=>o(Vl(l),Vl(d),p,!0)};return f.forEach(Object.keys({...e,...t}),function(d){if(d==="__proto__"||d==="constructor"||d==="prototype")return;let p=f.hasOwnProp(u,d)?u[d]:o,m=f.hasOwnProp(e,d)?e[d]:void 0,w=f.hasOwnProp(t,d)?t[d]:void 0,x=p(m,w,d);f.isUndefined(x)&&p!==c||(n[d]=x)}),f.hasOwnProp(t,"validateStatus")&&f.isUndefined(t.validateStatus)&&a("validateStatusUndefinedResolves")===!1&&(f.hasOwnProp(e,"validateStatus")?n.validateStatus=r(void 0,e.validateStatus):delete n.validateStatus),n}var wg=["content-type","content-length"];function _g(e,t,n){if(n!=="content-only"){e.set(t);return}Object.entries(t||{}).forEach(([r,o])=>{wg.includes(r.toLowerCase())&&e.set(r,o)})}var bg=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,n)=>String.fromCharCode(parseInt(n,16)));function xg(e){let t=Ne({},e),n=p=>f.hasOwnProp(t,p)?t[p]:void 0,r=n("data"),o=n("withXSRFToken"),i=n("xsrfHeaderName"),s=n("xsrfCookieName"),a=n("headers"),c=n("auth"),u=n("baseURL"),l=n("allowAbsoluteUrls"),d=n("url");if(t.headers=a=te.from(a),t.url=or(cr(u,d,l,t),n("params"),n("paramsSerializer")),c){let p=f.getSafeProp(c,"username")||"",m=f.getSafeProp(c,"password")||"";try{a.set("Authorization","Basic "+btoa(p+":"+(m?bg(m):"")))}catch(w){throw P.from(w,P.ERR_BAD_OPTION_VALUE,e)}}if(f.isFormData(r)&&(Y.hasStandardBrowserEnv||Y.hasStandardBrowserWebWorkerEnv||f.isReactNative(r)?a.setContentType(void 0):f.isFunction(r.getHeaders)&&_g(a,r.getHeaders(),n("formDataHeaderPolicy"))),Y.hasStandardBrowserEnv&&(f.isFunction(o)&&(o=o(t)),o===!0||o==null&&ql(t.url))){let m=i&&s&&Jl.read(s);m&&a.set(i,m)}return t}var ho=xg;var Eg=typeof XMLHttpRequest<"u",Wl=Eg&&function(e){return new Promise(function(n,r){let o=ho(e),i=o.data,s=te.from(o.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:u}=o,l,d,p,m,w;function x(){m&&m(),w&&w(),o.cancelToken&&o.cancelToken.unsubscribe(l),o.signal&&o.signal.removeEventListener("abort",l)}let _=new XMLHttpRequest;_.open(o.method.toUpperCase(),o.url,!0),_.timeout=o.timeout;function g(){if(!_)return;let b=te.from("getAllResponseHeaders"in _&&_.getAllResponseHeaders()),A={data:!a||a==="text"||a==="json"?_.responseText:_.response,status:_.status,statusText:_.statusText,headers:b,config:e,request:_};ar(function(D){n(D),x()},function(D){r(D),x()},A),_=null}"onloadend"in _?_.onloadend=g:_.onreadystatechange=function(){!_||_.readyState!==4||_.status===0&&!(_.responseURL&&_.responseURL.startsWith("file:"))||setTimeout(g)},_.onabort=function(){_&&(r(new P("Request aborted",P.ECONNABORTED,e,_)),x(),_=null)},_.onerror=function(S){let A=S&&S.message?S.message:"Network Error",O=new P(A,P.ERR_NETWORK,e,_);O.event=S||null,r(O),x(),_=null},_.ontimeout=function(){let S=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded",A=o.transitional||fn;o.timeoutErrorMessage&&(S=o.timeoutErrorMessage),r(new P(S,A.clarifyTimeoutError?P.ETIMEDOUT:P.ECONNABORTED,e,_)),x(),_=null},i===void 0&&s.setContentType(null),"setRequestHeader"in _&&f.forEach(co(s),function(S,A){_.setRequestHeader(A,S)}),f.isUndefined(o.withCredentials)||(_.withCredentials=!!o.withCredentials),a&&a!=="json"&&(_.responseType=o.responseType),u&&([p,w]=mn(u,!0),_.addEventListener("progress",p)),c&&_.upload&&([d,m]=mn(c),_.upload.addEventListener("progress",d),_.upload.addEventListener("loadend",m)),(o.cancelToken||o.signal)&&(l=b=>{_&&(r(!b||b.type?new Je(null,e,_):b),_.abort(),x(),_=null)},o.cancelToken&&o.cancelToken.subscribe(l),o.signal&&(o.signal.aborted?l():o.signal.addEventListener("abort",l)));let v=ms(o.url);if(v&&!Y.protocols.includes(v)){r(new P("Unsupported protocol "+v+":",P.ERR_BAD_REQUEST,e)),x();return}_.send(i||null)})};var vg=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;let n=new AbortController,r=!1,o=function(c){if(!r){r=!0,s();let u=c instanceof Error?c:this.reason;n.abort(u instanceof P?u:new Je(u instanceof Error?u.message:u))}},i=t&&setTimeout(()=>{i=null,o(new P(`timeout of ${t}ms exceeded`,P.ETIMEDOUT))},t),s=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),e=null)};e.forEach(c=>c.addEventListener("abort",o,{once:!0}));let{signal:a}=n;return a.unsubscribe=()=>f.asap(s),a},Xl=vg;var Sg=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},Ag=async function*(e,t){for await(let n of Rg(e))yield*Sg(n,t)},Rg=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()}},bs=(e,t,n,r)=>{let o=Ag(e,t),i=0,s,a=c=>{s||(s=!0,r&&r(c))};return new ReadableStream({async pull(c){try{let{done:u,value:l}=await o.next();if(u){a(),c.close();return}let d=l.byteLength;if(n){let p=i+=d;n(p)}c.enqueue(new Uint8Array(l))}catch(u){throw a(u),u}},cancel(c){return a(c),o.return()}},{highWaterMark:2})};var mo=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,Tg=(e,t,n)=>t+2<n&&mo(e.charCodeAt(t+1))&&mo(e.charCodeAt(t+2));function xs(e){if(!e||typeof e!="string"||!e.startsWith("data:"))return 0;let t=e.indexOf(",");if(t<0)return 0;let n=e.slice(5,t),r=e.slice(t+1);if(/;base64/i.test(n)){let s=r.length,a=r.length;for(let m=0;m<a;m++)if(r.charCodeAt(m)===37&&m+2<a){let w=r.charCodeAt(m+1),x=r.charCodeAt(m+2);mo(w)&&mo(x)&&(s-=2,m+=2)}let c=0,u=a-1,l=m=>m>=2&&r.charCodeAt(m-2)===37&&r.charCodeAt(m-1)===51&&(r.charCodeAt(m)===68||r.charCodeAt(m)===100);u>=0&&(r.charCodeAt(u)===61?(c++,u--):l(u)&&(c++,u-=3)),c===1&&u>=0&&(r.charCodeAt(u)===61||l(u))&&c++;let p=Math.floor(s/4)*3-(c||0);return p>0?p:0}let i=0;for(let s=0,a=r.length;s<a;s++){let c=r.charCodeAt(s);if(c===37&&Tg(r,s,a))i+=1,s+=2;else if(c<128)i+=1;else if(c<2048)i+=2;else if(c>=55296&&c<=56319&&s+1<a){let u=r.charCodeAt(s+1);u>=56320&&u<=57343?(i+=4,s++):i+=3}else i+=3}return i}var gn="1.18.1";var Yl=64*1024,{isFunction:go}=f,Pg=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,(t,n)=>String.fromCharCode(parseInt(n,16))),Ql=e=>{if(!f.isString(e))return e;try{return decodeURIComponent(e)}catch{return e}},ed=(e,...t)=>{try{return!!e(...t)}catch{return!1}},kg=e=>{let t=e.indexOf("://"),n=e;return t!==-1&&(n=n.slice(t+3)),n.includes("@")||n.includes(":")},Og=e=>{let t=f.global!==void 0&&f.global!==null?f.global:globalThis,{ReadableStream:n,TextEncoder:r}=t;e=f.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e);let{fetch:o,Request:i,Response:s}=e,a=o?go(o):typeof fetch=="function",c=go(i),u=go(s);if(!a)return!1;let l=a&&go(n),d=a&&(typeof r=="function"?(g=>v=>g.encode(v))(new r):async g=>new Uint8Array(await new i(g).arrayBuffer())),p=c&&l&&ed(()=>{let g=!1,v=new i(Y.origin,{body:new n,method:"POST",get duplex(){return g=!0,"half"}}),b=v.headers.has("Content-Type");return v.body!=null&&v.body.cancel(),g&&!b}),m=u&&l&&ed(()=>f.isReadableStream(new s("").body)),w={stream:m&&(g=>g.body)};a&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!w[g]&&(w[g]=(v,b)=>{let S=v&&v[g];if(S)return S.call(v);throw new P(`Response type '${g}' is not supported`,P.ERR_NOT_SUPPORT,b)})});let x=async g=>{if(g==null)return 0;if(f.isBlob(g))return g.size;if(f.isSpecCompliantForm(g))return(await new i(Y.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(f.isArrayBufferView(g)||f.isArrayBuffer(g))return g.byteLength;if(f.isURLSearchParams(g)&&(g=g+""),f.isString(g))return(await d(g)).byteLength},_=async(g,v)=>{let b=f.toFiniteNumber(g.getContentLength());return b??x(v)};return async g=>{let{url:v,method:b,data:S,signal:A,cancelToken:O,timeout:D,onDownloadProgress:L,onUploadProgress:ne,responseType:H,headers:h,withCredentials:E="same-origin",fetchOptions:C,maxContentLength:N,maxBodyLength:G}=ho(g),M=f.isNumber(N)&&N>-1,ut=f.isNumber(G)&&G>-1,zn=q=>f.hasOwnProp(g,q)?g[q]:void 0,In=o||fetch;H=H?(H+"").toLowerCase():"text";let K=Xl([A,O&&O.toAbortSignal()],D),W=null,xt=K&&K.unsubscribe&&(()=>{K.unsubscribe()}),Zt,$n=null,Ca=()=>new P("Request body larger than maxBodyLength limit",P.ERR_BAD_REQUEST,g,W);try{let q,ke=zn("auth");if(ke){let U=f.getSafeProp(ke,"username")||"",_e=f.getSafeProp(ke,"password")||"";q={username:U,password:_e}}if(kg(v)){let U=new URL(v,Y.origin);if(!q&&(U.username||U.password)){let _e=Ql(U.username),lt=Ql(U.password);q={username:_e,password:lt}}(U.username||U.password)&&(U.username="",U.password="",v=U.href)}if(q&&(h.delete("authorization"),h.set("Authorization","Basic "+btoa(Pg((q.username||"")+":"+(q.password||""))))),M&&typeof v=="string"&&v.startsWith("data:")&&xs(v)>N)throw new P("maxContentLength size of "+N+" exceeded",P.ERR_BAD_RESPONSE,g,W);if(ut&&b!=="get"&&b!=="head"){let U=await x(S);if(typeof U=="number"&&isFinite(U)&&(Zt=U,U>G))throw Ca()}let Tr=ut&&(f.isReadableStream(S)||f.isStream(S)),Da=(U,_e,lt)=>bs(U,Yl,Et=>{if(ut&&Et>G)throw $n=Ca();_e&&_e(Et)},lt);if(p&&b!=="get"&&b!=="head"&&(ne||Tr)){if(Zt=Zt??await _(h,S),Zt!==0||Tr){let U=new i(v,{method:"POST",body:S,duplex:"half"}),_e;if(f.isFormData(S)&&(_e=U.headers.get("content-type"))&&h.setContentType(_e),U.body){let[lt,Et]=ne&&gs(Zt,mn(ys(ne)))||[];S=Da(U.body,lt,Et)}}}else if(Tr&&!c&&l&&b!=="get"&&b!=="head")S=Da(S);else if(Tr&&c&&!p&&b!=="get"&&b!=="head")throw new P("Stream request bodies are not supported by the current fetch implementation",P.ERR_NOT_SUPPORT,g,W);f.isString(E)||(E=E?"include":"omit");let Cf=c&&"credentials"in i.prototype;if(f.isFormData(S)){let U=h.getContentType();U&&/^multipart\/form-data/i.test(U)&&!/boundary=/i.test(U)&&h.delete("content-type")}h.set("User-Agent","axios/"+gn,!1);let Ua={...C,signal:K,method:b.toUpperCase(),headers:co(h.normalize()),body:S,duplex:"half",credentials:Cf?E:void 0};W=c&&new i(v,Ua);let Ye=await(c?In(W,C):In(v,Ua)),Ma=te.from(Ye.headers);if(M){let U=f.toFiniteNumber(Ma.getContentLength());if(U!=null&&U>N)throw new P("maxContentLength size of "+N+" exceeded",P.ERR_BAD_RESPONSE,g,W)}let gi=m&&(H==="stream"||H==="response");if(m&&Ye.body&&(L||M||gi&&xt)){let U={};["status","statusText","headers"].forEach(Cn=>{U[Cn]=Ye[Cn]});let _e=f.toFiniteNumber(Ma.getContentLength()),[lt,Et]=L&&gs(_e,mn(ys(L),!0))||[],Na=0,Df=Cn=>{if(M&&(Na=Cn,Na>N))throw new P("maxContentLength size of "+N+" exceeded",P.ERR_BAD_RESPONSE,g,W);lt&&lt(Cn)};Ye=new s(bs(Ye.body,Yl,Df,()=>{Et&&Et(),xt&&xt()}),U)}H=H||"text";let Qe=await w[f.findKey(w,H)||"text"](Ye,g);if(M&&!m&&!gi){let U;if(Qe!=null&&(typeof Qe.byteLength=="number"?U=Qe.byteLength:typeof Qe.size=="number"?U=Qe.size:typeof Qe=="string"&&(U=typeof r=="function"?new r().encode(Qe).byteLength:Qe.length)),typeof U=="number"&&U>N)throw new P("maxContentLength size of "+N+" exceeded",P.ERR_BAD_RESPONSE,g,W)}return!gi&&xt&&xt(),await new Promise((U,_e)=>{ar(U,_e,{data:Qe,headers:te.from(Ye.headers),status:Ye.status,statusText:Ye.statusText,config:g,request:W})})}catch(q){if(xt&&xt(),K&&K.aborted&&K.reason instanceof P){let ke=K.reason;throw ke.config=g,W&&(ke.request=W),q!==ke&&Object.defineProperty(ke,"cause",{__proto__:null,value:q,writable:!0,enumerable:!1,configurable:!0}),ke}if($n)throw W&&!$n.request&&($n.request=W),$n;if(q instanceof P)throw W&&!q.request&&(q.request=W),q;if(q&&q.name==="TypeError"&&/Load failed|fetch/i.test(q.message)){let ke=new P("Network Error",P.ERR_NETWORK,g,W,q&&q.response);throw Object.defineProperty(ke,"cause",{__proto__:null,value:q.cause||q,writable:!0,enumerable:!1,configurable:!0}),ke}throw P.from(q,q&&q.code,g,W,q&&q.response)}}},zg=new Map,Es=e=>{let t=e&&e.env||{},{fetch:n,Request:r,Response:o}=t,i=[r,o,n],s=i.length,a=s,c,u,l=zg;for(;a--;)c=i[a],u=l.get(c),u===void 0&&l.set(c,u=a?new Map:Og(t)),l=u;return u},A0=Es();var vs={http:lo,xhr:Wl,fetch:{get:Es}};f.forEach(vs,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch{}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}});var td=e=>`- ${e}`,$g=e=>f.isFunction(e)||e===null||e===!1;function Cg(e,t){e=f.isArray(e)?e:[e];let{length:n}=e,r,o,i={};for(let s=0;s<n;s++){r=e[s];let a;if(o=r,!$g(r)&&(o=vs[(a=String(r)).toLowerCase()],o===void 0))throw new P(`Unknown adapter '${a}'`);if(o&&(f.isFunction(o)||(o=o.get(t))))break;i[a||"#"+s]=o}if(!o){let s=Object.entries(i).map(([c,u])=>`adapter ${c} `+(u===!1?"is not supported by the environment":"is not available in the build")),a=n?s.length>1?`since :
5
+ `+s.map(td).join(`
6
+ `):" "+td(s[0]):"as no adapter specified";throw new P("There is no suitable adapter to dispatch the request "+a,P.ERR_NOT_SUPPORT)}return o}var yo={getAdapter:Cg,adapters:vs};function Ss(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Je(null,e)}function wo(e){return Ss(e),e.headers=te.from(e.headers),e.data=ir.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),yo.getAdapter(e.adapter||hn.adapter,e)(e).then(function(r){Ss(e),e.response=r;try{r.data=ir.call(e,e.transformResponse,r)}finally{delete e.response}return r.headers=te.from(r.headers),r},function(r){if(!sr(r)&&(Ss(e),r&&r.response)){e.response=r.response;try{r.response.data=ir.call(e,e.transformResponse,r.response)}finally{delete e.response}r.response.headers=te.from(r.response.headers)}return Promise.reject(r)})}var _o={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{_o[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});var nd={};_o.transitional=function(t,n,r){function o(i,s){return"[Axios v"+gn+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,a)=>{if(t===!1)throw new P(o(s," has been removed"+(n?" in "+n:"")),P.ERR_DEPRECATED);return n&&!nd[s]&&(nd[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,a):!0}};_o.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function Dg(e,t,n){if(typeof e!="object"||e===null)throw new P("options must be an object",P.ERR_BAD_OPTION_VALUE);let r=Object.keys(e),o=r.length;for(;o-- >0;){let i=r[o],s=Object.prototype.hasOwnProperty.call(t,i)?t[i]:void 0;if(s){let a=e[i],c=a===void 0||s(a,i,e);if(c!==!0)throw new P("option "+i+" must be "+c,P.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new P("Unknown option "+i,P.ERR_BAD_OPTION)}}var ur={assertOptions:Dg,validators:_o};var de=ur.validators,yn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new cs,response:new cs}}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=(()=>{if(!o.stack)return"";let s=o.stack.indexOf(`
7
+ `);return s===-1?"":o.stack.slice(s+1)})();try{if(!r.stack)r.stack=i;else if(i){let s=i.indexOf(`
8
+ `),a=s===-1?-1:i.indexOf(`
9
+ `,s+1),c=a===-1?"":i.slice(a+1);String(r.stack).endsWith(c)||(r.stack+=`
10
+ `+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&&ur.assertOptions(r,{silentJSONParsing:de.transitional(de.boolean),forcedJSONParsing:de.transitional(de.boolean),clarifyTimeoutError:de.transitional(de.boolean),legacyInterceptorReqResOrdering:de.transitional(de.boolean),advertiseZstdAcceptEncoding:de.transitional(de.boolean),validateStatusUndefinedResolves:de.transitional(de.boolean)},!1),o!=null&&(f.isFunction(o)?n.paramsSerializer={serialize:o}:ur.assertOptions(o,{encode:de.function,serialize:de.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ur.assertOptions(n,{baseUrl:de.spelling("baseURL"),withXsrfToken:de.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&f.merge(i.common,i[n.method]);i&&f.forEach(["delete","get","head","post","put","patch","query","common"],w=>{delete i[w]}),n.headers=te.concat(s,i);let a=[],c=!0;this.interceptors.request.forEach(function(x){if(typeof x.runWhen=="function"&&x.runWhen(n)===!1)return;c=c&&x.synchronous;let _=n.transitional||fn;_&&_.legacyInterceptorReqResOrdering?a.unshift(x.fulfilled,x.rejected):a.push(x.fulfilled,x.rejected)});let u=[];this.interceptors.response.forEach(function(x){u.push(x.fulfilled,x.rejected)});let l,d=0,p;if(!c){let w=[wo.bind(this),void 0];for(w.unshift(...a),w.push(...u),p=w.length,l=Promise.resolve(n);d<p;)l=l.then(w[d++],w[d++]);return l}p=a.length;let m=n;for(;d<p;){let w=a[d++],x=a[d++];try{m=w(m)}catch(_){x.call(this,_);break}}try{l=wo.call(this,m)}catch(w){return Promise.reject(w)}for(d=0,p=u.length;d<p;)l=l.then(u[d++],u[d++]);return l}getUri(t){t=Ne(this.defaults,t);let n=cr(t.baseURL,t.url,t.allowAbsoluteUrls,t);return or(n,t.params,t.paramsSerializer)}};f.forEach(["delete","get","head","options"],function(t){yn.prototype[t]=function(n,r){return this.request(Ne(r||{},{method:t,url:n,data:r&&f.hasOwnProp(r,"data")?r.data:void 0}))}});f.forEach(["post","put","patch","query"],function(t){function n(r){return function(i,s,a){return this.request(Ne(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:i,data:s}))}}yn.prototype[t]=n(),t!=="query"&&(yn.prototype[t+"Form"]=n(!0))});var lr=yn;var As=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,s=new Promise(a=>{r.subscribe(a),i=a}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,a){r.reason||(r.reason=new Je(i,s,a),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}}},rd=As;function Rs(e){return function(n){return e.apply(null,n)}}function Ts(e){return f.isObject(e)&&e.isAxiosError===!0}var Ps={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(Ps).forEach(([e,t])=>{Ps[t]=e});var od=Ps;function id(e){let t=new lr(e),n=Qn(lr.prototype.request,t);return f.extend(n,lr.prototype,t,{allOwnKeys:!0}),f.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return id(Ne(e,o))},n}var ie=id(hn);ie.Axios=lr;ie.CanceledError=Je;ie.CancelToken=rd;ie.isCancel=sr;ie.VERSION=gn;ie.toFormData=gt;ie.AxiosError=P;ie.Cancel=ie.CanceledError;ie.all=function(t){return Promise.all(t)};ie.spread=Rs;ie.isAxiosError=Ts;ie.mergeConfig=Ne;ie.AxiosHeaders=te;ie.formToJSON=e=>po(f.isHTMLForm(e)?new FormData(e):e);ie.getAdapter=yo.getAdapter;ie.HttpStatusCode=od;ie.default=ie;var bo=ie;var{Axios:ER,AxiosError:vR,CanceledError:SR,isCancel:AR,CancelToken:RR,VERSION:TR,all:PR,Cancel:kR,isAxiosError:OR,spread:zR,toFormData:IR,AxiosHeaders:$R,HttpStatusCode:CR,formToJSON:DR,getAdapter:UR,mergeConfig:MR,create:NR}=bo;function Ug(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}function Te(e,t,n){if(!e.s){if(n instanceof ks)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Te.bind(null,e,t);return}if(n&&n.then){n.then(Te.bind(null,e,t),Te.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var ks=(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{Te(r,1,i(this.v))}catch(s){Te(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Te(r,1,t?t(s):s):n?Te(r,1,n(s)):Te(r,2,s)}catch(s){Te(r,2,s)}},r},e})();function wn(e){return e instanceof ks&&e.s&1}function Mg(e,t){var n;do{var r=e();if(r&&r.then)if(wn(r))r=r.v;else{n=!0;break}var o=t();if(wn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new ks,s=Te.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),wn(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(wn(r))r=r.v;else{r.then(a).then(void 0,s);return}}Te(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(wn(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),wn(u)&&(u=u.v),!u){Te(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Te(i,1,r)}}function sd(){return{plc:function(t,n){try{let o=function(){let l=typeof c?.["@context"]<"u"?"application/did+ld+json":"application/did+json";return i?{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{contentType:l}}},r,i=null,s=`https://plc.directory/${encodeURIComponent(t)}`,a={},c=null,u=Mg(function(){function l(){r||c?.id===t||(i="resolver_error: DID document id does not match requested did")}let d=Ug(function(){return Promise.resolve(bo.get(s)).then(function(p){c=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(u&&u.then?u.then(o):o(u))}catch(r){return Promise.reject(r)}}}}var ud=Nf(cd(),1);function Ng(e,t){try{var n=e()}catch(r){return t(r)}return n&&n.then?n.then(void 0,t):n}var Lg=function(e){try{return Promise.resolve((0,ud.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 Pe(e,t,n){if(!e.s){if(n instanceof Os)if(n.s)t&1&&(t=n.s),n=n.v;else{n.o=Pe.bind(null,e,t);return}if(n&&n.then){n.then(Pe.bind(null,e,t),Pe.bind(null,e,2));return}e.s=t,e.v=n;let r=e.o;r&&r(e)}}var Bg="/.well-known/did.json",Os=(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{Pe(r,1,i(this.v))}catch(s){Pe(r,2,s)}return r}else return this}return this.o=function(i){try{let s=i.v;i.s&1?Pe(r,1,t?t(s):s):n?Pe(r,1,n(s)):Pe(r,2,s)}catch(s){Pe(r,2,s)}},r},e})();function bn(e){return e instanceof Os&&e.s&1}function jg(e,t){var n;do{var r=e();if(r&&r.then)if(bn(r))r=r.v;else{n=!0;break}var o=t();if(bn(o)&&(o=o.v),!o)return r}while(!o.then);let i=new Os,s=Pe.bind(null,i,2);return(n?r.then(a):o.then(c)).then(void 0,s),i;function a(u){for(r=u;o=t(),bn(o)&&(o=o.v),!!o;){if(o.then){o.then(c).then(void 0,s);return}if(r=e(),r&&r.then)if(bn(r))r=r.v;else{r.then(a).then(void 0,s);return}}Pe(i,1,r)}function c(u){if(u){do{if(r=e(),r&&r.then)if(bn(r))r=r.v;else{r.then(a).then(void 0,s);return}if(u=t(),bn(u)&&(u=u.v),!u){Pe(i,1,r);return}}while(!u.then);u.then(c).then(void 0,s)}else Pe(i,1,r)}}function ld(){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:u,didResolutionMetadata:{error:"notFound",message:i}}:{didDocument:l,didDocumentMetadata:u,didResolutionMetadata:{contentType:p}}},r,i=null,s=decodeURIComponent(n.id)+Bg,a=n.id.split(":");a.length>1&&(s=a.map(decodeURIComponent).join("/")+"/did.json");let c=`https://${s}`,u={},l=null,d=jg(function(){function p(){r||l?.id===t||(i="resolver_error: DID document id does not match requested did")}let m=Ng(function(){return Promise.resolve(Lg(c)).then(function(w){l=w})},function(w){i=`resolver_error: DID must resolve to a valid https URL containing a JSON document: ${w}`,r=1});return m&&m.then?m.then(p):p(m)},function(){return!r&&!1});return Promise.resolve(d&&d.then?d.then(o):o(d))}catch(r){return Promise.reject(r)}}}}var vo=class{methods={...sd(),...ld()};resolver=new oo(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 $s;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&($s="oauth4webapi/v3.8.6");function mr(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 we="ERR_INVALID_ARG_VALUE",Ie="ERR_INVALID_ARG_TYPE";function V(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}var $t=Symbol(),Po=Symbol(),ko=Symbol(),Ct=Symbol();var So=Symbol();var Zg=new TextEncoder,Fg=new TextDecoder;function dd(e){return typeof e=="string"?Zg.encode(e):Fg.decode(e)}var Cs;Uint8Array.prototype.toBase64?Cs=e=>(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e.toBase64({alphabet:"base64url",omitPadding:!0})):Cs=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 Ds;Uint8Array.fromBase64?Ds=e=>{try{return Uint8Array.fromBase64(e,{alphabet:"base64url"})}catch(t){throw V("The input to be decoded is not correctly encoded.",we,t)}}:Ds=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 V("The input to be decoded is not correctly encoded.",we,t)}};function Us(e){return typeof e=="string"?Ds(e):Cs(e)}var wt=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=Do,Error.captureStackTrace?.(this,this.constructor)}},fr=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 $(e,t,n){return new fr(e,{code:t,cause:n})}function Ao(e){return!(e===null||typeof e!="object"||Array.isArray(e))}function Ms(e){mr(e,Headers)&&(e=Object.fromEntries(e.entries()));let t=new Headers(e??{});if($s&&!t.has("user-agent")&&t.set("user-agent",$s),t.has("authorization"))throw V('"options.headers" must not include the "authorization" header name',we);return t}function pd(e,t){if(t!==void 0){if(typeof t=="function"&&(t=t(e.href)),!(t instanceof AbortSignal))throw V('"options.signal" must return or be an instance of AbortSignal',Ie);return t}}function hd(e){return e.includes("//")?e.replace("//","/"):e}function Hg(e,t,n=!1){return e.pathname==="/"?e.pathname=t:e.pathname=hd(`${t}/${n?e.pathname:e.pathname.replace(/(\/)$/,"")}`),e}function Gg(e,t){return e.pathname=hd(`${e.pathname}/${t}`),e}async function qg(e,t,n,r){if(!(e instanceof URL))throw V(`"${t}" must be an instance of URL`,Ie);Io(e,r?.[$t]!==!0);let o=n(new URL(e.href)),i=Ms(r?.headers);return i.set("accept","application/json"),(r?.[Ct]||fetch)(o.href,{body:void 0,headers:Object.fromEntries(i.entries()),method:"GET",redirect:"manual",signal:pd(o,r?.signal)})}async function md(e,t){return qg(e,"issuerIdentifier",n=>{switch(t?.algorithm){case void 0:case"oidc":Gg(n,".well-known/openid-configuration");break;case"oauth2":Hg(n,".well-known/oauth-authorization-server");break;default:throw V('"options.algorithm" must be "oidc" (default), or "oauth2"',we)}return n},t)}function dr(e,t,n,r,o){try{if(typeof e!="number"||!Number.isFinite(e))throw V(`${n} must be a number`,Ie,o);if(e>0)return;if(t){if(e!==0)throw V(`${n} must be a non-negative number`,we,o);return}throw V(`${n} must be a positive number`,we,o)}catch(i){throw r?$(i.message,r,o):i}}function ye(e,t,n,r){try{if(typeof e!="string")throw V(`${t} must be a string`,Ie,r);if(e.length===0)throw V(`${t} must not be empty`,we,r)}catch(o){throw n?$(o.message,n,r):o}}async function gd(e,t){let n=e;if(!(n instanceof URL)&&n!==To)throw V('"expectedIssuerIdentifier" must be an instance of URL',Ie);if(!mr(t,Response))throw V('"response" must be an instance of Response',Ie);if(t.status!==200)throw $('"response" is not a conform Authorization Server Metadata response (unexpected HTTP status code)',Uo,t);Ks(t);let r=await Id(t);if(ye(r.issuer,'"response" body "issuer" property',F,{body:r}),n!==To&&new URL(r.issuer).href!==n.href)throw $('"response" body "issuer" property does not match the expected value',Mo,{expected:n.href,body:r,attribute:"issuer"});return r}function yd(e){Kg(e,"application/json")}function Jg(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,Gs,e)}function Kg(e,t){if(Zs(e)!==t)throw Jg(e,t)}function Vg(){return Us(crypto.getRandomValues(new Uint8Array(32)))}function wd(){return Vg()}function Ns(e){let t=e?.[Po];return typeof t=="number"&&Number.isFinite(t)?t:0}function Ls(e){let t=e?.[ko];return typeof t=="number"&&Number.isFinite(t)&&Math.sign(t)!==-1?t:30}function Bs(){return Math.floor(Date.now()/1e3)}function Oo(e){if(typeof e!="object"||e===null)throw V('"as" must be an object',Ie);ye(e.issuer,'"as.issuer"')}function zo(e){if(typeof e!="object"||e===null)throw V('"client" must be an object',Ie);ye(e.client_id,'"client.client_id"')}function js(e){return ye(e,'"clientSecret"'),(t,n,r,o)=>{r.set("client_id",n.client_id),r.set("client_secret",e)}}function _d(){return(e,t,n,r)=>{n.set("client_id",t.client_id)}}var Wg=URL.parse?(e,t)=>URL.parse(e,t):(e,t)=>{try{return new URL(e,t)}catch{return null}};function Io(e,t){if(t&&e.protocol!=="https:")throw $("only requests to HTTPS are allowed",qs,e);if(e.protocol!=="https:"&&e.protocol!=="http:")throw $("only HTTP and HTTPS requests are allowed",Js,e)}function fd(e,t,n,r){let o;if(typeof e!="string"||!(o=Wg(e)))throw $(`authorization server metadata does not contain a valid ${n?`"as.mtls_endpoint_aliases.${t}"`:`"as.${t}"`}`,e===void 0?xy:Ey,{attribute:n?`mtls_endpoint_aliases.${t}`:t});return Io(o,r),o}function $o(e,t,n,r){return n&&e.mtls_endpoint_aliases&&t in e.mtls_endpoint_aliases?fd(e.mtls_endpoint_aliases[t],t,n,r):fd(e[t],t,n,r)}function bd(e){if(e instanceof En){let{0:t,length:n}=e.cause;return n===1&&t.scheme==="dpop"&&t.parameters.error==="use_dpop_nonce"}return e instanceof xn?e.error==="use_dpop_nonce":!1}var xn=class extends Error{cause;code;error;status;error_description;response;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=_y,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)}},pr=class extends Error{cause;code;error;error_description;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=by,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)}},En=class extends Error{cause;code;response;status;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=wy,this.cause=n.cause,this.status=n.response.status,this.response=n.response,Object.defineProperty(this,"response",{enumerable:!1}),Error.captureStackTrace?.(this,this.constructor)}},Ro="[a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+",Xg="[a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2}",Yg='"((?:[^"\\\\]|\\\\[\\s\\S])*)"',Qg="("+Ro+")\\s*=\\s*"+Yg,ey="("+Ro+")\\s*=\\s*("+Ro+")",ty=new RegExp("^[,\\s]*("+Ro+")"),ny=new RegExp("^[,\\s]*"+Qg+"[,\\s]*(.*)"),ry=new RegExp("^[,\\s]*"+ey+"[,\\s]*(.*)"),oy=new RegExp("^("+Xg+")(?:$|[,\\s])(.*)");function iy(e){if(!mr(e,Response))throw V('"response" must be an instance of Response',Ie);let t=e.headers.get("www-authenticate");if(t===null)return;let n=[],r=t;for(;r;){let o=r.match(ty),i=o?.[1].toLowerCase();if(!i)return;let s=r.substring(o[0].length);if(s&&!s.match(/^[\s,]/))return;let a=s.match(/^\s+(.*)$/),c=!!a;r=a?a[1]:void 0;let u={},l;if(c)for(;r;){let p,m;if(o=r.match(ny)){if([,p,m,r]=o,m.includes("\\"))try{m=JSON.parse(`"${m}"`)}catch{}u[p.toLowerCase()]=m;continue}if(o=r.match(ry)){[,p,m,r]=o,u[p.toLowerCase()]=m;continue}if(o=r.match(oy)){if(Object.keys(u).length)break;[,l,r]=o;break}return}else r=s||void 0;let d={scheme:i,parameters:u};l&&(d.token68=l),n.push(d)}if(n.length)return n}async function sy(e){if(e.status>399&&e.status<500){Ks(e),yd(e);try{let t=await e.clone().json();if(Ao(t)&&typeof t.error=="string"&&t.error.length)return t}catch{}}}async function xd(e,t,n){if(e.status!==t){ly(e);let r;throw(r=await sy(e))?(await e.body?.cancel(),new xn("server responded with an error in the response body",{cause:r,response:e})):$(`"response" is not a conform ${n} response (unexpected HTTP status code)`,Uo,e)}}function ay(e){if(!Fs.has(e))throw V('"options.DPoP" is not a valid DPoPHandle',we)}function Zs(e){return e.headers.get("content-type")?.split(";")[0]}async function Ed(e,t,n,r,o,i,s){return await n(e,t,o,i),i.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),(s?.[Ct]||fetch)(r.href,{body:o,headers:Object.fromEntries(i.entries()),method:"POST",redirect:"manual",signal:pd(r,s?.signal)})}async function cy(e,t,n,r,o,i){let s=$o(e,"token_endpoint",t.use_mtls_endpoint_aliases,i?.[$t]!==!0);o.set("grant_type",r);let a=Ms(i?.headers);a.set("accept","application/json"),i?.DPoP!==void 0&&(ay(i.DPoP),await i.DPoP.addProof(s,a,"POST"));let c=await Ed(e,t,n,s,o,a,i);return i?.DPoP?.cacheNonce(c,s),c}var vd=new WeakMap,uy=new WeakMap;function Co(e){if(!e.id_token)return;let t=vd.get(e);if(!t)throw V('"ref" was already garbage collected or did not resolve from the proper sources',we);return t}async function Sd(e,t,n,r,o,i){if(Oo(e),zo(t),!mr(n,Response))throw V('"response" must be an instance of Response',Ie);await xd(n,200,"Token Endpoint"),Ks(n);let s=await Id(n);if(ye(s.access_token,'"response" body "access_token" property',F,{body:s}),ye(s.token_type,'"response" body "token_type" property',F,{body:s}),s.token_type=s.token_type.toLowerCase(),s.expires_in!==void 0){let a=typeof s.expires_in!="number"?parseFloat(s.expires_in):s.expires_in;dr(a,!0,'"response" body "expires_in" property',F,{body:s}),s.expires_in=a}if(s.refresh_token!==void 0&&ye(s.refresh_token,'"response" body "refresh_token" property',F,{body:s}),s.scope!==void 0&&typeof s.scope!="string")throw $('"response" body "scope" property must be a string',F,{body:s});if(s.id_token!==void 0){ye(s.id_token,'"response" body "id_token" property',F,{body:s});let a=["aud","exp","iat","iss","sub"];t.require_auth_time===!0&&a.push("auth_time"),t.default_max_age!==void 0&&(dr(t.default_max_age,!0,'"client.default_max_age"'),a.push("auth_time")),r?.length&&a.push(...r);let{claims:c,jwt:u}=await vy(s.id_token,Ay.bind(void 0,t.id_token_signed_response_alg,e.id_token_signing_alg_values_supported,"RS256"),Ns(t),Ls(t),o).then(my.bind(void 0,a)).then(fy.bind(void 0,e)).then(dy.bind(void 0,t.client_id));if(Array.isArray(c.aud)&&c.aud.length!==1){if(c.azp===void 0)throw $('ID Token "aud" (audience) claim includes additional untrusted audiences',Ke,{claims:c,claim:"aud"});if(c.azp!==t.client_id)throw $('unexpected ID Token "azp" (authorized party) claim value',Ke,{expected:t.client_id,claims:c,claim:"azp"})}c.auth_time!==void 0&&dr(c.auth_time,!0,'ID Token "auth_time" (authentication time)',F,{claims:c}),uy.set(n,u),vd.set(s,c)}if(i?.[s.token_type]!==void 0)i[s.token_type](n,s);else if(s.token_type!=="dpop"&&s.token_type!=="bearer")throw new wt("unsupported `token_type` value",{cause:{body:s}});return s}function ly(e){let t;if(t=iy(e))throw new En("server responded with a challenge in the WWW-Authenticate HTTP Header",{cause:t,response:e})}function dy(e,t){if(Array.isArray(t.claims.aud)){if(!t.claims.aud.includes(e))throw $('unexpected JWT "aud" (audience) claim value',Ke,{expected:e,claims:t.claims,claim:"aud"})}else if(t.claims.aud!==e)throw $('unexpected JWT "aud" (audience) claim value',Ke,{expected:e,claims:t.claims,claim:"aud"});return t}function fy(e,t){let n=e[Vs]?.(t)??e.issuer;if(t.claims.iss!==n)throw $('unexpected JWT "iss" (issuer) claim value',Ke,{expected:n,claims:t.claims,claim:"iss"});return t}var Fs=new WeakSet;function py(e){return Fs.add(e),e}var Hs=Symbol();async function Ad(e,t,n,r,o,i,s){if(Oo(e),zo(t),!Fs.has(r))throw V('"callbackParameters" must be an instance of URLSearchParams obtained from "validateAuthResponse()", or "validateJwtAuthResponse()',we);ye(o,'"redirectUri"');let a=It(r,"code");if(!a)throw $('no authorization code in "callbackParameters"',F);let c=new URLSearchParams(s?.additionalParameters);return c.set("redirect_uri",o),c.set("code",a),i!==Hs&&(ye(i,'"codeVerifier"'),c.set("code_verifier",i)),cy(e,t,n,"authorization_code",c,s)}var hy={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 my(e,t){for(let n of e)if(t.claims[n]===void 0)throw $(`JWT "${n}" (${hy[n]}) claim missing`,F,{claims:t.claims});return t}var zs=Symbol(),Is=Symbol();async function Rd(e,t,n,r){return typeof r?.expectedNonce=="string"||typeof r?.maxAge=="number"||r?.requireIdToken?gy(e,t,n,r.expectedNonce,r.maxAge,r[So],r.recognizedTokenTypes):yy(e,t,n,r?.[So],r?.recognizedTokenTypes)}async function gy(e,t,n,r,o,i,s){let a=[];switch(r){case void 0:r=zs;break;case zs:break;default:ye(r,'"expectedNonce" argument'),a.push("nonce")}switch(o??=t.default_max_age,o){case void 0:o=Is;break;case Is:break;default:dr(o,!0,'"maxAge" argument'),a.push("auth_time")}let c=await Sd(e,t,n,a,i,s);ye(c.id_token,'"response" body "id_token" property',F,{body:c});let u=Co(c);if(o!==Is){let l=Bs()+Ns(t),d=Ls(t);if(u.auth_time+o<l-d)throw $("too much time has elapsed since the last End-User authentication",vn,{claims:u,now:l,tolerance:d,claim:"auth_time"})}if(r===zs){if(u.nonce!==void 0)throw $('unexpected ID Token "nonce" claim value',Ke,{expected:void 0,claims:u,claim:"nonce"})}else if(u.nonce!==r)throw $('unexpected ID Token "nonce" claim value',Ke,{expected:r,claims:u,claim:"nonce"});return c}async function yy(e,t,n,r,o){let i=await Sd(e,t,n,void 0,r,o),s=Co(i);if(s){if(t.default_max_age!==void 0){dr(t.default_max_age,!0,'"client.default_max_age"');let a=Bs()+Ns(t),c=Ls(t);if(s.auth_time+t.default_max_age<a-c)throw $("too much time has elapsed since the last End-User authentication",vn,{claims:s,now:a,tolerance:c,claim:"auth_time"})}if(s.nonce!==void 0)throw $('unexpected ID Token "nonce" claim value',Ke,{expected:void 0,claims:s,claim:"nonce"})}return i}var wy="OAUTH_WWW_AUTHENTICATE_CHALLENGE",_y="OAUTH_RESPONSE_BODY_ERROR",Do="OAUTH_UNSUPPORTED_OPERATION",by="OAUTH_AUTHORIZATION_RESPONSE_ERROR";var hr="OAUTH_PARSE_ERROR",F="OAUTH_INVALID_RESPONSE";var Gs="OAUTH_RESPONSE_IS_NOT_JSON",Uo="OAUTH_RESPONSE_IS_NOT_CONFORM",qs="OAUTH_HTTP_REQUEST_FORBIDDEN",Js="OAUTH_REQUEST_PROTOCOL_FORBIDDEN",vn="OAUTH_JWT_TIMESTAMP_CHECK_FAILED",Ke="OAUTH_JWT_CLAIM_COMPARISON_FAILED",Mo="OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";var xy="OAUTH_MISSING_SERVER_METADATA",Ey="OAUTH_INVALID_SERVER_METADATA";async function Td(e,t,n,r,o){Oo(e),zo(t),ye(r,'"token"');let i=$o(e,"revocation_endpoint",t.use_mtls_endpoint_aliases,o?.[$t]!==!0),s=new URLSearchParams(o?.additionalParameters);s.set("token",r);let a=Ms(o?.headers);return a.delete("accept"),Ed(e,t,n,i,s,a,o)}async function Pd(e){if(!mr(e,Response))throw V('"response" must be an instance of Response',Ie);await xd(e,200,"Revocation Endpoint")}function Ks(e){if(e.bodyUsed)throw V('"response" body has been used already',we)}async function vy(e,t,n,r,o){let{0:i,1:s,length:a}=e.split(".");if(a===5)if(o!==void 0)e=await o(e),{0:i,1:s,length:a}=e.split(".");else throw new wt("JWE decryption is not configured",{cause:e});if(a!==3)throw $("Invalid JWT",F,e);let c;try{c=JSON.parse(dd(Us(i)))}catch(d){throw $("failed to parse JWT Header body as base64url encoded JSON",hr,d)}if(!Ao(c))throw $("JWT Header must be a top level object",F,e);if(t(c),c.crit!==void 0)throw new wt('no JWT "crit" header parameter extensions are supported',{cause:{header:c}});let u;try{u=JSON.parse(dd(Us(s)))}catch(d){throw $("failed to parse JWT Payload body as base64url encoded JSON",hr,d)}if(!Ao(u))throw $("JWT Payload must be a top level object",F,e);let l=Bs()+n;if(u.exp!==void 0){if(typeof u.exp!="number")throw $('unexpected JWT "exp" (expiration time) claim type',F,{claims:u});if(u.exp<=l-r)throw $('unexpected JWT "exp" (expiration time) claim value, expiration is past current timestamp',vn,{claims:u,now:l,tolerance:r,claim:"exp"})}if(u.iat!==void 0&&typeof u.iat!="number")throw $('unexpected JWT "iat" (issued at) claim type',F,{claims:u});if(u.iss!==void 0&&typeof u.iss!="string")throw $('unexpected JWT "iss" (issuer) claim type',F,{claims:u});if(u.nbf!==void 0){if(typeof u.nbf!="number")throw $('unexpected JWT "nbf" (not before) claim type',F,{claims:u});if(u.nbf>l+r)throw $('unexpected JWT "nbf" (not before) claim value',vn,{claims:u,now:l,tolerance:r,claim:"nbf"})}if(u.aud!==void 0&&typeof u.aud!="string"&&!Array.isArray(u.aud))throw $('unexpected JWT "aud" (audience) claim type',F,{claims:u});return{header:c,claims:u,jwt:e}}async function Sy(e){if(e.bodyUsed)throw V("form_post Request instances must contain a readable body",we,{cause:e});return e.text()}async function kd(e){if(e.method!=="POST")throw V("form_post responses are expected to use the POST method",we,{cause:e});if(Zs(e)!=="application/x-www-form-urlencoded")throw V("form_post responses are expected to use the application/x-www-form-urlencoded content-type",we,{cause:e});return Sy(e)}function Ay(e,t,n,r){if(e!==void 0){if(typeof e=="string"?r.alg!==e:!e.includes(r.alg))throw $('unexpected JWT "alg" header parameter',F,{header:r,expected:e,reason:"client configuration"});return}if(Array.isArray(t)){if(!t.includes(r.alg))throw $('unexpected JWT "alg" header parameter',F,{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 $('unexpected JWT "alg" header parameter',F,{header:r,expected:n,reason:"default value"});return}throw $('missing client or server configuration to verify used JWT "alg" header parameter',void 0,{client:e,issuer:t,fallback:n})}function It(e,t){let{0:n,length:r}=e.getAll(t);if(r>1)throw $(`"${t}" parameter must be provided only once`,F);return n}var Od=Symbol(),Ry=Symbol();function zd(e,t,n,r){if(Oo(e),zo(t),n instanceof URL&&(n=n.searchParams),!(n instanceof URLSearchParams))throw V('"parameters" must be an instance of URLSearchParams, or URL',Ie);if(It(n,"response"))throw $('"parameters" contains a JARM response, use validateJwtAuthResponse() instead of validateAuthResponse()',F,{parameters:n});let o=It(n,"iss"),i=It(n,"state");if(!o&&e.authorization_response_iss_parameter_supported)throw $('response parameter "iss" (issuer) missing',F,{parameters:n});if(o&&o!==e.issuer)throw $('unexpected "iss" (issuer) response parameter value',F,{expected:e.issuer,parameters:n});switch(r){case void 0:case Ry:if(i!==void 0)throw $('unexpected "state" response parameter encountered',F,{expected:void 0,parameters:n});break;case Od:break;default:if(ye(r,'"expectedState" argument'),i!==r)throw $(i===void 0?'response parameter "state" missing':'unexpected "state" response parameter value',F,{expected:r,parameters:n})}if(It(n,"error"))throw new pr("authorization response from the server is an error",{cause:n});let a=It(n,"id_token"),c=It(n,"token");if(a!==void 0||c!==void 0)throw new wt("implicit and hybrid flows are not supported");return py(new URLSearchParams(n))}async function Id(e,t=yd){let n;try{n=await e.json()}catch(r){throw t(e),$('failed to parse "response" body as JSON',hr,r)}if(!Ao(n))throw $('"response" body must be a top level object',F,{body:n});return n}var To=Symbol(),Vs=Symbol();var yr,$d;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&($d="openid-client/v6.8.4",yr={"user-agent":$d});var Le=e=>Xs.get(e),Xs,Ws;function Py(e){return e!==void 0?js(e):(Ws||=new WeakMap,(t,n,r,o)=>{let i;return(i=Ws.get(n))||(ky(n.client_secret,'"metadata.client_secret"'),i=js(n.client_secret),Ws.set(n,i)),i(t,n,r,o)})}function ky(e,t){if(typeof e!="string")throw Ve(`${t} must be a string`,_r);if(e.length===0)throw Ve(`${t} must not be empty`,wr)}function Oy(){return _d()}var Sn=Ct;var wr="ERR_INVALID_ARG_VALUE",_r="ERR_INVALID_ARG_TYPE";function Ve(e,t,n){let r=new TypeError(e,{cause:n});return Object.assign(r,{code:t}),r}function Dd(){return wd()}var An=class extends Error{code;constructor(t,n){super(t,n),this.name=this.constructor.name,this.code=n?.code,Error.captureStackTrace?.(this,this.constructor)}},CT=new TextDecoder;function he(e,t,n){return new An(e,{cause:t,code:n})}function gr(e){if(e instanceof TypeError||e instanceof An||e instanceof xn||e instanceof pr||e instanceof En)throw e;if(e instanceof fr)switch(e.code){case qs:throw he("only requests to HTTPS are allowed",e,e.code);case Js:throw he("only requests to HTTP or HTTPS are allowed",e,e.code);case Uo:throw he("unexpected HTTP response status code",e.cause,e.code);case Gs:throw he("unexpected response content-type",e.cause,e.code);case hr:throw he("parsing error occured",e,e.code);case F:throw he("invalid response encountered",e,e.code);case Ke:throw he("unexpected JWT claim value encountered",e,e.code);case Mo:throw he("unexpected JSON attribute value encountered",e,e.code);case vn:throw he("JWT timestamp claim value failed validation",e,e.code);default:throw he(e.message,e,e.code)}if(e instanceof wt)throw he("unsupported operation",e,e.code);if(e instanceof DOMException)switch(e.name){case"OperationError":throw he("runtime operation error",e,Do);case"NotSupportedError":throw he("runtime unsupported operation",e,Do);case"TimeoutError":throw he("operation timed out",e,"OAUTH_TIMEOUT");case"AbortError":throw he("operation aborted",e,"OAUTH_ABORT")}throw new An("something went wrong",{cause:e})}function zy(e,t,n){return e.origin==="https://login.microsoftonline.com"&&(!n?.algorithm||n.algorithm==="oidc")?(t[Md]=!0,!0):!1}function Iy(e,t){return!!(e.hostname.endsWith(".b2clogin.com")&&(!t?.algorithm||t.algorithm==="oidc"))}async function Ud(e,t,n,r,o){let i=await $y(e,o),s=new Rn(i,t,n,r),a=Le(s);if(o?.[Sn]&&(a.fetch=o[Sn]),o?.timeout&&(a.timeout=o.timeout),o?.execute)for(let c of o.execute)c(s);return s}async function $y(e,t){if(!(e instanceof URL))throw Ve('"server" must be an instance of URL',_r);let n=!e.href.includes("/.well-known/"),r=t?.timeout??30,o=AbortSignal.timeout(r*1e3),i=await(n?md(e,{algorithm:t?.algorithm,[Ct]:t?.[Sn],[$t]:t?.execute?.includes(Cd),signal:o,headers:new Headers(yr)}):(t?.[Sn]||fetch)((Io(e,!t?.execute?.includes(Cd)),e.href),{headers:Object.fromEntries(new Headers({accept:"application/json",...yr}).entries()),body:void 0,method:"GET",redirect:"manual",signal:o})).then(s=>gd(To,s)).catch(gr);return n&&new URL(i.issuer).href!==e.href&&(zy(e,i,t)||Iy(e,t)||(()=>{throw new An("discovered metadata issuer does not match the expected issuer",{code:Mo,cause:{expected:e.href,body:i,attribute:"issuer"}})})()),i}function Cy(e){return{supportsPKCE:{__proto__:null,value(t="S256"){return e.code_challenge_methods_supported?.includes(t)===!0}}}}function Dy(e){Object.defineProperties(e,Cy(e))}var Md=Symbol(),Rn=class{constructor(t,n,r,o){if(typeof n!="string"||!n.length)throw Ve('"clientId" must be a non-empty string',_r);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',wr);let i={...structuredClone(r),client_id:n};i[Po]=r?.[Po]??0,i[ko]=r?.[ko]??30;let s;o?s=o:typeof i.client_secret=="string"&&i.client_secret.length?s=Py(i.client_secret):s=Oy();let a=Object.freeze(i),c=structuredClone(t);Md in t&&(c[Vs]=({claims:{tid:l}})=>t.issuer.replace("{tenantid}",l));let u=Object.freeze(c);Xs||=new WeakMap,Xs.set(this,{__proto__:null,as:u,c:a,auth:s,tlsOnly:!0,jwksCache:{}})}serverMetadata(){let t=structuredClone(Le(this).as);return Dy(t),t}clientMetadata(){return structuredClone(Le(this).c)}get timeout(){return Le(this).timeout}set timeout(t){Le(this).timeout=t}get[Sn](){return Le(this).fetch}set[Sn](t){Le(this).fetch=t}};Object.freeze(Rn.prototype);function Uy(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 Co(this)}catch{return}}}}}function My(e){Object.defineProperties(e,Uy(e))}function Cd(e){Le(e).tlsOnly=!1}function Ny(e){return e=new URL(e),e.search="",e.hash="",e.href}function Ly(e,t){try{return Object.getPrototypeOf(e)[Symbol.toStringTag]===t}catch{return!1}}async function Ys(e,t,n,r,o){if(Qs(e),o?.flag!==No&&!(t instanceof URL)&&!Ly(t,"Request"))throw Ve('"currentUrl" must be an instance of URL, or Request',_r);let i,s,{as:a,c,auth:u,fetch:l,tlsOnly:d,jarm:p,hybrid:m,nonRepudiation:w,timeout:x,decrypt:_,implicit:g}=Le(e);if(o?.flag===No)i=o.authResponse,s=o.redirectUri;else{if(!(t instanceof URL)){let A=t;switch(t=new URL(t.url),A.method){case"GET":break;case"POST":let O=new URLSearchParams(await kd(A));if(m)t.hash=O.toString();else for(let[D,L]of O.entries())t.searchParams.append(D,L);break;default:throw Ve("unexpected Request HTTP method",wr)}}switch(s=Ny(t),!0){case!!p:i=await p(t,n?.expectedState);break;case!!m:i=await m(t,n?.expectedNonce,n?.expectedState,n?.maxAge);break;case!!g:throw new TypeError("authorizationCodeGrant() cannot be used by response_type=id_token clients");default:try{i=zd(a,c,t.searchParams,n?.expectedState)}catch(A){gr(A)}}}let v=await Ad(a,c,u,i,s,n?.pkceCodeVerifier||Hs,{additionalParameters:r,[Ct]:l,[$t]:!d,DPoP:o?.DPoP,headers:new Headers(yr),signal:Ld(x)}).catch(gr);(typeof n?.expectedNonce=="string"||typeof n?.maxAge=="number")&&(n.idTokenExpected=!0);let b=Rd(a,c,v,{expectedNonce:n?.expectedNonce,maxAge:n?.maxAge,requireIdToken:n?.idTokenExpected,[So]:_}),S;try{S=await b}catch(A){if(By(A,o))return Ys(e,void 0,n,r,{...o,flag:No,authResponse:i,redirectUri:s});gr(A)}return S.id_token&&await w?.(v),My(S),S}function Nd(e,t){Qs(e);let{as:n,c:r,tlsOnly:o,hybrid:i,jarm:s,implicit:a}=Le(e),c=$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":a?"id_token":"code"),a&&!t.has("nonce"))throw Ve("response_type=id_token clients must provide a nonce parameter in their authorization request parameters",wr);s&&t.set("response_mode","jwt")}for(let[u,l]of t.entries())c.searchParams.append(u,l);return c}function Qs(e){if(!(e instanceof Rn))throw Ve('"config" must be an instance of Configuration',_r);if(Object.getPrototypeOf(e)!==Rn.prototype)throw Ve("subclassing Configuration is not allowed",wr)}function Ld(e){return e?AbortSignal.timeout(e*1e3):void 0}function By(e,t){return t?.DPoP&&t.flag!==No?bd(e):!1}var No=Symbol();async function Bd(e,t,n){Qs(e);let{as:r,c:o,auth:i,fetch:s,tlsOnly:a,timeout:c}=Le(e);return Td(r,o,i,t,{[Ct]:s,[$t]:!a,additionalParameters:new URLSearchParams(n),headers:new Headers(yr),signal:Ld(c)}).then(Pd).catch(gr)}var jd="oauth2:",br="graffiti-auth-oauth2-data",Lo=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(" "),s=Dd(),a,c;if(typeof window<"u"){a=window.location.href;let d={loginId:n,redirectUri:a,authorizationEndpoint:t,state:s,serviceEndpoints:r};window.localStorage.setItem(br,JSON.stringify(d))}else{let p=(await import("node:http").catch(w=>{throw new Error("Unrecognized environment: cannot find window or node:http")})).createServer();try{await new Promise((w,x)=>{p.once("error",x),p.listen(0,"::1",w)})}catch{try{p.close()}catch{}throw new Error("Failed to start local oauth callback server.")}let m=p.address();if(!m){try{p.close()}catch{}throw new Error("Failed to get local oauth callback server address.")}a=typeof m=="string"?`http://${m}`:`http://${m.family==="IPv6"?`[${m.address}]`:m.address}:${m.port}`,c=new Promise((w,x)=>{let _=setTimeout(()=>{try{p.close()}catch{}x("Oauth callback timed out.")},3e5),g=new Set;p.on("connection",b=>{g.add(b),b.on("close",()=>{g.delete(b)})});let v=async(b,S)=>{try{let A=new URL(b.url??"/",a);await this.onCallbackUrl({loginId:n,callbackUrl:A,configuration:o,expectedState:s,serviceEndpoints:r}),S.statusCode=200,S.setHeader("Content-Type","text/plain"),S.end("You may now close this window.")}catch(A){throw S.statusCode=500,S.setHeader("Content-Type","text/plain"),S.end("Error processing OAuth callback."),A}finally{clearTimeout(_),p.off("request",v);for(let A of g)A.destroy();p.close(()=>w())}};p.on("request",v)})}let u=new URL(a);u.hash="",u.search="";let l=Nd(o,{scope:i,redirect_uri:u.toString(),state:s});typeof window<"u"?window.location.href=l.toString():(console.log("Please open the following URL in your browser:"),console.log(l.toString()),await c)}completeOauth(){if(typeof window>"u")return;let t=window.localStorage.getItem(br);if(!t)return;let n;try{n=JSON.parse(t)}catch{console.error("Invalid OAuth2 login data in local storage."),window.localStorage.removeItem(br);return}let r=jy.safeParse(n);if(!r.success){console.error("Invalid OAuth2 login data structure in local storage.",r.error),window.localStorage.removeItem(br);return}let{loginId:o,redirectUri:i,authorizationEndpoint:s,state:a,serviceEndpoints:c}=r.data;try{let u=new URL(i),l=new URL(window.location.href);if(u.pathname!==l.pathname)return;let d=l.searchParams;return!d.has("code")&&!d.has("error")?void 0:(window.history.replaceState({},document.title,u.toString()),window.localStorage.removeItem(br),new Promise(p=>setTimeout(p,0)).then(()=>this.getAuthorizationConfiguration(s)).then(p=>this.onCallbackUrl({loginId:o,callbackUrl:l,configuration:p,expectedState:a,serviceEndpoints:c})).catch(p=>{let m=p instanceof Error?p:new Error("Unknown error"),w={loginId:o,error:m};this.eventTarget.dispatchEvent(new CustomEvent("login",{detail:w}))}))}catch(u){console.error(u)}}async onCallbackUrl(t){let{loginId:n,callbackUrl:r,configuration:o,expectedState:i,serviceEndpoints:s}=t,a=await Ys(o,r,{expectedState:i}),c=a.access_token,l=a.scope?.split(" ").map(decodeURIComponent)||s;if(!s.every(p=>l.includes(p)))throw new Error("Not all requested service endpoints were granted.");let d=new CustomEvent("login",{detail:{loginId:n,token:c}});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"),s={logoutId:n,error:i};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:s}))}}async logout_(t,n,r){let o=await this.getAuthorizationConfiguration(t);await Bd(o,r);let i={logoutId:n};this.eventTarget.dispatchEvent(new CustomEvent("logout",{detail:i}))}async getAuthorizationConfiguration(t){if(!t.startsWith(jd))throw new Error(`Unrecognized authorization endpoint method: ${t}`);let n=t.slice(jd.length),r;try{r=new URL(n)}catch{throw new Error("Invalid issuer URL.")}return await Ud(r,"graffiti-client")}},Zd=qc(be({loginId:B()}),ft([be({token:B(),error:ee(Gc())}),be({error:Jt(Error)})])),Fd=be({logoutId:B(),error:ee(Jt(Error))}),Hd=ee(Ze(be({error:ee(Jt(Error))}))),jy=be({loginId:B(),redirectUri:Z(),authorizationEndpoint:Z(),state:B(),serviceEndpoints:J(Z())});var Zy="https://";function $e(e){if(!e.startsWith(Zy))throw new Error("Unrecognized storage bucket endpoint type")}async function Bo(e){$e(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 Dt=class e extends Error{constructor(t){super(t),this.name="GraffitiErrorUnauthorized",Object.setPrototypeOf(this,e.prototype)}};async function We(...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 Dt(n):t.status===403?new dt(n):t.status===404?new re(n):t.status===410?new Ce(n):t.status===413?new Ht(n):new Error(n)}return t}var jo=class{getAuthorizationEndpoint=Bo;async put(t,n,r,o){$e(t);let i=`${t}/value/${encodeURIComponent(n)}`;await We(i,{method:"PUT",headers:{"Content-Type":"application/octet-stream",Authorization:`Bearer ${o}`},body:r.slice()})}async delete(t,n,r){$e(t);let o=`${t}/value/${encodeURIComponent(n)}`;await We(o,{method:"DELETE",headers:{Authorization:`Bearer ${r}`}})}async get(t,n,r){$e(t);let o=`${t}/value/${encodeURIComponent(n)}`,i=await We(o),s=i.body?.getReader();if(!s)throw new Error("Failed to read value from storage bucket");let a=i.headers.get("Content-Length"),c=a?Number(a):void 0;if(!!c&&!!Number.isFinite(c)&&c>=0){let w=c;if(r!==void 0&&w>r)throw new Error("Value exceeds maximum byte limit");let x=new Uint8Array(w),_=0,g=!1;try{for(;_<=x.length;){let{done:v,value:b}=await s.read();if(v){g=!0;break}if(!b||b.length===0)continue;let S=_+b.length;if(S>x.length)throw new Error("Received more data than expected");x.set(b,_),_=S}}finally{s.releaseLock()}if(!g)throw new Error("Failed to read complete value from storage bucket");return _===w?x:x.slice(0,_)}let l=[],d=0;try{for(;;){let{done:w,value:x}=await s.read();if(w)break;if(!(!x||x.length===0)){if(d+=x.length,r!==void 0&&d>r)throw new Error("Value exceeds maximum byte limit");l.push(x.slice())}}}finally{s.releaseLock()}let p=new Uint8Array(d),m=0;for(let w of l)p.set(w,m),m+=w.length;return p}async*export(t,n){$e(t);let r=`${t}/export`,o;for(;;){let s=await(await We(o?`${r}?cursor=${encodeURIComponent(o)}`:r,{headers:{Authorization:`Bearer ${n}`}})).blob(),a=qe(await s.arrayBuffer()),c=Fy.parse(a);for(let u of c.keys)yield{key:u};if(c.cursor)o=c.cursor;else break}}},Fy=be({keys:J(B()),cursor:ee(Ze(B()))});var Fo=class{getAuthorizationEndpoint=Bo;cache_=null;get cache(){return this.cache_||(this.cache_=Wy()),this.cache_}async send(t,n){$e(t);let r=`${t}/send`,i=await(await We(r,{method:"PUT",headers:{"Content-Type":"application/cbor"},body:new Uint8Array(Re({m:n}))})).blob(),s=qe(await i.arrayBuffer());return Jy.parse(s).id}async get(t,n,r){let o=Zo(t,n),i=await this.cache,s=await i.messages.get(o);if(s!==void 0)return s;let a=`${t}/message/${n}`,c=null;try{c=await We(a,{method:"GET",headers:{...r?{Authorization:`Bearer ${r}`}:{}}})}catch(p){if(p instanceof re)return await i.messages.set(o,null),null;throw p}let u=await c.blob(),l=qe(await u.arrayBuffer()),d=Vd.parse(l);return await i.messages.set(o,d),d}async label(t,n,r,o){if($e(t),o){let c=`${t}/label/${n}`;await We(c,{method:"PUT",headers:{"Content-Type":"application/cbor",Authorization:`Bearer ${o}`},body:new Uint8Array(Re({l:r}))})}let i=await this.cache,s=Zo(t,n),a=await i.messages.get(s);a&&await i.messages.set(s,{...a,l:r})}async fetchMessageBatch(t,n,r,o,i){let s=await We(`${t}/${n}${i?`?cursor=${encodeURIComponent(i)}`:""}`,{method:"POST",headers:{"Content-Type":"application/cbor",...o?{Authorization:`Bearer ${o}`}:{}},body:r}),a=s.headers.get("Retry-After"),c=a?parseInt(a):void 0,u=c&&Number.isFinite(c)?Date.now()+c*1e3:void 0;return{response:s,waitTil:u}}async*yieldFromCache(t,n,r,o,i=0){let s=o.messageIds.slice(i);yield*await Promise.all(s.map(async c=>{let u=await t.messages.get(Zo(n,c));if(!u){try{await t.messageIds.del(r)}catch{}throw new Error("Cache out of sync - perhaps clear browser storage")}return u}))}async*lockedMessageStreamer(...t){if(typeof window>"u"||!await Wd()){let w=this.messageStreamer(...t);for(;;){let x=await w.next();if(x.done)return x.value;yield x.value}}let n=await t[0],r=`graffiti:inbox:${n}`,o=()=>{},i=!1;if(await new Promise(w=>{window.navigator.locks.request(r,{mode:"exclusive",ifAvailable:!0},async x=>{i=!!x,w(),await new Promise(_=>o=_)})}),i)try{let w=this.messageStreamer(...t);for(;;){let x=await w.next();if(x.done)return x.value;yield x.value}}finally{o()}o(),await window.navigator.locks.request(r,()=>{});let s=t[1],a=t[5]??{},c=t[6],u=t[7],l=await this.cache,d=await l.messageIds.get(n);if(!d)throw new Error("Cache not found");if(c!==void 0&&c!==d.version)throw new Ce("Cursor is stale");let p=this.yieldFromCache(l,s,n,d,u);for await(let w of p)yield w;let m={numSeen:d.messageIds.length,version:d.version,messageIdsCacheKey:n,objectSchema:a};return JSON.stringify(m)}async*messageStreamer(t,n,r,o,i,s={},a,c=0){let u=await Or(s),l=await t,d=await this.cache,p=await d.messageIds.get(l);if(a!==void 0&&a!==p?.version)throw new Ce("Cursor is stale");let m=p?.waitTil;await Jd(m);let w=p?.cursor,x;try{let A=await this.fetchMessageBatch(n,r,o,i,w);x=A.response,m=A.waitTil}catch(A){if(!(A instanceof Ce&&w))throw console.error("Unexpected error in stream, waiting 5 seconds before continuing..."),await new Promise(O=>setTimeout(O,5e3)),A;if(await d.messageIds.del(l),a===void 0)p=void 0;else throw A}if(x!==void 0&&p){let A=this.yieldFromCache(d,n,l,p,c);for await(let O of A)yield O}if(x===void 0){let A=await this.fetchMessageBatch(n,r,o,i);x=A.response,m=A.waitTil}let _=x,g,v=p?.version??crypto.randomUUID(),b=p?.messageIds??[];for(;;){let A=await _.blob(),O=qe(await A.arrayBuffer()),{results:D,hasMore:L,cursor:ne}=Ky.parse(O);g=ne;let H=D.map(E=>{let C=E[Ut][st];if(!u(C))throw new Error("Server returned data that does not match schema");return{...E,[Ut]:{...E[Ut],[st]:C}}});await Promise.all(H.map(E=>d.messages.set(Zo(n,E[ea]),E))),b=[...b,...H.map(E=>E[ea])],await d.messageIds.set(l,{cursor:g,version:v,messageIds:b,waitTil:m}),c+=H.length;for(let E of H)yield E;if(!L)break;await Jd(m);let h=await this.fetchMessageBatch(n,r,void 0,i,g);_=h.response,m=h.waitTil}return JSON.stringify({numSeen:c,version:v,messageIdsCacheKey:l,objectSchema:s})}query(t,n,r,o){$e(t);let i=Re({tags:n,schema:r}),s=Gd(t,"query",i);return this.lockedMessageStreamer(s,t,"query",new Uint8Array(i),o,r)}continueQuery(t,n,r){$e(t);let o=JSON.parse(n),{messageIdsCacheKey:i,numSeen:s,objectSchema:a,version:c}=Vy.parse(o);return this.lockedMessageStreamer(Promise.resolve(i),t,"query",void 0,r,a,c,s)}export(t,n){$e(t);let r=Gd(t,"export");return this.lockedMessageStreamer(r,t,"export",void 0,n)}},Hy=xe({value:me({}),channels:J(B()),allowed:ee(Ze(J(Z()))),url:Z(),actor:Z()}),Kd=Rt(e=>e instanceof Uint8Array),Gy=J(Kd),xr="t",st="o",Er="m",qy=xe({[xr]:Gy,[st]:Hy,[Er]:Kd}),ea="id",Ut="m",Ho="l",Vd=xe({[ea]:B(),[Ut]:qy,[Ho]:Hc()}),Jy=xe({id:B()}),Ky=xe({results:J(Vd),hasMore:Ii(),cursor:B()}),Vy=xe({messageIdsCacheKey:B(),version:B(),numSeen:qt().check(At()),objectSchema:ft([me({}),Ii()])});async function Wd(){try{return globalThis.indexedDB?(await new Promise((e,t)=>{let n=indexedDB.open("__idb_probe__",1);n.onupgradeneeded=()=>n.result.createObjectStore("k"),n.onsuccess=()=>{n.result.close(),e()},n.onerror=()=>t(n.error)}),!0):!1}catch{return!1}}function Zo(e,t){return`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}async function Gd(e,t,n){let r=Re({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 qd(){await new Promise(e=>{let t=indexedDB.deleteDatabase("graffiti-inbox-cache");t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})}async function Wy(){if(await Wd()){let{openDB:n}=await import("./build-DM3HADDZ.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 qd();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 qd();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 Jd(e){if(e!==void 0){let t=e-Date.now();t>0&&await new Promise(n=>setTimeout(n,t))}}var Tn="base64url";var Go=class{async encode(t,n){if(t!==Tn)throw new Error(`Unsupported string encoding method: ${t}`);return"u"+btoa(String.fromCodePoint(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,"")}async decode(t){if(!t.startsWith("u"))throw new Error(`Unsupported string encoding prefix: ${t[0]}`);t=t.slice(1);let n=t.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";return Uint8Array.from(atob(n),r=>r.charCodeAt(0))}};function Xd(){let t=(typeof globalThis=="object"?globalThis.crypto:null)?.subtle;if(typeof t=="object"&&t!=null)return t;throw new Error("crypto.subtle must be defined")}function Yd(e,t,n){let r=async o=>{jr(o);let i=Xd();return new Uint8Array(await i.digest(e,o))};return r.webCryptoName=e,r.outputLen=n,r.blockLen=t,r.create=()=>{throw new Error("not implemented")},Object.freeze(r)}function Xy(e){if(Yc(e),typeof e.webCryptoName!="string")throw new Error("non-web hash")}var Mt=Yd("SHA-256",64,32);var Qd=Yd("SHA-512",128,64),ta=(()=>{let e=async(t,n,r)=>{let o=Xd();jr(n,void 0,"key"),jr(r,void 0,"message"),Xy(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 qo="sha2-256",vr=18,Pn=32,Jo=class{async register(t,n){if(t!==qo)throw new Error(`Unsupported content address method: ${t}`);let r=await Mt(n),o=new Uint8Array(2+r.length);return o[0]=vr,o[1]=Pn,o.set(r,2),o}async getMethod(t){if(t[0]===vr&&t[1]===Pn&&t.length===2+Pn)return qo;throw new Error("Unrecognized content address format.")}};var cf=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Vo,n:Ko,Gx:ef,Gy:tf,a:na,d:ra,h:Yy}=cf,kn=32,Qy=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ue=(e="")=>{let t=new Error(e);throw Qy(t,ue),t},ew=e=>typeof e=="bigint",tw=e=>typeof e=="string",nw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Be=(e,t,n="")=>{let r=nw(e),o=e?.length,i=t!==void 0;if(!r||i&&o!==t){let s=n&&`"${n}" `,a=i?` of length ${t}`:"",c=r?`length=${o}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw r?new RangeError(u):new TypeError(u)}return e},aa=e=>new Uint8Array(e),ca=e=>Uint8Array.from(e),uf=(e,t)=>e.toString(16).padStart(t,"0"),lf=e=>Array.from(Be(e)).map(t=>uf(t,2)).join(""),at={_0:48,_9:57,A:65,F:70,a:97,f:102},nf=e=>{if(e>=at._0&&e<=at._9)return e-at._0;if(e>=at.A&&e<=at.F)return e-(at.A-10);if(e>=at.a&&e<=at.f)return e-(at.a-10)},df=e=>{let t="hex invalid";if(!tw(e))return ue(t);let n=e.length,r=n/2;if(n%2)return ue(t);let o=aa(r);for(let i=0,s=0;i<r;i++,s+=2){let a=nf(e.charCodeAt(s)),c=nf(e.charCodeAt(s+1));if(a===void 0||c===void 0)return ue(t);o[i]=a*16+c}return o},rw=()=>globalThis?.crypto,ow=()=>rw()?.subtle??ue("crypto.subtle must be defined, consider polyfill"),Sr=(...e)=>{let t=0;for(let o of e)t+=Be(o).length;let n=aa(t),r=0;return e.forEach(o=>{n.set(o,r),r+=o.length}),n};var Wo=BigInt,Nt=(e,t,n,r="bad number: out of range")=>{if(!ew(e))throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},Q=(e,t=Vo)=>{let n=e%t;return n>=0n?n:t+n},rf=(1n<<255n)-1n,k=e=>{e<0n&&ue("negative coordinate");let t=(e>>255n)*19n+(e&rf);return t=(t>>255n)*19n+(t&rf),t%Vo},ff=e=>Q(e,Ko),iw=(e,t)=>{(e===0n||t<=0n)&&ue("no inverse n="+e+" mod="+t);let n=Q(e,t),r=t,o=0n,i=1n,s=1n,a=0n;for(;n!==0n;){let c=r/n,u=r%n,l=o-s*c,d=i-a*c;r=n,n=u,o=s,i=a,s=l,a=d}return r===1n?Q(o,t):ue("no inverse")},sw=e=>{let t=da[e];return typeof t!="function"&&ue("hashes."+e+" not set"),t},aw=e=>Be(e,64,"digest");var oa=e=>e instanceof ct?e:ue("Point expected"),ia=2n**256n,ct=class e{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,o){let i=ia;this.X=Nt(t,0n,i),this.Y=Nt(n,0n,i),this.Z=Nt(r,1n,i),this.T=Nt(o,0n,i),Object.freeze(this)}static CURVE(){return cf}static fromAffine(t){return new e(t.x,t.y,1n,k(t.x*t.y))}static fromBytes(t,n=!1){let r=ra,o=ca(Be(t,kn)),i=t[31];o[31]=i&-129;let s=ua(o);Nt(s,0n,n?ia:Vo);let c=k(s*s),u=Q(c-1n),l=k(r*c+1n),{isValid:d,value:p}=uw(u,l);d||ue("bad point: y not sqrt");let m=(p&1n)===1n,w=(i&128)!==0;return!n&&p===0n&&w&&ue("bad point: x==0, isLastByteOdd"),w!==m&&(p=Q(-p)),new e(p,s,1n,k(p*s))}static fromHex(t,n){return e.fromBytes(df(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=na,n=ra,r=this;if(r.is0())return ue("bad point: ZERO");let{X:o,Y:i,Z:s,T:a}=r,c=k(o*o),u=k(i*i),l=k(s*s),d=k(l*l),p=k(c*t),m=k(l*(p+u)),w=Q(d+k(n*k(c*u)));if(m!==w)return ue("bad point: equation left != right (1)");let x=k(o*i),_=k(s*a);return x!==_?ue("bad point: equation left != right (2)"):this}equals(t){let{X:n,Y:r,Z:o}=this,{X:i,Y:s,Z:a}=oa(t),c=k(n*a),u=k(i*o),l=k(r*a),d=k(s*o);return c===u&&l===d}is0(){return this.equals(Lt)}negate(){return new e(Q(-this.X),this.Y,this.Z,Q(-this.T))}double(){let{X:t,Y:n,Z:r}=this,o=na,i=k(t*t),s=k(n*n),a=k(2n*r*r),c=k(o*i),u=Q(t+n),l=Q(k(u*u)-i-s),d=Q(c+s),p=Q(d-a),m=Q(c-s),w=k(l*p),x=k(d*m),_=k(l*m),g=k(p*d);return new e(w,x,g,_)}add(t){let{X:n,Y:r,Z:o,T:i}=this,{X:s,Y:a,Z:c,T:u}=oa(t),l=na,d=ra,p=k(n*s),m=k(r*a),w=k(k(i*d)*u),x=k(o*c),_=Q(k(Q(n+r)*Q(s+a))-p-m),g=Q(x-w),v=Q(x+w),b=Q(m-k(l*p)),S=k(_*g),A=k(v*b),O=k(_*b),D=k(g*v);return new e(S,A,D,O)}subtract(t){return this.add(oa(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Nt(t,1n,Ko),!n&&this.is0()))return Lt;if(t===1n)return this;if(this.equals(_t))return mw(t).p;let r=Lt,o=_t;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(Lt))return{x:0n,y:1n};let o=iw(r,Vo);k(r*o)!==1n&&ue("invalid inverse");let i=k(t*o),s=k(n*o);return{x:i,y:s}}toBytes(){let{x:t,y:n}=this.toAffine(),r=pf(n);return r[31]|=t&1n?128:0,r}toHex(){return lf(this.toBytes())}clearCofactor(){return this.multiply(Wo(Yy),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Ko/2n,!1).double();return Ko%2n&&(t=t.add(this)),t.is0()}},_t=new ct(ef,tf,1n,Q(ef*tf)),Lt=new ct(0n,1n,1n,0n);ct.BASE=_t;ct.ZERO=Lt;var pf=e=>df(uf(Nt(e,0n,ia),64)).reverse(),ua=e=>Wo("0x"+lf(ca(Be(e)).reverse())),Xe=(e,t)=>{let n=e;for(;t-- >0n;)n=k(n*n);return n},cw=e=>{let t=k(e*e),n=k(t*e),r=k(Xe(n,2n)*n),o=k(Xe(r,1n)*e),i=k(Xe(o,5n)*o),s=k(Xe(i,10n)*i),a=k(Xe(s,20n)*s),c=k(Xe(a,40n)*a),u=k(Xe(c,80n)*c),l=k(Xe(u,80n)*c),d=k(Xe(l,10n)*i);return{pow_p_5_8:k(Xe(d,2n)*e),b2:n}},of=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,uw=(e,t)=>{let n=k(t*k(t*t)),r=k(k(n*n)*t),o=cw(k(e*r)).pow_p_5_8,i=k(e*k(n*o)),s=k(t*k(i*i)),a=i,c=k(i*of),u=s===e,l=s===Q(-e),d=s===Q(-e*of);return u&&(i=a),(l||d)&&(i=c),(Q(i)&1n)===1n&&(i=Q(-i)),{isValid:u||l,value:i}},Xo=e=>ff(ua(e)),la=(...e)=>Promise.resolve(sw("sha512Async")(Sr(...e))).then(aw);var lw=e=>{let t=ca(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32,64),o=Xo(n),i=_t.multiply(o),s=i.toBytes();return{head:n,prefix:r,scalar:o,point:i,pointBytes:s}},hf=e=>la(Be(e,kn)).then(lw);var mf=e=>hf(e).then(t=>t.pointBytes);var gf=e=>la(e.hashable).then(e.finish);var dw=(e,t,n)=>{let{pointBytes:r,scalar:o}=e,i=Xo(t),s=_t.multiply(i).toBytes();return{hashable:Sr(s,r,n),finish:u=>{let l=ff(i+Xo(u)*o);return Be(Sr(s,pf(l)),64)}}},yf=async(e,t)=>{let n=Be(e),r=await hf(t),o=await la(r.prefix,n);return gf(dw(r,o,n))};var wf={zip215:!0},fw=(e,t,n,r=wf)=>{e=Be(e,64),t=Be(t),n=Be(n,kn);let{zip215:o=!0}=r,i=e.subarray(0,kn),s=ua(e.subarray(kn,kn*2)),a,c,u,l=Uint8Array.of(),d=!1;try{a=ct.fromBytes(n,o),c=ct.fromBytes(i,o),u=_t.multiply(s,!1),l=Sr(i,n,t),d=!0}catch{}return{hashable:l,finish:m=>{if(!d||!o&&a.isSmallOrder())return!1;let w=Xo(m);return c.add(a.multiply(w,!1)).subtract(u).clearCofactor().is0()}}},_f=async(e,t,n,r=wf)=>gf(fw(e,t,n,r));var da={sha512Async:async e=>{let t=ow(),n=Sr(e);return aa(await t.digest("SHA-512",n.buffer))},sha512:void 0};var Yo=8,pw=256,bf=Math.ceil(pw/Yo)+1,sa=2**(Yo-1),hw=()=>{let e=[],t=_t,n=t;for(let r=0;r<bf;r++){n=t,e.push(n);for(let o=1;o<sa;o++)n=n.add(t),e.push(n);t=n.double()}return e},sf,af=(e,t)=>{let n=t.negate();return e?n:t},mw=e=>{let t=sf||(sf=hw()),n=Lt,r=_t,o=2**Yo,i=o,s=Wo(o-1),a=Wo(Yo);for(let c=0;c<bf;c++){let u=Number(e&s);e>>=a,u>sa&&(u-=i,e+=1n);let l=c*sa,d=l,p=l+Math.abs(u)-1,m=c%2!==0,w=u<0;u===0?r=r.add(af(m,t[d])):n=n.add(af(w,t[p]))}return e!==0n&&ue("invalid wnaf"),{p:n,f:r}};da.sha512Async=Qd;var Bt="pk:sha2-256+ed25519",fa=0,Qo=class{async register(t,n){if(t!==Bt)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]===fa)return Bt;throw new Error("Unrecognized channel attestation method.")}async channelToPrivateKey(t){let n=new TextEncoder().encode(t);return await Mt(n)}async channelPublicIdFromPrivateKey(t){let n=await mf(t),r=new Uint8Array(n.length+1);return r[0]=fa,r.set(n,1),r}async attest(t,n,r){if(t!==Bt)throw new Error(`Unsupported channel attestation method: ${t}`);let o=await this.channelToPrivateKey(r),i=await this.channelPublicIdFromPrivateKey(o),s=new TextEncoder().encode(n);return{attestation:await yf(s,o),channelPublicId:i}}async validate(t,n,r){let o=r[0];if(o!==fa)throw new Error(`Unrecognized channel attestation method prefix: ${o}`);return await _f(t,new TextEncoder().encode(n),r.slice(1))}};var pa="hmac:sha2-256",xf=0,ei=class{async attest(t,n){if(t!==pa)throw new Error(`Unsupported allowed attestation method: ${t}`);let r=Tt(),o=await ta(Mt,r,new TextEncoder().encode(n)),i=new Uint8Array(r.length+3);return i[0]=xf,i[1]=vr,i[2]=Pn,i.set(r,3),{attestation:o,ticket:i}}async validate(t,n,r){let o=r[0],i=r[1],s=r[2];if(o!==xf||i!==vr||s!==Pn)throw new Error("Unrecognized allowed ticket format");let a=await ta(Mt,r.slice(3),new TextEncoder().encode(n));return t.length!==a.length?!1:a.every((c,u)=>t[u]===c)}};var ha="did:web:",ti=class{constructor(t){this.services=t}services;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(ha))throw new Error(`Handle DID ${r} is not a valid handle`);let o=r.slice(ha.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=`${ha}${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}};function ni(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)r!=="__proto__"&&(e[r]=n[r])}return e}var gw={read:function(e){return e[0]==='"'&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function ma(e,t){function n(o,i,s){if(!(typeof document>"u")){s=ni({},t,s),typeof s.expires=="number"&&(s.expires=new Date(Date.now()+s.expires*864e5)),s.expires&&(s.expires=s.expires.toUTCString()),o=encodeURIComponent(o).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var c in s)s[c]&&(a+="; "+c,s[c]!==!0&&(a+="="+s[c].split(";")[0]));return document.cookie=o+"="+e.write(i,o)+a}}function r(o){if(!(typeof document>"u"||arguments.length&&!o)){for(var i=document.cookie?document.cookie.split("; "):[],s={},a=0;a<i.length;a++){var c=i[a].split("="),u=c.slice(1).join("=");try{var l=decodeURIComponent(c[0]);if(l in s||(s[l]=e.read(u,l)),o===l)break}catch{}}return o?s[o]:s}}return Object.create({set:n,get:r,remove:function(o,i){n(o,"",ni({},i,{expires:-1}))},withAttributes:function(o){return ma(this.converter,ni({},this.attributes,o))},withConverter:function(o){return ma(ni({},this.converter,o),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(e)}})}var ri=ma(gw,{path:"/"});var yw=365;function Ef(e,t){ri.set(e,t,Sf())}function vf(e){return ri.get(e)}function ga(e){ri.remove(e,Sf())}function Sf(){let e={expires:yw,path:"/",sameSite:"lax"};return typeof window<"u"&&window.location.protocol==="https:"&&(e.sameSite="none",e.secure=!0),e}var ai="GraffitiInbox",ui="GraffitiStorageBucket",ba="#graffitiPersonalInbox",li="#graffitiStorageBucket",ww="#graffitiSharedInbox_",ci=class{constructor(t){this.services=t;let n=new Promise(o=>{this.services.authorization.eventTarget.addEventListener("initialized",i=>{if(!(i instanceof CustomEvent))return;let s=Hd.safeParse(i.detail);if(!s.success)return;let a=s.data?.error;a&&console.error(a),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),s=new URL(window.location.toString());s.searchParams.delete("actor"),window.history.replaceState({},"",s.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 s=new CustomEvent("login",{detail:{session:{actor:i.actor}}});this.sessionEvents.dispatchEvent(s)}await n;let o=new CustomEvent("initialized");this.sessionEvents.dispatchEvent(o)})()}services;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(b=>b.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(b=>b.id===li&&b.type===ui),s=o.find(b=>b.id===ba&&b.type===ai),a=o.filter(b=>b.id.match(new RegExp(`^${ww}\\d+$`))&&b.type===ai);if(!s||!i||a.length===0)throw new Error(`Required services not found in actor document for ${t}`);let c=wa(i),u=wa(s),l=a.map(wa),d=[{endpoint:c,type:"bucket"},{endpoint:u,type:"personal-inbox"},...l.map(b=>({endpoint:b,type:"shared-inbox"}))],p=await Promise.all(d.map(async({endpoint:b,type:S})=>{let A=await(S==="bucket"?this.services.storageBuckets.getAuthorizationEndpoint(b):this.services.inboxes.getAuthorizationEndpoint(b));return{endpoint:b,authorizationEndpoint:A,type:S}})),m=new Map;p.forEach(({authorizationEndpoint:b,endpoint:S,type:A})=>{m.has(b)||m.set(b,[]),m.get(b).push({endpoint:S,type:A})});let w=[...m.entries()],_={...{actor:t},tokens:[],servicesByAuthorization:w};typeof window<"u"?window.localStorage.setItem(oi,JSON.stringify(_)):this.inProgressLogin=_;let[g,v]=w[0];await this.services.authorization.login(g,t,v.map(b=>b.endpoint))}async onLogin(t){if(!(t instanceof CustomEvent))return;let n=Zd.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(oi);if(!i)throw new Error("No in-progress login found");let s=JSON.parse(i);o=_a.parse(s)}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(oi);let i=o.servicesByAuthorization.flatMap(([u,l],d)=>l.map(p=>({token:o.tokens[d],serviceEndpoint:p.endpoint,authorizationEndpoint:u,type:p.type}))),s={...o,storageBucket:i.find(u=>u.type==="bucket"),personalInbox:i.find(u=>u.type==="personal-inbox"),sharedInboxes:i.filter(u=>u.type==="shared-inbox")},a=this.loggedInSessions;a.push(s),this.loggedInSessions=a;let c=new CustomEvent("login",{detail:{session:{actor:r}}});this.sessionEvents.dispatchEvent(c)}else{typeof window<"u"?window.localStorage.setItem(oi,JSON.stringify(o)):this.inProgressLogin=o;let[i,s]=o.servicesByAuthorization[o.tokens.length];await this.services.authorization.login(i,r,s.map(a=>a.endpoint))}}async logout(t){try{await this.logout_(t)}catch(n){let r=new CustomEvent("logout",{detail:{error:n instanceof Dt?void 0:n instanceof Error?n:new Error(String(n)),actor:t}});this.sessionEvents.dispatchEvent(r)}}async logout_(t){let n=this.loggedInSessions.find(s=>s.actor===t);if(!n)throw new Error(`No session found for actor ${t}`);this.loggedInSessions=this.loggedInSessions.filter(s=>s.actor!==t);let r=n.tokens.pop();if(!r)throw new Error("No tokens found in session");typeof window<"u"?window.localStorage.setItem(ii,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=Fd.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(ii);if(!i)throw new Error("No in-progress logout found");let s=JSON.parse(i);r=_a.parse(s)}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(ii,JSON.stringify(r)):this.inProgressLogout=r;let[i,s]=r.servicesByAuthorization[r.tokens.length];await this.services.authorization.logout(i,n,o)}else{typeof window>"u"?this.inProgressLogout=void 0:window.localStorage.removeItem(ii);let i=new CustomEvent("logout",{detail:{actor:n}});this.sessionEvents.dispatchEvent(i)}}get loggedInSessions(){if(typeof window>"u")return Af;let t=vf(si);if(!t)return[];let n;try{n=JSON.parse(t)}catch{return console.error("Error parsing stored session data"),ga(si),[]}let r=J(xw).safeParse(n);return r.success?r.data:(console.error("Stored session data is invalid"),ga(si),[])}set loggedInSessions(t){if(typeof window>"u"){Af=t;return}Ef(si,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}},Af=[],oi="graffiti-login-in-progress",ii="graffiti-logout-in-progress",si="graffiti-sessions-logged-in",_w=be({actor:Z()}),ya=be({token:B(),serviceEndpoint:Z(),authorizationEndpoint:Z()}),bw=J(pe([Z(),J(be({endpoint:Z(),type:Kc(["bucket","personal-inbox","shared-inbox"])}))])),_a=rt(_w,{tokens:J(B()),servicesByAuthorization:bw}),xw=rt(_a,{storageBucket:ya,personalInbox:ya,sharedInboxes:J(ya)});function wa(e){if(typeof e.serviceEndpoint=="string")return e.serviceEndpoint;throw new Error(`Service endpoint for ${e.id} is not a string`)}var di=32*1024,fi=class{constructor(t){this.primitives=t}primitives;async encode(t,n){t=Ra(t);let r=[...new Set(t.channels)],o=await Promise.all(r.map(x=>this.primitives.channelAttestations.attest(Bt,n,x))),i=o.map(x=>x.attestation),s=o.map(x=>x.channelPublicId),a={[Ea]:t.value,[va]:i,[Pf]:Tt(32)},c;if(Array.isArray(t.allowed)){let x=await Promise.all(t.allowed.map(async _=>this.primitives.allowedAttestations.attest(pa,_)));a[Sa]=x.map(_=>_.attestation),c=x.map(_=>_.ticket)}let u=Re(a);if(u.byteLength>di)throw new Error("The object is too large");let l=await this.primitives.contentAddresses.register(qo,u),d=await this.primitives.stringEncoder.encode(Tn,l),p=vw(n,d),m=[new TextEncoder().encode(p),...s];return{object:{value:t.value,channels:r,url:p,actor:n,...t.allowed?{allowed:t.allowed}:{}},tags:m,objectBytes:u,allowedTickets:c}}async validate(t,n,r,o){if(r.byteLength>di)throw new Error("Object is too big");let{actor:i,contentAddress:s}=Ta(t.url);if(i!==t.actor)throw new Error("Object actor does not match URL actor");let a=n.at(0);if(!a)throw new Error("No object URL tag");if(new TextDecoder().decode(a)!==t.url)throw new Error("Object URL tag does not match object URL");let c=n.slice(1),u=await this.primitives.stringEncoder.decode(s),l=await this.primitives.contentAddresses.getMethod(u),d=await this.primitives.contentAddresses.register(l,r);if(d.length!==u.length||!d.every((b,S)=>b===u[S]))throw new Error("Content address is invalid");let p=qe(r),m=Ew.parse(p),w=m[Ea],x=m[va],_=m[Sa],g=Re(w),v=Re(t.value);if(g.length!==v.length||!g.every((b,S)=>b===v[S]))throw new Error("Object value does not match storage value");if(x.length!==c.length)throw new Error("Not as many channel attestations and public ids");for(let[b,S]of x.entries()){let A=c[b];if(!await this.primitives.channelAttestations.validate(S,i,A))throw new Error("Invalid channel attestation")}if(t.channels.length){if(t.channels.length!==c.length)throw new Error("Number of claimed channels does not match attestations/public IDs");let b=await this.primitives.channelAttestations.getMethod(c[0]),S=await Promise.all(t.channels.map(A=>this.primitives.channelAttestations.register(b,A)));for(let[A,O]of S.entries()){let D=c[A];if(O.length!==D.length||!O.every((L,ne)=>L===D[ne]))throw new Error("Channel public id does not match expected")}}if(o){if(!_)throw new Error("Object is public but thought to be private");let b,S,A;if("recipient"in o?(b=[o.recipient],S=[o.allowedTicket],A=_.filter((O,D)=>D===o.allowedIndex)):(b=[...t.allowed??[]],S=o.allowedTickets,A=_),b.length!==t.allowed?.length)throw new Error("Recipient count does not match object allowed list");if(!b.every(O=>t.allowed?.includes(O)))throw new Error("Recipient not in object allowed list");for(let[O,D]of b.entries()){let L=S.at(O),ne=A.at(O);if(!L)throw new Error("Missing allowed ticket for recipient");if(!ne)throw new Error("Missing allowed attestation for recipient");if(!await this.primitives.allowedAttestations.validate(ne,D,L))throw new Error("Invalid allowed attestation for recipient")}}else if(_)throw new Error("Object is private but no recipient info provided")}},Ea="v",va="c",Sa="a",Pf="n",xa=Rt(e=>e instanceof Uint8Array),Ew=xe({[Ea]:me({}),[va]:J(xa),[Sa]:ee(J(xa)),[Pf]:xa}),Aa="graffiti:";function Rf(e){let t=e.replace(/:/g,"!").replace(/\//g,"~");return encodeURIComponent(t)}function Tf(e){return decodeURIComponent(e).replace(/!/g,":").replace(/~/g,"/")}function vw(e,t){return`${Aa}${Rf(e)}:${Rf(t)}`}function Ta(e){if(!e.startsWith(Aa))throw new Error("Invalid object URL");let n=e.slice(Aa.length).split(":");if(n.length!==2)throw new Error("Invalid object URL format");let[r,o]=n;return{actor:Tf(r),contentAddress:Tf(o)}}function Ra(e){return e===void 0?null:Array.isArray(e)?e.map(Ra):typeof e=="object"?Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0).map(([t,n])=>[t,Ra(n)])):e}var kf=class{dialog=document.createElement("dialog");shadow;main_;useTemplateHTML;templates_;onManualClose;displayTemplateSeq=0;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-BOBMBTYJ-GXWKT5M3.js"),import("./graffiti-KV3G3O72-TAZN6KIP.js"),import("./rock-salt-LI7DAH66-TZP5ZWGV.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 s=new FontFace("Rock Salt",`url(${n})`,{style:"normal",weight:"400"});document.fonts.add(s),await s.load(),e=e.replace("url(graffiti.jpg)",`url(${t})`);let a=new CSSStyleSheet;return a.replace(e).then(()=>{this.shadow.adoptedStyleSheets=[a]}),i})),this.main_}async open(){await this.main,this.dialog.showModal(),this.dialog.focus()}close(){this.dialog.close()}async displayTemplate(e){let t=++this.displayTemplateSeq,n=()=>{if(t!==this.displayTemplateSeq)throw new Error(`displayTemplate(${e}) overridden by concurrent call`)},r=await this.main;n();let o=(await this.templates).get(e);if(n(),!o)throw new Error(`Template not found: ${e}`);let i=o.content.cloneNode(!0);return r.replaceChildren(i),r}};var If=Rt(e=>e instanceof Uint8Array),Oa="k",On="t",$a=xe({[Oa]:B(),[On]:ee(B())}),jt="id",za="e",Ar="a",Sw=J(xe({[jt]:B(),[za]:ee(Z()),[Ar]:ee(Z())})),pi="s",hi="n",Aw=rt($a,{[pi]:ee(J(If)),[hi]:Sw}),Rr="a",Ia="i",Rw=rt($a,{[Rr]:If,[Ia]:qt().check(At())}),Tw=ft([$a,Aw,Rw]),Pw=0,Pa=1,bt=2,ka=3,kw=16,Of="graffiti-login-remembered-handle",mi=class{dids=new vo;authorization=new Lo;storageBuckets=new jo;inboxes=new Fo;stringEncoder=new Go;contentAddresses=new Jo;channelAttestations=new Qo;allowedAttestations=new ei;sessions=new ci({dids:this.dids,authorization:this.authorization,storageBuckets:this.storageBuckets,inboxes:this.inboxes});handles=new ti({dids:this.dids});objectEncoding=new fi({stringEncoder:this.stringEncoder,contentAddresses:this.contentAddresses,channelAttestations:this.channelAttestations,allowedAttestations:this.allowedAttestations});modal=typeof window>"u"?void 0:new kf({useTemplateHTML:()=>import("./login-dialog.html-E6VRKMXH.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){if("manual"in r&&r.manual)return;alert("Login failed: "+r.error.message);let s=r.session?.actor,a;if(s)try{a=await this.actorToHandle(s)}catch(c){console.error("Failed to handle actor:",c)}this.login_(a);return}let o=r.session.actor,i;try{i=await this.actorToHandle(o)}catch(s){console.error("Failed to load handle from actor:",s)}i&&await this.rememberHandleInPasswordManager(i,o)});for(let n of["post","get","delete","postMedia","getMedia","deleteMedia"]){let r=this[n];this[n]=async(...o)=>{try{return await r(...o)}catch(i){let s=o[o.length-1];throw await this.tryLogoutIfUnauthorized(i,s),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"),i=t||await this.getRememberedHandleFromPasswordManager();o&&(o.value=i??""),o?.addEventListener("focus",()=>o?.select()),setTimeout(()=>o?.focus(),0),n?.querySelector("#graffiti-login-handle-form")?.addEventListener("submit",async s=>{s.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 c=o.value;if(!c.includes(".")&&!c.startsWith("localhost")){let l=new URL(this.identityCreatorEndpoint).host;c=`${c}.${l}`}let u;try{u=await this.handleToActor(c)}catch{alert("Could not find an identity associated with that handle."),this.login_(c);return}try{await this.sessions.login(u)}catch(l){alert("Error logging in."),console.error(l),this.login_(c)}})}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(s=>{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(s=>{r.question(`Please enter your handle${t?` (default: ${t})`:""}: `,a=>{r.close(),s(a||t)})});if(!o)throw new Error("No handle provided");let i=await this.handleToActor(o);await this.sessions.login(i)}}async rememberHandleInPasswordManager(t,n){if(typeof window>"u")return;let r=window.navigator.credentials,o=window.PasswordCredential;if(!r?.store||!o){this.rememberHandleInBrowserStorage(t);return}try{let i=new o({id:t,password:"no-password",name:t});await r.store(i)}catch(i){console.error("Failed to remember handle in password manager:",i),this.rememberHandleInBrowserStorage(t)}}async getRememberedHandleFromPasswordManager(){if(typeof window>"u")return;let t=window.navigator.credentials,n=window.PasswordCredential;if(!t?.get||!n)return this.getRememberedHandleFromBrowserStorage();try{let r=await t.get({password:!0,mediation:"optional"});if(r&&"id"in r&&typeof r.id=="string")return r.id}catch(r){return console.error("Failed to load handle from password manager:",r),this.getRememberedHandleFromBrowserStorage()}}rememberHandleInBrowserStorage(t){if(!(typeof window>"u"))try{window.localStorage.setItem(Of,t)}catch(n){console.error("Failed to remember handle in browser storage:",n)}}getRememberedHandleFromBrowserStorage(){if(!(typeof window>"u"))try{return window.localStorage.getItem(Of)??void 0}catch(t){console.error("Failed to load handle from browser storage:",t);return}}logout=async t=>{await this.sessions.logout(t.actor)};post=async(...t)=>{let[n,r]=t,o=this.sessions.resolveSession(r),{object:i,tags:s,objectBytes:a,allowedTickets:c}=await this.objectEncoding.encode(n,r.actor),u=Tt(),l=await this.stringEncoder.encode(Tn,u);return await this.storageBuckets.put(o.storageBucket.serviceEndpoint,l,a,o.storageBucket.token),await this.announceObject(i,s,c,l,r),i};get=async(...t)=>{let[n,r,o]=t,i,s=await Or(r);if(o){let u=this.sessions.resolveSession(o);i=[u.personalInbox,...u.sharedInboxes]}else i=this.defaultInboxEndpoints.map(u=>({serviceEndpoint:u}));let a=wi(n),c=[new TextEncoder().encode(a)];for(let u of i){let l,d=this.querySingleEndpoint(u.serviceEndpoint,{tags:c,objectSchema:{}},u.token,o?.actor);for await(let p of d)p.object.url===a&&(p.tombstone?l=void 0:l=p.object);if(l){if(!s(l))throw new Pr("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=wi(t),{actor:i}=Ta(o);if(i!==n.actor)throw new dt("Cannot delete someone else's actor");let s=this.querySingleEndpoint(r.personalInbox.serviceEndpoint,{tags:[new TextEncoder().encode(o)],objectSchema:{}},r.personalInbox.token),a;for await(let w of s)w.object.url===o&&(w.tombstone?a=void 0:a=w);if(!a)throw new re(`Object ${o} not found`);let{object:c,storageBucketKey:u,tags:l,allowedTickets:d,announcements:p,messageId:m}=a;return await this.storageBuckets.delete(r.storageBucket.serviceEndpoint,u,r.storageBucket.token),await this.announceObject(c,l,d,u,n,[...p??[],{[Ar]:n.actor,[jt]:m}]),c};postMedia=async(...t)=>{let[n,r]=t,o=n.data.type,i=this.sessions.resolveSession(r),s=Tt(),a=await this.stringEncoder.encode(Tn,s);await this.storageBuckets.put(i.storageBucket.serviceEndpoint,a,new Uint8Array(await n.data.arrayBuffer()),i.storageBucket.token);let{url:c}=await this.post({value:{key:a,type:o,size:n.data.size},channels:[],allowed:n.allowed},r);return c};getMedia=async(...t)=>{let[n,r,o]=t,i=await this.get(n,Ow,o),{key:s,type:a,size:c}=i.value;if(r?.maxBytes&&c>r.maxBytes)throw new Ht("File size exceeds limit");if(r?.types&&!La(a,r.types))throw new kr(`Unacceptable media type, ${a}`);let l=(await this.dids.resolve(i.actor))?.service?.find(w=>w.id===li&&w.type===ui);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,s,c);return{data:new Blob([p.slice()],{type:a}),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,s;if(o){let d=this.sessions.resolveSession(o);s=[d.personalInbox,...d.sharedInboxes]}else s=this.defaultInboxEndpoints.map(d=>({serviceEndpoint:d}));for(let d in r)if(!s.some(p=>p.serviceEndpoint===d))throw new dt("Cursor does not match actor's inboxes");let a=await Promise.all(t.map(d=>this.channelAttestations.register(Bt,d))),c=s.map(d=>{let p=r[d.serviceEndpoint];return this.querySingleEndpoint(d.serviceEndpoint,p?{cursor:p}:{tags:a,objectSchema:n},d.token,o?.actor)}),u=c.map(async(d,p)=>zf(d,p)),l=u.length;try{for(;l>0;){let d=await Promise.race(u);if(d.error!==void 0)u[d.index]=new Promise(()=>{}),l--,yield{error:d.error,origin:s[d.index].serviceEndpoint},this.tryLogoutIfUnauthorized(d.error,o);else if(d.result.done){let p=s[d.index];r[p.serviceEndpoint]=d.result.value,u[d.index]=new Promise(()=>{}),l--}else{u[d.index]=zf(c[d.index],d.index);let{object:p,tombstone:m,tags:w}=d.result.value;if(m){if(i.get(p.url)===!0)continue;i.set(p.url,!0),yield{tombstone:m,object:{url:p.url}}}else{if(i.get(p.url)===!1)continue;let _=a.reduce((g,v,b)=>{for(let S of w)if(v.length===S.length&&v.every((A,O)=>S[O]===A)){g.push(b);break}return g},[]).map(g=>t[g]);_.length===0&&(yield{error:new Error("Inbox returned object without matching channels"),origin:s[d.index].serviceEndpoint}),i.set(p.url,!1),yield{object:{...p,channels:_}}}}}}catch(d){throw this.tryLogoutIfUnauthorized(d,o),d}finally{await Promise.all(c.map(async d=>{await d.return("")}))}return{cursor:JSON.stringify({channels:t,cursors:r})}}discover=(...t)=>{let[n,r,o]=t;return this.discoverMeta(n,r,{},o)};continueDiscover=(...t)=>{let[n,r]=t,o,i;try{let s=JSON.parse(n),a=zw.parse(s);o=a.channels,i=a.cursors}catch{return(async function*(){throw new Ce("Invalid cursor")})()}return this.discoverMeta(o,{},i,r)};async tryLogoutIfUnauthorized(t,n){t instanceof Dt&&n&&await this.sessions.logout(n.actor)}async announceObject(t,n,r,o,i,s){let a=this.sessions.resolveSession(i),c={[Oa]:o},u=[],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 m=await Promise.allSettled(l.map(async(w,x)=>{let _=JSON.parse(JSON.stringify(t)),g=_i(_,[],w),b=(await this.dids.resolve(w)).service?.find(D=>D.type===ai&&D.id===ba);if(!b)throw new Error(`Recipient ${w} does not have a personal inbox`);if(typeof b.serviceEndpoint!="string")throw new Error(`Recipient ${w} does not have a valid personal inbox endpoint`);let S=s?s.find(D=>D[Ar]===w)?.[jt]:void 0,A={...c,...S?{[On]:S}:{},[Rr]:r[x],[Ia]:x},O=await this.inboxes.send(b.serviceEndpoint,{[xr]:n,[st]:g,[Er]:Re(A)});u.push({[jt]:O,[Ar]:w})}));for(let[w,x]of m.entries())if(x.status==="rejected"){let _=l[w];console.error("Error sending to recipient:",_),console.error(x.reason)}}else{let m=JSON.parse(JSON.stringify(t)),w=_i(m,[]),x=a.sharedInboxes,_=await Promise.allSettled(x.map(async g=>{let v=s?s.find(A=>A[za]===g.serviceEndpoint)?.[jt]:void 0,b={...c,...v?{[On]:v}:{}},S=await this.inboxes.send(g.serviceEndpoint,{...v?{[On]:v}:{},[xr]:n,[st]:w,[Er]:Re(b)});u.push({[jt]:S,[za]:g.serviceEndpoint})}));for(let[g,v]of _.entries())if(v.status==="rejected"){let b=x[g];console.error("Error sending to inbox:",b),console.error(v.reason)}}let d=s?s.find(m=>m[Ar]===i.actor)?.[jt]:void 0,p={...c,...r?{[pi]:r}:{},...d?{[On]:d}:{},[hi]:u};await this.inboxes.send(a.personalInbox.serviceEndpoint,{[xr]:n,[st]:t,[Er]:Re(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),s=[],a=null;try{for(;;){for(;a===null&&s.length<kw;){let l=await i.next();if(l.done){a=l.value;break}let d=this.processOneLabeledMessage(t,l.value,r,o).catch(p=>{throw p});s.push(d)}let c=s.shift();if(!c){if(a!==null)return a;throw new Error("Process queue empty but no return value")}let u=await c;u&&(yield u)}}finally{await i.return("")}}async processOneLabeledMessage(t,n,r,o){let i=n.l;if(i!==Pa&&i!==Pw&&i!==bt)return;let s=n.id,{o:a,m:c,t:u}=n.m,l;try{let _=qe(c);l=Tw.parse(_)}catch{this.inboxes.label(t,s,ka,r);return}let{[Oa]:d,[On]:p}=l,m=pi in l?l[pi]:void 0,w=hi in l?l[hi]:void 0;if(i===Pa)return{messageId:s,object:a,storageBucketKey:d,allowedTickets:m,tags:u,announcements:w};if(i===bt){if(!p)return;let _=await this.inboxes.get(t,p,r);return!_||_[Ut][st].url!==a.url?void 0:(_[Ho]!==bt&&this.inboxes.label(t,p,bt,r),{messageId:s,tombstone:!0,object:a,storageBucketKey:d,allowedTickets:m,tags:u,announcements:w})}let x;try{let _=a.actor,v=(await this.dids.resolve(_))?.service?.find(O=>O.id===li&&O.type===ui);if(!v)throw new re(`Actor ${_} has no storage bucket service`);if(typeof v.serviceEndpoint!="string")throw new re(`Actor ${_} does not have a valid storage bucket endpoint`);let b=v.serviceEndpoint,S=await this.storageBuckets.get(b,d,di);if(Rr in l&&!o)throw new dt("Recipient is required when allowed ticket is present");let A=m?{allowedTickets:m}:Rr in l?{recipient:o??"null",allowedTicket:l[Rr],allowedIndex:l[Ia]}:void 0;await this.objectEncoding.validate(a,u,S,A)}catch(_){x=_}if(p){if(x instanceof re)return this.inboxes.get(t,p,r).then(_=>{_&&_[Ut][st].url===a.url&&_[Ho]!==bt&&this.inboxes.label(t,p,bt,r),this.inboxes.label(t,s,bt,r)}),{messageId:s,tombstone:!0,object:a,storageBucketKey:d,allowedTickets:m,tags:u,announcements:w};console.error("Recieved an incorrect tombstone object"),console.error(x),this.inboxes.label(t,s,ka,r)}else{if(x===void 0)return this.inboxes.label(t,s,Pa,r),{messageId:s,object:a,storageBucketKey:d,tags:u,allowedTickets:m,announcements:w};x instanceof re?this.inboxes.label(t,s,bt,r):(console.error("Recieved an incorrect object"),console.error(x),this.inboxes.label(t,s,ka,r))}}},Ow={properties:{value:{properties:{type:{type:"string"},size:{type:"number"},key:{type:"string"}},required:["type","size","key"]}}},zw=xe({cursors:Jc(Z(),B()),channels:J(B())});async function zf(e,t){try{return{index:t,result:await e.next()}}catch(n){if(n instanceof Ce||n instanceof Ft)throw n;return{index:t,error:n instanceof Error?n:new Error(String(n))}}}var $f=class extends Lr{constructor(t){let n=new mi(t);super(n)}};export{$f as GraffitiDecentralized};
8
11
  /*! Bundled license information:
9
12
 
10
- @noble/hashes/utils.js:
11
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
12
-
13
13
  @noble/ed25519/index.js:
14
14
  (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
15
+
16
+ js-cookie/dist/js.cookie.mjs:
17
+ (*! js-cookie v3.0.8 | MIT *)
15
18
  */
16
19
  //# sourceMappingURL=index.js.map